` | No | Source directory: workflow.ts, functions/*, .sim/lock.json and .sim/base.json. Defaults to `.`. |
| `--dry` | No | Check the source and show the outcome without saving or writing files. |
| `-y, --yes` | No | Apply without asking for confirmation. |
-| `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. |
+| `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. With several triggers (an API and a webhook), name the one to enter through by its const: --run 'shopWebhook={…}' (--run shopWebhook alone: no input). Repeat --run to test more inputs or triggers: every run is made and reported, and --deploy needs all to complete. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. |
| `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). |
| `--allow-delete` | No | Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused. |
@@ -8706,7 +8706,7 @@ sim workflows source create [options]
| `--name ` | No | The workflow name (default: the source's). |
| `--folder ` | No | The folder to create it in (default: the root). |
| `-y, --yes` | No | Create without asking for confirmation. |
-| `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. |
+| `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. With several triggers (an API and a webhook), name the one to enter through by its const: --run 'shopWebhook={…}' (--run shopWebhook alone: no input). Repeat --run to test more inputs or triggers: every run is made and reported, and --deploy needs all to complete. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. |
| `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). |
@@ -8741,7 +8741,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser
Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics.
-These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block.
+These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block; --no-strict fails on none of them. An unwired condition or router branch (W_BRANCH_UNWIRED) stays a warning: a run that takes it ends there, as an else that should do nothing may. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block.
Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished.
@@ -8841,10 +8841,10 @@ Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one i
### sim workflows source find
-Print a block's declaration, edges and readers with line numbers (offline)
+Print blocks' declarations, edges and readers with line numbers (offline)
```bash
-sim workflows source find [options]
+sim workflows source find [options]
```
**Arguments**
@@ -8853,7 +8853,7 @@ sim workflows source find [options]
| Argument | Required | Description |
| --- | --- | --- |
-| `block` | Yes | Block name, key or identifier; a part of a name matches every block |
+| `block...` | Yes | Block names, keys or identifiers; a part of a name matches every block |
@@ -8867,9 +8867,9 @@ sim workflows source find [options]
-Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. <block> is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir. When the source does not compile, readers are left out (JSON output carries compiles: false).
+Prints each block the names match, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file (its text too, up to 30 lines), the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. Each <block> is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20 in all). Name every block a change touches in one call (find 'Refunds Score' 'Security Fetch Policy'). Run it from a workflow source directory, or pass --dir. When the source does not compile, readers are left out (JSON output carries compiles: false).
-Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the directory is not a workflow source directory.
+Exit codes: 0 printed; 1 a name matches no block (the blocks the other names match are printed first, and the closest name is suggested), or the directory is not a workflow source directory.
### sim workflows get
@@ -10159,7 +10159,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na
Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials; 13 when there is no login to download it with). With --output json, stdout is one document that also lists every finding under diagnostics.
-These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block.
+These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block; --no-strict fails on none of them. An unwired condition or router branch (W_BRANCH_UNWIRED) stays a warning: a run that takes it ends there, as an else that should do nothing may. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block.
Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished.
diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx
index 7b94f23fc94..8bb1e13dded 100644
--- a/apps/docs/content/docs/cli/workflows.mdx
+++ b/apps/docs/content/docs/cli/workflows.mdx
@@ -1447,7 +1447,7 @@ sim workflows source create [options]
| `--name ` | No | The workflow name (default: the source's). |
| `--folder ` | No | The folder to create it in (default: the root). |
| `-y, --yes` | No | Create without asking for confirmation. |
-| `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. |
+| `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. With several triggers (an API and a webhook), name the one to enter through by its const: --run 'shopWebhook={…}' (--run shopWebhook alone: no input). Repeat --run to test more inputs or triggers: every run is made and reported, and --deploy needs all to complete. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. |
| `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). |
@@ -1483,7 +1483,7 @@ sim workflows source apply [workflowId] [options]
| `--dir ` | No | Source directory: workflow.ts, functions/*, .sim/lock.json and .sim/base.json. Defaults to `.`. |
| `--dry` | No | Check the source and show the outcome without saving or writing files. |
| `-y, --yes` | No | Apply without asking for confirmation. |
-| `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. |
+| `--run [input]` | No | After the write is saved, dry-run the draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it): a run that does not complete exits 1 and deploys nothing. With several triggers (an API and a webhook), name the one to enter through by its const: --run 'shopWebhook={…}' (--run shopWebhook alone: no input). Repeat --run to test more inputs or triggers: every run is made and reported, and --deploy needs all to complete. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in sideEffects.unchecked, so --run --deploy in CI sends those. |
| `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). |
| `--allow-delete` | No | Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused. |
@@ -1535,7 +1535,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser
Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics.
-These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block.
+These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block; --no-strict fails on none of them. An unwired condition or router branch (W_BRANCH_UNWIRED) stays a warning: a run that takes it ends there, as an else that should do nothing may. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block.
Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished.
@@ -1571,12 +1571,12 @@ Without --server, each file created, edited or deleted since the directory was r
API request and response schemas: [getWorkflowSource](/api-reference/workflows/getWorkflowSource).
-### Print a block's declaration, edges and readers with line numbers
+### Print blocks' declarations, edges and readers with line numbers
Offline.
```bash
-sim workflows source find [options]
+sim workflows source find [options]
```
**Arguments**
@@ -1585,7 +1585,7 @@ sim workflows source find [options]
| Argument | Required | Description |
| --- | --- | --- |
-| `block` | Yes | Block name, key or identifier; a part of a name matches every block |
+| `block...` | Yes | Block names, keys or identifiers; a part of a name matches every block |
@@ -1599,9 +1599,9 @@ sim workflows source find [options]
-Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. <block> is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir. When the source does not compile, readers are left out (JSON output carries compiles: false).
+Prints each block the names match, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file (its text too, up to 30 lines), the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. Each <block> is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20 in all). Name every block a change touches in one call (find 'Refunds Score' 'Security Fetch Policy'). Run it from a workflow source directory, or pass --dir. When the source does not compile, readers are left out (JSON output carries compiles: false).
-Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the directory is not a workflow source directory.
+Exit codes: 0 printed; 1 a name matches no block (the blocks the other names match are printed first, and the closest name is suggested), or the directory is not a workflow source directory.
### Print a builder's params and outputs from the cached block catalog
diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx
index bb48be0d59f..60950234009 100644
--- a/apps/docs/content/docs/cli/workspaces.mdx
+++ b/apps/docs/content/docs/cli/workspaces.mdx
@@ -791,7 +791,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na
Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials; 13 when there is no login to download it with). With --output json, stdout is one document that also lists every finding under diagnostics.
-These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block.
+These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block; --no-strict fails on none of them. An unwired condition or router branch (W_BRANCH_UNWIRED) stays a warning: a run that takes it ends there, as an else that should do nothing may. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block.
Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished.
diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx
index 6a83edcf0e5..680fbaf6100 100644
--- a/apps/docs/content/docs/workflows/code/diagnostics.mdx
+++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx
@@ -65,7 +65,7 @@ Reading and writing `workflow.ts`.
| `W_SUBFLOW_HANDLE_SCOPE` | `edge()` from a loop or parallel's start handle to a block outside it (the executor runs it as the container's exit), or from another of its handles into its own child. The canvas never draws one; stored ones print this way so they round-trip. |
| `E_EDGE_CYCLE` | Wiring that closes a cycle among enabled blocks, a self-loop included: no block on it ever runs. Framed at the edge back to a block declared earlier, the one to remove; repeat work with `loop()`/`parallel()`. |
| `W_EDGE_CYCLE` | A cycle the stored workflow already holds, kept so it round-trips; none of it runs. An offline check reports it for a cycle among blocks the lock binds, which an apply keeps only if the stored workflow holds every edge of it. |
-| `W_BRANCH_UNWIRED` | A condition or router branch no edge leaves, so a run that takes it ends there; the hint names the wiring. Not reported for a branch the stored workflow already leaves unwired. |
+| `W_BRANCH_UNWIRED` | A condition or router branch no edge leaves, so a run that takes it ends there and completes: right for an `else` that should do nothing, so it is never more than a warning; the hint names the wiring. Not reported for a branch the stored workflow already leaves unwired. |
| `E_UNKNOWN_BUILDER` | A builder path the catalog does not have, a bare builder-shaped call (`apii('Name', …)`) nothing binds, or a namespace the SDK lacks or the file did not import; `hint` names the builder a common other name stands for (`http.request` → `api`), then prefers a synonymous verb (`postMessage` → `sendMessage`), then the closest path, then the namespace's builders. |
| `E_UNKNOWN_PARAM` | A param the block does not have; the hint has a did-you-mean, or for block meta written there (`retry`, `disabled`, `locked`, `errorPort`) the third argument that takes it. |
| `E_FIXED_PARAM` | A param the builder already pins. |
diff --git a/apps/docs/content/docs/workflows/code/edit.mdx b/apps/docs/content/docs/workflows/code/edit.mdx
index 4ca4c981e70..75c4f0136a8 100644
--- a/apps/docs/content/docs/workflows/code/edit.mdx
+++ b/apps/docs/content/docs/workflows/code/edit.mdx
@@ -29,7 +29,7 @@ Edit `workflow.ts`, then compile it on your machine with Sim's compiler:
sim workflows source check --dir ./support-triage
```
-`check` makes no request. It needs the block catalog the last `get` cached in `~/.sim/cache/source-catalog/`; with none cached it exits `1` and tells you to run `get` once. It exits `1` on an error, and on the warnings `sim workflows source check --help` lists (a missing required field, an unknown option, an unwired condition or router branch, a literal secret and more) in a block you added since the get. `--strict` fails on these in every block, except an unwired branch on a block the get printed; `--no-strict` never fails on a warning.
+`check` makes no request. It needs the block catalog the last `get` cached in `~/.sim/cache/source-catalog/`; with none cached it exits `1` and tells you to run `get` once. It exits `1` on an error, 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 you added since the get. `--strict` fails on these in every block; `--no-strict` never fails on a warning. An unwired condition or router branch stays a warning: a run that takes it ends there.
Then it adds the blocks the workflow now uses to `tsconfig.json` and type-checks the directory with it, using the TypeScript release the generated declarations are built for, as your editor does. Each type error is an `E_TYPE` error at its line, with TypeScript's own code (`TS2339: …`) at the start of the message. A type error is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them), where the dry run decides; one that another file's edit causes there is reported. The first check installs that release with `npm` into `~/.sim/cache/typescript/`, once (none when `SIM_TYPESCRIPT_DIR` already holds it); offline before then, `check` warns `W_TYPES_UNCHECKED` and passes or fails on the compile alone. `--no-types` skips the type check. `tsconfig.full.json` includes every block, for an editor.
diff --git a/apps/docs/content/docs/workflows/code/syntax.mdx b/apps/docs/content/docs/workflows/code/syntax.mdx
index 2690afe854b..c21b0153694 100644
--- a/apps/docs/content/docs/workflows/code/syntax.mdx
+++ b/apps/docs/content/docs/workflows/code/syntax.mdx
@@ -226,7 +226,7 @@ In a JavaScript file, `$ref.block.path` reads another block's output and `$env.N
- A condition's params object lists its rows in order, each a string or template. Write `else: true` last for the empty else. Two or more rows must end with `else` (`E_BRANCH_ELSE_LAST`).
- A router's rows are `routes: { key: text }`.
- A branch key is unique (`E_DUPLICATE_BRANCH_KEY`) and may not be an output name, `to` or `onError` (`E_BRANCH_KEY_COLLIDES`).
-- A branch that no edge leaves ends the run on that path; `check` reports it as `W_BRANCH_UNWIRED`.
+- A branch that no edge leaves ends the run on that path, and the run completes; `check` reports it as the warning `W_BRANCH_UNWIRED`, so an `else` that should do nothing needs no block.
## Loops and parallel blocks
diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json
index 90c66e268e5..2fe30baf048 100644
--- a/apps/docs/scripts/fixtures/content-baseline.json
+++ b/apps/docs/scripts/fixtures/content-baseline.json
@@ -13220,7 +13220,7 @@
{
"lang": "bash",
"meta": null,
- "sha256": "d7ee275831d1d82d0812ddf90e79aaf3861d23bc0b5474e2e365aabf466d1ddb",
+ "sha256": "c59fc91cf1a45ac30224842069008b364bdf19061fbc6ccec793d30914167cb4",
"bytes": null,
"line": null
},
@@ -17799,7 +17799,7 @@
{
"lang": "bash",
"meta": null,
- "sha256": "d7ee275831d1d82d0812ddf90e79aaf3861d23bc0b5474e2e365aabf466d1ddb",
+ "sha256": "c59fc91cf1a45ac30224842069008b364bdf19061fbc6ccec793d30914167cb4",
"bytes": null,
"line": null
},
diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts
index 00b7e6d0b01..815c9b24b5d 100644
--- a/packages/sim-cli/src/commands/protocol/source-check.ts
+++ b/packages/sim-cli/src/commands/protocol/source-check.ts
@@ -92,14 +92,6 @@ const SERVER_ONLY_CODES: ReadonlySet = new Set(['E_STORED_VALUE_MISSING'
*/
const STRICT_CODES: ReadonlySet = new Set(STRICT_FINDINGS.keys())
-/**
- * {@link STRICT_CODES} warnings the stored workflow exempts, which a check never fails on a block
- * the lock binds, `--strict` included: the server stays quiet when the stored workflow holds the
- * same state, and an offline check cannot read it. `W_BRANCH_UNWIRED`: a branch the stored
- * workflow leaves unwired.
- */
-const STORED_EXEMPT_CODES: ReadonlySet = new Set(['W_BRANCH_UNWIRED'])
-
/**
* Warnings a check reports, as the server does, only on a JSON field the edit made store a
* reference anew: the compile reads what the source the last get or apply printed held from
@@ -153,9 +145,9 @@ every finding under diagnostics.
These warnings, which an apply saves as written, fail the check as errors on every block the lock
does not bind (a block added since the get, or every block of a new workflow):
${[...STRICT_CODES].map((code) => ` ${code}`).join(',\n')}.
---strict fails on them in every block, except ${[...STORED_EXEMPT_CODES].join(', ')} on a block the
-lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails
-on none of them. In every mode, as the server refuses them: ${EDIT_REFUSALS.map(
+--strict fails on them in every block; --no-strict fails on none of them. An unwired condition or
+router branch (W_BRANCH_UNWIRED) stays a warning: a run that takes it ends there, as an else that
+should do nothing may. In every mode, as the server refuses them: ${EDIT_REFUSALS.map(
({ warning, refusal, where }) => `${warning} is the error ${refusal} ${REFUSAL_WHERE[where]}`
).join('; ')}. A block counts as changed when the lock does not bind it, when the source moved it
into another container, or when it compiles differently than in the source the last get or
@@ -730,7 +722,6 @@ export async function checkWorkflowDir(
}
const fails = (code: string, blockKey: string | undefined) =>
STRICT_CODES.has(code) &&
- !(STORED_EXEMPT_CODES.has(code) && bound(blockKey)) &&
(options.strict === 'all' || (options.strict === 'new' && !bound(blockKey)))
const prefix = options.prefix ?? ''
const reported = (code: string, blockKey: string | undefined) =>
diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts
index be4d6dd791f..8997d2388ee 100644
--- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts
+++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts
@@ -83,6 +83,9 @@ export function workflowSourceLoopHelp(surface: PrimerSurface): string {
return `
${WORKFLOW_LOOP_LINES[surface]} --allow-delete lets an edit remove a block or variable; apply --dry only
prints the plan; get --force replaces unapplied edits or another workflow's source.
+A large workflow: chain \`&& sim workflows source find '' '' --dir ./wf\` onto the
+get, naming every block the change touches: it prints only those (lines, function file, wiring,
+readers), not the whole workflow.ts.
A new workflow: \`sim workflows source create --dir ./new --workspace \` writes a
starter; edit and check it, then \`create --dir ./new --yes${surface === 'chat' ? '' : " --run '{…}' --deploy"}\`.
${WORKSPACE_LINE}
diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts
index 16e386aac41..f4ca6710ade 100644
--- a/packages/sim-cli/src/commands/protocol/source-primer.ts
+++ b/packages/sim-cli/src/commands/protocol/source-primer.ts
@@ -62,7 +62,7 @@ function sharedRules(extra: { renames?: string; patterns?: string; debug?: strin
${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any builder: \`${PARAMS_COMMAND} \`):
- Condition: keys test in order, first true wins, \`else: true\` last; wire \`route.high.to(alert)\`.
- Loop: \`const each = loop.forEach('Each Order', { collection: recent.rows }, (p) => {\`; inside, \`p.currentItem.data.orderId\` and \`p.index\`; after, \`each.results\`.
- - Failure: \`shape.onError(invalid)\`; \`invalid\` reads \`shape.error\` (an \`api\` block's too); only a Function also has \`.errorMessage\` (message only).
+ - Failure: \`lookup.onError(failed)\`; \`failed\` reads its message as \`lookup.error\` (any block; a Function's adds the line: \`.errorMessage\` doesn't).
- Retry: an \`api\` block resends with \`retries: 3\`, \`retryDelayMs: 500\`; any block's Retry on fail: 3rd argument, \`{ retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } }\`.
- Child: \`const enrich = runWorkflow('Enrich Lead', {\` with \`workflowId: childWorkflow('enrich-lead')\`, \`inputMapping: { email: start.email }\`; read \`enrich.result.data.\`.
- Tables: \`table.queryRows\` outputs \`rows\` (\`recent.rows[0].data.status\`), not \`row\`; \`table.upsertRow\` takes \`conflictColumn: 'orderId'\`.
@@ -98,7 +98,7 @@ const APPLY_REWRITES = `\`check\` also type-checks (no \`tsc\`). Apply re-checks
* test runs through `sim_cli`, whose `--dir` reads the same workbench.
*/
const WORKFLOW_EDIT_LOOP: Record = {
- cli: `${EDIT_LOOP_LEAD}; fix what it reports: \`${WORKFLOW_LOOP}${CLI_LOOP_RUN.workflow}\` applies, dry-runs that input, and deploys only if it completed (no \`--deploy\`: stays a draft). ${APPLY_REWRITES}`,
+ cli: `${EDIT_LOOP_LEAD}; fix what it reports: \`${WORKFLOW_LOOP}${CLI_LOOP_RUN.workflow}\` applies, dry-runs that input, and deploys only if it completed (no \`--deploy\`: stays a draft); several triggers: one \`--run '={…}'\` each. Secrets: \`sim secrets set NAME --scope workspace\`, read \`env.NAME\`. ${APPLY_REWRITES}`,
chat: `${EDIT_LOOP_LEAD} in run_code's shell; fix what it reports: \`${WORKFLOW_LOOP}\`. ${APPLY_REWRITES} Test the draft with sim_cli, as the shell refuses runs: \`workflows run --dry --input '{…}' --dir \` (from /home/user), then \`workflows deploy --expected-draft-fingerprint \` (from \`.sim/base.json\`).`,
}
@@ -210,14 +210,36 @@ function builderSnippets(catalog: BlockCatalog, sources: Iterable): stri
return `## Builders this source uses\n\n${snippets.join('\n')}\n${rest}`
}
-/** The `surface` primer with the snippets of the builders `sources` call. */
+/**
+ * A workflow source at least this many lines long gets {@link longSourceNote}: past a few hundred
+ * lines, an agent spends turns searching it for the blocks a change names.
+ */
+const LONG_SOURCE_LINES = 300
+
+/**
+ * The note on reading a long workflow source by block: one `find` naming every block a change
+ * touches prints their lines, function files, wiring and readers, where rounds of grep and sed
+ * would. Empty for a workspace (its primer names `find`) or a short source.
+ */
+function longSourceNote(kind: PrimerKind, sources: readonly string[]): string {
+ if (kind !== 'workflow') return ''
+ const lines = Math.max(0, ...sources.map((text) => text.split('\n').length))
+ if (lines < LONG_SOURCE_LINES) return ''
+ return `## A long source
+
+\`${SOURCE_ENTRY_FILE}\` has ${lines} lines: read only the blocks a change touches. Name them all in one call (a part of a name matches every block with it): \`sim workflows source find '' '' --dir .\` prints each block's lines, function file, wiring and readers, each as file:line.
+`
+}
+
+/** The `surface` primer, a long source's note, then the snippets of the builders `sources` call. */
export function primerFor(
kind: PrimerKind,
surface: PrimerSurface,
catalog: BlockCatalog,
sources: Iterable
): string {
- const primer = sourcePrimer(kind, surface)
- const snippets = builderSnippets(catalog, sources)
- return snippets ? `${primer}\n${snippets}` : primer
+ const texts = [...sources]
+ return [sourcePrimer(kind, surface), longSourceNote(kind, texts), builderSnippets(catalog, texts)]
+ .filter((part) => part !== '')
+ .join('\n')
}
diff --git a/packages/sim-cli/src/commands/protocol/source-strict.ts b/packages/sim-cli/src/commands/protocol/source-strict.ts
index 12799b4aa31..69519c02c91 100644
--- a/packages/sim-cli/src/commands/protocol/source-strict.ts
+++ b/packages/sim-cli/src/commands/protocol/source-strict.ts
@@ -16,7 +16,6 @@ export const STRICT_FINDINGS: ReadonlyMap = new Map([
['W_TABLE_UNKNOWN_COLUMN', 'a table write to an unknown column'],
['W_CHILD_INPUT_UNKNOWN', 'an input a child workflow does not declare'],
['W_CHILD_RESULT_PATH', "a path a child workflow's result does not hold"],
- ['W_BRANCH_UNWIRED', 'an unwired condition or router branch'],
['W_UNRESOLVED_REF', 'a reference that names nothing'],
['W_REF_OUT_OF_SCOPE', 'an iteration field read outside its loop or parallel'],
['W_LOOP_CONDITION_SYNTAX', 'a loop condition that is not a JavaScript expression'],
diff --git a/packages/sim-cli/src/commands/protocol/source-types.ts b/packages/sim-cli/src/commands/protocol/source-types.ts
index 46866a423bf..6deb08b5bd7 100644
--- a/packages/sim-cli/src/commands/protocol/source-types.ts
+++ b/packages/sim-cli/src/commands/protocol/source-types.ts
@@ -559,3 +559,33 @@ export async function withStaleTableHints(
}
})
}
+
+/**
+ * tsc's error on an `env.NAME` the generated `WorkspaceEnv` lacks, with no close name to suggest
+ * (a near miss is TS2551, "Did you mean", and stays an error: likely a typo).
+ */
+const UNTYPED_ENV_NAME =
+ /^TS2339: Property '([^']+)' does not exist on type '\{ readonly [^']*: EnvRef;[^']*\}'\.?$/
+
+/**
+ * Downgrades a type error on an env name the types the last get wrote lack to the warning the
+ * server gives an unknown env name (`W_ENV_UNKNOWN`), naming the refresh: a secret set since
+ * (`sim secrets set`) is missing from those types until a command that reads the server
+ * (`source status`) rewrites them, and a check makes no request. The apply checks the name against
+ * the server's env either way, so a check never fails on what it cannot know is stale.
+ */
+export function withStaleEnvTypes(findings: Diagnostic[], dir: string): Diagnostic[] {
+ const refresh = `sim workflows source status --dir ${shellWord(dir)}`
+ return findings.map((finding) => {
+ const untyped = finding.code === 'E_TYPE' ? UNTYPED_ENV_NAME.exec(finding.message) : null
+ if (!untyped) return finding
+ const name = untyped[1]
+ return {
+ ...finding,
+ code: 'W_ENV_UNKNOWN',
+ severity: 'warning',
+ message: `env.${name} is not among the env names the types the last get wrote hold.`,
+ hint: `If it was set since (sim secrets set), the apply finds it; \`${refresh}\` refreshes the types. Otherwise set it: sim secrets set ${name} --scope workspace.`,
+ }
+ })
+}
diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts
index e32698edbdb..bd8864c4c84 100644
--- a/packages/sim-cli/src/commands/protocol/source-ui.ts
+++ b/packages/sim-cli/src/commands/protocol/source-ui.ts
@@ -239,12 +239,31 @@ function findingAnnotation(diagnostic: Diagnostic, dir: string | undefined): str
*/
const QUIET_INFO_CODES: ReadonlySet = new Set(['I_MAT_NEEDS_LAYOUT'])
+/** The compiler's message on a password field holding a literal secret, naming the param. */
+const LITERAL_PASSWORD = /^(\S+) holds a literal secret instead of an env reference/
+
+/**
+ * A finding with the CLI's own next step in its hint: a literal secret in a password field (a
+ * webhook token, an API key) names the commands that store it and the reference that reads it,
+ * so the fix is one command and one edit, not a lookup.
+ */
+function withCliHint(diagnostic: Diagnostic): Diagnostic {
+ if (diagnostic.code !== 'W_LITERAL_SECRET') return diagnostic
+ const param = LITERAL_PASSWORD.exec(diagnostic.message)?.[1]
+ if (param === undefined) return diagnostic
+ return {
+ ...diagnostic,
+ hint: `Store the value as a secret, never in the file: \`sim secrets set NAME --scope workspace --value @-\` with the value piped from a file or variable, never typed into the command, then write ${param}: env.NAME (import env from '@sim/workflow-sdk'). A check passes a name set since the get; the apply checks it against the workspace.`,
+ }
+}
+
/**
* The {@link FindingsOutput} of `format`; `verbose` keeps info findings in a machine result, and
* the {@link QUIET_INFO_CODES} in a display one. In a GitHub Actions step every error and warning
* is also annotated at its file under the source directory `dir`, whatever the format. It is
- * the CLI's output edge, where each finding's message and hint are cut (`boundFindingText`): a
- * finding an offline check made is as long as its source made it until here.
+ * the CLI's output edge, where a finding gets the CLI's hint (`withCliHint`) and each message
+ * and hint is cut (`boundFindingText`): a finding an offline check made is as long as its source
+ * made it until here.
*/
export function findingsOutput(
format: OutputFormat,
@@ -262,14 +281,14 @@ export function findingsOutput(
(verbose || !QUIET_INFO_CODES.has(diagnostic.code)) &&
fresh(printed, findingKey(diagnostic))
)
- .map((diagnostic) => boundFindingText(diagnostic))
+ .map((diagnostic) => boundFindingText(withCliHint(diagnostic)))
if (!machine) printDiagnostics(unseen)
printAnnotations(unseen.flatMap((diagnostic) => findingAnnotation(diagnostic, dir)))
},
result: (diagnostics) =>
resultDiagnostics(
format,
- diagnostics.map((diagnostic) => boundFindingText(diagnostic)),
+ diagnostics.map((diagnostic) => boundFindingText(withCliHint(diagnostic))),
verbose
),
}
diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts
index cbbd19f9cb9..97d0ad3de9c 100644
--- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts
+++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts
@@ -508,14 +508,16 @@ function testRunResult(record: Record): TestRun {
/**
* The run record of `sim workflows run --dry --input `: the saved draft run
- * with its writes stubbed, waited for. `input` is read as `--input` reads it (JSON, or `@file`).
- * A failed run is returned, not thrown: the caller decides what it stops.
+ * with its writes stubbed, waited for, entering through the trigger block `triggerBlockId` when
+ * given (`--trigger`). `input` is read as `--input` reads it (JSON, or `@file`). A failed run is
+ * returned, not thrown: the caller decides what it stops.
*/
async function dryRunDraft(
client: OperationClient<'executeWorkflow'>,
workflowId: string,
input: string | undefined,
- workspaceId: string | null
+ workspaceId: string | null,
+ triggerBlockId: string | undefined
): Promise> {
const commandSpec = CLI_CONTRACT.executeWorkflow ?? {}
try {
@@ -524,7 +526,11 @@ async function dryRunDraft(
workflowId,
input === undefined ? {} : { input },
workspaceId,
- { source: 'draft', dry: true }
+ {
+ source: 'draft',
+ dry: true,
+ ...(triggerBlockId ? { entry: { type: 'trigger', blockId: triggerBlockId } } : {}),
+ }
)
// A dry run is never detached (it cannot take --wait-timeout); a server that did is reported.
if ('detachedRunId' in result) {
@@ -569,20 +575,23 @@ export interface DraftTest {
}
/**
- * Dry-runs the saved draft of `workflowId` with `input` and, when the run does not complete, maps
- * its failure to a line of `sourceDir` and says why. A run the server refuses (a 400: an input the
- * trigger's fields do not match) is a test that failed before it started, not an error of the write.
+ * Dry-runs the saved draft of `workflowId` with `input`, through the trigger block
+ * `triggerBlockId` when given, and, when the run does not complete, maps its failure to a line of
+ * `sourceDir` and says why. A run the server refuses (a 400: an input the trigger's fields do not
+ * match, or no trigger named where the workflow has several) is a test that failed before it
+ * started, not an error of the write.
*/
export async function testRunDraft(
client: OperationClient<'executeWorkflow'>,
sourceDir: string,
workflowId: string,
input: string | undefined,
- workspaceId: string | null
+ workspaceId: string | null,
+ triggerBlockId?: string
): Promise {
let record: Record
try {
- record = await dryRunDraft(client, workflowId, input, workspaceId)
+ record = await dryRunDraft(client, workflowId, input, workspaceId, triggerBlockId)
} catch (error) {
if (!(error instanceof SimApiError) || error.status !== 400) throw error
return {
diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts
index 56635cf818d..4abdc9aca33 100644
--- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts
+++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts
@@ -1259,6 +1259,225 @@ describe('sim workflows source apply', () => {
expect(printed.at(-1)?.to).toBe('stdout')
})
+ describe('in a workflow with an API and a webhook trigger', () => {
+ /** An apply whose stored lock binds an API trigger `api` and a webhook `shopWebhook`. */
+ const twoTriggers = () => {
+ const answer = outcome()
+ answer.data.lock = {
+ ...LOCK,
+ blocks: {
+ api: { id: 'b-api', parent: null, ident: 'api', order: 0 },
+ shopwebhook: { id: 'b-hook', parent: null, ident: 'shopWebhook', order: 1 },
+ },
+ } as typeof LOCK
+ return answer
+ }
+ const serveTwoTriggers = () =>
+ request.mockImplementation(async (path: string) =>
+ path === DEPLOY_PATH ? deployed : path === STATUS_PATH ? liveStatus : twoTriggers()
+ )
+ const several =
+ 'This workflow has multiple runnable triggers. Pass run.entry.blockId to choose one: b-api (API), b-hook (Shop Webhook).'
+
+ it('names each trigger and the corrected command when a --run names none', async () => {
+ setTerminal(false)
+ serveTwoTriggers()
+ contextMockFns.mockRequestRaw.mockRejectedValue(
+ new SimApiError(several, 400, 'BAD_REQUEST')
+ )
+
+ const failure = apply(WORKFLOW_ID, '--dir', dir, '--yes', '--run', '{"x":1}', '--deploy')
+
+ await expect(failure).rejects.toThrow(
+ /more than one trigger.*--run 'api=\{"x":1\}'.*shopWebhook=/
+ )
+ expect(request.mock.calls.map((call) => call[0])).toEqual([APPLY_PATH])
+ expect(stdoutJson()).toMatchObject({
+ next: {
+ command: `sim workflows source apply --dir ${dir} --run 'api={"x":1}' --deploy --yes`,
+ },
+ })
+ })
+
+ it('enters each --run through the trigger it names, reports every run, then deploys', async () => {
+ setTerminal(false)
+ serveTwoTriggers()
+ contextMockFns.mockRequestRaw
+ .mockResolvedValueOnce(runAnswer({ status: 'completed', output: { source: 'api' } }))
+ .mockResolvedValueOnce(runAnswer({ status: 'completed', output: { written: 0 } }))
+
+ await apply(
+ WORKFLOW_ID,
+ '--dir',
+ dir,
+ '--yes',
+ '--run',
+ 'api={"orderId":"O-1"}',
+ '--run',
+ 'shopWebhook={"event":"ping","data":{}}',
+ '--deploy'
+ )
+
+ const sent = contextMockFns.mockRequestRaw.mock.calls.map(([, request]) => request.body)
+ expect(sent).toEqual([
+ expect.objectContaining({
+ input: { orderId: 'O-1' },
+ run: { source: 'draft', dry: true, entry: { type: 'trigger', blockId: 'b-api' } },
+ }),
+ expect.objectContaining({
+ input: { event: 'ping', data: {} },
+ run: { source: 'draft', dry: true, entry: { type: 'trigger', blockId: 'b-hook' } },
+ }),
+ ])
+ const result = stdoutJson()
+ expect(result).toMatchObject({
+ runs: [
+ { trigger: 'api', status: 'completed', output: { source: 'api' } },
+ { trigger: 'shopWebhook', status: 'completed', output: { written: 0 } },
+ ],
+ live: 'version 4, serving (this deploy)',
+ })
+ expect(String(result.summary)).toContain('2 test runs completed')
+ })
+
+ it('enters a --run through a trigger named by its block id, a UUID', async () => {
+ setTerminal(false)
+ const hookId = '5f0c2b1e-8a4d-4c3b-9e2f-1a2b3c4d5e6f'
+ request.mockImplementation(async (path: string) => {
+ if (path === DEPLOY_PATH) return deployed
+ if (path === STATUS_PATH) return liveStatus
+ const answer = twoTriggers()
+ answer.data.lock = {
+ ...LOCK,
+ blocks: {
+ api: { id: 'b-api', parent: null, ident: 'api', order: 0 },
+ shopwebhook: { id: hookId, parent: null, ident: 'shopWebhook', order: 1 },
+ },
+ } as typeof LOCK
+ return answer
+ })
+ contextMockFns.mockRequestRaw.mockResolvedValueOnce(
+ runAnswer({ status: 'completed', output: {} })
+ )
+
+ await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--run', `${hookId}={"event":"ping"}`)
+
+ expect(contextMockFns.mockRequestRaw.mock.calls[0][1].body).toMatchObject({
+ input: { event: 'ping' },
+ run: { entry: { type: 'trigger', blockId: hookId } },
+ })
+ })
+
+ it('enters a --run through a trigger named by a block key a plain name cannot be, like a collision suffix', async () => {
+ setTerminal(false)
+ request.mockImplementation(async (path: string) => {
+ if (path === DEPLOY_PATH) return deployed
+ if (path === STATUS_PATH) return liveStatus
+ const answer = twoTriggers()
+ answer.data.lock = {
+ ...LOCK,
+ blocks: {
+ api: { id: 'b-api', parent: null, ident: 'api', order: 0 },
+ 'shopwebhook~2': { id: 'b-hook', parent: null, ident: 'shopWebhook2', order: 1 },
+ },
+ } as typeof LOCK
+ return answer
+ })
+ contextMockFns.mockRequestRaw.mockResolvedValueOnce(
+ runAnswer({ status: 'completed', output: {} })
+ )
+
+ await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--run', 'shopwebhook~2={"event":"ping"}')
+
+ expect(contextMockFns.mockRequestRaw.mock.calls[0][1].body).toMatchObject({
+ input: { event: 'ping' },
+ run: { entry: { type: 'trigger', blockId: 'b-hook' } },
+ })
+ })
+
+ it('names a runnable trigger, not the refused block, when a --run names a block that is no trigger', async () => {
+ setTerminal(false)
+ serveTwoTriggers()
+ contextMockFns.mockRequestRaw.mockRejectedValue(
+ new SimApiError(
+ 'run.entry.blockId "b-hook" is not a runnable trigger in the saved workflow. Valid triggers: b-api (API).',
+ 400,
+ 'BAD_REQUEST'
+ )
+ )
+
+ const failure = apply(WORKFLOW_ID, '--dir', dir, '--yes', '--run', 'shopWebhook={"x":1}')
+
+ await expect(failure).rejects.toThrow(
+ /shopWebhook is not a trigger.*name one of api before/
+ )
+ expect(stdoutJson()).toMatchObject({
+ next: { command: `sim workflows source apply --dir ${dir} --run 'api={"x":1}' --yes` },
+ })
+ })
+
+ it('keeps the runs that finished when a later --run cannot be sent', async () => {
+ setTerminal(false)
+ serveTwoTriggers()
+ contextMockFns.mockRequestRaw
+ .mockResolvedValueOnce(runAnswer({ status: 'completed', output: { source: 'api' } }))
+ .mockRejectedValueOnce(new SimApiError('Internal error', 500, 'INTERNAL'))
+
+ const failure = apply(
+ WORKFLOW_ID,
+ '--dir',
+ dir,
+ '--yes',
+ '--run',
+ 'api={}',
+ '--run',
+ 'shopWebhook={}'
+ )
+
+ await expect(failure).rejects.toThrow(/Internal error/)
+ expect(stdoutJson()).toMatchObject({
+ run: { trigger: 'api', status: 'completed', output: { source: 'api' } },
+ })
+ })
+
+ it('runs every --run, and deploys nothing when one fails', async () => {
+ setTerminal(false)
+ serveTwoTriggers()
+ contextMockFns.mockRequestRaw
+ .mockResolvedValueOnce(
+ runAnswer({ status: 'failed', error: { message: 'status is not a string' } })
+ )
+ .mockResolvedValueOnce(runAnswer({ status: 'completed', output: {} }))
+
+ const failure = apply(
+ WORKFLOW_ID,
+ '--dir',
+ dir,
+ '--yes',
+ '--run',
+ 'api={}',
+ '--run',
+ 'shopWebhook={}',
+ '--deploy'
+ )
+
+ await expect(failure).rejects.toThrow(
+ /the test run api failed: status is not a string\. Nothing was deployed\./
+ )
+ expect(contextMockFns.mockRequestRaw).toHaveBeenCalledTimes(2)
+ expect(request.mock.calls.map((call) => call[0])).toEqual([APPLY_PATH])
+ expect(stdoutJson()).toMatchObject({
+ runs: [
+ { trigger: 'api', status: 'failed' },
+ { trigger: 'shopWebhook', status: 'completed' },
+ ],
+ next: {
+ command: `sim workflows source apply --dir ${dir} --run 'api={}' --run 'shopWebhook={}' --deploy --yes`,
+ },
+ })
+ })
+ })
+
it('refuses beside --dry, before sending anything', async () => {
await expect(apply(WORKFLOW_ID, '--dir', dir, '--dry', '--run', '{}')).rejects.toThrow(
/--run test-runs what the write saves, and --dry saves nothing/
diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts
index def1f5fbce6..7b05c86418f 100644
--- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts
+++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts
@@ -80,7 +80,16 @@ import {
writeSourceDirectory,
writeSourceScaffold,
} from './workflow-dir'
-import { printSideEffects, readRunInput, type TestRun, testRunDraft } from './workflow-run-follow'
+import { printSideEffects } from './workflow-run-follow'
+import {
+ type NamedTestRun,
+ type RunOutcome,
+ type RunRequest,
+ readRuns,
+ runFlags,
+ runLabel,
+ runTests,
+} from './workflow-test-runs'
type SourceApplyData = ApplyWorkflowSourceResponse['data']
@@ -91,17 +100,13 @@ interface SourceWriteOptions {
allowDelete?: boolean
verbose?: boolean
deploy?: boolean
- /** `--run [input]`: the test run's input as `--input` takes it, or `true` for none. */
- run?: string | true
+ /** Each `--run [[=]]` as typed, `''` for a bare `--run`. */
+ run?: string[]
+ /** The `--run` values read and checked, before anything is saved. */
+ runs?: RunRequest[]
summaryFile?: string
}
-/** The `--run` flag as written in a next command. */
-function runFlag(run: SourceWriteOptions['run']): string {
- if (run === undefined) return ''
- return run === true ? ' --run' : ` --run ${shellWord(run)}`
-}
-
/**
* Prints a write's diagnostics and, in a display format, its notes (such as a custom tool the
* save could not store; a machine result lists them), each once: after a terminal preview, the
@@ -187,10 +192,11 @@ async function writeWorkflowSource(args:
/** This write as a command, without `--yes`: what a `plan` run names next with it. */
command: string
/**
- * The write to run again once this one is saved, without `--yes`: an apply's own command; a
- * create's is an apply of the workflow it created, whose name a second create finds taken.
+ * The write to run again once this one is saved, with these `--run` values and without `--yes`:
+ * an apply's own command; a create's is an apply of the workflow it created, whose name a
+ * second create finds taken.
*/
- savedCommand: string
+ savedCommand: (run: string[] | undefined) => string
}): Promise {
const { options, creating } = args
assertSendableCodeFiles(args.body.files)
@@ -222,7 +228,11 @@ async function writeWorkflowSource(args:
* Prints the result: a one-line `summary` first and `errors`, `warnings`, `live` and `next`
* last, so both `| head` and `| tail` of a long result (findings, many blocks) show the outcome.
*/
- const report = (data: SourceApplyData, deployment: DeployOutcome = {}, run?: TestRun) => {
+ const report = (
+ data: SourceApplyData,
+ deployment: DeployOutcome = {},
+ runs: readonly NamedTestRun[] = []
+ ) => {
const { live: deployedLive, deployed, next, ...outcome } = deployment
const live = deployedLive ?? liveAgainstDraft(data.deployedVersion, data.needsRedeployment)
publishSummary(() => planMarkdown(data, creating, live), {
@@ -235,9 +245,10 @@ async function writeWorkflowSource(args:
// `deployed.version` is the version the deploy admitted, which may not be live yet: a person
// reads `live` instead, and a machine result keeps the record.
const result = {
- summary: summaryLine(data, creating, { errors, warnings, run, live }),
+ summary: summaryLine(data, creating, { errors, warnings, runs, live }),
...details,
- ...(run ? { run } : {}),
+ // One run keeps the `run` field a single `--run` always had; several are listed in order.
+ ...(runs.length === 1 ? { run: runs[0] } : runs.length > 1 ? { runs } : {}),
...(deployed && findings.machine ? { deployed } : {}),
...outcome,
...findings.result(data.diagnostics),
@@ -247,8 +258,8 @@ async function writeWorkflowSource(args:
...(next ? { next } : {}),
}
// Before the result, so its errors, warnings, live and next stay the last lines printed.
- if (run?.sideEffects && !findings.machine) {
- printSideEffects(run.sideEffects, undefined, data.workflowId)
+ for (const run of findings.machine ? [] : runs) {
+ if (run.sideEffects) printSideEffects(run.sideEffects, undefined, data.workflowId)
}
printProtocolResult(args.output, result, {
...(details.created ? { created: createdText(details.created) } : {}),
@@ -292,35 +303,43 @@ async function writeWorkflowSource(args:
report(data)
return
}
- let run: TestRun | undefined
+ const runs: NamedTestRun[] = []
/** Runs a step after the stored write; a failure prints the write's result first: it stands. */
const afterWrite = async (step: () => Promise): Promise => {
try {
return await step()
} catch (error) {
- report(data, {}, run)
+ report(data, {}, runs)
throw error
}
}
- if (options.run !== undefined) {
- const input = options.run === true ? undefined : options.run
- const test = await afterWrite(() =>
- testRunDraft(args.client, options.dir, data.workflowId, input, args.workspaceId)
+ if (options.runs?.length) {
+ const requests = options.runs
+ const outcomes = await afterWrite(() =>
+ runTests(args.client, {
+ dir: options.dir,
+ workflowId: data.workflowId,
+ workspaceId: args.workspaceId,
+ lock: data.lock,
+ runs: requests,
+ onRun: (run) => runs.push(run),
+ })
)
- run = test.run
- if (test.failure !== undefined) {
+ const failed = outcomes.filter((outcome) => outcome.failure !== undefined)
+ if (failed.length > 0) {
+ const refused = failed.some((outcome) => outcome.refused)
const next = {
- command: `${args.savedCommand} --yes`,
- reason: test.refused
+ command: `${args.savedCommand(outcomes.map((outcome) => outcome.next))} --yes`,
+ reason: refused
? 'applies again and tests it with your fixed --run input'
: 'applies your fix and tests it again',
}
- report(data, { next }, run)
+ report(data, { next }, runs)
const written = data.applied
? `The ${verb} was saved into ${options.dir}, but`
: `Nothing changed: the draft already matched ${options.dir}, and`
throw new SimApiError(
- `${written} the test run ${String(run.status)}: ${asSentence(test.failure)}${options.deploy ? ' Nothing was deployed.' : ''} Fix the ${test.refused ? '--run input' : 'source'}, then run \`${next.command}\`.`,
+ `${written} ${failedRunsText(outcomes)}${options.deploy ? ' Nothing was deployed.' : ''} Fix the ${refused ? '--run input' : 'source'}, then run \`${next.command}\`.`,
0
)
}
@@ -332,12 +351,27 @@ async function writeWorkflowSource(args:
machine: findings.machine,
// Read only without --deploy: an untested draft's next names the tested deploy too.
testedDeploy:
- run === undefined && !creating
- ? `${args.savedCommand} --yes --run '{…}' --deploy`
+ runs.length === 0 && !creating
+ ? `${args.savedCommand(options.run)} --yes --run '{…}' --deploy`
: undefined,
})
)
- report(data, deployment, run)
+ report(data, deployment, runs)
+}
+
+/**
+ * Each run that did not complete, as one sentence: `the test run failed: …` for a lone run, else
+ * each named by its trigger (`the test run api failed: …; the test run #2 …`).
+ */
+function failedRunsText(outcomes: readonly RunOutcome[]): string {
+ const failures = outcomes.flatMap((outcome, index) =>
+ outcome.failure === undefined
+ ? []
+ : [
+ `the test run${outcomes.length > 1 ? ` ${runLabel(outcome.run, index)}` : ''} ${String(outcome.run.status)}: ${outcome.failure.replace(/[.!?]$/, '')}`,
+ ]
+ )
+ return asSentence(failures.join('; '))
}
/** `text` ending as a sentence, so a sentence can follow it. */
@@ -357,7 +391,7 @@ function countOf(data: SourceApplyData, severity: 'error' | 'warning'): number {
function summaryLine(
data: SourceApplyData,
creating: boolean,
- outcome: { errors: number; warnings: number; run?: TestRun; live?: string }
+ outcome: { errors: number; warnings: number; runs: readonly NamedTestRun[]; live?: string }
): string {
const { blocks, edges } = data.diff
const changes = data.diff.noop
@@ -366,11 +400,23 @@ function summaryLine(
return [
`${writeOutcome(data, creating, outcome.errors)}: ${changes}`,
`${outcome.errors} error(s), ${outcome.warnings} warning(s)`,
- ...(outcome.run ? [`test run ${String(outcome.run.status)}`] : []),
+ ...(outcome.runs.length > 0 ? [testRunsClause(outcome.runs)] : []),
...(outcome.live ? [`live: ${outcome.live}`] : []),
].join('; ')
}
+/**
+ * The test runs in a clause: `test run completed` for one, `2 test runs completed` when every one
+ * did, else each by its trigger (`test runs: api failed, shopWebhook completed`).
+ */
+function testRunsClause(runs: readonly NamedTestRun[]): string {
+ if (runs.length === 1) return `test run ${String(runs[0].status)}`
+ if (runs.every((run) => run.status === 'completed')) {
+ return `${runs.length} test runs completed`
+ }
+ return `test runs: ${runs.map((run, index) => `${runLabel(run, index)} ${String(run.status)}`).join(', ')}`
+}
+
/** What a write did, in a word or two. */
function writeOutcome(data: SourceApplyData, creating: boolean, errors: number): string {
if (data.dry) return 'plan'
@@ -571,11 +617,11 @@ function deployFailure(
* invocation with the server options the caller typed ({@link simInvocation}).
*/
function applyCommand(options: SourceWriteOptions, sim: string): string {
- return `${sim} workflows source apply --dir ${shellWord(options.dir)}${options.allowDelete ? ' --allow-delete' : ''}${runFlag(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`
+ return `${sim} workflows source apply --dir ${shellWord(options.dir)}${options.allowDelete ? ' --allow-delete' : ''}${runFlags(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`
}
/**
- * The write options with `--run`'s input read and checked as JSON, before anything is saved: a
+ * The write options with each `--run` input read and checked as JSON, before anything is saved: a
* bad input never leaves a saved draft behind an error. Refuses `--deploy` or `--run` beside
* `--dry`, as a dry run stores nothing to deploy or run.
*/
@@ -585,25 +631,30 @@ async function checkedWriteOptions(options: SourceWriteOptions): Promise {
+ runs.push(value ?? '')
+ command.setOptionValue('run', [...runs])
+ })
.option(
'--deploy',
'After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does)'
@@ -674,7 +725,7 @@ export function attachWorkflowSourceApply(source: Command): void {
creating: false,
question: `Apply these changes to workflow ${workflowId}?`,
command: applyCommand(options, sim),
- savedCommand: applyCommand(options, sim),
+ savedCommand: (run) => applyCommand({ ...options, run }, sim),
output: profile.output,
client,
workspaceId: base.workspaceId,
@@ -750,7 +801,7 @@ export function attachWorkflowSourceCreate(source: Command): void {
const sim = simInvocation(invoked)
/** This create in `workspaceId` as a command, without `--yes`: every flag the caller chose. */
const createLine = (workspaceId: string) =>
- `${createCommand(options.dir, workspaceId, sim)}${options.name !== undefined ? ` --name ${shellWord(options.name)}` : ''}${options.folder !== undefined ? ` --folder ${shellWord(options.folder)}` : ''}${runFlag(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`
+ `${createCommand(options.dir, workspaceId, sim)}${options.name !== undefined ? ` --name ${shellWord(options.name)}` : ''}${options.folder !== undefined ? ` --folder ${shellWord(options.folder)}` : ''}${runFlags(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`
await withSourceCommandLock(
options.dir,
async () => {
@@ -802,7 +853,7 @@ export function attachWorkflowSourceCreate(source: Command): void {
creating: true,
question: 'Create this workflow?',
command: createLine(workspaceId),
- savedCommand: applyCommand(options, sim),
+ savedCommand: (run) => applyCommand({ ...options, run }, sim),
output: profile.output,
client,
operation: 'createWorkflowFromSource',
diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts
index c10decb894a..0cf3da8450f 100644
--- a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts
+++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts
@@ -1409,6 +1409,43 @@ export default workflow('W', {}, () => {
expect(process.exitCode).toBeUndefined()
})
+ it('passes a new condition whose else branch is unwired, as the run ends there, and says it may stay so', async () => {
+ cacheCatalog()
+ writeFileSync(
+ join(dir, 'workflow.ts'),
+ CLEAN.replace('import { response,', 'import { condition, response,').replace(
+ ' start.to(done)',
+ " const route = condition('Route', { paid: 'x > 1', else: true })\n start.to(route)\n route.paid.to(done)"
+ )
+ )
+
+ await check()
+
+ expect(findingLines()).toMatch(
+ /warning W_BRANCH_UNWIRED: Route has no edge from its else branch[\s\S]*hint: .*leave it unwired/
+ )
+ expect(result()).toMatchObject({ errors: 0 })
+ expect(process.exitCode).toBeUndefined()
+ })
+
+ it('names the secret flow on a literal secret in a new webhook trigger, and still fails on it', async () => {
+ cacheCatalog()
+ writeFileSync(
+ join(dir, 'workflow.ts'),
+ CLEAN.replace(
+ "trigger.start('Start', { inputFormat: { message: 'string' } })",
+ "trigger.webhook('Hook', { requireAuth: true, token: 'ordsync-hook-7d41c9', secretHeaderName: 'X-Shop-Token', inputFormat: { message: 'string' } })"
+ )
+ )
+
+ await check()
+
+ expect(findingLines()).toMatch(
+ /error W_LITERAL_SECRET: token holds a literal secret[\s\S]*hint: .*sim secrets set NAME --scope workspace --value @-.*token: env\.NAME/
+ )
+ expect(process.exitCode).toBe(1)
+ })
+
it('passes that stored state on blocks renamed in source, which keep their lock ident', async () => {
cacheCatalog()
writeFileSync(join(dir, 'workflow.ts'), STORED_SHAPES_RENAMED)
diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts
index debb5f90c6b..e775916e4e3 100644
--- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts
+++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts
@@ -30,6 +30,7 @@ import {
type TypesOptions,
typeCheck,
typesFlag,
+ withStaleEnvTypes,
withStaleTableHints,
} from './source-types'
import { verboseFlag } from './source-ui'
@@ -128,7 +129,10 @@ export function attachWorkflowSourceCheck(source: Command): void {
const checked = await typeCheck(options.dir, { enabled, compiled: findings })
types = {
...checked,
- findings: await withStaleTableHints(checked.findings, options.dir),
+ findings: withStaleEnvTypes(
+ await withStaleTableHints(checked.findings, options.dir),
+ options.dir
+ ),
}
}
reportCheck(
diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts
index 6971b3187f6..8b869f81dd8 100644
--- a/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts
+++ b/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts
@@ -145,6 +145,28 @@ describe('sim workflows source find', () => {
expect(stdoutJson().blocks.map((block) => block.name)).toEqual(['Fetch Policy', 'Score'])
})
+ it('prints every block it is named in one call, each once', async () => {
+ await find('Score', 'Audit', 'score')
+ expect(stdoutJson().blocks.map((block) => block.name)).toEqual(['Score', 'Audit'])
+ })
+
+ it("prints a block's declaration and a short function file's text, so it reads without a sed or cat", async () => {
+ await find('Score')
+ expect(stdoutJson().blocks[0]).toMatchObject({
+ declaration: " const score = fn('Score', { code: codeFile('./functions/score.js') })",
+ codeFile: 'functions/score.js',
+ codeText: expect.stringContaining('return $ref.fetchpolicy.data ?? $ref.fetchpolicy.status'),
+ })
+ })
+
+ it('prints the blocks it found before refusing a name no block has', async () => {
+ await expect(find('Score', 'Fetch Polcy')).rejects.toMatchObject({
+ code: 'BLOCK_UNKNOWN',
+ message: expect.stringContaining('Did you mean Fetch Policy?'),
+ })
+ expect(stdoutJson().blocks.map((block) => block.name)).toEqual(['Score'])
+ })
+
it('refuses a name no block has, suggesting the closest', async () => {
await expect(find('Fetch Polcy')).rejects.toMatchObject({
code: 'BLOCK_UNKNOWN',
diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-find.ts b/packages/sim-cli/src/commands/protocol/workflow-source-find.ts
index 1cc5223cacd..cbdc8a27bf2 100644
--- a/packages/sim-cli/src/commands/protocol/workflow-source-find.ts
+++ b/packages/sim-cli/src/commands/protocol/workflow-source-find.ts
@@ -29,17 +29,22 @@ import { lookupCatalog } from './workflow-source-params'
/** The most blocks one find prints, so a broad match stays readable. */
const MAX_FOUND = 20
+/** A function file this short is printed with its block; a longer one is only named. */
+const MAX_CODE_LINES = 30
+
const FIND_HELP = `
-Prints each block the name matches, read from the directory alone (no request is made): its
-declaration in workflow.ts with line numbers, its function file, the wiring statements of its
-incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a
-function file's $ref), each as file:line. is a block name (Security Score), its key
-(securityscore) or its identifier (securityScore); with no exact match, every block whose name
-contains it is printed (at most ${MAX_FOUND}). Run it from a workflow source directory, or pass --dir.
-When the source does not compile, readers are left out (JSON output carries compiles: false).
+Prints each block the names match, read from the directory alone (no request is made): its
+declaration in workflow.ts with line numbers, its function file (its text too, up to
+${MAX_CODE_LINES} lines), the wiring statements of its incoming and outgoing edges, and every block
+that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. Each
+ is a block name (Security Score), its key (securityscore) or its identifier
+(securityScore); with no exact match, every block whose name contains it is printed (at most
+${MAX_FOUND} in all). Name every block a change touches in one call (find 'Refunds Score'
+'Security Fetch Policy'). Run it from a workflow source directory, or pass --dir. When the source
+does not compile, readers are left out (JSON output carries compiles: false).
-Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the
-directory is not a workflow source directory.`
+Exit codes: 0 printed; 1 a name matches no block (the blocks the other names match are printed
+first, and the closest name is suggested), or the directory is not a workflow source directory.`
interface Located {
file: string
@@ -63,7 +68,11 @@ interface FoundBlock extends Located {
ident: string
type: string | null
endLine: number
+ /** The declaration's lines as written, so a machine reader needs no second read of the file. */
+ declaration: string
codeFile: string | null
+ /** The function file's text when it has at most {@link MAX_CODE_LINES} lines. */
+ codeText: string | null
incoming: FoundEdge[]
outgoing: FoundEdge[]
readers: Reader[]
@@ -233,6 +242,14 @@ function statementText(index: SourceIndex, span: SourceSpan): string {
}, '')
}
+/** A function file's text when it is short enough to print beside its block, else `null`. */
+function shortCodeText(index: SourceIndex, codeFile: string | null): string | null {
+ const lines = codeFile ? index.linesOf(codeFile) : null
+ if (!lines) return null
+ const count = lines.lines.length - (lines.lines.at(-1) === '' ? 1 : 0)
+ return count > MAX_CODE_LINES ? null : lines.text
+}
+
function describeBlock(
index: SourceIndex,
readers: ReadonlyMap,
@@ -251,6 +268,7 @@ function describeBlock(
statement: written ? statementText(index, written) : '',
}
}
+ const codeFile = index.codeFileOf(key)
const ends = (side: 'from' | 'to', other: 'from' | 'to') =>
edges.flatMap((ref, at) => (ref[side] === key ? [edge(at, ref[other])] : [])).sort(byLine)
return {
@@ -261,22 +279,32 @@ function describeBlock(
file: span?.file ?? SOURCE_ENTRY_FILE,
line: span?.line ?? 0,
endLine: span?.endLine ?? 0,
- codeFile: index.codeFileOf(key),
+ declaration: span
+ ? (index
+ .linesOf(span.file)
+ ?.lines.slice(span.line - 1, span.endLine)
+ .join('\n') ?? '')
+ : '',
+ codeFile,
+ codeText: shortCodeText(index, codeFile),
incoming: ends('to', 'from'),
outgoing: ends('from', 'to'),
readers: [...(readers.get(key) ?? [])].sort(byLine),
}
}
-function printFound(index: SourceIndex, found: FoundBlock): void {
+/** `lines` numbered from `first`, the numbers padded to one width. */
+function printNumbered(lines: readonly string[], first: number, indent: string): void {
+ const width = String(first + lines.length - 1).length
+ lines.forEach((text, at) => printLine(`${indent}${String(first + at).padStart(width)} ${text}`))
+}
+
+function printFound(found: FoundBlock): void {
const kind = found.type ? `${found.type}, ` : ''
printLine(`${found.name} (${kind}key ${found.key}, ${found.ident})`)
- const lines = index.linesOf(found.file)?.lines ?? []
- const width = String(found.endLine).length
- for (let line = Math.max(found.line, 1); line <= found.endLine; line += 1) {
- printLine(`${String(line).padStart(width)} ${lines[line - 1] ?? ''}`)
- }
+ if (found.declaration !== '') printNumbered(found.declaration.split('\n'), found.line, '')
if (found.codeFile) printLine(`code: ${found.codeFile}`)
+ if (found.codeText !== null) printNumbered(found.codeText.replace(/\n$/, '').split('\n'), 1, ' ')
const section = (label: string, rows: string[]) => {
printLine(rows.length === 0 ? `${label}: none` : `${label}:`)
for (const row of rows) printLine(` ${row}`)
@@ -293,29 +321,34 @@ function printFound(index: SourceIndex, found: FoundBlock): void {
}
/**
- * `sim workflows source find [--dir ]`: one block's code, function file, edges and
- * readers with their lines, from the directory alone, so locating a block in a long workflow is
- * one command instead of rounds of search.
+ * `sim workflows source find [--dir ]`: each named block's code, function file,
+ * edges and readers with their lines, from the directory alone, so locating the blocks a change
+ * touches in a long workflow is one command instead of rounds of search. A name that matches no
+ * block is refused after the blocks the other names match are printed.
*/
export function attachWorkflowSourceFind(source: Command): void {
source
.command('find')
- .argument('', 'Block name, key or identifier; a part of a name matches every block')
+ .argument(
+ '',
+ 'Block names, keys or identifiers; a part of a name matches every block'
+ )
.option('--dir ', 'Workflow source directory to read', '.')
- .allowExcessArguments(false)
- .description("Print a block's declaration, edges and readers with line numbers (offline)")
+ .description("Print blocks' declarations, edges and readers with line numbers (offline)")
.addHelpText('after', FIND_HELP)
- .action(async (query: string, options: { dir: string }, command: Command) => {
+ .action(async (queries: string[], options: { dir: string }, command: Command) => {
const profile = actingProfileFrom(command)
await assertSourceDirKind(options.dir, 'workflow')
const catalog = await lookupCatalog(options.dir, profile)
const { compiled, files } = await compileWorkflowDir(options.dir, catalog)
- if (normalizeWorkflowBlockName(query) === '') {
+ if (queries.some((query) => normalizeWorkflowBlockName(query) === '')) {
throw new CliUsageError('Name a block.', { code: 'BLOCK_UNKNOWN' })
}
const index = new SourceIndex(compiled, files)
- const keys = matchBlocks(index, query)
- if (keys.length === 0) throw unknownBlock(index, query)
+ const matched = queries.map((query) => ({ query, keys: matchBlocks(index, query) }))
+ const keys = [...new Set(matched.flatMap((match) => match.keys))]
+ const unknown = matched.find((match) => match.keys.length === 0)
+ if (keys.length === 0 && unknown) throw unknownBlock(index, unknown.query)
const readers = readersByKey(index)
const found = keys
.slice(0, MAX_FOUND)
@@ -328,15 +361,16 @@ export function attachWorkflowSourceFind(source: Command): void {
compiles: compiled.workflow !== null,
...(more > 0 ? { more } : {}),
})
- return
- }
- if (compiled.workflow === null) {
- printLine('The source has compile errors, so readers are left out: run `source check`.')
+ } else {
+ if (compiled.workflow === null) {
+ printLine('The source has compile errors, so readers are left out: run `source check`.')
+ }
+ found.forEach((block, position) => {
+ if (position > 0) printLine('')
+ printFound(block)
+ })
+ if (more > 0) printLine(`\n${more} more blocks match; name one exactly to print it.`)
}
- found.forEach((block, position) => {
- if (position > 0) printLine('')
- printFound(index, block)
- })
- if (more > 0) printLine(`\n${more} more blocks match; name one exactly to print it.`)
+ if (unknown) throw unknownBlock(index, unknown.query)
})
}
diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts
index cdf80b49b1a..4921b481d3d 100644
--- a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts
+++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts
@@ -163,6 +163,7 @@ beforeEach(() => {
})
afterEach(() => {
+ process.exitCode = undefined
rmSync(rootDir, { recursive: true, force: true })
})
@@ -337,6 +338,20 @@ describe('sim workflows source get --dir', () => {
expect(agents).not.toContain('`slack.sendMessage`')
})
+ it('tells the guide of a long source to read the blocks a change names with one find, and a short one nothing', async () => {
+ const block = (at: number) => `const step${at} = fn('Step ${at}', {})\n`
+ const long = `// @sim-sdk 1\n${Array.from({ length: 400 }, (_, at) => block(at)).join('')}`
+ serve({ [SOURCE_PATH]: () => source({ 'workflow.ts': long }) })
+ await get('--dir', outDir)
+ expect(readFileSync(join(outDir, '.sim/AGENTS.md'), 'utf8')).toMatch(
+ /`sim workflows source find '' '' --dir \.`/
+ )
+
+ serve({ [SOURCE_PATH]: () => source({ 'workflow.ts': `// @sim-sdk 1\n${block(1)}` }) })
+ await get('--dir', outDir, '--force')
+ expect(readFileSync(join(outDir, '.sim/AGENTS.md'), 'utf8')).not.toContain('source find')
+ })
+
it("names the primer's edit loop: the test run and deploy for a coding agent, the apply alone in Mothership", async () => {
serve()
const editLoop = async (...args: string[]) => {
@@ -750,6 +765,60 @@ describe('sim workflows source get --dir', () => {
])
})
+ it('passes an env name set since the get, which the types it wrote lack, with a warning naming the refresh', async () => {
+ const workflow = [
+ '// @sim-sdk 1',
+ "import { trigger, workflow } from '@sim/workflow-sdk'",
+ '',
+ "export default workflow('W', {}, () => {",
+ " const hook = trigger.webhook('Hook', { requireAuth: true, token: env.OPENAI_KEY })",
+ '})',
+ '',
+ ].join('\n')
+ serve({
+ [SOURCE_PATH]: () => source({ 'workflow.ts': workflow }, ['generic_webhook']),
+ [MANIFEST_PATH]: () => ({ data: { ...MANIFEST.data, env: ['OPENAI_KEY'] } }),
+ })
+ await get('--dir', outDir)
+ writeFileSync(
+ join(outDir, 'workflow.ts'),
+ workflow
+ .replace('{ trigger, workflow }', '{ env, trigger, workflow }')
+ .replace('env.OPENAI_KEY', 'env.SHOP_TOKEN')
+ )
+ contextMockFns.mockProfileFrom.mockReturnValue({
+ ...mockedProfile(),
+ workspaceId: WORKSPACE_ID,
+ output: 'json',
+ })
+ const check = new Command('source')
+ attachWorkflowSourceCheck(check)
+ check.commands.forEach((command) => command.exitOverride())
+ await check.parseAsync(['node', 'source', 'check', '--dir', outDir])
+
+ expect(process.exitCode).toBeUndefined()
+ const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}')
+ expect(printed.checked).toEqual(['compile', 'types'])
+ expect(printed.errors).toBe(0)
+ expect(printed.diagnostics).toContainEqual(
+ expect.objectContaining({
+ severity: 'warning',
+ file: 'workflow.ts',
+ line: 5,
+ message: expect.stringContaining('env.SHOP_TOKEN'),
+ hint: expect.stringContaining(`sim workflows source status --dir ${outDir}`),
+ })
+ )
+
+ writeFileSync(
+ join(outDir, 'workflow.ts'),
+ readFileSync(join(outDir, 'workflow.ts'), 'utf8').replace('SHOP_TOKEN', 'OPENAI_KYE')
+ )
+ await check.parseAsync(['node', 'source', 'check', '--dir', outDir])
+ expect(process.exitCode).toBe(1)
+ process.exitCode = undefined
+ })
+
it('writes the example workflows beside the guide, outside what the tsconfig files type-check', async () => {
serve()
diff --git a/packages/sim-cli/src/commands/protocol/workflow-test-runs.ts b/packages/sim-cli/src/commands/protocol/workflow-test-runs.ts
new file mode 100644
index 00000000000..7f0c4d13c8f
--- /dev/null
+++ b/packages/sim-cli/src/commands/protocol/workflow-test-runs.ts
@@ -0,0 +1,202 @@
+/**
+ * The `--run` test runs of a workflow source write: each `--run [=]` read before
+ * anything is saved, then run in turn against the saved draft through the trigger it names, so a
+ * workflow with an API and a webhook trigger tests both paths in one apply.
+ */
+import { parseWorkflowLock } from '@sim/workflow-code'
+import type { OperationClient } from '../../runtime/called-operations'
+import { shellWord } from './source-ui'
+import { type DraftTest, readRunInput, type TestRun, testRunDraft } from './workflow-run-follow'
+
+/** One `--run` as written, and what it asks for. */
+export interface RunRequest {
+ /** The value as typed, `''` for a bare `--run`: what a next command repeats. */
+ raw: string
+ /** The trigger it enters through: its const, block key or id. Unset: the workflow's only one. */
+ trigger?: string
+ /** The input as `--input` takes it (JSON, or `@file`); unset: none. */
+ input?: string
+}
+
+/** A `--run` test as a write's result shows it: the trigger it named, then the run. */
+export type NamedTestRun = TestRun & { trigger?: string }
+
+/** A `--run` run in turn: its result, why it did not complete, and the `--run` to repeat next. */
+export interface RunOutcome extends DraftTest {
+ run: NamedTestRun
+ /** The `--run` value the next command repeats: a trigger the refusal pointed at, else `raw`. */
+ next: string
+}
+
+/** How an input starts: a JSON object, array or string, or `@file`. */
+const INPUT_START = /^\s*[{["@]/
+
+/** Whether `raw` parses as JSON: a number or `true`, `false`, `null` is input too. */
+function isJson(raw: string): boolean {
+ try {
+ JSON.parse(raw)
+ return true
+ } catch {
+ return false
+ }
+}
+
+/** The server's refusal of a run that names no trigger where the workflow has several. */
+const SEVERAL_TRIGGERS = /multiple runnable triggers/
+
+/** The server's refusal of a run through a block that is no runnable trigger. */
+const NOT_A_TRIGGER = /is not a runnable trigger/
+
+/**
+ * `--run [=]`: `` alone runs it without input, a bare `--run` too. JSON or
+ * `@file` is the input; anything else names a trigger (its const, block key or id) before the
+ * first `=`, so a block key of any characters (`shopwebhook~2`) or a UUID id is named as written.
+ */
+function parseRun(raw: string): RunRequest {
+ if (raw === '') return { raw }
+ if (INPUT_START.test(raw) || isJson(raw)) return { raw, input: raw }
+ const at = raw.indexOf('=')
+ const trigger = at === -1 ? raw : raw.slice(0, at)
+ const input = at === -1 ? '' : raw.slice(at + 1)
+ return input === '' ? { raw, trigger } : { raw, trigger, input }
+}
+
+/**
+ * Each `--run` value parsed, its input read as `--input` reads it (JSON, or `@file`) and checked
+ * to parse, so a bad one is refused before anything is saved rather than after.
+ */
+export async function readRuns(values: readonly string[] | undefined): Promise {
+ return Promise.all(
+ (values ?? []).map(async (value) => {
+ const run = parseRun(value)
+ if (run.input === undefined) return run
+ const label = run.trigger === undefined ? '--run' : `--run ${run.trigger}`
+ return {
+ ...run,
+ input: await readRunInput(run.input, `${label}: its input is not JSON. Nothing was saved.`),
+ }
+ })
+ )
+}
+
+/** The `--run` flags of `values` as a next command writes them. */
+export function runFlags(values: readonly string[] | undefined): string {
+ return (values ?? [])
+ .map((value) => (value === '' ? ' --run' : ` --run ${shellWord(value)}`))
+ .join('')
+}
+
+/** A block of the saved lock by the names a `--run` may give it: its const, key and id. */
+interface LockBlock {
+ id: string
+ ident: string
+ key: string
+}
+
+/** Each block of the saved lock by the names a `--run` may give it. */
+function lockBlocks(lock: unknown): LockBlock[] {
+ const blocks = parseWorkflowLock(lock).lock?.blocks ?? {}
+ return Object.entries(blocks).map(([key, block]) => ({ id: block.id, ident: block.ident, key }))
+}
+
+/** The id of the block `name` is in the saved lock, or `name` itself for the server to judge. */
+function triggerId(blocks: readonly LockBlock[], name: string): string {
+ const match =
+ blocks.find((block) => block.ident === name) ??
+ blocks.find((block) => block.key === name || block.id === name)
+ return match?.id ?? name
+}
+
+/** The consts of the triggers a refusal lists by id, in its order, but the block `refusedId`. */
+function listedTriggers(
+ message: string,
+ blocks: readonly LockBlock[],
+ refusedId: string | undefined
+): string[] {
+ return blocks
+ .filter((block) => block.id !== refusedId && message.includes(block.id))
+ .sort((a, b) => message.indexOf(a.id) - message.indexOf(b.id))
+ .map((block) => block.ident)
+}
+
+/**
+ * A refused run's failure in `--run` terms: the server names triggers by id and asks for
+ * `run.entry.blockId`, which a `--run` writes as `=`. Returns the failure and the
+ * `--run` value a next command repeats: its input through the first listed trigger.
+ */
+function triggerRefusal(
+ request: RunRequest,
+ message: string,
+ blocks: readonly LockBlock[],
+ refusedId: string | undefined
+): { failure: string; next: string } | undefined {
+ const triggers = listedTriggers(message, blocks, refusedId)
+ if (triggers.length === 0) return undefined
+ if (request.trigger === undefined && SEVERAL_TRIGGERS.test(message)) {
+ const [first, ...others] = triggers
+ const next = `${first}=${request.raw}`
+ return {
+ failure: `the workflow has more than one trigger (${triggers.join(', ')}), so name the one each --run enters through: --run ${shellWord(next)}${others.length > 0 ? ` (or ${others.map((other) => `${other}=`).join(', ')})` : ''}`,
+ next,
+ }
+ }
+ if (request.trigger !== undefined && NOT_A_TRIGGER.test(message)) {
+ return {
+ failure: `${request.trigger} is not a trigger of this workflow; name one of ${triggers.join(', ')} before = in --run`,
+ next: `${triggers[0]}${request.raw.slice(request.trigger.length)}`,
+ }
+ }
+ return undefined
+}
+
+/**
+ * Runs each `--run` in turn against the saved draft of `workflowId`, through the trigger it names
+ * (found in the saved `lock`, so a trigger the write just added is found too). Every run is made,
+ * whatever an earlier one did, so one apply reports both a happy and a failure path. `onRun`
+ * gets each run as it ends, so a later run that cannot be sent still leaves the earlier reported.
+ */
+export async function runTests(
+ client: OperationClient<'executeWorkflow'>,
+ args: {
+ dir: string
+ workflowId: string
+ workspaceId: string
+ lock: unknown
+ runs: readonly RunRequest[]
+ onRun: (run: NamedTestRun) => void
+ }
+): Promise {
+ const blocks = lockBlocks(args.lock)
+ const outcomes: RunOutcome[] = []
+ for (const request of args.runs) {
+ const entryId = request.trigger === undefined ? undefined : triggerId(blocks, request.trigger)
+ const test = await testRunDraft(
+ client,
+ args.dir,
+ args.workflowId,
+ request.input,
+ args.workspaceId,
+ entryId
+ )
+ const named = request.trigger === undefined ? {} : { trigger: request.trigger }
+ const refusal = test.refused
+ ? triggerRefusal(request, String(test.run.error), blocks, entryId)
+ : undefined
+ const outcome: RunOutcome = refusal
+ ? {
+ ...test,
+ run: { ...named, ...test.run, error: refusal.failure },
+ failure: `the server refused it before it started: ${refusal.failure}`,
+ next: refusal.next,
+ }
+ : { ...test, run: { ...named, ...test.run }, next: request.raw }
+ outcomes.push(outcome)
+ args.onRun(outcome.run)
+ }
+ return outcomes
+}
+
+/** How a run is named among several: its trigger, else its place (`#2`). */
+export function runLabel(run: NamedTestRun, index: number): string {
+ return run.trigger ?? `#${index + 1}`
+}
diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md
index 28a4322c0b3..4a898db5ac6 100644
--- a/packages/workflow-code/src/compile/SYNTAX.md
+++ b/packages/workflow-code/src/compile/SYNTAX.md
@@ -432,7 +432,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio
| `W_SUBFLOW_HANDLE_SCOPE` | `edge()` from a loop or parallel's start handle to a block outside it (the executor runs it as the container's exit), or from another of its handles into its own child. The canvas never draws one; stored ones print this way so they round-trip. |
| `E_EDGE_CYCLE` | Wiring that closes a cycle among enabled blocks, a self-loop included: no block on it ever runs. Framed at the edge back to a block declared earlier, the one to remove; repeat work with `loop()`/`parallel()`. |
| `W_EDGE_CYCLE` | A cycle the stored workflow already holds, kept so it round-trips; none of it runs. An offline check reports it for a cycle among blocks the lock binds, which an apply keeps only if the stored workflow holds every edge of it. |
-| `W_BRANCH_UNWIRED` | A condition or router branch no edge leaves, so a run that takes it ends there; the hint names the wiring. Not reported for a branch the stored workflow already leaves unwired. |
+| `W_BRANCH_UNWIRED` | A condition or router branch no edge leaves, so a run that takes it ends there and completes: right for an `else` that should do nothing, so it is never more than a warning; the hint names the wiring. Not reported for a branch the stored workflow already leaves unwired. |
| `E_UNKNOWN_BUILDER` | A builder path the catalog does not have, a bare builder-shaped call (`apii('Name', …)`) nothing binds, or a namespace the SDK lacks or the file did not import; `hint` names the builder a common other name stands for (`http.request` → `api`), then prefers a synonymous verb (`postMessage` → `sendMessage`), then the closest path, then the namespace's builders. |
| `E_UNKNOWN_PARAM` | A param the block does not have; the hint has a did-you-mean, or for block meta written there (`retry`, `disabled`, `locked`, `errorPort`) the third argument that takes it. |
| `E_FIXED_PARAM` | A param the builder already pins. |
diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts
index a0c4ad856dd..afc0dffee7b 100644
--- a/packages/workflow-code/src/compile/checks.test.ts
+++ b/packages/workflow-code/src/compile/checks.test.ts
@@ -496,7 +496,9 @@ describe('unwired branches', () => {
expect(unwired?.message).toBe(
'Route has no edge from its else branch, so a run that takes it ends there.'
)
- expect(unwired?.hint).toBe('Wire it: route.else.to(...).')
+ expect(unwired?.hint).toBe(
+ 'If that path should do nothing, leave it unwired (no block needed); else wire it: route.else.to(...).'
+ )
})
it('stays quiet when every branch is wired', () => {
diff --git a/packages/workflow-code/src/compile/edges.ts b/packages/workflow-code/src/compile/edges.ts
index b8d39dbc1f4..2a2b816520f 100644
--- a/packages/workflow-code/src/compile/edges.ts
+++ b/packages/workflow-code/src/compile/edges.ts
@@ -284,9 +284,11 @@ export class EdgeCollector {
}
/**
- * Reports each condition or router branch row no edge leaves: a run that takes it ends there,
- * which a source author rarely means. A branch the stored workflow holds unwired on the same
- * block stays quiet, so a canvas-built workflow keeps compiling without new warnings.
+ * Reports each condition or router branch row no edge leaves: a run that takes it ends there
+ * and completes (the executor treats the chosen branch as a dead end), which is right for an
+ * `else` that should do nothing but a slip for a branch meant to act. A branch the stored
+ * workflow holds unwired on the same block stays quiet, so a canvas-built workflow keeps
+ * compiling without new warnings.
*/
reportUnwiredBranches(stored: CanonicalWorkflow | undefined): void {
const wiredIn = (edges: readonly CanonicalEdge[]) =>
@@ -310,7 +312,10 @@ export class EdgeCollector {
'W_BRANCH_UNWIRED',
`${decl.name} has no edge from its ${branch} branch, so a run that takes it ends there.`,
rangeOf(this.ctx, decl.anchorNode),
- { hint: `Wire it: ${decl.ident ?? 'block'}.${branch}.to(...).`, blockKey: key }
+ {
+ hint: `If that path should do nothing, leave it unwired (no block needed); else wire it: ${decl.ident ?? 'block'}.${branch}.to(...).`,
+ blockKey: key,
+ }
)
}
}