diff --git a/.claude/rules/sim-workflow-code.md b/.claude/rules/sim-workflow-code.md index e93c164628a..7a170078358 100644 --- a/.claude/rules/sim-workflow-code.md +++ b/.claude/rules/sim-workflow-code.md @@ -55,6 +55,9 @@ and per-kind layout tables of `exit-codes.mdx`, `diagnostics.mdx`, `limits.mdx` `bun run generate:workflow-code-docs` (`check:workflow-code-docs` fails on drift, a diagnostic code a page names that no engine emits, a limit or diagnostic code with no docs entry, and a `typescript@x.y.z` pin other than the CLI's). A limit also needs a label in the generator's `WORKFLOW_LIMIT_LABELS` or `WORKSPACE_LIMIT_LABELS`. +A new exit code also needs a `[#exit-]` section in `troubleshooting.mdx`, which the same check requires +for every non-zero code `sourceExitCodeRows` lists. Behaviour a user relies on (identity, stale, the three-way rule, +promotion) is explained once, in `how-it-works.mdx`; change it there when an engine changes it. Dependencies point one way: `packages/workflow-types` → `packages/workflow-code` → `packages/workspace-code` and `packages/workflow-sdk` → the CLI and `apps/sim`. `check:boundaries` keeps both engines and `packages/table-cells` pure (no diff --git a/.cursor/rules/sim-workflow-code.mdc b/.cursor/rules/sim-workflow-code.mdc index 9ea97adf333..b55a0e7ed5e 100644 --- a/.cursor/rules/sim-workflow-code.mdc +++ b/.cursor/rules/sim-workflow-code.mdc @@ -35,6 +35,9 @@ and per-kind layout tables of `exit-codes.mdx`, `diagnostics.mdx`, `limits.mdx` `bun run generate:workflow-code-docs` (`check:workflow-code-docs` fails on drift, a diagnostic code a page names that no engine emits, a limit or diagnostic code with no docs entry, and a `typescript@x.y.z` pin other than the CLI's). A limit also needs a label in the generator's `WORKFLOW_LIMIT_LABELS` or `WORKSPACE_LIMIT_LABELS`. +A new exit code also needs a `[#exit-]` section in `troubleshooting.mdx`, which the same check requires +for every non-zero code `sourceExitCodeRows` lists. Behaviour a user relies on (identity, stale, the three-way rule, +promotion) is explained once, in `how-it-works.mdx`; change it there when an engine changes it. Dependencies point one way: `packages/workflow-types` → `packages/workflow-code` → `packages/workspace-code` and `packages/workflow-sdk` → the CLI and `apps/sim`. `check:boundaries` keeps both engines and `packages/table-cells` pure (no diff --git a/apps/docs/content/docs/cli/troubleshooting.mdx b/apps/docs/content/docs/cli/troubleshooting.mdx index 1b27eed3a54..5b7fb7591c4 100644 --- a/apps/docs/content/docs/cli/troubleshooting.mdx +++ b/apps/docs/content/docs/cli/troubleshooting.mdx @@ -148,6 +148,10 @@ Retain the original request/operation IDs and exact input. An operation may have A workflow wait timeout also leaves its run active. Inspect that run ID; do not assume another execution is a retry of the same work. +## A `sim workflows source` or `sim workspaces source` command failed + +These commands exit with codes of their own, such as `5` when the workflow changed since it was read and `10` when another apply is running, and print each problem with its file, line and code. [Workflows as code troubleshooting](/workflows/code/troubleshooting) covers each exit code and the common diagnostic codes. + ## Anything else For an unexpected stack trace, [open an issue](https://github.com/simstudioai/sim/issues) with the CLI version, command, sanitized trace, and relevant resolved settings. Remove credentials, sensitive inputs, and private file contents before posting. Debug output can contain request selectors. @@ -158,3 +162,4 @@ For an unexpected stack trace, [open an issue](https://github.com/simstudioai/si - [Configuration](/cli/configuration) - [Output formats](/cli/output) - [Scripting](/cli/scripting) +- [Workflows as code troubleshooting](/workflows/code/troubleshooting) diff --git a/apps/docs/content/docs/cli/workflow-sync.mdx b/apps/docs/content/docs/cli/workflow-sync.mdx index 7431f696b9b..7ce8308fe62 100644 --- a/apps/docs/content/docs/cli/workflow-sync.mdx +++ b/apps/docs/content/docs/cli/workflow-sync.mdx @@ -239,6 +239,7 @@ Validate provider connections in the destination environment as well as the plat - [Workspace forking](/platform/enterprise/forks) - [Workflow commands](/cli/workflows) - [Workspace commands](/cli/workspaces) +- [Promote to another workspace](/workflows/code/promote): copy a workspace directory kept in git to another workspace, without linking the two - [Selectors](/cli/selectors) - [Exit codes](/cli/scripting#exit-codes) - [Workflow-sync contributor harness](/api-reference/workflow-sync#related-docs) diff --git a/apps/docs/content/docs/workflows/code/adopt.mdx b/apps/docs/content/docs/workflows/code/adopt.mdx new file mode 100644 index 00000000000..1ac43570882 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/adopt.mdx @@ -0,0 +1,84 @@ +--- +title: Bring existing workflows into code +description: Put workflows built in the workflow builder into git, keep editing them in the builder, and decide who owns each change. +--- + +Result: workflows you built in the workflow builder kept in a git repository, with edits from the builder and from the files brought together instead of overwritten. + +Nothing has to be converted. Every workflow already has a source form: `get` prints it, and the workflow keeps its ID, block IDs, webhook URLs, schedules and run history. + +## Choose what to put in git + +- **One workflow**: `sim workflows source get --dir ` writes one workflow directory. Use it when a few workflows change through code and the rest stay in the builder. +- **A whole workspace**: `sim workspaces source get --dir ` writes the workflows together with the tables, knowledge bases, files, custom tools, skills, MCP servers, secret names and credential keys they use. Use it when the repository should describe the workspace, so one apply can create what a workflow needs before the workflow. + +A workspace directory manages only the kinds whose folder or file it holds: to leave one kind in the builder only, read the rest with `--only`, such as `--only tables,workflows`. + +## 1. Read the workflows + +```bash +sim workspaces source get --dir ./workspace +``` + +`get` names everything it could not write, such as a resource over a [limit](/workflows/code/limits), and lists it in `.sim/skipped.json`. Each workflow lands in `workflows//workflow.ts`, keyed by its name. + +## 2. Confirm the files match Sim + +```bash +sim workspaces source check --dir ./workspace +sim workspaces source status --dir ./workspace +``` + +A fresh `get` applies back unchanged, so `check` reports no errors and `status` exits `0` until someone edits either side. A warning on a block you have not changed does not fail the check: it describes a value the workflow already stores, such as a required field left empty in the builder. Fix it in the file when you next change that block. + +## 3. Commit the directory + +Commit everything `get` wrote, `.sim/` included. The `.sim/` files are how a later apply recognizes each block and resource and knows which version you read. [Directory layout](/workflows/code/directory) lists what to commit for each kind of directory. + +## 4. Change it from the files + +Make the first change through the loop in [Edit a workflow](/workflows/code/edit) or [Manage a workspace as code](/workflows/code/workspace), then commit the files the apply rewrote. To review changes on pull requests and apply them on merge, see [Run in CI](/workflows/code/ci). + +## Keep editing in the workflow builder + +The builder stays fully editable. Its **Code** tab shows the same workflow as read-only source. The files and the builder never overwrite each other silently: + +- A builder edit since the `get` is **drift**: `status` exits `12`. When the directory holds no unapplied edits, its `Next:` line is a `get` into the same directory, which brings the files up to date. Commit them. +- When the files and the builder changed the same workflow, it is a **conflict**: an apply is refused with exit `5` and writes nothing; see [Exit 5](/workflows/code/troubleshooting#exit-5). There is no automatic merge. +- In a workspace directory, drift on a resource you did not edit is kept: the apply writes your changes and leaves the other resource as Sim holds it (`W_SERVER_CHANGED`). + +To find drift before an apply does, run `status` on a schedule; see [Detect drift on a schedule](/workflows/code/ci#detect-drift-on-a-schedule). + +## What stays in the builder + +Block positions, values in fields the current settings hide, and your comments stay in the stored workflow, and an apply keeps them; [How it works](/workflows/code/how-it-works#the-canonical-form) has the rules. An apply saves the draft only: deploy with `apply --deploy` or `sim workflows deploy`, or, in a workspace directory, with a file in `deployments/`. + +## Agree on who changes what + +Decide per workflow where its changes are made, and write it down for the team: + +- **Files first**: changes go through pull requests, and the builder is for viewing and quick fixes that someone brings back with a `get`. Run the scheduled drift check. +- **Builder first**: the repository is a record. Refresh it with a `get` on a schedule or after a change, and open a pull request with what changed. + +Locked blocks cannot be changed from the files, by anyone. Lock a block in the builder to keep it out of reach of an apply. + +## Roll back + +- **The deployed version**: `sim workflows rollback ` (workspace Admin) makes the previous deployment live again and leaves the draft and the directory as they are. +- **The draft, from a deployment**: `sim workflows revert create --yes` replaces the draft with that deployed version. The directory then has drift (`status` exits `12`); `get` brings it up to date. +- **The draft, from git**: restore the source files of an earlier commit but keep the current `.sim/`, then apply: + + ```bash + git restore --source= -- ./support-triage ':(exclude,glob)support-triage/**/.sim/**' + sim workflows source apply --dir ./support-triage --dry-run + ``` + + Applying an earlier commit as a whole, `.sim/` included, is refused as stale (exit `5`), because its `.sim/base.json` records an older version than Sim holds. A block or resource deleted since that commit comes back as a new one, without its run history, webhook URLs or schedules, and blocks added since are deletes the apply refuses without `--allow-delete`. + +## Related docs + +- [Edit a workflow](/workflows/code/edit) +- [Manage a workspace as code](/workflows/code/workspace) +- [Run in CI](/workflows/code/ci) +- [How it works](/workflows/code/how-it-works) +- [Troubleshooting](/workflows/code/troubleshooting) diff --git a/apps/docs/content/docs/workflows/code/exit-codes.mdx b/apps/docs/content/docs/workflows/code/exit-codes.mdx index fb20995b618..5fde9f37d5b 100644 --- a/apps/docs/content/docs/workflows/code/exit-codes.mdx +++ b/apps/docs/content/docs/workflows/code/exit-codes.mdx @@ -70,12 +70,11 @@ The table for the kind of directory you work in. Both are built from the table ` {/* workflow-code-docs:exit-codes:end */} -Earlier CLI releases exited `1` when an apply held changes back, whether or not it wrote the rest, and its dry run exited `1` in either case. A script that reads `1` as "held back" should test for `15` too. - Exit `9` follows the CLI's retries: it resends a request the API answered `429` only when sending it twice is safe, which includes every `GET`, a source `apply` and a `create`. See [Scripting](/cli/scripting#exit-codes) for the retry schedule and the codes every command shares (`13` and `9`). ## Related docs +- [Troubleshooting](/workflows/code/troubleshooting): the causes behind each code - [Run in CI](/workflows/code/ci) - [Diagnostic codes](/workflows/code/diagnostics) - [Limits](/workflows/code/limits) diff --git a/apps/docs/content/docs/workflows/code/how-it-works.mdx b/apps/docs/content/docs/workflows/code/how-it-works.mdx new file mode 100644 index 00000000000..e3144b2c3d3 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/how-it-works.mdx @@ -0,0 +1,102 @@ +--- +title: How it works +description: How Sim turns a file into a saved workflow, keeps each block's identity, and refuses an apply that would overwrite someone else's change. +--- + +A source file is a declaration, not a program. Sim reads it, compares it with the stored workflow, and saves the difference. This page explains the rules behind `get`, `check` and `apply`, so their results and refusals are predictable. + +## Nothing in the file runs + +`workflow.ts` is TypeScript so that your editor can complete and type-check it, but no command executes it. Sim parses the file and reads each `const x = builder('Name', {…})` as one block, each `.to()` as one connection, and each param as one setting. That is why the file holds declarations only: a helper function, a loop that creates blocks, or an import from anything but `@sim/workflow-sdk` has no value Sim could read without running it, so it is refused with `E_UNSUPPORTED_SYNTAX` and a hint. + +`check` runs this compiler on your machine, the same one the server runs, against the block catalog the last `get` cached. Function code under `functions/` is not run either: it is stored as the Function block's code and runs in Sim, like code typed into the workflow builder. + +## From a file to a saved draft + +An apply goes through three steps, and a dry run stops after the second: + +1. **Compile.** The file becomes the workflow's canonical form: its blocks keyed by name, their settings, connections, branches, loops and variables, with no IDs and no layout. +2. **Evaluate.** Sim reads the stored draft into the same form, matches each compiled block to a stored one, and checks what a save would change: unknown settings, missing required fields, references, permissions, locked blocks, deletes and the workflow's lint. Every finding maps back to a line in your files. +3. **Commit.** Sim writes the new draft in one transaction, after checking again that nobody saved the workflow meanwhile. + +Deploying is never part of an apply unless you pass `--deploy` (or, for a workspace directory, add a file under `deployments/`). + +## The canonical form + +The stored workflow and the file are two views of one canonical form, so a round trip changes nothing: + +- `get` prints the canonical form. An `apply` of an unchanged directory is a no-op, and the stored workflow stays byte for byte the same. +- A setting equal to the value a block gets when you add it in the workflow builder is left out of the file. Writing it out has the same effect as leaving it out. +- After a save, Sim prints the files again from what it stored. A value the server normalized, a resource key it allocated, or a reference it rewrote for a rename shows up in your files, so read them again before the next edit and commit what changed. + +Some state has no syntax in the file. Sim keeps it from the stored workflow on every apply: + +- **Layout.** Block positions stay in Sim. A new block is placed automatically. Moving blocks never makes a directory stale. +- **Settings that do not run.** A value in a field that the block's current choices hide stays stored, so switching back in the workflow builder brings it back. +- **Comments.** Comments in `workflow.ts` are stored with the workflow, by block, so a builder edit or a rename keeps them. + +## Block identity + +Each stored block has an ID that its webhook URL, schedules and run history hang on. The file names blocks by `const` name and display name instead, so Sim needs a way to tell an edited block from a new one. + +`.sim/lock.json` records, for each block in the file, the ID of the stored block it is. An apply matches each block in the file, in this order: + +1. by its block key in the lock, the display name lowercased with whitespace and dots removed; +2. by its `const` name in the lock, so changing only the display name keeps the block; +3. by its block key in the stored workflow, when the lock does not have it; +4. by inference: when a block left and one of the same type appeared in the same place with the same connections or settings, it is a rename (`W_MAT_INFERRED_RENAME`). + +A block that matches nothing is new, and a stored block nothing matched is a delete, which an apply refuses without `--allow-delete` (`E_APPLY_BLOCK_DELETE`). Renaming two blocks of the same type in the same place in one save leaves the inference nothing to tell apart, so rename them one save at a time. + +Sim also stores each block's `const` name, its order in the file and its comments, by block ID. A `get` into a new directory, or after a builder edit, prints the same names in the same order, so a one-setting change stays a one-line diff. + +## Stale: what you read is not what Sim holds + +`.sim/base.json` records a fingerprint of the draft you read: a hash of its canonical form, its variables and its block IDs, without layout. An apply sends it, and Sim computes the fingerprint of the draft it holds now: + +- the same: the apply goes ahead; +- different: someone saved the workflow since you read it. The apply is refused as stale with exit `5`, on a dry run too, and nothing is written; [Troubleshooting](/workflows/code/troubleshooting#exit-5) has the steps. + +The check is made again inside the write's transaction, so two applies that race cannot both win. `status` asks the same question with a dry run and reports it as drift (exit `12`) before you apply. + +The base also records the block catalog you read against. When a compile fails and the catalog changed since, for example after a block gained a setting, the apply adds `W_APPLY_CATALOG_MOVED`: run `get` again to pick up the new types. + +## Workspaces: one rule per resource + +A workspace directory adds tables, knowledge bases, files, custom tools, skills, MCP servers, secret names, credential keys and deployments. Each resource has a key, its file or folder name, which Sim stores and never changes: a rename in Sim keeps the key, and a workflow names the resource by it, as in `table('orders')`. + +`.sim/base.json` at the root records each resource's ID and fingerprint as the last `get` or apply saw it. An apply decides each declared resource by comparing three fingerprints: your file (local), the base, and what Sim holds now (server): + +| Your file vs the base | Sim vs the base | Outcome | +| --- | --- | --- | +| Same | Any | Nothing to do. When Sim changed it, the apply keeps Sim's version (`W_SERVER_CHANGED`) | +| Changed | Same | Written | +| Changed | Changed | Nothing to do when both made the same change; otherwise stale, exit `5` | + +A resource with no base entry is created, or **adopted** when Sim already holds one under the same name. An adopt only adds to what is there, such as a column or a document; one that would change or remove anything is refused with `E_APPLY_NO_BASE`. A resource the directory stops declaring is deleted only when the base recorded it and you pass `--allow-delete`; anything else Sim holds is kept and named in a `W_UNDECLARED` warning. + +Workflows are the exception to this table. Each workflow folder is applied exactly as a single workflow, with its own `.sim/lock.json` and `.sim/base.json`: a folder you did not edit is skipped without asking whether Sim changed it, so it gets no `W_SERVER_CHANGED`, and an edited folder is refused as stale whenever Sim changed the workflow since its base, even when both made the same change. + +An apply writes resources in dependency order, so a table exists before the workflow that writes to it, and deletes run in reverse. + +### Applying a workspace + +- **Whole or nothing at planning.** Every check runs before the first write. One error refuses the whole apply. +- **One apply at a time.** An apply holds the workspace from planning to its last write. A second apply meanwhile exits `10` with nothing written. A dry run does not take part, so it never waits. +- **Writes commit one by one.** If a write fails part-way, the apply stops, saves what it wrote into the directory and exits `8`. Applying the same directory again finishes the rest. +- **Held back.** A change that uses a secret with no value in the workspace, or a credential key nothing binds to, is held back while the rest is written, and the apply exits `15`. +- **Files travel separately.** Workspace files and knowledge base documents are uploaded before the apply, and only the ones Sim does not have yet, so a retry uploads nothing again. + +## Promotion + +`apply --to ` sends a directory read from one workspace to another. Sim sees an ordinary apply against the target's own IDs: each resource binds by key, so a workflow keeps its ID and webhook URLs in the target, and secrets and credentials bind by name to the target's own. + +The directory stays bound to the workspace it was read from. The only file a promotion writes is `.sim/targets/.json`, a record of what it left in the target. The next promotion uses that record as the base for the three-way rule above, so a hotfix made in the target is kept when the directory left that resource alone, and refused as stale when the directory changed it too. See [Promote to another workspace](/workflows/code/promote). + +## Related docs + +- [Edit a workflow](/workflows/code/edit) +- [Manage a workspace as code](/workflows/code/workspace) +- [Directory layout](/workflows/code/directory) +- [Troubleshooting](/workflows/code/troubleshooting) +- [Diagnostic codes](/workflows/code/diagnostics) diff --git a/apps/docs/content/docs/workflows/code/index.mdx b/apps/docs/content/docs/workflows/code/index.mdx index e9012034dc0..b7891446174 100644 --- a/apps/docs/content/docs/workflows/code/index.mdx +++ b/apps/docs/content/docs/workflows/code/index.mdx @@ -52,6 +52,9 @@ Claude Code, Cursor, Codex and other coding agents work from a directory that `g - [Edit a workflow](/workflows/code/edit) - [Manage a workspace as code](/workflows/code/workspace) - [Run in CI](/workflows/code/ci) +- [Bring existing workflows into code](/workflows/code/adopt) +- [Troubleshooting](/workflows/code/troubleshooting) +- [How it works](/workflows/code/how-it-works) - [File syntax](/workflows/code/syntax) - [Exit codes](/workflows/code/exit-codes), [diagnostic codes](/workflows/code/diagnostics) and [limits](/workflows/code/limits) - [CLI workflow commands](/cli/workflows#workflows-as-code) and [workspace commands](/cli/workspaces#workspace-as-code) diff --git a/apps/docs/content/docs/workflows/code/meta.json b/apps/docs/content/docs/workflows/code/meta.json index bca32e90566..42ecb64f9ae 100644 --- a/apps/docs/content/docs/workflows/code/meta.json +++ b/apps/docs/content/docs/workflows/code/meta.json @@ -10,11 +10,15 @@ "promote", "ci", "coding-agents", + "adopt", + "troubleshooting", "---Reference---", "syntax", "directory", "exit-codes", "diagnostics", - "limits" + "limits", + "---Explanation---", + "how-it-works" ] } diff --git a/apps/docs/content/docs/workflows/code/troubleshooting.mdx b/apps/docs/content/docs/workflows/code/troubleshooting.mdx new file mode 100644 index 00000000000..b93ba36e084 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/troubleshooting.mdx @@ -0,0 +1,160 @@ +--- +title: Troubleshooting +description: Fix a failed sim workflows source or sim workspaces source command, by exit code and by diagnostic code. +--- + +Every `sim workflows source` and `sim workspaces source` command reports a failure in two ways: an exit code for the kind of failure, and findings that each name a code, a file, a line and a hint. Find the exit code below first, then the code of the first error it printed. + +Each finding prints as `file:line:column`, with the code around it and a hint. `--output json` puts the same findings in a `diagnostics` array, and a refused write prints an `{error:…}` document on stderr whose `details.code` names the refusal, such as `SOURCE_STALE`. Fix the first error first: later ones often follow from it. + +## By exit code + +[Exit codes](/workflows/code/exit-codes) has the full table. These are the causes behind each code and how to get past them. + +### Exit `1`: errors, or the command failed [#exit-1] + +- **The source has errors.** Fix each one at the line it names. The [diagnostic codes](#by-diagnostic-code) below cover the common ones, and [Diagnostic codes](/workflows/code/diagnostics) lists every code. +- **`check` failed on a warning.** An apply saves some warnings as written, such as a required field left empty, so `check` fails on them in a block you added since the `get`. `sim workflows source check --help` lists them. +- **"No block catalog is cached".** `sim workflows source check` and `params` work from the catalog the last `get` or `create` cached on this machine. Run `get` once, for example on a fresh CI runner. `sim workspaces source check` downloads the catalog itself. +- **A name is taken.** `SOURCE_NAME_TAKEN` on `create`: pass `--name`. `E_NAME_TAKEN` on an apply: another resource of the same kind already has that name, such as another workflow in the folder for the name `workflow('…')` gives, or another skill or custom tool in a workspace directory. +- **`get` refused the directory.** `SOURCE_LOCAL_EDITS` means the directory holds edits no apply has saved: apply them, get into another directory, or pass `--force` to discard them. `SOURCE_WORKFLOW_MISMATCH` means it holds another workflow, and `SOURCE_DIR_KIND_MISMATCH` that it is the other kind of directory, which `--force` never overrides. +- **The directory belongs to another workspace.** `SOURCE_OTHER_WORKSPACE`: a directory acts on the workspace it was read from. Drop `--workspace`, or promote it with `--to`. +- **Binary files were never downloaded.** `SOURCE_BLOBS_NOT_FETCHED`: run `get` again before applying. + +### Exit `5`: stale [#exit-5] + +Someone saved what this directory was read from after you read it, in the workflow builder, through the API, or with another apply. A workflow apply, and a workspace apply refused while planning, writes nothing; a dry run exits `5` the same way. A workspace apply that found a resource changed part-way through its writes has saved the changes before it into the directory, so carry over only the rest. + +1. See what changed in Sim: `sim workflows source diff --dir --server`. +2. Get the current version into a fresh directory: `sim workflows source get --dir `. +3. Carry your edit over, then dry-run and apply from the fresh directory. + +In CI, this happens when an apply rewrote files that were not committed back, or when two branches each applied: commit the files an apply rewrites, as [Run in CI](/workflows/code/ci) does. In a promotion, it means the target changed a resource the directory changed too; carry the target's change into the source workspace, or undo it in the target. + +### Exit `6`: locked [#exit-6] + +The workflow, its folder or a table is locked against changes (`E_APPLY_LOCKED`). Ask someone who can to unlock it in Sim. A locked block inside an unlocked workflow exits `1` instead, with `E_APPLY_LOCKED_BLOCK`. + +### Exit `7`: over a limit [#exit-7] + +The workflow or directory is larger than one get or apply may handle, and the finding names each measured size. Split a large workflow into a parent and a child workflow, or apply a workspace in parts with `--only`. The numbers are in [Limits](/workflows/code/limits). + +### Exit `8`: a workspace apply stopped part-way [#exit-8] + +A write failed on the server after earlier writes were saved. The CLI saved what was written into the directory and printed the plan with each change marked written or not written. Run the same apply again until it exits `0`; it continues where it stopped. + +### Exit `9`: rate limited [#exit-9] + +The API still answered `429` after the CLI's retries, and nothing more was written. Wait a minute and run the same command again. In CI, avoid several jobs applying at once with a `concurrency` key. + +### Exit `10`: busy [#exit-10] + +- `SOURCE_BUSY`: another apply is writing the same workspace. Run yours again once it finished. +- `SOURCE_DIR_BUSY`: another `sim` command is using this directory, or the workspace directory it is a folder of. The CLI holds `.sim/command.lock/` while a command runs, and takes it over once the process holding it has gone, so run the command again. + +Nothing was read or written either way. + +### Exit `11`: your edits are not applied [#exit-11] + +Only `status` exits `11`, and it is not a failure: the directory holds edits that applying would write. Dry-run, then apply. In a scheduled CI check, `11` usually means a merge whose apply failed. + +### Exit `12`: Sim changed since the get [#exit-12] + +Only `status` exits `12`. Follow its `Next:` line: + +- **Drift**, Sim changed and the directory did not: `get` into the same directory brings it up to date. Commit the result. +- **A conflict**, both changed the same workflow or resource: an apply would be refused as stale. Get into a fresh directory and carry your edit over, as for [exit `5`](#exit-5). + +### Exit `13`: not signed in [#exit-13] + +No login, an expired login, or a credential the server refused (`AUTH_REQUIRED`). Run `sim login`, or fix or unset `SIM_API_KEY` when the key comes from it, then run the same command again. See [Authentication](/cli/authentication). + +### Exit `14`: apply without `--yes` [#exit-14] + +`apply` or `create` found no errors, printed the plan, and wrote nothing, because there was no terminal to confirm in. Run the same command with `--yes`. + +### Exit `15`: changes held back [#exit-15] + +A workspace apply wrote what it could and held back each change that uses a secret the workspace has no value for (`E_SECRET_MISSING`) or a credential key no credential binds to (`E_CREDENTIAL_MISSING`, `E_CREDENTIAL_AMBIGUOUS`). Set the secret with `sim secrets set NAME --scope workspace`, or connect the credential, then apply again. A dry run exits `15` too, so a script can find out first. + +### Exit `130`: interrupted [#exit-130] + +Ctrl-C. If the CLI says a write may have happened, `status` shows whether it did. + +## A command answers `403` [#forbidden] + +- **"Workflows as code is in preview and not enabled for this workspace".** The feature is off for this workspace; see [Workflows as code](/workflows/code) for how it is enabled. +- **A workspace API key.** Saving a workflow acts as a person, so it needs a personal API key or an OAuth login. In a workspace directory, a workspace key can apply only some kinds and the rest are refused with `E_APPLY_FORBIDDEN`; see [Workspace API keys](/workflows/code/workspace#workspace-api-keys). + +## By diagnostic code + +### `E_UNSUPPORTED_SYNTAX` [#e-unsupported-syntax] + +The file holds a form Sim cannot read without running it, such as a helper function, an `if`, a loop that creates blocks, or an import from anything but `@sim/workflow-sdk`. Write each block as its own `const`, use `loop()`, `parallel()`, `condition` or `router` blocks for control flow, and put logic inside function code. The hint names the supported form; [File syntax](/workflows/code/syntax) lists them all. + +### `E_UNKNOWN_BUILDER` and `E_UNKNOWN_PARAM` [#e-unknown-param] + +A builder or param name the block catalog does not have. The hint suggests the closest name. `sim workflows source params ` prints a builder's params and outputs, and a namespace such as `gmail` lists its builders. + +### `W_REQUIRED_MISSING` [#w-required-missing] + +A required field is empty, or holds `todo()`. Fill it in, or use `env.NAME` for a value you keep in an environment variable. + +### `E_APPLY_UNRESOLVED_REF` [#e-apply-unresolved-ref] + +A reference names a block that does not exist, or an output path the block does not have. In `workflow.ts`, read an output through the block's `const`, as in `triage.content`. In function code, `$ref.` uses the block key: the display name lowercased with whitespace and dots removed. The hint lists the outputs the block has. + +### `E_MAT_UNKNOWN_RESOURCE` [#e-mat-unknown-resource] + +A resource helper, such as `table('orders')` or `credential('support-slack')`, names a key no live resource has. Keys are exact. `sim workflows source resources` lists the keys of your workspace; in a workspace directory, a key is the resource's file or folder name, and `check` lists the declared ones. + +### `E_APPLY_BLOCK_DELETE` and `W_MAT_INFERRED_RENAME` [#e-apply-block-delete] + +The save would delete blocks: a stored block no longer matches any block in the file. If you meant to delete them, apply again with `--allow-delete`; a deleted block's webhook URL, schedules and run history go with it. + +If you meant a rename, keep the `.sim/` folder, change the display name and keep the `const` name, or the other way round, and apply that before the next rename. When the file adds a block of the deleted one's type, the finding names it as a possible rename and says how to keep the ID. A rename Sim inferred from type, position and connections is reported as `W_MAT_INFERRED_RENAME`: check the plan names the block you meant. `E_APPLY_VARIABLE_DELETE` is the same for workflow variables. + +### `E_APPLY_LOCKED_BLOCK` [#e-apply-locked-block] + +The change touches a locked block, or a block inside a locked loop or parallel. Nobody can change it from the file. Unlock it in the workflow builder, or leave it as it is. + +### `E_APPLY_NO_BASE` [#e-apply-no-base] + +A declaration in a workspace directory matches a resource Sim holds that the directory never read, such as a table someone made in Sim under the same name. The apply may only add to such a resource. Run `get` into a new directory to read it, then make your edit there, or give the declaration another name. + +### `E_KEY_RENAMED` [#e-key-renamed] + +A resource file or folder in a workspace directory was renamed. Keys never change: move it back to its key, and change the resource's `name` inside the file instead. + +### `E_APPLY_FORBIDDEN` [#e-apply-forbidden] + +Your role in the workspace, or a workspace API key, does not allow the change. The finding names each resource. Use a personal API key or an OAuth login with the role the change needs, or narrow the apply with `--only`. + +### `E_EDGE_CYCLE` [#e-edge-cycle] + +The wiring closes a cycle, so no block on it would ever run. Remove the edge the finding points at, and repeat work with `loop()` instead. + +### `E_STORED_VALUE_MISSING` [#e-stored-value-missing] + +`stored()` stands for a saved value, such as a secret, that `get` does not print. A workflow created from a copy has no saved value to keep. Replace `stored()` with `env.NAME` or the value. + +### `W_APPLY_CATALOG_MOVED` [#w-apply-catalog-moved] + +The compile failed, and the block catalog changed since you read the workflow, for example because a block gained a setting. Run `get` again to update the types, then reapply your edit. + +### `W_APPLY_TRIGGER_REMOVED` [#w-apply-trigger-removed] + +You deleted or retyped a block that serves a live webhook, schedule, chat or MCP tool. The deployed version keeps serving it until the next deploy. Deploy when the change should take effect, and update whatever called the old webhook URL. + +## Other problems + +- **The builder does not show a change.** An apply saves the draft. The builder shows it at once, but runs of the deployed version do not change until you deploy. +- **The Code tab is missing.** Workflows as code is not enabled for the workspace; see [Workflows as code](/workflows/code). + +## Related docs + +- [Exit codes](/workflows/code/exit-codes) +- [Diagnostic codes](/workflows/code/diagnostics) +- [Limits](/workflows/code/limits) +- [How it works](/workflows/code/how-it-works) +- [CLI troubleshooting](/cli/troubleshooting) diff --git a/apps/sim/lib/mothership/generated/docs-manifest.ts b/apps/sim/lib/mothership/generated/docs-manifest.ts index b365dff58b2..48599cca1b1 100644 --- a/apps/sim/lib/mothership/generated/docs-manifest.ts +++ b/apps/sim/lib/mothership/generated/docs-manifest.ts @@ -500,6 +500,7 @@ export const DOCS_MANIFEST: readonly string[] = [ 'workflows/blocks/webhook.mdx', 'workflows/blocks/workflow.mdx', 'workflows/code.mdx', + 'workflows/code/adopt.mdx', 'workflows/code/ci.mdx', 'workflows/code/coding-agents.mdx', 'workflows/code/create.mdx', @@ -508,9 +509,11 @@ export const DOCS_MANIFEST: readonly string[] = [ 'workflows/code/edit.mdx', 'workflows/code/exit-codes.mdx', 'workflows/code/get-started.mdx', + 'workflows/code/how-it-works.mdx', 'workflows/code/limits.mdx', 'workflows/code/promote.mdx', 'workflows/code/syntax.mdx', + 'workflows/code/troubleshooting.mdx', 'workflows/code/workspace.mdx', 'workflows/connections.mdx', 'workflows/data-flow.mdx', diff --git a/packages/sim-cli/README.md b/packages/sim-cli/README.md index 2a8115f57ac..dc8382b6fa8 100644 --- a/packages/sim-cli/README.md +++ b/packages/sim-cli/README.md @@ -323,11 +323,10 @@ Success exits 0 and most failures exit 1. Two failures any command can hit have creates and dry runs, are resent up to 6 times first, each wait the longer of `Retry-After` (up to 60 seconds) and a backoff of about 1 to 30 seconds; any other write exits 9 at once. Before this release both exited 1. Ctrl-C exits 130; a source apply or create already sent is finished and -saved into its directory first. The `workflows source` and `workspaces source` commands also use -5 (stale), 6 (a locked workflow or folder; a locked block exits 1), 7 (too large), 8 (a workspace -apply stopped part-way), 10 (busy), 11 (status: local changes), 12 (status: the server changed), -14 (a write without `--yes` where no terminal can ask: it printed the plan and wrote nothing) and 15 -(a workspace apply wrote part of its plan and held the rest back). Command-specific codes: [Exit codes](https://docs.sim.ai/cli/scripting#exit-codes). +saved into its directory first. The `workflows source` and `workspaces source` commands have codes +of their own, such as 5 (stale) and 12 (`status`: the server changed): see +[Workflows as code exit codes](https://docs.sim.ai/workflows/code/exit-codes). Other +command-specific codes: [Exit codes](https://docs.sim.ai/cli/scripting#exit-codes). ## Workflows and workspaces as code diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts index 06cf8d8e4c9..13d1991b456 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts @@ -1,5 +1,3 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it } from 'vitest' import * as exitCodes from '../../exit-codes' import { sourceExitCodesHelp } from './source-exit-codes' @@ -19,16 +17,10 @@ const SOURCE_EXIT_CODES = [ 130, ].sort((a, b) => a - b) -const WORKFLOW_SDK_README = readFileSync( - join(import.meta.dirname, '../../../../workflow-sdk/README.md'), - 'utf8' -) - describe('the exit-code tables an agent or a reader relies on', () => { it.each([ ['the workflow directory guide', WORKFLOW_TREE.agents], ['the workspace directory guide', WORKSPACE_TREE.agents], - ['the workflow SDK README', WORKFLOW_SDK_README], ])('%s lists every code a source command exits with', (_name, text) => { const listed = [...text.matchAll(/^\| (\d+) \|/gm)].map((match) => Number(match[1])) expect(listed).toEqual(SOURCE_EXIT_CODES) diff --git a/packages/workflow-sdk/README.md b/packages/workflow-sdk/README.md index af0c4d36f83..bd9f58e3e1d 100644 --- a/packages/workflow-sdk/README.md +++ b/packages/workflow-sdk/README.md @@ -1,169 +1,17 @@ # @sim/workflow-sdk -Types for Sim workflows written as TypeScript. A workflow file imports from this package, but -**nothing in it runs**: the server compiles the file statically, and every runtime export throws -`SimSdkNotExecutable`. The guide is [docs.sim.ai/workflows/code](https://docs.sim.ai/workflows/code); -in the Sim repository the full grammar is `packages/workflow-code/src/compile/SYNTAX.md`. - -## Edit loop - -```bash -sim workflows source get --dir ./wf # 1. write the source tree -# 2. edit ./wf/workflow.ts (and ./wf/functions/*) -sim workflows source check --dir ./wf # compile locally, no request; exit 0 to go on -sim workflows source status --dir ./wf # what changed here and on the server; diff shows it -sim workflows source apply --dir ./wf --dry-run # 3. check on the server; writes nothing -sim workflows source apply --dir ./wf --yes # 4. save the draft -``` - -`apply` reads the workflow id from `./wf/.sim/base.json`; pass it (`apply --dir`) to -have the CLI confirm the directory holds that workflow. - -1. **Get** writes `workflow.ts`, function files, the lock, the base and the types. -2. **Edit** `workflow.ts`. Declare blocks with `const x = builder('Name', params)` and wire them - with `x.to(y)`. Then run `sim workflows source check --dir ./wf`: it compiles with the server's - compiler against the cached catalog, without a request, in milliseconds, and catches what `tsc` - cannot (duplicate names, cycles, literal secrets). It exits 1 on errors and on the warnings - `sim workflows source check --help` lists (a missing required field, an unknown option, a - literal secret and more) in a block the lock does not bind yet (`--strict`: in every block; `--no-strict`: never on a - warning). It also adds the blocks the source now uses to `tsconfig.json`. Then always run - `bunx -p typescript@7.0.2 tsc -p ./wf` after an edit and fix what it reports: it takes about a - second and catches what check and the dry run do not, such as a reference to a start input the - trigger does not declare. It type-checks with the TypeScript release the declarations are built - for. `tsconfig.json` includes only the blocks the source used at the - last check, get or apply (fast); `tsconfig.full.json` includes every current block, from the CLI's cache. A builder of a block - the directory does not hold yet type-checks once `check` has run: it writes that block's file. In a - workspace directory, `sim workspaces source check --dir .` checks every workflow against the - directory's own secrets, credentials, resource keys and table columns, and - `sim workflows source check` run in a `workflows/` folder does the same for one. -3. **Dry run** compiles and runs every server check. Fix each error it prints, then run it again - until it exits 0. -4. **Apply** saves the draft. It rewrites `./wf` from what was stored, in canonical form (normalized - values, order and quoting show up there, so re-read `workflow.ts` before the next edit), and - refreshes `.sim/lock.json`, `.sim/base.json` and `tsconfig.json`. It deploys only with `--deploy`. -5. **On a 409** (`SOURCE_STALE`, exit 5) the workflow changed since you read it and nothing was - saved. Run `get` into a fresh directory, reapply your edit there (diff your copy against the old - source to find it), dry-run, apply. Keep the fresh `.sim/` files: `.sim/base.json` holds the - fingerprint that makes the next apply safe. -6. **New workflow**: write `workflow.ts` in an empty directory and run - `sim workflows source create --dir ./wf --workspace [--name ] [--folder ] --yes`. It prints the - new workflow id and writes the full tree a `get` writes: the `.sim/sdk` types, `tsconfig.json`, - `.sim/AGENTS.md` and the lock files. Continue with the loop above. Run on a directory without - `workflow.ts` and without `--dry-run` or `--yes`, `create --dir ./wf --workspace ` writes a - starter `workflow.ts` and that workspace's types instead, records the workspace in - `.sim/starter.json`, and creates nothing; the create that follows targets that workspace, and - one into another workspace is refused unless `--workspace` names it. - -`apply` and `create` ask for confirmation on a terminal. With no terminal to ask and no `--yes`, -they print the plan, write nothing and exit `14` (or `1` when the plan has errors): run the same -command with `--yes` to write it. `--dry-run` never asks. - -## Where the types live - -| Path | Contents | -|------|----------| -| `workflow.ts`, `functions/*` | The source. Edit these. | -| `.sim/lock.json` | Binds each block to its stored id. Renaming a display name keeps the id; renaming the const too keeps it only when settings, neighbours or references still tie the block. Do not edit. | -| `.sim/base.json` | The workflow, workspace, fingerprint and catalog hash the source was read at. Do not edit. | -| `.sim/written.json` | The CLI's record of each file as it last wrote it, so `status`, `diff` and a later `get` can tell your unapplied edits from files it may replace. Commit it with the lock and base. Do not edit. | -| `.sim/sdk/core.d.ts` | This package: `workflow`, `t`, `env`, `credential`, `table`, `BlockMeta`, ... | -| `.sim/sdk/INDEX.md` | The block type → builder naming rule, how a workflow runs, and one line per builder of the blocks the directory holds: `slack.sendMessage — Slack: Send Message → blocks/slack_v2.d.ts (SlackSendMessageParams)`. Any other builder: `sim workflows source params `. | -| `.sim/sdk/blocks/{type}.d.ts` | One block type's builders with their params and outputs, for the blocks the source uses and the core builders' (`check` adds a block an edit starts using). `sim workflows source params` prints one builder rather than a file whole. | -| `.sim/sdk/index.d.ts` | Names the catalog and generator the declarations come from, and imports the blocks the directory holds. | -| `~/.sim/cache/source-catalog//sdk-/` | Every block's declarations and the full `INDEX.md`, generated once per catalog and shared by every directory; `tsconfig.full.json` includes its `index.d.ts` (every current block). | -| `.sim/sdk/workspace.d.ts` | This workspace's tables (with columns), knowledge bases, credentials, workflows (with inputs), skills, custom tools, MCP servers (with tools) and env var names, so `table('tickets')`, `credential('support-slack')`, `skill('triage')` and `env.X` are checked. | -| `tsconfig.json` | Resolves `@sim/workflow-sdk` to `.sim/sdk` and type-checks `workflow.ts` with the blocks it uses (from the source and the server's `blockTypes`) and the core builders' blocks: a few dozen files for `tsc` instead of every block. | -| `tsconfig.full.json` | The same with every current block (the cached index, an absolute path on this machine), plus any legacy-only block the workflow uses. | -| `.sim/AGENTS.md` | The authoring guide for agents: the primer `get` prints (edit loop, identity, references, deletes, deploy, exit codes, and a snippet for each builder the source calls), then a reference linking [the docs](https://docs.sim.ai/workflows/code). A top-level `AGENTS.md` of your own is never touched. | -| `.sim/examples/*.ts` | Example workflows, together one correct example of each common block: `cookbook.ts` (agent, condition, function, table, knowledge, Slack, human in the loop, loop, response), `integrations.ts` (webhook, weekday cron, HTTP headers, table update by id, Gmail, `onError`), `agents.ts` (router, agent tools, child workflow, parallel). Read them before writing. They name example resources, so the tsconfig files leave them out. | -| `.gitattributes` | `text eol=lf` for the source files, merged into any file already there. | - -`sim workflows source resources` lists the resource keys source can name in the active -workspace (`-w ` for another). - -## Diagnostics - -One finding per line, pinned to the file you sent, then the code frame and the hint: - -``` -workflow.ts:56:7 error E_UNKNOWN_PARAM: Slack has no param chanel. - 54 | const notify = slack.sendMessage('Notify', { - 55 | credential: credential('support-slack'), -> 56 | chanel: 'C0SUPPORT', - | ^^^^^^^^^^^^^^^^^^^ - 57 | text: t`New ${classify.category} ticket: ${ticketIn.subject}`, - hint: Did you mean channel? -``` - -- `E_*` errors refuse the whole apply; nothing is saved. -- `W_*` warnings are saved as written. They name real problems (a required field left empty, an - output path no block has), so read them. -- Lock problems print as `.sim/lock.json#/`. -- The API returns the same findings in `data.diagnostics` (`error.details.diagnostics` on a - refusal) with `code`, `severity`, `message`, `hint`, `file`, `line`, `column` and `frame`. - -Every code and its meaning: the "Diagnostics" table of `SYNTAX.md` in the Sim repository. - -## Exit codes - -Every `sim workflows source` and `sim workspaces source` command exits with one of these: - -| Code | Meaning | Do | -|---|---|---| -| 0 | Applied or created, a dry run or check with no errors, or a clean status | Done | -| 1 | The source has errors, a locked block (`E_APPLY_LOCKED_BLOCK`), a name another workflow holds (`SOURCE_NAME_TAKEN`), a cancelled prompt, or the command failed | Fix what it printed | -| 5 | `SOURCE_STALE`: the workflow changed since `get`, and nothing was written | Get again, reapply the edit (step 5) | -| 6 | The workflow or its folder is locked (`E_APPLY_LOCKED`) | Ask someone to unlock it in the workflow builder | -| 7 | The source is too large (on a get, status or diff too) | Split function code or remove blocks | -| 8 | `sim workspaces source apply` stopped part-way; what was written is saved into the directory | Apply again until it exits 0 | -| 9 | Still rate limited (HTTP 429) after the CLI's retries; nothing more was written | Wait a minute and run the same command again | -| 10 | Busy: another apply is writing the workspace, or another `sim` command is using the directory; nothing was written | Run it again once the other finished | -| 11 | `status`: only your local edits | Dry-run, then apply | -| 12 | `status`: the server changed since the get (drift, or a conflict with your edits) | Follow the `Next:` line it prints | -| 13 | Not logged in, or the server refused the credential (`AUTH_REQUIRED`); nothing was sent | `sim login`, or fix or unset `SIM_API_KEY` | -| 14 | `apply` or `create` without `--yes` and no terminal to ask: it printed the plan, found no errors, and wrote nothing | Run the same command with `--yes` | -| 15 | `sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret with no value, or a credential key nothing binds to | Set the secret or connect the credential, then apply again | -| 130 | Interrupted (Ctrl-C). An apply or create already sent is finished and saved first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and says it may have been written | `sim workflows source status --dir ./wf` | - -## Write declarations, not programs - -The compiler reads the file; it never runs it. So the file holds only what it can read -statically: imports from `@sim/workflow-sdk`, block declarations, and wiring statements. A helper -function, a `for` loop that creates blocks, a conditional, or an import of your own has no stored -form and is refused with `E_UNSUPPORTED_SYNTAX` and a hint naming the supported form. Put the -logic in the graph instead: - -```ts -// repeat work over data -const each = loop.forEach('Each lead', { collection: start.leads }, (p) => { - const save = table.updateRowById('Save', { - tableId: table('leads'), - rowId: p.currentItem.id, - data: { seen: true }, - }) - p.to(save) -}) -// choose a path at run time -const route = condition('Route', { billing: js`${cls.category} === 'billing'`, else: true }) -// reuse logic -const handoff = runWorkflow('Hand off', { workflowId: childWorkflow('assign-owner') }) -``` - -Write each value where it is used. A param equal to the editor default can be left out. - -## Escape hatch: function files - -When logic does not fit a block, put it in a function block and keep the code in a file: - -```ts -const score = fn('Score lead', { code: codeFile('./functions/score-lead.js') }) -``` - -The file is a function body (top-level `return` and `await` work). In JavaScript, read block -outputs with `$ref.blockKey.path` and environment variables with `$env.NAME`; Python and shell -files are stored verbatim. One file per block; imports between function files are not supported. - -## Package layout (for maintainers) +The authoring types for Sim workflows written as TypeScript. A workflow file imports from this +package, but **nothing in it runs**: Sim compiles the file statically, and every runtime export +throws `SimSdkNotExecutable`. The package is private: the CLI embeds its declarations and writes +them into each source directory's `.sim/sdk/`, so no user installs it. + +User docs, including the edit loop, the directory layout, the file syntax, exit codes and +diagnostic codes, are at [docs.sim.ai/workflows/code](https://docs.sim.ai/workflows/code) +(source: `apps/docs/content/docs/workflows/code/`). In this repository, the full grammar is +`packages/workflow-code/src/compile/SYNTAX.md`, and the engines' design is in +`packages/workflow-code/DESIGN.md` and `packages/workspace-code/DESIGN.md`. + +## Package layout | Path | Contents | |------|----------| diff --git a/packages/workflow-sdk/src/diagnostics-table.test.ts b/packages/workflow-sdk/src/diagnostics-table.test.ts deleted file mode 100644 index 55dda36ba61..00000000000 --- a/packages/workflow-sdk/src/diagnostics-table.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { readFileSync } from 'node:fs' -import path from 'node:path' -import { DIAGNOSTIC_CODES } from '@sim/workflow-code/diagnostics/codes' -import { describe, expect, it } from 'vitest' - -describe('the Diagnostics table the README points at', () => { - it('has a SYNTAX.md row for every diagnostic code, and names no other code', () => { - const syntax = readFileSync( - path.join(import.meta.dirname, '../../workflow-code/src/compile/SYNTAX.md'), - 'utf8' - ) - const firstCells = [...syntax.matchAll(/^\| (`[EWI]_[A-Z_]+`(?:, `[EWI]_[A-Z_]+`)*) \|/gm)] - const documented = firstCells.flatMap(([, cell]) => - cell.split(', ').map((code) => code.slice(1, -1)) - ) - expect(new Set(documented)).toEqual(new Set(DIAGNOSTIC_CODES)) - }) -}) diff --git a/scripts/sync-workflow-code-docs.ts b/scripts/sync-workflow-code-docs.ts index 708bcbfedbc..e00a15f69fb 100644 --- a/scripts/sync-workflow-code-docs.ts +++ b/scripts/sync-workflow-code-docs.ts @@ -15,8 +15,9 @@ * * Content is rewritten between the `workflow-code-docs:` markers of the pages under * `apps/docs/content/docs/workflows/code/`. The check also fails on a diagnostic code a page - * names that no engine emits, and on a `typescript@x.y.z` pin in the docs other than the release - * the CLI type-checks a directory with. + * names that no engine emits, on a `typescript@x.y.z` pin in the docs other than the release + * the CLI type-checks a directory with, and on a `troubleshooting.mdx` without exactly one + * `[#exit-]` section per non-zero code `sourceExitCodeRows` lists. * * Usage: * bun run scripts/sync-workflow-code-docs.ts # write @@ -83,6 +84,11 @@ function cell(text: string): string { return mdx(text.replaceAll('\n', ' ')).replaceAll('|', '\\|') } +const SOURCE_GROUPS: readonly SourceCommandGroup[] = [ + 'sim workflows source', + 'sim workspaces source', +] + const indent = (block: string, spaces: number) => block .split('\n') @@ -105,12 +111,12 @@ function buildExitCodes(): string { "", ' ', '', - indent(exitCodeTable('sim workflows source'), 4), + indent(exitCodeTable(SOURCE_GROUPS[0]), 4), '', ' ', ' ', '', - indent(exitCodeTable('sim workspaces source'), 4), + indent(exitCodeTable(SOURCE_GROUPS[1]), 4), '', ' ', '', @@ -487,6 +493,27 @@ function checkProse(errors: string[]): void { } } +/** + * The troubleshooting page explains each exit code in depth, so it needs exactly one `#exit-` + * section per non-zero code a source command exits with. + */ +function checkTroubleshooting(errors: string[]): void { + const file = path.join(PAGES_DIR, 'troubleshooting.mdx') + const expected = [ + ...new Set(SOURCE_GROUPS.flatMap((group) => sourceExitCodeRows(group).map((row) => row.code))), + ] + .filter(Boolean) + .sort((a, b) => a - b) + const found = [...fs.readFileSync(file, 'utf8').matchAll(/^#+ .*\[#exit-(\d+)\]$/gm)] + .map((match) => Number(match[1])) + .sort((a, b) => a - b) + if (found.join() !== expected.join()) { + errors.push( + `${path.relative(rootDir, file)} needs one [#exit-] section per source exit code: expected ${expected.join(', ')}, found ${found.join(', ')}` + ) + } +} + function main(): void { const checkMode = process.argv.includes('--check') const errors: string[] = [] @@ -497,6 +524,7 @@ function main(): void { 'directory-kinds': buildDirectoryKinds(), } checkProse(errors) + checkTroubleshooting(errors) const writes: Array<{ rel: string; file: string; next: string }> = [] for (const region of Object.keys(REGIONS) as Region[]) {