@sanity/workflows-cli 0.0.0-stage → 0.39.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.
Files changed (134) hide show
  1. package/CHANGELOG.md +1981 -0
  2. package/LICENSE +21 -0
  3. package/README.md +848 -2
  4. package/bin/run.js +8 -0
  5. package/dist/command-ids.d.ts +10 -0
  6. package/dist/command-ids.js +10 -0
  7. package/dist/commands/workflows/abort.d.ts +29 -0
  8. package/dist/commands/workflows/abort.js +50 -0
  9. package/dist/commands/workflows/blueprints/generate.d.ts +12 -0
  10. package/dist/commands/workflows/blueprints/generate.js +46 -0
  11. package/dist/commands/workflows/codemod/packages.d.ts +13 -0
  12. package/dist/commands/workflows/codemod/packages.js +41 -0
  13. package/dist/commands/workflows/definitions/delete.d.ts +44 -0
  14. package/dist/commands/workflows/definitions/delete.js +74 -0
  15. package/dist/commands/workflows/definitions/diff.d.ts +23 -0
  16. package/dist/commands/workflows/definitions/diff.js +55 -0
  17. package/dist/commands/workflows/definitions/list.d.ts +52 -0
  18. package/dist/commands/workflows/definitions/list.js +139 -0
  19. package/dist/commands/workflows/definitions/show.d.ts +66 -0
  20. package/dist/commands/workflows/definitions/show.js +129 -0
  21. package/dist/commands/workflows/definitions/validate.d.ts +14 -0
  22. package/dist/commands/workflows/definitions/validate.js +50 -0
  23. package/dist/commands/workflows/deploy.d.ts +117 -0
  24. package/dist/commands/workflows/deploy.js +266 -0
  25. package/dist/commands/workflows/diagnose.d.ts +53 -0
  26. package/dist/commands/workflows/diagnose.js +195 -0
  27. package/dist/commands/workflows/fire-action.d.ts +53 -0
  28. package/dist/commands/workflows/fire-action.js +182 -0
  29. package/dist/commands/workflows/list.d.ts +79 -0
  30. package/dist/commands/workflows/list.js +249 -0
  31. package/dist/commands/workflows/nuke.d.ts +73 -0
  32. package/dist/commands/workflows/nuke.js +175 -0
  33. package/dist/commands/workflows/reset-activity.d.ts +32 -0
  34. package/dist/commands/workflows/reset-activity.js +60 -0
  35. package/dist/commands/workflows/show.d.ts +30 -0
  36. package/dist/commands/workflows/show.js +156 -0
  37. package/dist/commands/workflows/start.d.ts +57 -0
  38. package/dist/commands/workflows/start.js +196 -0
  39. package/dist/commands/workflows/tail.d.ts +24 -0
  40. package/dist/commands/workflows/tail.js +83 -0
  41. package/dist/commands/workflows/whoami.d.ts +16 -0
  42. package/dist/commands/workflows/whoami.js +53 -0
  43. package/dist/help.d.ts +13 -0
  44. package/dist/help.js +50 -0
  45. package/dist/hooks/finally/telemetry.d.ts +3 -0
  46. package/dist/hooks/finally/telemetry.js +10 -0
  47. package/dist/hooks/prerun/telemetry.d.ts +33 -0
  48. package/dist/hooks/prerun/telemetry.js +52 -0
  49. package/dist/index.d.ts +1 -0
  50. package/dist/index.js +1 -0
  51. package/dist/lib/base-command.d.ts +14 -0
  52. package/dist/lib/base-command.js +41 -0
  53. package/dist/lib/blueprint-emit.d.ts +56 -0
  54. package/dist/lib/blueprint-emit.js +233 -0
  55. package/dist/lib/blueprint-needs.d.ts +5 -0
  56. package/dist/lib/blueprint-needs.js +284 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +118 -0
  59. package/dist/lib/cause-detail.d.ts +9 -0
  60. package/dist/lib/cause-detail.js +112 -0
  61. package/dist/lib/client.d.ts +27 -0
  62. package/dist/lib/client.js +45 -0
  63. package/dist/lib/codemod/ast.d.ts +17 -0
  64. package/dist/lib/codemod/ast.js +14 -0
  65. package/dist/lib/codemod/export-rename.d.ts +19 -0
  66. package/dist/lib/codemod/export-rename.js +337 -0
  67. package/dist/lib/codemod/manifest-rewrite.d.ts +17 -0
  68. package/dist/lib/codemod/manifest-rewrite.js +133 -0
  69. package/dist/lib/codemod/package-map.d.ts +27 -0
  70. package/dist/lib/codemod/package-map.js +99 -0
  71. package/dist/lib/codemod/report.d.ts +4 -0
  72. package/dist/lib/codemod/report.js +51 -0
  73. package/dist/lib/codemod/run.d.ts +25 -0
  74. package/dist/lib/codemod/run.js +108 -0
  75. package/dist/lib/codemod/source-rewrite.d.ts +20 -0
  76. package/dist/lib/codemod/source-rewrite.js +150 -0
  77. package/dist/lib/command-context.d.ts +20 -0
  78. package/dist/lib/command-context.js +24 -0
  79. package/dist/lib/command-telemetry.d.ts +54 -0
  80. package/dist/lib/command-telemetry.js +82 -0
  81. package/dist/lib/context.d.ts +151 -0
  82. package/dist/lib/context.js +263 -0
  83. package/dist/lib/default-partition.d.ts +23 -0
  84. package/dist/lib/default-partition.js +47 -0
  85. package/dist/lib/definition-files.d.ts +14 -0
  86. package/dist/lib/definition-files.js +60 -0
  87. package/dist/lib/definitions.d.ts +63 -0
  88. package/dist/lib/definitions.js +84 -0
  89. package/dist/lib/diff.d.ts +12 -0
  90. package/dist/lib/diff.js +93 -0
  91. package/dist/lib/env.d.ts +7 -0
  92. package/dist/lib/env.js +8 -0
  93. package/dist/lib/fail.d.ts +36 -0
  94. package/dist/lib/fail.js +55 -0
  95. package/dist/lib/failure-kind.d.ts +7 -0
  96. package/dist/lib/failure-kind.js +66 -0
  97. package/dist/lib/flags.d.ts +53 -0
  98. package/dist/lib/flags.js +127 -0
  99. package/dist/lib/follow-up-command.d.ts +18 -0
  100. package/dist/lib/follow-up-command.js +12 -0
  101. package/dist/lib/history-rows.d.ts +3 -0
  102. package/dist/lib/history-rows.js +44 -0
  103. package/dist/lib/load-config.d.ts +51 -0
  104. package/dist/lib/load-config.js +108 -0
  105. package/dist/lib/nuke.d.ts +124 -0
  106. package/dist/lib/nuke.js +206 -0
  107. package/dist/lib/operation-args.d.ts +42 -0
  108. package/dist/lib/operation-args.js +21 -0
  109. package/dist/lib/ops-report.d.ts +45 -0
  110. package/dist/lib/ops-report.js +31 -0
  111. package/dist/lib/params.d.ts +3 -0
  112. package/dist/lib/params.js +21 -0
  113. package/dist/lib/pick-resource.d.ts +13 -0
  114. package/dist/lib/pick-resource.js +82 -0
  115. package/dist/lib/prompt.d.ts +35 -0
  116. package/dist/lib/prompt.js +11 -0
  117. package/dist/lib/read-fanout.d.ts +45 -0
  118. package/dist/lib/read-fanout.js +45 -0
  119. package/dist/lib/resource-target.d.ts +10 -0
  120. package/dist/lib/resource-target.js +12 -0
  121. package/dist/lib/select-deployment.d.ts +31 -0
  122. package/dist/lib/select-deployment.js +91 -0
  123. package/dist/lib/share-definitions.d.ts +101 -0
  124. package/dist/lib/share-definitions.js +188 -0
  125. package/dist/lib/telemetry-setup.d.ts +77 -0
  126. package/dist/lib/telemetry-setup.js +117 -0
  127. package/dist/lib/telemetry.d.ts +81 -0
  128. package/dist/lib/telemetry.js +90 -0
  129. package/dist/lib/ui.d.ts +88 -0
  130. package/dist/lib/ui.js +114 -0
  131. package/dist/standalone-argv.d.ts +14 -0
  132. package/dist/standalone-argv.js +57 -0
  133. package/oclif.manifest.json +1894 -0
  134. package/package.json +118 -3
package/README.md CHANGED
@@ -1,3 +1,849 @@
1
- # Temporary Holding Version
1
+ # @sanity/workflows-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Documentation:** [Workflows docs](https://www.sanity.io/docs/workflows). For this package, see [CLI reference](https://www.sanity.io/docs/workflows/cli-reference).
4
+
5
+ Command-line tool for deploying, inspecting, and administering Sanity workflow
6
+ definitions and instances.
7
+
8
+ The package is in prerelease and is publicly available on npm. Commands that
9
+ access Sanity use the resources in `sanity.workflow.ts` and authenticate with a
10
+ login session or an API token. `deploy --check` validates definitions and
11
+ checks the generated runtime offline, and `definitions validate` checks
12
+ definition JSON files without a config.
13
+
14
+ ## Run
15
+
16
+ Use Node.js 20.12 or later. Install the CLI and its engine peer from the same
17
+ Workflows release in your project:
18
+
19
+ ```sh
20
+ npm install --save-dev @sanity/workflows-cli @sanity/workflows
21
+ npx @sanity/workflows-cli --help
22
+ ```
23
+
24
+ After authentication and [configuration](#configuration), run commands through
25
+ the project-local package:
26
+
27
+ ```sh
28
+ npx @sanity/workflows-cli deploy --dry-run
29
+ npx @sanity/workflows-cli list --include-completed
30
+ npx @sanity/workflows-cli show INSTANCE_ID
31
+ ```
32
+
33
+ Replace `INSTANCE_ID` with the workflow instance ID returned by `list`.
34
+
35
+ The package is an [oclif](https://oclif.io) plugin: every command's canonical
36
+ id nests under the `workflows` topic
37
+ (`sanity-workflows workflows deploy`), so the `sanity` CLI runs the same
38
+ commands as `sanity workflows …` without colliding with its own root
39
+ commands (the sanity CLI already has a `deploy`). The short forms used
40
+ throughout this README (`deploy`, `definitions list`, …) are the standalone
41
+ binary's stable surface — its entrypoint rewrites them onto the topic before
42
+ oclif resolves the command. Those short forms are **not** registered as oclif
43
+ aliases, so a host mount does not pollute the host root.
44
+
45
+ Authenticate with `npx sanity@latest login`; the CLI reads that session token.
46
+ For CI, set `SANITY_AUTH_TOKEN` instead. Create a `sanity.workflow.ts` in your
47
+ project, as described in [Configuration](#configuration).
48
+
49
+ The token must span **every resource the workflow references**, not just the
50
+ workflow resource. Runtime commands build one client from the deployment
51
+ descriptor; when a workflow's subject or `doc.ref` fields point into other
52
+ datasets (or a canvas / media library), the engine reaches them through
53
+ sibling clients derived from that same token. A `sanity login` session or an
54
+ org-capable token covers this out of the box; a token scoped to a single
55
+ project will fail on cross-resource reads.
56
+
57
+ ## Configuration
58
+
59
+ The CLI is configured by a `sanity.workflow.ts` (or `.js`/`.mjs`). It looks in
60
+ the directory you run from, then in each parent directory, and uses the first
61
+ one it finds. Pass `--path` to name a config file, or a directory to start the
62
+ search from. Wherever you run the command, `blueprints generate` writes the
63
+ generated Blueprint files next to the config file, and `deploy` checks them
64
+ there.
65
+
66
+ The file exports a config built with `defineWorkflowConfig`, declaring your
67
+ **deployments** (typically one per environment):
68
+
69
+ ```ts
70
+ import type {WorkflowDeploymentInput} from '@sanity/workflows'
71
+ import {defineWorkflowConfig} from '@sanity/workflows/define'
72
+
73
+ import {articleReview, urlDraft} from './src/workflows.ts'
74
+
75
+ // Export each deployment under its own `name`, then list the exports in the
76
+ // config. `blueprints generate` requires these named exports, and so does
77
+ // `deploy` once a generated runtime sits next to this file; nothing else does.
78
+ export const production = {
79
+ expectedMinReaderModel: 4,
80
+ name: 'production', // the deployment's unique identity (lowercase letters, digits, dashes)
81
+ partition: 'prod', // the environment partition the engine's docs are scoped to
82
+ workflowResource: {type: 'dataset', id: 'acme.workflows'}, // where those docs live
83
+ resourceAliases: [
84
+ // binds each `@<handle>:` a definition references to a physical resource
85
+ // in a DIFFERENT dataset from `workflowResource` (same-resource content
86
+ // needs no alias — see below)
87
+ {name: 'content', resource: {type: 'dataset', id: 'acme.content'}},
88
+ {name: 'assets', resource: {type: 'dataset', id: 'acme.assets'}},
89
+ ],
90
+ definitions: [articleReview, urlDraft], // the batch this deployment ships
91
+ } satisfies WorkflowDeploymentInput
92
+
93
+ export default defineWorkflowConfig({deployments: [production]})
94
+ ```
95
+
96
+ `name` is the deployment's identity: unique across the config and constrained
97
+ to the same grammar as `partition`. Partitions group deployments by environment and may
98
+ repeat, as long as no two deployments share both a `workflowResource` and a
99
+ `partition`. The config rejects that collision and names both deployments.
100
+
101
+ For `deploy`, `start`, `definitions diff`, and `definitions delete`, select a
102
+ deployment with `--deployment <name>`. With one deployment configured, you can
103
+ omit the selector. `--partition <partition>` selects one deployment when the partition is unique;
104
+ on `deploy`, it targets every deployment carrying the partition. With several
105
+ deployments and no selector, these commands prompt for a deployment in an
106
+ interactive terminal. In a non-interactive shell, they fail asking for
107
+ `--deployment` or `--partition`; `deploy` also suggests `--all-partitions`.
108
+
109
+ The instance-targeted commands `abort`, `reset-activity`, `fire-action`,
110
+ `diagnose`, `show`, and `tail` locate the instance by ID across
111
+ configured resources. Their optional `--deployment` and `--partition` flags
112
+ narrow the resources searched; the operation's partition comes from the loaded
113
+ instance.
114
+
115
+ `list`, `definitions list`, and `definitions show` read every configured resource
116
+ and partition by default. `--partition` filters to one partition, and
117
+ `--deployment` reads only that deployment's resource and partition.
118
+
119
+ The read commands `list`, `show`, `tail`, `diagnose`, `definitions list`,
120
+ `definitions show`, and `whoami` can also read one resource you name, with or without a
121
+ `sanity.workflow.ts`. Pass `--workflow-resource <type>:<id>` for any resource
122
+ type: `dataset:<projectId>.<dataset>`, `media-library:<id>`, `canvas:<id>` or
123
+ `dashboard:<id>`, the same form a deployment's `workflowResource` takes as a
124
+ string. For a dataset you can also use the Sanity CLI flags `--project-id <id>`
125
+ and `--dataset <name>` (`-p` and `-d`) together. `--media-library-id <id>` is
126
+ deprecated; use `--workflow-resource media-library:<id>`. The CLI then reads
127
+ only that resource and loads no config, so `--deployment` and `--path` can't be
128
+ combined with them. `--partition` still filters. Commands that write, such as
129
+ `start`, `abort`, and `deploy`, always act through a deployment in
130
+ `sanity.workflow.ts`.
131
+
132
+ While the experimental `SANITY_STUDIO_WORKFLOWS_SERVICE=true` is set in your
133
+ shell, `start`, `fire-action`, and `abort` send their write to the project's
134
+ Workflows service when your token can read workflow instances but not write
135
+ them, and the project has a service. Otherwise they write directly with your
136
+ token.
137
+
138
+ ```sh
139
+ sanity workflows definitions list --workflow-resource dataset:abc123.production
140
+ sanity workflows list --workflow-resource media-library:mlAbc123
141
+ sanity workflows show prod.wf-instance.x7k2 -p abc123 -d production
142
+ ```
143
+
144
+ When no `sanity.workflow.ts` is found and you pass none of these flags or
145
+ `--path` or `--deployment`, a read in an interactive terminal asks you to pick
146
+ a resource type, then a resource of that type your login can access (for a
147
+ dataset, a project and then one of its datasets). It then prints the
148
+ `--workflow-resource` flag that reads the same resource, so you can script the
149
+ next run. With `--json` or in a non-interactive shell, the read fails and names
150
+ the flags instead.
151
+
152
+ When an instance ID or definition name is found in more than one deployment,
153
+ for example two deployments on different resources that both use `default`,
154
+ an interactive terminal prompts you to pick one. Each choice shows the
155
+ deployment name with its resource. With `--json` or in a non-interactive shell,
156
+ the command fails, lists each candidate as `name (<resource type> <id>)` (for
157
+ example `production (dataset acme.production)`), and asks for `--deployment`.
158
+
159
+ A deployment alone on its configured resource may omit `partition`; it resolves
160
+ to `default`, independent of its name. If several deployments share that
161
+ resource, give every one an explicit, distinct partition. The engine stores the
162
+ partition on every definition and instance the deployment writes, so a
163
+ deployment only reaches documents written under its own partition value.
164
+
165
+ `--all-partitions` deploys every deployment in the config in one run: a failure in one doesn't
166
+ stop the rest — the run continues, prints a summary of what failed, and exits
167
+ non-zero. The client's project + dataset are derived from the deployment's
168
+ `workflowResource`, and `deploy` expands each definition's `@<handle>:`
169
+ reference to the bound physical resource. An invalid config fails with a clean,
170
+ path-prefixed error before the command runs.
171
+
172
+ `resourceAliases` is only for content that lives in a _different_ resource from
173
+ `workflowResource`. A definition can reference a document in the **same**
174
+ resource by bare id, no alias needed — bare ids root at `workflowResource` at
175
+ runtime. `@<handle>:` references exist at deploy time only: `deploy` expands
176
+ each one to its bound physical GDR, and nothing alias-shaped survives into the
177
+ deployed definition or the runtime. Rule of thumb: **different resource →
178
+ bind an alias; same resource → use a bare id and omit `resourceAliases`
179
+ entirely.** So the simplest single-dataset setup is just a `workflowResource`
180
+ and `definitions`, with no `resourceAliases` at all.
181
+
182
+ Refs supplied at runtime (`start --field`, `fire-action` ref params) are gated
183
+ separately: they may target the `workflowResource` itself or any resource the
184
+ deployment binds in `resourceAliases`, and anything else is rejected at the
185
+ write with `RefResourceUndeclaredError`. To start a workflow on content in
186
+ another dataset or project, bind that resource even when no definition
187
+ references the alias. The CLI reaches each bound resource with the same token
188
+ and API host it uses for `workflowResource`, so that login must be a member of
189
+ every bound project. Instance commands use the bindings of the configured
190
+ deployment that owns the instance's partition on the resource it was found in.
191
+ When no configured deployment owns that partition, refs may target only the
192
+ workflow resource.
193
+
194
+ For a `release.ref` field, `start --field` also takes a bare Content Release
195
+ name, such as `--field release=rA1b2C3d4`. The CLI builds the release ref on
196
+ the one resource the deployment binds in `resourceAliases` other than
197
+ `workflowResource`, or on `workflowResource` when it binds no other. When it
198
+ binds several other resources, name one with `--release-resource <alias>` or
199
+ pass the full object instead.
200
+
201
+ | Var | Purpose |
202
+ | ------------------- | ---------------------------------------------------------------------------------------------------- |
203
+ | `SANITY_AUTH_TOKEN` | Explicit token for CI / scripted use — wins over the `sanity login` session (editor role for writes) |
204
+ | `SANITY_API_HOST` | Optional API host override (defaults to the prod API) |
205
+
206
+ Your `sanity.workflow.ts` loads straight from TypeScript source: the CLI
207
+ transpiles the config file on the fly with `jiti`. Definitions you author
208
+ **inline** in the config, or import by **relative path**, transpile the same
209
+ way — no build step. A definition imported from an installed package loads
210
+ that package's published JavaScript.
211
+
212
+ ## Command list
213
+
214
+ Invoke as `sanity workflows <command>` in the Sanity CLI, or `sanity-workflows <command>` through the standalone binary. Suggested next commands in the output use whichever form you ran.
215
+
216
+ | Command | Description |
217
+ | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
218
+ | `deploy` | Validate the definitions, check any generated runtime still matches them and, with the experimental service switch set, that the Workflows service can read them, then deploy the selected deployment. |
219
+ | `deploy --all-partitions` | Deploy every deployment in the config. A failure in one does not stop the rest. |
220
+ | `deploy --check` | Validate local definitions and check the generated runtime, without contacting the dataset or the Workflows service. |
221
+ | `deploy --dry-run` | Check the generated runtime and, with the experimental service switch set, the Workflows service's data model, then show a diff against what is already deployed, without writing. |
222
+ | `deploy --verbose` | Print the full report of the functions the selected deployments need when no generated runtime is here, in place of the summary. |
223
+ | `deploy --only <name>` | Limit deploy, check, or dry-run to one definition. The generated-runtime check still covers the whole config. |
224
+ | `start <name>` | Start an instance from a deployed definition. Pass `--field` for input values. |
225
+ | `list` | List instances (in-flight by default). Filter with `--definition`. |
226
+ | `show <instance-id>` | Show an instance's state, activities, and effects. |
227
+ | `diagnose <instance-id>` | Explain why an instance is or isn't progressing, and what would unstick it. |
228
+ | `tail <instance-id>` | Stream new history entries as they land. |
229
+ | `abort <instance-id>` | Stop an in-flight instance. Pending effects cancel; the instance stays where it is. |
230
+ | `reset-activity <instance-id> <activity>` | Re-run a failed activity, or `--skip` it so a gated transition can fire. |
231
+ | `fire-action <instance-id>` | Fire an action on a waiting activity. Omit `--action` to list what can be fired. |
232
+ | `whoami` | Show your user ID as Workflows records it. Put the Sanity user ID in user assignee fields. `--json` prints an object. |
233
+ | `blueprints generate` | Write the Sanity Blueprints runtime the definitions require next to `sanity.workflow.ts`. |
234
+ | `blueprints generate --check` | Verify that runtime still matches the definitions. Writes nothing; exits non-zero on any difference. |
235
+ | `blueprints generate --verbose` | Print the full runtime-needs report, every file with its status, and the heartbeat stack's instructions on every run, in place of the summary. |
236
+ | `definitions list` | List deployed definitions. |
237
+ | `definitions show <name>` | Show a deployed definition (latest version, or `--version`). |
238
+ | `definitions validate <file...>` | Validate definitions in JSON files without a config, login, or network. `--json` prints the machine-readable report. |
239
+ | `definitions diff <name>` | Diff the in-code definition against what is deployed. |
240
+ | `definitions delete <name>` | Delete a deployed definition. Refuses while live instances exist unless `--cascade`. |
241
+ | `nuke --deployment <name>` / `nuke --partition <partition>` | Dev reset: delete every engine-owned document for that partition (instances, definitions, guards). Prints a plan, then asks for confirmation. Content documents are never touched. |
242
+ | `nuke --instance <id>` | Dev reset: delete one finished instance and its guards. Refuses in-flight instances (abort first). |
243
+
244
+ The `definitions` and `blueprints` commands also answer to the singular
245
+ `definition` and `blueprint`, so `definition list` runs `definitions list`.
246
+
247
+ ## Generating the Blueprints runtime
248
+
249
+ A definition that declares an effect, reads `$now`, or starts autonomously needs
250
+ server-side code: something has to run the effect handlers, sample deadlines, and
251
+ start instances from document writes. `blueprints generate` derives that runtime
252
+ from the definitions and writes it next to `sanity.workflow.ts`, so
253
+ `npx sanity@latest blueprints deploy` has something to deploy. A purely interactive
254
+ workflow needs none of it, and the command says so.
255
+
256
+ Current gaps:
257
+
258
+ - A start watcher in a dataset starts a definition on the write that makes its
259
+ `start.filter` true, even for a document that already has an instance from
260
+ an earlier time it became true. A start filter that reads `$now` or another
261
+ document, reads `$tag` or `$definition` and a field of the document other
262
+ than `_type` (or the whole document), or is not an expression the generator
263
+ recognizes as boolean, starts on every matching write instead, and the
264
+ generator warns about it and names which of these applies. Only the definition's own
265
+ start requirements refuse a start, such as a `singleSubject` requirement.
266
+ - A Media Library trigger receives one upload as more than one write, so
267
+ `blueprints generate` fails for an autonomous asset definition watched on a
268
+ Media Library whose `start.filter` would start on every write: one that reads
269
+ `$now` or another document, reads `$tag` or `$definition` and a field of
270
+ the asset other than `_type`, or is not an expression the generator
271
+ recognizes as boolean, unless the heartbeat starts it on the clock as
272
+ described below; then it gets no library watcher and the heartbeat alone
273
+ starts it. Other asset start filters are watched as on a dataset.
274
+ - Definitions and functions deploy in two steps, definitions first, until the
275
+ Blueprints service registers the `sanity.workflow` resource.
276
+ - A generated file cannot be taken over: editing one is drift, and the next
277
+ generation rewrites it.
278
+ - A retry policy is not checked against its function's timeout at generation, so
279
+ an effect can be configured to retry for longer than its function may run.
280
+
281
+ Blueprint generation parses `sanity.blueprint.ts` without loading your
282
+ project's TypeScript installation. The CLI works beside TypeScript 6 or 7 and
283
+ does not require TypeScript for this command.
284
+
285
+ Five prerequisites:
286
+
287
+ - **Each deployment is exported under its own `name`, and the export is the
288
+ deployment object itself**, as the [Configuration](#configuration) example
289
+ does: every generated module imports its deployment from `./sanity.workflow`
290
+ by that name. The command refuses to write anything until each name is
291
+ exported, and names the export to add. It checks the name only, so make sure
292
+ each export is the deployment your config lists. A typecheck of the generated
293
+ modules catches a wrong export only where a generated function uses it, and a
294
+ deployment that needs no functions emits none.
295
+ - **`sanity.workflow.ts` is importable inside a deployed function.** Every
296
+ generated module imports it, and each function bundles it, so the file runs
297
+ where your shell and your `.env` do not exist. Reading an absent variable
298
+ there yields `undefined`; what fails is a config that **throws** when a
299
+ variable is missing, or requires one to build the deployment, because that
300
+ runs on init before your handler is reached. Keep the deployment's resource
301
+ coordinates literal in the file and read secrets inside your handlers.
302
+ - **The Blueprints packages the generated modules import are installed**,
303
+ alongside the CLI and its peers.
304
+ - **Your definitions are deployed before the functions.** The generated
305
+ `workflows.blueprint.ts` carries the definitions entry commented out, because
306
+ the Blueprints service does not accept the `sanity.workflow` resource type
307
+ yet, so `npx sanity@latest blueprints deploy` does not deploy them. Run
308
+ `npx @sanity/workflows-cli deploy` first: a function that starts or advances an
309
+ instance resolves its definition from the Content Lake, and finds nothing
310
+ until that deploy has run.
311
+ - **A generated heartbeat deploys from its own directory, with an organization
312
+ deploy token.** The heartbeat is a scheduled function, and the platform only
313
+ accepts one on a stack in organization scope. The command writes it into
314
+ `workflows-heartbeat/sanity.blueprint.ts`, a blueprint of its own, so the
315
+ document functions in your `sanity.blueprint.ts` deploy to a project-scoped
316
+ stack with a token that can deploy to the project. Each heartbeat stack counts
317
+ toward your organization's limit of 10 organization-scoped stacks. How often
318
+ it may run is a plan limit rather than something the generator chooses — see
319
+ [the schedule](#the-generated-heartbeats-schedule) below.
320
+
321
+ ```sh
322
+ npm install --save-dev @sanity/blueprints @sanity/functions @sanity/workflows
323
+ npx @sanity/workflows-cli blueprints generate
324
+ npx @sanity/workflows-cli deploy
325
+ # Project stack, with a token that can deploy to the project
326
+ npx sanity@latest blueprints init . --project-id <projectId> # first deploy only
327
+ npx sanity@latest blueprints deploy
328
+ # Heartbeat stack, with an organization deploy token, when one was generated
329
+ cd workflows-heartbeat
330
+ npx sanity@latest blueprints init . --organization-id <organizationId> # first deploy only
331
+ npx sanity@latest blueprints deploy
332
+ ```
333
+
334
+ Each generated function's `package.json`, and the heartbeat stack's
335
+ `workflows-heartbeat/package.json`, copies the specifications your project
336
+ declares for `@sanity/functions`, `@sanity/workflows/blueprints`, and
337
+ `@sanity/workflows`. A package you declare nowhere fails the command
338
+ rather than being stamped with a guessed range. The Functions build installs a
339
+ function's dependencies from the `package.json` beside the blueprint it deploys
340
+ from, so the heartbeat built from `workflows-heartbeat/` runs the versions your
341
+ project pins rather than the latest ones.
342
+
343
+ The command prints a short summary: one line per deployment saying how many
344
+ functions it needs, the files that need you (a new handler scaffold, a change to
345
+ your own `sanity.blueprint.ts`, anything it could not resolve), a count of the
346
+ files it wrote, and a `Deploy:` section naming which stack to deploy with which
347
+ token. The project stack is always named when there are document functions,
348
+ because each function bundles `sanity.workflow.ts`; the heartbeat stack is named
349
+ when this run created or updated one of its files, and on every run when a
350
+ deployment has scheduled drains (a workflow stored in a Media Library). On the
351
+ first run:
352
+
353
+ ```
354
+ Runtime needs:
355
+ prod (prod) needs 3 Sanity Functions (1 effect drain, 1 heartbeat, 1 start watcher)
356
+
357
+ Generated tree:
358
+ created effect-handlers/send-notification.ts yours now — implement the effect
359
+ created sanity.blueprint.ts the workflow resources spread
360
+
361
+ ✔ 12 file(s) written (12 created), 0 left untouched
362
+
363
+ Deploy:
364
+ project stack: `npx sanity@latest blueprints deploy` here, with a token that can deploy to the project. It holds every document function; redeploy it after any definition change.
365
+ heartbeat stack: `npx sanity@latest blueprints deploy` in workflows-heartbeat/, with an organization deploy token. It holds only the scheduled heartbeat.
366
+ ⚠ Without the heartbeat stack nothing checks these on a schedule, and nothing reports it:
367
+ $now deadlines take effect only when another engine call evaluates them in article-review
368
+ an effect queued before its drain existed, or whose drain timed out, waits until a later drain picks it up: send-notification
369
+
370
+ Pass --verbose for the full report.
371
+ ```
372
+
373
+ When a later run changes a heartbeat-stack file, the command cannot tell
374
+ whether you deployed that stack, so it names the files and asks conditionally:
375
+
376
+ ```
377
+ ⚠ workflows-heartbeat/sanity.blueprint.ts changed: if you have deployed the heartbeat stack, redeploy it with the organization deploy token.
378
+ ```
379
+
380
+ `--verbose` prints the full needs report, every file with its status, and the
381
+ heartbeat stack's instructions whether or not this run changed its files.
382
+
383
+ The heartbeat stack's blueprint lists, in its header, the partition, the
384
+ workflow resource and each resource an alias binds, the `'function'`-hosted
385
+ workflows the heartbeat ticks, the `'function'`-hosted effects it re-queues, any
386
+ effects it drains on schedule, and each definition it starts on the clock with
387
+ its resource, subject types and start filter. Editing an existing workflow
388
+ stored in a dataset leaves it unchanged unless it changes which definitions the
389
+ heartbeat starts on the clock, or their start filter or subject types, so the default `Deploy:` section does not name the
390
+ heartbeat stack, and `--verbose` lists the file as `unchanged`. A workflow
391
+ stored in a Media Library drains its effects from the heartbeat stack, which
392
+ bundles your handlers, so the `Deploy:` section always names that stack: redeploy
393
+ it after you change a handler or a definition. Adding or removing a
394
+ `'function'`-hosted workflow or effect changes it: redeploy the heartbeat stack
395
+ too. So does moving the declared specification of `@sanity/functions`,
396
+ `@sanity/workflows/blueprints`, or `@sanity/workflows`,
397
+ which changes `workflows-heartbeat/package.json`, the manifest the heartbeat
398
+ stack's build installs from; the `Deploy:`
399
+ section names every heartbeat-stack file that changed. The heartbeat bundles the
400
+ installed runtime when it is deployed, so after upgrading the Workflows packages
401
+ redeploy both stacks even when every file is `unchanged`. `blueprints generate
402
+ --check` reports a changed file as `differs` until you regenerate, like any
403
+ other generated file.
404
+
405
+ Fill in each `effect-handlers/<effect name>.ts`: they are yours, scaffolded once
406
+ and never overwritten. Everything marked `created`, `updated`, or `unchanged`
407
+ under `workflows.blueprint.ts`, `workflows-heartbeat/`,
408
+ `functions/`, and `effect-handlers/all.ts` is regenerated on every run, so
409
+ edits there do not survive. Your own `sanity.blueprint.ts` receives the `workflowResources` import and spread once;
410
+ after that the command leaves it alone. The command never deletes a file. A
411
+ handler for an effect you removed, a scaffold blocked by a path that differs
412
+ only in case, and a blueprint it could not wire are reported for you to resolve.
413
+ So is a stale function directory: one under `functions/` whose `index.ts`
414
+ carries the generator's header but which the definitions no longer produce,
415
+ such as the directory a renamed function leaves behind. The generated blueprint
416
+ does not deploy it. A directory whose `index.ts` has no generator header is
417
+ yours, and is never reported. When no deployment needs a heartbeat any more, a
418
+ `workflows-heartbeat/sanity.blueprint.ts` left from an earlier run is reported
419
+ too: destroy its stack with the organization deploy token, then delete the
420
+ directory.
421
+
422
+ The command covers every deployment in the config, because the emitted
423
+ `workflows.blueprint.ts` declares them all, and
424
+ `workflows-heartbeat/sanity.blueprint.ts` declares every one that needs a
425
+ heartbeat.
426
+
427
+ ### Where each workflow runs
428
+
429
+ The `--verbose` report opens with the hosting each `runtime` block resolved to, after every
430
+ level has inherited from the one above it. It matters because a name listed
431
+ under `durableFunction` or `selfHosted` has no emitted function to point at:
432
+
433
+ - `function` — a drain and the start watchers on the project stack, and the
434
+ heartbeat on its own stack.
435
+ - `durableFunction` — nothing is emitted yet. The rest of the deployment emits
436
+ normally around it.
437
+ - `selfHosted` — nothing is emitted, and the report ends with what your own
438
+ process must do instead: which deadlines to tick, which effects to drain,
439
+ which parents to re-evaluate after they miss a child settling, and which
440
+ autonomous definitions to start. The heartbeat ticks only the
441
+ `'function'`-hosted workflows.
442
+
443
+ ### The generated heartbeat's schedule
444
+
445
+ The heartbeat is emitted on `* * * * *`, one run a minute, and how often the
446
+ platform will actually run it is a plan limit rather than something the
447
+ generator can choose: Sanity documents the threshold as
448
+ [Free daily, Growth hourly, Enterprise minutely](https://www.sanity.io/docs/functions/functions-introduction).
449
+ A workflow whose deadlines depend on the heartbeat advances no faster than the
450
+ heartbeat runs. An effect no drain picked up becomes eligible to re-queue five
451
+ minutes after it was queued, and a later heartbeat run re-queues it; each run
452
+ re-queues on at most 30 instances, so a large backlog takes several runs. Check
453
+ your plan's cadence before relying on a `$now` deadline in a deployed workflow.
454
+
455
+ A `'function'`-hosted autonomous definition whose `start.filter` reads `$now`,
456
+ such as `embargoAt <= $now`, also starts from the heartbeat when the filter
457
+ reads no other document and is recognized as a boolean expression, its
458
+ subject is taken from the started document, and its `start.roles`, if any,
459
+ admit the project `editor` role the heartbeat robot holds (with a Media
460
+ Library workflow resource, a definition declaring `start.roles` is not
461
+ started on the clock). Each run queries every resource
462
+ the definition's subjects can live in for the documents the filter admits at
463
+ that moment and that no instance of the definition holds yet, and starts them.
464
+ In the workflow resource, a document created before its embargo starts on the
465
+ first run past the embargo, with no further write. In another resource, each
466
+ run checks a window of 500 matching documents, held ones included, and with
467
+ `n` matching documents, a heartbeat that runs every minute checks every window
468
+ within `2 * ceil(n / 500) - 1` runs; on an hourly or daily cadence the windows
469
+ still rotate, with no fixed bound. Each run starts at most its share, so a backlog of eligible documents,
470
+ such as every document the filter already admits when the heartbeat is first
471
+ deployed, starts over several runs. A start the engine
472
+ refuses, such as one an unmet start requirement refuses, is logged and
473
+ skipped. The report lists the queries
474
+ this costs per run. A run then shares its 60 instances evenly between
475
+ re-queueing, ticking and starting, 20 each. A `$now` start filter that does not
476
+ qualify starts only on a write: the report warns about it on a dataset, and
477
+ `blueprints generate` fails for it on a Media Library.
478
+
479
+ ### Checking for drift in CI
480
+
481
+ `blueprints generate --check` renders the same runtime in memory and compares it
482
+ with the files on disk. It writes nothing and exits zero when they match:
483
+
484
+ ```
485
+ $ npx @sanity/workflows-cli blueprints generate --check
486
+ ✔ the generated tree matches the definitions
487
+ ```
488
+
489
+ Otherwise it exits `1` and names every file, so the log alone says what to fix:
490
+
491
+ ```
492
+ $ npx @sanity/workflows-cli blueprints generate --check
493
+ ✖ The generated tree does not match the definitions (1):
494
+ differs effect-handlers/all.ts
495
+ Run `sanity-workflows blueprints generate` to bring it back in line.
496
+ $ echo $?
497
+ 1
498
+ ```
499
+
500
+ A file reports `missing` when nothing is at its path, `differs` when the file
501
+ there has other contents, and a handler for a declared effect reports `missing`
502
+ when you have not written it yet. A stale function directory also fails the
503
+ check, and the report names it. Add the command to the job that builds your
504
+ blueprint and a definition change can no longer ship without the runtime it
505
+ needs.
506
+
507
+ ### Every deploy runs the same check
508
+
509
+ `deploy` validates the definitions, then looks for `workflows.blueprint.ts` next
510
+ to `sanity.workflow.ts`. When that file is there, the deploy runs the same
511
+ comparison as [Checking for drift in CI](#checking-for-drift-in-ci), and a
512
+ difference stops it:
513
+
514
+ ```
515
+ $ npx @sanity/workflows-cli deploy --partition prod
516
+ ✖ The generated tree does not match the definitions (1):
517
+ differs workflows.blueprint.ts
518
+ Run `sanity-workflows blueprints generate` to bring it back in line.
519
+ $ echo $?
520
+ 1
521
+ ```
522
+
523
+ Nothing is written when that happens: the check runs before the first definition
524
+ reaches the dataset, and before the CLI resolves a token. A stale function directory
525
+ does not stop the deploy, because the generated blueprint does not deploy it.
526
+ The deploy prints a warning naming the directory and continues. Run
527
+ `blueprints generate`, review what it wrote, and deploy again.
528
+
529
+ Definitions deploy first and the functions follow: `sanity-workflows deploy`
530
+ writes the definitions, then `npx sanity@latest blueprints deploy` ships the runtime
531
+ that serves them. That order is why the deploy is where drift is caught. It is
532
+ the step that would otherwise put definitions in front of a runtime that cannot
533
+ serve them.
534
+
535
+ When no `workflows.blueprint.ts` is there, the deploy summarises the functions
536
+ the selected deployments need and continues, so a project that has not
537
+ generated one yet still deploys:
538
+
539
+ ```
540
+ $ npx @sanity/workflows-cli deploy --partition prod
541
+ Runtime needs:
542
+ prod (prod) needs 3 Sanity Functions (1 effect drain, 1 heartbeat, 1 start watcher)
543
+
544
+ ⚠ No generated runtime is here. Run `sanity-workflows blueprints generate` to emit one, unless a runtime you maintain yourself already serves these definitions. Pass --verbose for the full report.
545
+ ```
546
+
547
+ `deploy --verbose` prints the full report in place of the summary: each
548
+ function, what it runs, and why the definitions need it, the same report
549
+ `blueprints generate --verbose` prints before it writes. Nothing is written either way.
550
+ The summary and the report cover the deployments the run selects, so a
551
+ deployment needing no functions prints nothing about the runtime even when a
552
+ sibling needs some. Definitions no runtime can be derived from at all print a
553
+ warning saying so. Either way the deploy continues.
554
+
555
+ The check has no off switch, by design: the definition deploy is the one moment
556
+ every deployment passes through, and a flag would be reached for in exactly the
557
+ situation the check exists to catch, which is shipping a definition change whose
558
+ runtime was never regenerated. Nothing runs for a hand-written runtime, because
559
+ a project that never generated a tree has no `workflows.blueprint.ts` for the
560
+ check to compare.
561
+
562
+ Two consequences worth knowing:
563
+
564
+ - The check covers the whole config, because the generated tree declares every
565
+ deployment in it. `deploy --deployment one` still holds the tree to every
566
+ deployment's definitions, so a sibling deployment stops it by drifting or by
567
+ failing validation.
568
+ - `deploy --check` and `deploy --dry-run` run it too, and the check itself is
569
+ offline in both. `--check` is the complete credential-free pre-flight:
570
+ definitions valid, runtime in line, dataset untouched. `--dry-run` goes on to
571
+ authenticate and read the deployed state to build its diff.
572
+
573
+ ## Telemetry
574
+
575
+ The CLI collects usage telemetry through Sanity's standard pipeline. Consent
576
+ is the account-wide status managed by `npx sanity telemetry enable|disable|status`.
577
+ CI and trueish `DO_NOT_TRACK` suppress everything except a deploy that may share
578
+ new definitions, which forces that deploy's telemetry unless `--no-share-defs`
579
+ is passed — see [Definition sharing](#definition-sharing). A session that isn't
580
+ logged in sends nothing. A logged-in run sends whether or not a
581
+ `sanity.workflow.ts` is found. A one-time notice on stderr discloses collection
582
+ on first use.
583
+
584
+ What may be collected is governed by [Sanity's telemetry
585
+ policy](https://www.sanity.io/telemetry). This package sends a subset of it.
586
+
587
+ Collected:
588
+
589
+ - The resource the run reads or writes (its type and id), the project id and
590
+ dataset when that resource is a dataset, and the organization id that owns
591
+ it, as session properties. The organization id is best effort: it needs a
592
+ lookup that can resolve to nothing, and the event sends either way.
593
+ - Operating system, CPU architecture, JavaScript runtime and version, and the
594
+ CLI version.
595
+ - The command invoked, and the flags it was given. Each is normalised to its
596
+ canonical long form, so `--partition=prod`, `--partition prod`, and the
597
+ deprecated `--tag prod` all report `--partition=prod`. A flag the command declared, and did not redact, reports its
598
+ **value**; because values ship, a flag naming a definition, stage,
599
+ deployment, document, or user reports that name or id verbatim. Redact a
600
+ flag whose value should not leave the machine.
601
+ - Structural counts and closed vocabulary values derived from a definition or
602
+ instance: stage and action counts, activity and field kinds, lifecycle,
603
+ status enums, and durations.
604
+ - Content fingerprints of definitions, and random run ids.
605
+ - `instanceId`, the instance document `_id`. Engine-minted ids embed the
606
+ deployment partition (`<partition>.wf-instance.<random>`), so the partition
607
+ reaches telemetry through this field. A caller-supplied instance id is sent verbatim.
608
+ - The author-chosen effect name, on effect events.
609
+ - Whether a command succeeded and, when it failed, the kind of failure: a
610
+ fixed label such as `usage`, `auth-missing`, `permission-denied`,
611
+ `resource-not-found`, `request-failed`, `config-invalid`,
612
+ `definition-file-invalid`, or the engine error kind (for example
613
+ `instance-not-found`). A failure that matches none of these reports `other`.
614
+
615
+ Never collected, because the policy excludes them:
616
+
617
+ - Environment variables, file paths, and file contents.
618
+ - Logs and serialized JavaScript stack traces.
619
+
620
+ Never collected, because this package goes further than the policy requires.
621
+ The policy does not prohibit any of these, so their absence here is this
622
+ package's choice and not a company-wide guarantee:
623
+
624
+ - The value of a redacted flag. A flag whose value is text a person typed
625
+ reports its name alone: `--reason` on `abort` and `definitions delete`,
626
+ `--field` on `start`, and `--param` on `fire-action`.
627
+ - The value of any flag the command did not declare, including a misspelling
628
+ of a redacted flag. Only the name is reported, and the token after it is
629
+ withheld unless the flag carries its value in the same token (`--resaon=x`,
630
+ `-zx`). The `sanity` CLI sends these whole; withholding them is what keeps
631
+ a mistyped `--reason` from sending the text redaction exists to withhold.
632
+ - Anything after the `--` terminator. Those tokens are not reported at all.
633
+ - Error messages, and stack traces of any language. The policy permits error
634
+ information that excludes sensitive data, but this package's errors quote
635
+ definition names, partitions, and argv, so none is sent. A failure is reported as
636
+ a success boolean and a fixed failure kind, never the error's text.
637
+ - Document content, GROQ, and field values.
638
+ - Definition names and stage names in the engine's own event payloads. A stage
639
+ transition reports positions in `stages[]`, never names. This does not
640
+ extend to flag values, which ship verbatim as described above.
641
+
642
+ Note that a dataset name, a deployment partition, and an effect name are all
643
+ customer-authored. They are collected deliberately, as identifiers and as a
644
+ closed label, not as free text.
645
+
646
+ Definition sharing sends the definition document to a first-party feedback
647
+ endpoint, not through this pipeline; telemetry only records the content-free
648
+ markers below.
649
+
650
+ Each event includes `context.surface: 'cli'`, the `@sanity/workflows-cli`
651
+ package version in `context.packageVersion` (also when run as `sanity
652
+ workflows`), and its process execution mode in `context.environment`. `NODE_ENV=production` reports `production`;
653
+ `development` and `test` report `development`. Unset, empty, and unrecognized
654
+ values default to `production` for installed CLI and MCP runs. The SDK reports
655
+ build mode and defaults to `development` instead.
656
+
657
+ When comparing activity across surfaces, group or filter by `context.surface`
658
+ alongside `context.environment`. Environment does not identify a production
659
+ dataset or deployment; the API host, dataset name, and deployment partition do not
660
+ set it. Existing telemetry consent and opt-out settings still apply.
661
+
662
+ One extension point: supply your own logger as `telemetry` in
663
+ `sanity.workflow.ts` and the built-in pipeline is not constructed at all —
664
+ every event flows to your implementation unconditionally (CI included), and
665
+ consent, suppression, and destination become its business.
666
+
667
+ ### Session properties
668
+
669
+ The built-in store attaches these user properties once per invocation (joined
670
+ to events by session id). User identity is not in the payload; the intake
671
+ service resolves the sender from the authenticated session.
672
+
673
+ | Property | What it is |
674
+ | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
675
+ | `surface` | Always `'cli'`. |
676
+ | `machinePlatform` | Node `process.platform` (for example `darwin`, `linux`). |
677
+ | `cpuArchitecture` | Node `process.arch`. |
678
+ | `runtime` | Always `'node'` for this CLI. |
679
+ | `runtimeVersion` | Node `process.version`. |
680
+ | `cliVersion` | The CLI package version, when oclif supplied it. |
681
+ | `resourceType` | The type of the resource the run names with `--workflow-resource`, `--project-id`/`--dataset` or `--media-library-id`, else of the `--deployment` it names, else (without `--deployment`) of the first deployment in `sanity.workflow.ts`. Absent when none exists, or when `--deployment` names no deployment in the config. |
682
+ | `resourceId` | That resource's id. Absent when none exists. |
683
+ | `projectId` | That resource's project, when it is a dataset. |
684
+ | `dataset` | That resource's dataset name, when it is a dataset. |
685
+ | `orgId` | Organization id that owns that resource, when the lookup succeeds before the command flushes. Optional. |
686
+
687
+ ### CLI events
688
+
689
+ These events are defined by this package.
690
+
691
+ #### `Workflows CLI Command Executed` (version 3)
692
+
693
+ One trace per workflows command, shaped like the `sanity` CLI's own
694
+ `CLI Command Executed` so both join on the same columns. The built-in store
695
+ fixes the invocation's identity as the trace context in the prerun hook and
696
+ completes the trace in the finally hook; the context rides every event the
697
+ trace emits. Host commands outside the `workflows` topic do not emit.
698
+
699
+ The context carries:
700
+
701
+ | Field | Type | What is collected |
702
+ | ------------------ | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
703
+ | `groupOrCommand` | `string` | Always `'workflows'`. |
704
+ | `commandArguments` | `string[]` | The oclif command path below the topic: `['deploy']`, `['definitions', 'list']`. Empty for the bare topic and for an invocation oclif resolved to no command. Never argv free-text. |
705
+ | `extraArguments` | `string[]` | Each flag on the invocation, in the order given and repeated if repeated, in its canonical `--name=value` form: `--partition prod`, `--partition=prod`, and the deprecated `--tag prod` all report `--partition=prod`. A boolean reports `--name` or `--no-name`. A redacted flag reports `--name` alone, and an undeclared flag reports its name as typed (`--resaon`, `-z`) alone. Tokens after `--` are not reported. |
706
+ | `coreOptions` | `object` | `{debug, help, version}`. `debug` comes from a set `DEBUG` variable, `help` from a literal `help` token, `version` from `--version`. |
707
+
708
+ The payload is sent on `trace.log`:
709
+
710
+ | Field | Type | What is collected |
711
+ | ------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
712
+ | `success` | `boolean` | `true` when the command finished without an oclif error. |
713
+ | `failureKind` | `string` | Present only when `success` is `false`. The engine error kind (for example `instance-not-found`), or one of `usage`, `auth-missing`, `permission-denied`, `resource-not-found`, `request-failed`, `config-invalid`, `definition-file-invalid`, and `other`. Never the error's message, name, or stack. |
714
+
715
+ A config-supplied logger has no trace, so it receives the four context fields,
716
+ `success`, and on failure `failureKind`, together as one log payload.
717
+
718
+ #### `Workflows CLI Definition Shared` (version 1)
719
+
720
+ One content-free marker per newly created definition version that actually
721
+ reached Sanity's definition-feedback endpoint. Unchanged redeploys, dry runs,
722
+ and `--check` never emit it. The document itself is not in this event.
723
+
724
+ | Field | Type | What is collected |
725
+ | ------------------ | ---------- | ---------------------------------------------------------------------------------------------------- |
726
+ | `contentHash` | `string` | Content fingerprint of the donated definition. |
727
+ | `deployId` | `string` | Random run id shared with that invocation's `Workflows Engine Definition Deployed` events. |
728
+ | `stageCount` | `number` | Declared stages. |
729
+ | `activityCount` | `number` | Activities across those stages. |
730
+ | `actionCount` | `number` | Actions across those activities. |
731
+ | `transitionCount` | `number` | Declared transitions. |
732
+ | `fieldCount` | `number` | Declared field entries at workflow, stage, and activity scope. |
733
+ | `activityKinds` | `string[]` | Distinct effective activity kinds, sorted: `user`, `service`, `script`, `manual`, `receive`. |
734
+ | `fieldKinds` | `string[]` | Distinct declared field kinds, sorted (engine field kinds such as `string`, `subject`, `assignees`). |
735
+ | `guardCount` | `number` | Guards declared on stages. |
736
+ | `effectCount` | `number` | Effects declared on actions. |
737
+ | `subworkflowCount` | `number` | Actions that carry a `spawn` block. |
738
+ | `lifecycle` | `string` | `'standalone'` or `'child'`. |
739
+
740
+ #### `Workflows CLI Definition Sharing Decided` (version 2)
741
+
742
+ One event per `deploy` that created at least one new definition version,
743
+ whether or not anything was donated. Measures opt-out rate without carrying
744
+ the document.
745
+
746
+ | Field | Type | What is collected |
747
+ | ----------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------- |
748
+ | `decision` | `string` | `'opt-in'` (`--share-defs`), `'opt-out'` (`--no-share-defs`), or `'default'` (neither flag). |
749
+ | `shared` | `boolean` | Whether a donation POST reached the endpoint. `false` for any non-sharing decision, and for a chosen share whose POST failed. |
750
+ | `definitionCount` | `number` | Newly created definition versions this invocation could have donated. |
751
+
752
+ ### Engine events the CLI records
753
+
754
+ Write commands pass the CLI logger into the engine, so a successful operation
755
+ that writes directly also records the engine's adoption events on the same
756
+ session. A `start`, `fire-action`, or `abort` sent to the project's Workflows
757
+ service records none here, and `createWorkflowService` records no product
758
+ telemetry for it either. Read commands
759
+ (`list`, `show`, `diagnose`, `tail`, `definitions list` / `show` / `diff`) do
760
+ not emit engine events. `nuke` deletes engine-owned documents outside those
761
+ verbs and does not emit them either.
762
+
763
+ Every engine event includes:
764
+
765
+ | Field | Type | What is collected |
766
+ | ------------------ | -------- | --------------------------------------------------------------------------------------- |
767
+ | `executionRuntime` | `string` | The JavaScript runtime the engine detected around itself. Always `'node'` for this CLI. |
768
+ | `executionKind` | `string` | The host the engine was told it is running in. Always `'cli'` for this CLI. |
769
+
770
+ Every instance-scoped engine event additionally includes:
771
+
772
+ | Field | Type | What is collected |
773
+ | ----------------------- | -------- | -------------------------------------------------------------------------------------------------- |
774
+ | `definitionContentHash` | `string` | Content fingerprint of the pinned definition. Omitted when the definition predates fingerprinting. |
775
+ | `instanceId` | `string` | Instance document `_id`. |
776
+
777
+ | Event | Version | When the CLI emits it | Additional payload |
778
+ | -------------------------------------- | ------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
779
+ | `Workflows Engine Definition Deployed` | 2 | `deploy` for each definition (created or unchanged) | Same structural counts as `Workflows CLI Definition Shared`, plus `status`: `'created'` or `'unchanged'`. |
780
+ | `Workflows Engine Instance Started` | 2 | `start`, and a `fire-action` that spawns a child | `initialFieldCount` (number of caller-supplied initial fields), `viaSpawn` (`true` only for a spawned child), `lifecycle`. |
781
+ | `Workflows Engine Stage Transitioned` | 2 | A committed hop from `fire-action`, `start`, or `reset-activity` | `fromStageIndex`, `toStageIndex` (indexes into `stages[]`, never names), `toIsTerminal`, `isRevisit`, `dwellMs` (milliseconds in the exited stage, omitted if that entry is missing), `via`: `'transition'`. Unsampled. |
782
+ | `Workflows Engine Action Fired` | 2 | `fire-action` | `activityKind` (optional; derived kind of the fired activity), `hasParams` (whether params were supplied — not the params), `cascaded` (auto-transitions in the post-action cascade). |
783
+ | `Workflows Engine Instance Aborted` | 2 | `abort` | `changed`: `false` if the instance was already terminal. |
784
+ | `Workflows Engine Activity Reset` | 2 | `reset-activity` | `changed`: `false` if already at the target status, or the instance was terminal. |
785
+ | `Workflows Engine Definition Deleted` | 2 | `definitions delete` | `deletedVersionCount`, `cascadeAbortedCount`, `deletedGuardCount` (guards only when the last version goes). |
786
+ | `Workflows Engine Effect Completed` | 2 | `abort` cancelling a pending effect | `effect` (author-chosen name), `status` (`'done'`, `'failed'`, or `'cancelled'`), `origin` (`'action'`), `cascaded`. |
787
+
788
+ The engine also defines `Workflows Engine Field Edited`,
789
+ `Workflows Engine Instance Ticked`, `Workflows Engine Effects Drained`, and
790
+ `Workflows Engine Effect State Reported`. This CLI does not call those verbs,
791
+ so it does not record those events. Field-edit and tick events are sampled at
792
+ most once per 60 seconds when some other shell does emit them.
793
+
794
+ ## Definition sharing
795
+
796
+ Separate from telemetry, a `deploy` that creates new definition versions
797
+ donates those documents to Sanity — verbatim (structure, names, titles, GROQ
798
+ filters, effect configuration, seeded values), plus their deployment
799
+ coordinates (project and dataset, or resource id) — never content documents,
800
+ instances, or your auth token. The documents go to Sanity's first-party
801
+ definition-feedback endpoint, not the telemetry pipeline; telemetry carries
802
+ only a content-free marker (content hash plus structural counts) per shared
803
+ definition and a per-invocation decision event.
804
+
805
+ Sharing is **opt-out in every environment**. Pass `--no-share-defs` to decline
806
+ for one invocation. With neither flag, the first interactive deploy prints a
807
+ full notice before sending and remembers that the notice was shown; every later
808
+ flagless deploy prints a status block showing that sharing is on by default and
809
+ showing runnable shell examples for the default, explicit opt-in, and opt-out
810
+ forms; the explicit flags suppress the status block. Unattended runs (CI,
811
+ `DO_NOT_TRACK`, or a non-TTY pipe) also share by default and print that status
812
+ block in their logs.
813
+ A flagless deploy or explicit `--share-defs` forces that deploy's telemetry
814
+ through the environment gate so donated definitions retain their content-free
815
+ markers; account-level `sanity telemetry disable` still applies. A failed share
816
+ only warns, never failing a completed deploy.
817
+
818
+ ## Known gaps
819
+
820
+ - **Not listed in `sanity --help` yet.** Every command runs as
821
+ `sanity workflows <command>`, but the Sanity CLI's help output does not list
822
+ the `workflows` topic. Run `npx @sanity/workflows-cli --help` to see the
823
+ commands.
824
+
825
+ ## Identity
826
+
827
+ Identity is the token behind the configured client: the engine resolves the
828
+ acting user (and their roles) from `/users/me`, so every write is attributed
829
+ to whoever the token authenticates — there is no identity injection and no
830
+ `--as` impersonation. Run `whoami` to see that user: its Sanity user ID is the
831
+ value user assignee fields take. `whoami` asks about one resource; when the
832
+ config names several, pass `--deployment` or `--workflow-resource <type>:<id>`.
833
+ Alongside that "who", the CLI declares an advisory "via what": every verb carries
834
+ `executionContext: { kind: "cli", id: "workflow-cli" }`, stamped on the history
835
+ entries of the writes it commits directly. A write it sends to the project's
836
+ Workflows service is stamped `{ kind: "server", id: "workflows-service" }`.
837
+
838
+ ## Tech stack
839
+
840
+ Mirrors the Sanity CLI's stack so the eventual plugin port is small:
841
+
842
+ - [`@oclif/core`](https://oclif.io) for command definitions, flags,
843
+ help.
844
+ - `@oclif/plugin-help` for help output.
845
+ - `ora`, `boxen`, `log-symbols`, `console-table-printer` for terminal UX;
846
+ color comes from `node:util`'s `styleText` (no separate color dep).
847
+ - `@sanity/cli-core` for timestamp formatting (absolute for detail views, relative
848
+ "… ago" for list tables).
849
+ - `diff` for the colored JSON unified diff in `deploy --dry-run`.