diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 3ddc7276894..7404db340a7 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8518,7 +8518,7 @@ sim workflows run [options] | `--draft` | No | Run the saved draft instead of the active deployment, sending its writes. | | `--deployment-version ` | No | Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --draft or any flag that runs the draft. | | `--dry` | No | Dry run of the saved draft (implies --draft): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | -| `--allow ` | No | Send this block's writes for real during a dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls.; repeatable. | +| `--allow ` | No | Send this block's writes for real during a dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | | `--mock =` | No | Answer this block with the given JSON object instead of running it during a dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock <block> takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only (the API reference lists the fields a mock cannot set). The run records only which blocks were mocked, not the outputs, so a rerun reads them again with --mock-from; repeatable. | | `--mock-from ` | No | Answer each block a bare --mock <block> names with the output it recorded in this earlier run of the workflow, redacted as the run shows it: this workflow's blocks (not a child's; not inside a loop or parallel unless that run mocked it); fields a mock cannot set, such as cost or model, are left out. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the saved draft (implies --draft). | @@ -8536,7 +8536,7 @@ sim workflows run [options] Without --draft (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --draft runs the saved draft, as the source loop leaves it, sending its writes. ---dry runs the saved draft without its writes: each call that could change something (a write tool, any MCP call, an HTTP request other than GET/HEAD/OPTIONS, code's other fetches) gets a placeholder (ids like dry_run_row_1, numbers above 900000000) and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. A read that would send a placeholder is held back too (reason placeholder), and an MCP call its server calls read-only says so (reason mcp-read-only). Reads, model calls and code run for real; code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. --allow <block> sends that block's writes for real (use a test resource). --mock <block>=<json> answers a block with fixed output, to steer a branch; --mock-from <runId> with a bare --mock <block> answers it with the output that run recorded. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block>. --allow, --mock and --mock-from imply --dry; --draft sends every write, so it refuses them. Overrides the run never reached are listed in sideEffects.unreached, and mock fields a block never gets in sideEffects.mockFields. The API reference describes each list and refusal. +--dry runs the saved draft without its writes: each call that could change something (a write tool, any MCP call, an HTTP request other than GET/HEAD/OPTIONS, code's other fetches) gets a placeholder (ids like dry_run_row_1, numbers above 900000000) and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. A read that would send a placeholder is held back too (reason placeholder), and an MCP call its server calls read-only says so (reason mcp-read-only). Reads, model calls and code run for real; code in a remote sandbox (shell, Python, imports) runs for real too, its network requests included, and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. --allow <block> sends that block's writes for real (use a test resource). --mock <block>=<json> answers a block with fixed output, to steer a branch; --mock-from <runId> with a bare --mock <block> answers it with the output that run recorded. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block>. --allow, --mock and --mock-from imply --dry; --draft sends every write, so it refuses them. Overrides the run never reached are listed in sideEffects.unreached, and mock fields a block never gets in sideEffects.mockFields. The API reference describes each list and refusal. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. @@ -8675,7 +8675,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. | +| `--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. | | `--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. | +| `--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. | | `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). | @@ -8841,7 +8841,7 @@ Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one i ### sim workflows source find -Print a block's code, edges and readers with line numbers (offline) +Print a block's declaration, edges and readers with line numbers (offline) ```bash sim workflows source find [options] @@ -10125,7 +10125,7 @@ sim workspaces source apply [options] | `--delete-target-only` | No | With --to and --allow-delete, also delete the target's resources this directory never declared and no promotion from it left there (prod-only tables and their rows, skills made in prod). Without it a promotion keeps them, naming each with a warning. | | `--only ` | No | Apply only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--to ` | No | Promote the directory to another workspace (dev to prod): its resources bind by key to that workspace's own and are updated in place. Only .sim/targets/<workspaceId>.json changes, the record the next promotion compares with: a resource changed there since is kept, or refused as stale (exit 5) when the directory changed it too. | -| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. | +| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked. | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index db507500e8c..7b94f23fc94 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -835,7 +835,7 @@ sim workflows run [options] | `--draft` | No | Run the saved draft instead of the active deployment, sending its writes. | | `--deployment-version ` | No | Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --draft or any flag that runs the draft. | | `--dry` | No | Dry run of the saved draft (implies --draft): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | -| `--allow ` | No | Send this block's writes for real during a dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls.; repeatable. | +| `--allow ` | No | Send this block's writes for real during a dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | | `--mock =` | No | Answer this block with the given JSON object instead of running it during a dry run (its id, display name or key, or <workflow>.<block> for a workflow it calls), to steer a branch or give a stubbed write a realistic result; a bare --mock <block> takes its output from --mock-from. Not a locked block, or one of a locked workflow or folder; data only (the API reference lists the fields a mock cannot set). The run records only which blocks were mocked, not the outputs, so a rerun reads them again with --mock-from; repeatable. | | `--mock-from ` | No | Answer each block a bare --mock <block> names with the output it recorded in this earlier run of the workflow, redacted as the run shows it: this workflow's blocks (not a child's; not inside a loop or parallel unless that run mocked it); fields a mock cannot set, such as cost or model, are left out. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the saved draft (implies --draft). | @@ -853,7 +853,7 @@ sim workflows run [options] Without --draft (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --draft runs the saved draft, as the source loop leaves it, sending its writes. ---dry runs the saved draft without its writes: each call that could change something (a write tool, any MCP call, an HTTP request other than GET/HEAD/OPTIONS, code's other fetches) gets a placeholder (ids like dry_run_row_1, numbers above 900000000) and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. A read that would send a placeholder is held back too (reason placeholder), and an MCP call its server calls read-only says so (reason mcp-read-only). Reads, model calls and code run for real; code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. --allow <block> sends that block's writes for real (use a test resource). --mock <block>=<json> answers a block with fixed output, to steer a branch; --mock-from <runId> with a bare --mock <block> answers it with the output that run recorded. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block>. --allow, --mock and --mock-from imply --dry; --draft sends every write, so it refuses them. Overrides the run never reached are listed in sideEffects.unreached, and mock fields a block never gets in sideEffects.mockFields. The API reference describes each list and refusal. +--dry runs the saved draft without its writes: each call that could change something (a write tool, any MCP call, an HTTP request other than GET/HEAD/OPTIONS, code's other fetches) gets a placeholder (ids like dry_run_row_1, numbers above 900000000) and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. A read that would send a placeholder is held back too (reason placeholder), and an MCP call its server calls read-only says so (reason mcp-read-only). Reads, model calls and code run for real; code in a remote sandbox (shell, Python, imports) runs for real too, its network requests included, and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. --allow <block> sends that block's writes for real (use a test resource). --mock <block>=<json> answers a block with fixed output, to steer a branch; --mock-from <runId> with a bare --mock <block> answers it with the output that run recorded. --allow and --mock also name a block of a workflow this one calls as <workflow>.<block>. --allow, --mock and --mock-from imply --dry; --draft sends every write, so it refuses them. Overrides the run never reached are listed in sideEffects.unreached, and mock fields a block never gets in sideEffects.mockFields. The API reference describes each list and refusal. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. @@ -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. | +| `--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. | | `--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. | +| `--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. | | `--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. | @@ -1571,7 +1571,7 @@ 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 code, edges and readers with line numbers +### Print a block's declaration, edges and readers with line numbers Offline. diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 217965fcb56..bb48be0d59f 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -759,7 +759,7 @@ sim workspaces source apply [options] | `--delete-target-only` | No | With --to and --allow-delete, also delete the target's resources this directory never declared and no promotion from it left there (prod-only tables and their rows, skills made in prod). Without it a promotion keeps them, naming each with a warning. | | `--only ` | No | Apply only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--to ` | No | Promote the directory to another workspace (dev to prod): its resources bind by key to that workspace's own and are updated in place. Only .sim/targets/<workspaceId>.json changes, the record the next promotion compares with: a resource changed there since is kept, or refused as stale (exit 5) when the directory changed it too. | -| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. | +| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked. | diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx index d76d8a07e23..b66da76a980 100644 --- a/apps/docs/content/docs/workflows/code/coding-agents.mdx +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -8,7 +8,7 @@ Claude Code, Cursor, Codex and other coding agents work from a directory that `g ## What get gives an agent - A **primer**, which opens `.sim/AGENTS.md`. `get` prints a short summary instead (the files written, the guide, and the `editLoop` command to run). It covers the edit loop, how block identity, references and renames work, failures and retries, test runs, deletes, deploy, exit codes, and the params of each builder the workflow already uses. -- **`.sim/AGENTS.md`**: the primer followed by a reference, by task. A workspace directory also gets `.sim/GUIDE-advanced.md`. +- **`.sim/AGENTS.md`**: the primer followed by a reference, by task. **`.sim/GUIDE-advanced.md`** beside it has the rest, by task, in a workflow directory and a workspace directory alike. - **`.sim/examples/`**: one correct example of each common block to copy from. - **`.sim/sdk/`**: the type declarations, with `.sim/sdk/INDEX.md` listing the builders. diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx index cbd3060b1e0..6a83edcf0e5 100644 --- a/apps/docs/content/docs/workflows/code/diagnostics.mdx +++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx @@ -93,6 +93,7 @@ Reading and writing `workflow.ts`. | `E_CODE_FILE_PATH` | A code file path outside the directory, or with the wrong extension. | | `W_CODE_FILE_INLINED` | Print: the code could not round-trip through a file and was inlined. | | `W_CODE_FILE_REF_SYNTAX` | `$ref.key.path` or `$env.NAME` in a Python or shell code file, which runs as text; the hint names the `` or `{{NAME}}` form. Refused as `E_APPLY_CODE_FILE_REF_SYNTAX` in a file the edit changed. | +| `W_CODE_FILE_REF_QUOTED` | A `` tag between quotes of its own in a Python code file (`""`): the run substitutes it as a Python literal, so a string value arrives with its quotes in it. Remove the quotes. A file's path (`open('')`), spliced raw, is not reported. | | `W_UNRESOLVED_REF` | Print: a stored `` token that resolves to nothing. Compile: a code file `$ref` chain that does. Either is kept as text. | | `W_FORWARD_REF_LITERALIZED` | Print: a ref in a cycle printed as text. | | `W_COMMENT_MOVED` | A comment hoisted to the nearest anchor. | diff --git a/apps/docs/content/docs/workflows/code/directory.mdx b/apps/docs/content/docs/workflows/code/directory.mdx index 617d4d7b861..3bd416acb86 100644 --- a/apps/docs/content/docs/workflows/code/directory.mdx +++ b/apps/docs/content/docs/workflows/code/directory.mdx @@ -19,6 +19,7 @@ description: Every file a workflow directory and a workspace directory holds, wh | `.sim/stored-edges.json` | The connections the stored workflow held when it was printed, so an offline `check` tells them from connections you added. The CLI's own record, never sent | Commit | | `.sim/starter.json` | The workspace a starter was written for, before `create` | Not kept: removed once the workflow exists | | `.sim/AGENTS.md` | The guide for coding agents: the primer, then a reference | Optional, written again by `get` | +| `.sim/GUIDE-advanced.md` | The rest of the guide, by task: the edit loop step by step and what a dry run stubs, a new workflow or a fork, finding a builder and its types, the rules, and every diagnostic and exit code | Optional, written again by `get` | | `.sim/examples/` | Example workflows to copy from | Optional, written again by `get` | | `.sim/sdk/` | Type declarations for the blocks the workflow uses, and your workspace's tables, credentials, knowledge bases and environment variable names. `.sim/sdk/INDEX.md` lists the builders | Optional, written again by `get` and `check` | | `tsconfig.json` | Resolves the declarations and type-checks the blocks the workflow uses. Left as it is if you already have one | Commit | diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index ed5a2685d53..92fb0894f75 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -19787,6 +19787,7 @@ "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", "W_CODE_FILE_REF_SYNTAX", + "W_CODE_FILE_REF_QUOTED", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -20264,6 +20265,7 @@ "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", "W_CODE_FILE_REF_SYNTAX", + "W_CODE_FILE_REF_QUOTED", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -21246,6 +21248,7 @@ "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", "W_CODE_FILE_REF_SYNTAX", + "W_CODE_FILE_REF_QUOTED", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -22204,6 +22207,7 @@ "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", "W_CODE_FILE_REF_SYNTAX", + "W_CODE_FILE_REF_QUOTED", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -27269,6 +27273,7 @@ "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", "W_CODE_FILE_REF_SYNTAX", + "W_CODE_FILE_REF_QUOTED", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -27855,6 +27860,7 @@ "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", "W_CODE_FILE_REF_SYNTAX", + "W_CODE_FILE_REF_QUOTED", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -28271,6 +28277,7 @@ "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", "W_CODE_FILE_REF_SYNTAX", + "W_CODE_FILE_REF_QUOTED", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -29137,6 +29144,7 @@ "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", "W_CODE_FILE_REF_SYNTAX", + "W_CODE_FILE_REF_QUOTED", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -29553,6 +29561,7 @@ "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", "W_CODE_FILE_REF_SYNTAX", + "W_CODE_FILE_REF_QUOTED", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", diff --git a/apps/sim/executor/variables/resolver.ts b/apps/sim/executor/variables/resolver.ts index c54a58557be..08e7b299e5c 100644 --- a/apps/sim/executor/variables/resolver.ts +++ b/apps/sim/executor/variables/resolver.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' +import { isFilePathReference } from '@sim/utils/workflow-references' import { JSON_TEXT_CONTAINER_TYPES } from '@sim/workflow-code/json-text' import { isUserFileWithMetadata } from '@/lib/core/utils/user-file' import { mergeLargeValueKeys } from '@/lib/execution/payloads/access-keys' @@ -862,10 +863,10 @@ export class VariableResolver { matchIndex: number, contextVarAccumulator: Record ): Promise<{ replacement: string; display: string } | null> { - const parts = parseReferencePath(reference) - if (parts.length < 3 || parts.at(-1) !== 'path') { + if (!isFilePathReference(reference)) { return null } + const parts = parseReferencePath(reference) const fileReference = `${REFERENCE.START}${parts.slice(0, -1).join(REFERENCE.PATH_DELIMITER)}${REFERENCE.END}` const file = await this.resolveReference(fileReference, context) diff --git a/apps/sim/lib/api/contracts/v2/workflow-graph.test.ts b/apps/sim/lib/api/contracts/v2/workflow-graph.test.ts index 094a3cbfee8..66ddaef2bad 100644 --- a/apps/sim/lib/api/contracts/v2/workflow-graph.test.ts +++ b/apps/sim/lib/api/contracts/v2/workflow-graph.test.ts @@ -1,6 +1,7 @@ import { createEmptyWorkflowLintReport } from '@sim/testing/factories/workflow-lint.factory' import { describe, expect, it } from 'vitest' import { + v2ApplyWorkflowOperationsBodySchema, v2ApplyWorkflowOperationsDataSchema, v2ReplaceWorkflowStateBodySchema, v2WorkflowGraphSchema, @@ -219,3 +220,25 @@ describe('v2ApplyWorkflowOperationsDataSchema', () => { expect(result.data?.lint).toEqual(FULL_LINT) }) }) + +describe('an operation whose operation_type names no kind', () => { + const refusal = (operation: Record) => { + const parsed = v2ApplyWorkflowOperationsBodySchema.safeParse({ operations: [operation] }) + return parsed.success ? null : parsed.error.issues.map((issue) => issue.message) + } + + it('lists the kinds there are, and names the key an operation spelled another way', () => { + expect(refusal({ operation_type: 'insert', block_id: 'b' })).toEqual([ + 'operation_type must be one of: add, edit, delete, insert_into_subflow, extract_from_subflow.', + ]) + expect(refusal({ type: 'add', block_id: 'b' })).toEqual([ + "operation_type must be one of: add, edit, delete, insert_into_subflow, extract_from_subflow. Name each operation's kind in operation_type, not type.", + ]) + }) + + it("keeps a known kind's own refusal", () => { + expect(refusal({ operation_type: 'delete', block_id: 'b', extra: 1 })).toEqual([ + 'Unrecognized key: "extra"', + ]) + }) +}) diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 97e3bb85082..ac1d89cbddc 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { BLOCK_RETRY_MAX_TRIES, BLOCK_RETRY_MAX_WAIT_MS, @@ -4288,48 +4289,59 @@ const v2WorkflowOperationBlockIdSchema = z * name, and `delete` accepts no parameters at all. */ export const v2WorkflowOperationSchema = z - .discriminatedUnion('operation_type', [ - z - .object({ - operation_type: z.literal('add').describe('Create a new block.'), - block_id: v2WorkflowOperationBlockIdSchema, - params: v2AddWorkflowBlockParamsSchema, - }) - .strict(), - z - .object({ - operation_type: z - .literal('edit') - .describe('Change an existing block: its inputs, name, or connections.'), - block_id: v2WorkflowOperationBlockIdSchema, - params: v2WorkflowOperationParamsSchema, - }) - .strict(), - z - .object({ - operation_type: z.literal('delete').describe('Remove a block and every edge touching it.'), - block_id: v2WorkflowOperationBlockIdSchema, - }) - .strict(), - z - .object({ - operation_type: z - .literal('insert_into_subflow') - .describe('Create a block inside a loop or parallel container.'), - block_id: v2WorkflowOperationBlockIdSchema, - params: v2InsertIntoSubflowParamsSchema, - }) - .strict(), - z - .object({ - operation_type: z - .literal('extract_from_subflow') - .describe('Move a block out of its loop or parallel container.'), - block_id: v2WorkflowOperationBlockIdSchema, - params: v2SubflowMembershipParamsSchema, - }) - .strict(), - ]) + .discriminatedUnion( + 'operation_type', + [ + z + .object({ + operation_type: z.literal('add').describe('Create a new block.'), + block_id: v2WorkflowOperationBlockIdSchema, + params: v2AddWorkflowBlockParamsSchema, + }) + .strict(), + z + .object({ + operation_type: z + .literal('edit') + .describe('Change an existing block: its inputs, name, or connections.'), + block_id: v2WorkflowOperationBlockIdSchema, + params: v2WorkflowOperationParamsSchema, + }) + .strict(), + z + .object({ + operation_type: z + .literal('delete') + .describe('Remove a block and every edge touching it.'), + block_id: v2WorkflowOperationBlockIdSchema, + }) + .strict(), + z + .object({ + operation_type: z + .literal('insert_into_subflow') + .describe('Create a block inside a loop or parallel container.'), + block_id: v2WorkflowOperationBlockIdSchema, + params: v2InsertIntoSubflowParamsSchema, + }) + .strict(), + z + .object({ + operation_type: z + .literal('extract_from_subflow') + .describe('Move a block out of its loop or parallel container.'), + block_id: v2WorkflowOperationBlockIdSchema, + params: v2SubflowMembershipParamsSchema, + }) + .strict(), + ], + { + // A missing or unknown `operation_type` is `invalid_union`, whose default message is the + // unactionable `Invalid input`; a member's own failures keep theirs. + error: (issue) => + issue.code === 'invalid_union' ? unknownOperationType(issue.input) : undefined, + } + ) .meta({ id: 'WorkflowEditOperation', title: 'Workflow edit operation', @@ -4338,6 +4350,19 @@ export const v2WorkflowOperationSchema = z export type V2WorkflowOperation = z.input +/** + * The refusal of an operation whose `operation_type` names no kind: the kinds there are, and the + * key itself when the operation spelled it another way (`type: 'add'`). + */ +function unknownOperationType(input: unknown): string { + const kinds = v2WorkflowOperationSchema.options.map((option) => option.shape.operation_type.value) + const named = + isRecordLike(input) && !('operation_type' in input) + ? ` Name each operation's kind in operation_type${'type' in input ? ', not type' : ''}.` + : '' + return `operation_type must be one of: ${kinds.join(', ')}.${named}` +} + export const v2ApplyWorkflowOperationsBodySchema = z .object({ operations: z diff --git a/apps/sim/lib/workflow-tests/protocol.test.ts b/apps/sim/lib/workflow-tests/protocol.test.ts index 653c0efcc6a..7ae5deb2767 100644 --- a/apps/sim/lib/workflow-tests/protocol.test.ts +++ b/apps/sim/lib/workflow-tests/protocol.test.ts @@ -37,22 +37,4 @@ describe('storedTestReportSchema', () => { expect(parsed.sideEffects?.executions['exec-1'].stubbed).toEqual([{ ...call, mcp: null }]) }) - - it('reads the reason a report stored as flags, before it was named', () => { - const parsed = storedTestReportSchema.parse( - stored([ - { ...call, dependsOnStub: true, readOnlyHint: true }, - { ...call, dependsOnStub: false, readOnlyHint: true }, - { ...call, dependsOnStub: false, readOnlyHint: false }, - { ...call, reason: 'placeholder' }, - ]) - ) - - expect(parsed.sideEffects?.executions['exec-1'].stubbed).toEqual([ - { ...call, mcp: null, reason: 'placeholder' }, - { ...call, mcp: null, reason: 'mcp-read-only' }, - { ...call, mcp: null }, - { ...call, mcp: null, reason: 'placeholder' }, - ]) - }) }) diff --git a/apps/sim/lib/workflow-tests/protocol.ts b/apps/sim/lib/workflow-tests/protocol.ts index 9b148219940..6596a4062c3 100644 --- a/apps/sim/lib/workflow-tests/protocol.ts +++ b/apps/sim/lib/workflow-tests/protocol.ts @@ -129,31 +129,21 @@ export const testReportSchema = z.object({ }) /** - * A stubbed call of a stored report, read from either shape it was stored in: `reason`, or the - * `dependsOnStub` and `readOnlyHint` flags a report stored before it held. The MCP target and - * reason are absent from a report stored before they were recorded. + * A stubbed call of a stored report. The MCP target and reason are absent from a report stored + * before they were recorded. */ -const storedStubbedCallSchema = z - .object({ - workflowId: z.string(), - blockId: z.string().nullable(), - block: z.string().nullable(), - tool: z.string().nullable(), - /** The MCP server and tool an MCP block's call named; null for any other call. */ - mcp: z.object({ server: z.string(), tool: z.string() }).nullable().default(null), - /** Why a call that is not a plain write was held back; unset for a plain write. */ - reason: z.enum(['placeholder', 'mcp-read-only']).optional(), - dependsOnStub: z.boolean().optional(), - readOnlyHint: z.boolean().optional(), - /** Calls folded into this entry. */ - count: z.number().int().positive(), - }) - .transform(({ dependsOnStub, readOnlyHint, reason, ...call }) => { - const read = - reason ?? - (dependsOnStub ? 'placeholder' : readOnlyHint ? ('mcp-read-only' as const) : undefined) - return { ...call, ...(read ? { reason: read } : {}) } - }) +const storedStubbedCallSchema = z.object({ + workflowId: z.string(), + blockId: z.string().nullable(), + block: z.string().nullable(), + tool: z.string().nullable(), + /** The MCP server and tool an MCP block's call named; null for any other call. */ + mcp: z.object({ server: z.string(), tool: z.string() }).nullable().default(null), + /** Why a call that is not a plain write was held back; unset for a plain write. */ + reason: z.enum(['placeholder', 'mcp-read-only']).optional(), + /** Calls folded into this entry. */ + count: z.number().int().positive(), +}) /** What one workflow run of a test did with the writes it reached, without their payloads. */ const testRunSideEffectsSchema = z.object({ diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 1787f9b6fbe..00b7e6d0b01 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -44,6 +44,7 @@ import { SOURCE_ENTRY_FILE, SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { KIND_DIRS } from '@sim/workspace-code' import { KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' import type { Command } from 'commander' +import { isMachineFormat } from '../../config/index' import { setSoftExitCode } from '../../embed-context' import { printError } from '../../output/io' import { SourceDirError } from './local-errors' @@ -56,6 +57,7 @@ import { type Written, workspaceFolderOf, } from './source-dir' +import { primerSurface } from './source-primer' import { STRICT_FINDINGS } from './source-strict' import { cachedCatalog, @@ -914,6 +916,9 @@ export function reportCheck( }) // A failed check's stderr ends with its first error, so a caller that reads the last stderr // line as the failure reads the mistake, never a notice (the TypeScript install's) or a warning. + // A machine result already holds it and stays one document under `2>&1`; only Mothership, + // whose shell runs the check with the default JSON output, reads that line beside it. + if (isMachineFormat(output) && primerSurface() !== 'chat') return const first = findings.find((finding) => finding.severity === 'error') if (first) printError(`Error: ${findingLine(first)}`) else if (errors > 0) printError(`Error: ${errors} errors past the findings a check lists.`) 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 f268786f01f..be4d6dd791f 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -96,15 +96,15 @@ The loop, two shell calls: sim workspaces source get --dir ./ws && cat ./ws/${SOURCE_AGENTS_FILE} edit every file (a new workflow: workflows//workflow.ts), then: sim workspaces source check --dir ./ws && sim workspaces source apply --dir ./ws --yes --run ='{…}' -A non-zero exit stops the chain at the first failure; fix what it reported and run it again. check +${CHAIN_STOPS} check compiles and type-checks (TypeScript installs on first run; --no-types skips it); apply re-checks and writes the workspace; --run ='{…}' (one per workflow, its workflows// folder) dry-runs that input on the saved draft: code runs and GET fetches are sent (point them at test resources); writes are stubbed and listed under runs[].sideEffects, whose .unchecked lists -sandboxed code that ran unchecked and .omitted counts entries left out. Use --run when the apply -changes a workflow. A -workflow deploys on apply when deployments/.ts declares it; with --run, deployments/ is -applied only after every run completed. +sandboxed code that really ran, network requests included, and .omitted counts entries left +out. Use --run when the apply changes a workflow. A workflow deploys on apply when +deployments/.ts declares it; with --run, deployments/ is applied only after every run +completed. --allow-delete lets an edit remove a resource, column, rows, document, or a workflow's block or variable; apply --dry only prints the plan; get --force replaces edits no apply has saved. Promote dev to prod: \`sim workspaces source apply --dir ./ws --to --dry\`, then --yes. diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 06b4f99be60..16e386aac41 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -57,18 +57,18 @@ export const PATTERNS_HEADING = '- **Patterns**' /** The rules every source directory shares, after the kind's own edit loop. */ function sharedRules(extra: { renames?: string; patterns?: string; debug?: string } = {}): string { - return `- **Renames**: rename blocks' display names (first argument) or consts, with other edits: \`${SOURCE_LOCK_FILE}\` keeps each block and apply rewrites every reference, \`$ref.\` too. Changing both on one block keeps it only if its settings or neighbours match, else a delete (\`E_APPLY_BLOCK_DELETE\`). One workflow variable per apply.${extra.renames ?? ''} + return `- **Renames**: rename display names (first argument) or consts, with other edits: \`${SOURCE_LOCK_FILE}\` keeps each block and apply rewrites every reference, \`$ref.\` too. Changing both on one block keeps it only if its settings or neighbours match, else a delete (\`E_APPLY_BLOCK_DELETE\`). One workflow variable per apply.${extra.renames ?? ''} - **References**: \`${SOURCE_ENTRY_FILE}\` reads \`x.content\`, text as \`\` t\`…\` \`\`, env as \`env.NAME\`. A function file (\`codeFile('./functions/x.js')\`) reads \`$ref..\` (key: display name lowercased, no spaces or dots), \`$ref.loop.currentItem\` / \`.index\` in a body (\`parallel\` too), \`$env.NAME\`; \`.py\`/\`.sh\` files \`\`, \`{{NAME}}\`. A block that never ran reads \`null\` (\`''\` in text). ${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). - - Retry: an \`api\` block's retries and retry delay are \`retries: 3\`, \`retryDelayMs: 500\` (resend the request); a block's Retry on fail is the 3rd argument, \`{ retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } }\`. + - 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'\`. - Rejoin: before one \`response\`, a Function picks the branch that ran with \`??\`.${extra.patterns ?? ''} - **Credentials**: \`sim credentials connect --name ""\`, send the owner its link, then \`credential('')\`. -- **Run**: \`sim workflows run \` runs the active deployment; \`--dry\` runs the draft stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. With \`--dry\`, \`--allow \` sends its writes; \`--draft\` sends all (use test resources). \`--mock ='{…}'\` fixes its output (bare, with \`--mock-from \`: that run's); a child's block: \`.\`. +- **Run**: \`sim workflows run \` runs the active deployment; \`--dry\` runs the draft stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--allow \` (implies \`--dry\`) sends its writes; \`--draft\` alone sends all (use test resources). \`--mock ='{…}'\` fixes its output (bare, with \`--mock-from \`: that run's); a child's block: \`.\`. - **Debug**: \`--dir \` maps a failure to file:line; \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list \`; rerun: \`--from-block --source-run \`; \`--stop-after \`.${extra.debug ?? ''} - **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo in a fresh get), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.` } @@ -76,11 +76,17 @@ ${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any build const WORKFLOW_LOOP = 'sim workflows source check --dir . && sim workflows source apply --dir . --yes' -const WORKSPACE_LOOP = - "sim workspaces source check --dir . && sim workspaces source apply --dir . --yes --run ='{…}'" +/** + * What a coding agent chains onto each kind's apply: a workflow's test run, then its deploy; a + * workspace's test run of each workflow it changes. Mothership's shell refuses runs, so its loop + * stops at the apply. + */ +export const CLI_LOOP_RUN: Record = { + workflow: " --run '{…}' --deploy", + workspace: " --run ='{…}'", +} -/** What a coding agent chains onto a workflow apply: the test run, then the deploy. */ -const RUN_AND_DEPLOY = " --run '{…}' --deploy" +const WORKSPACE_LOOP = `sim workspaces source check --dir . && sim workspaces source apply --dir . --yes${CLI_LOOP_RUN.workspace}` const EDIT_LOOP_LEAD = '**Edit loop**: write every file, then run one chained command' @@ -92,19 +98,19 @@ 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}${RUN_AND_DEPLOY}\` 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). ${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\`).`, } function workflowPrimer(surface: PrimerSurface): string { return `# Sim workflow source: primer -\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it; nothing in it runs. Commands here (table ones too) act on the workflow \`${SOURCE_BASE_FILE}\` names and its workspace (a starter's \`${SOURCE_STARTER_FILE}\` names the workspace; its loop runs \`create\` in place of \`apply\`). +\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it; nothing in it runs. Commands here (table ones too) act on the workflow \`${SOURCE_BASE_FILE}\` names and its workspace (a starter's \`${SOURCE_STARTER_FILE}\` names the workspace; its loop runs \`create\`, not \`apply\`). ${WORKFLOW_EDIT_LOOP[surface]} -- **Scope**: the workflow alone. Tables: \`sim tables columns create
--column '{…}'\` (or \`update\`), \`sim tables rows update
--data '{…}'\`; change columns before the get (its table types go stale). -- **Deletes**: removing a block or variable needs \`apply --allow-delete\`. +- **Scope**: the workflow alone. Tables: \`sim tables columns create
--column '{…}'\`, \`sim tables columns update
--column-name --updates '{…}'\`, \`sim tables rows update
--data '{…}'\`; change columns before the get (its table types go stale). +- **Deletes**: removing a block or variable: \`apply --allow-delete\`. ${sharedRules()} ` } @@ -142,7 +148,7 @@ const WORKSPACE_POINTER_LOOP = `\`${WORKSPACE_LOOP}\` (one \`--run\` per workflo /** The loop line of the pointer, after its lead, by directory kind and surface. */ const POINTER_LOOPS: Record> = { workflow: { - cli: `\`${WORKFLOW_LOOP}${RUN_AND_DEPLOY}\`; fix what it reports next.${STARTER_LOOP}`, + cli: `\`${WORKFLOW_LOOP}${CLI_LOOP_RUN.workflow}\`; fix what it reports next.${STARTER_LOOP}`, chat: `\`${WORKFLOW_LOOP}\`; fix what it reports next. Then test the draft with sim_cli as \`${SOURCE_AGENTS_FILE}\` says.${STARTER_LOOP}`, }, workspace: { cli: WORKSPACE_POINTER_LOOP, chat: WORKSPACE_POINTER_LOOP }, diff --git a/packages/sim-cli/src/commands/protocol/source-status.test.ts b/packages/sim-cli/src/commands/protocol/source-status.test.ts index 2ed2708c202..f8fb5aeedc7 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.test.ts @@ -1,6 +1,7 @@ import { expectLinearGrowth } from '@sim/testing/helpers/scaling' -import { describe, it } from 'vitest' -import { pathFilter } from './source-status' +import type { SourceStatus } from '@sim/workspace-code/status' +import { describe, expect, it } from 'vitest' +import { nextStep, pathFilter } from './source-status' describe('pathFilter', () => { it('reads a filter with a long run of slashes before its last segment in linear time', () => { @@ -10,3 +11,37 @@ describe('pathFilter', () => { }, 4_000) }) }) + +describe('nextStep', () => { + const input = { + prefix: 'sim workflows source', + dir: './my wf', + getArgs: 'wf_1 ', + server: 'checked' as const, + errors: 0, + deletes: false, + scope: '', + } + const edited: SourceStatus = { + state: 'local', + local: [{ kind: 'workflow', key: 'wf_1', change: 'edited', files: [] }], + drift: [], + conflicts: [], + } + + it('quotes a directory with a space in each command it recommends, so it runs as printed', () => { + expect(nextStep(edited, input)?.command).toBe( + "sim workflows source apply --dir './my wf' --yes" + ) + expect(nextStep(edited, { ...input, server: 'unreachable' })?.command).toBe( + "sim workflows source apply --dir './my wf' --dry" + ) + const drifted: SourceStatus = { + ...edited, + state: 'drift', + local: [], + drift: [{ kind: 'workflow', key: 'wf_1', server: 'changed' }], + } + expect(nextStep(drifted, input)?.command).toBe("sim workflows source get wf_1 --dir './my wf'") + }) +}) diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index 1de0c439901..670bc8184bc 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -12,7 +12,7 @@ import type { FileChange, SourceStatus } from '@sim/workspace-code/status' import { createTwoFilesPatch, FILE_HEADERS_ONLY } from 'diff' import { publishSummary } from '#sim-cli/output/github-actions' import type { NextStep } from '#sim-cli/output/next-step' -import type { OutputFormat } from '../../config/index' +import { isMachineFormat, type OutputFormat } from '../../config/index' import { AUTH_REQUIRED_CODE, AUTH_REQUIRED_EXIT_CODE, @@ -33,6 +33,7 @@ import { errorBullets, findingsOutput, markdownCell, + shellWord, summaryFileFlag, summaryMarker, } from './source-ui' @@ -352,7 +353,7 @@ function colorLine(line: string): string { * unavailable. */ export function printDiffReport(format: OutputFormat, report: DiffReport): void { - if (format === 'json' || format === 'yaml') { + if (isMachineFormat(format)) { printDocument(format, report) return } @@ -469,7 +470,10 @@ export function pathFilter( /** What the next command depends on beyond the status itself. */ interface NextStepInput { - /** `sim workspaces source` or `sim workflows source`. */ + /** + * `sim workspaces source` or `sim workflows source`, with the server options the caller typed + * (`simInvocation`). + */ prefix: string dir: string /** What `get` takes before `--dir` (a workflow id), with its trailing space. */ @@ -502,7 +506,8 @@ interface NextStepInput { * checked or the changes have errors, else apply. `null` when there is nothing to do. */ export function nextStep(status: SourceStatus, input: NextStepInput): NextStep | null { - const { prefix, dir } = input + const { prefix } = input + const dir = shellWord(input.dir) if (input.login) { return { command: input.login, diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index fffd0e19a5f..db7e01f5789 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -29,7 +29,7 @@ import { type WorkspaceManifest, } from '@sim/workflow-sdk/codegen' import { printError, printLine } from '#sim-cli/output/io' -import type { OutputFormat } from '../../config/index' +import { isMachineFormat, type OutputFormat } from '../../config/index' import { readJsonFile, writeJsonFile } from '../../config/json-file' import { configDir } from '../../config/paths' import { embedStore } from '../../embed-context' @@ -56,6 +56,7 @@ import { import { AGENTS_POINTER_MARKER, agentsPointer, + CLI_LOOP_RUN, type PrimerKind, type PrimerSurface, primerFor, @@ -609,7 +610,7 @@ export function printTreeResult( format: OutputFormat, result: Record & { primer?: string } ): void { - if (format === 'json' || format === 'yaml') { + if (isMachineFormat(format)) { printProtocolResult(format, result) return } @@ -619,15 +620,19 @@ export function printTreeResult( } /** - * The edit loop of a directory for a get's result, as the one chained command the primer - * recommends: runnable from anywhere because it names the directory. Apply re-checks everything - * on the server, so a dry run is not a step of it. Still a list, so the JSON field keeps the shape + * The edit loop of a directory for a get's result, as the one chained command the primer of this + * surface recommends, naming the directory so it runs from anywhere: a coding agent's adds the + * test run (and a workflow's deploy) with a `{…}` input to fill in, so it is a template to read, + * never a `next` to run as printed; Mothership's stops at the apply. `sim` carries the server + * options the caller typed (`simInvocation`). Apply re-checks everything on + * the server, so a dry run is not a step of it. Still a list, so the JSON field keeps the shape * earlier results had. */ -export function editLoop(kind: PrimerKind, dir: string): string[] { - const group = kind === 'workflow' ? 'sim workflows source' : 'sim workspaces source' +export function editLoop(kind: PrimerKind, dir: string, sim: string): string[] { + const group = `${sim} ${kind === 'workflow' ? 'workflows' : 'workspaces'} source` const at = shellWord(dir) - return [`${group} check --dir ${at} && ${group} apply --dir ${at} --yes`] + const run = primerSurface() === 'chat' ? '' : CLI_LOOP_RUN[kind] + return [`${group} check --dir ${at} && ${group} apply --dir ${at} --yes${run}`] } /** What a directory's editable tree holds beside the printed source. */ diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index b9d78493bfa..e32698edbdb 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -16,7 +16,7 @@ import type { Command } from 'commander' import { annotationLine, annotationPath, printAnnotations } from '#sim-cli/output/github-actions' import { printError } from '#sim-cli/output/io' import { askLine } from '#sim-cli/terminal/line-input' -import type { OutputFormat } from '../../config/index' +import { isMachineFormat, type OutputFormat } from '../../config/index' import { embedStore, setSoftExitCode } from '../../embed-context' import { SOURCE_BUSY_EXIT_CODE, @@ -151,11 +151,6 @@ function printDiagnostics(diagnostics: readonly Diagnostic[]): void { /** A finding in a source command's `--output json` (or `yaml`) result: the frame stays human-only. */ type ResultDiagnostic = Omit & { code: Diagnostic['code'] } -/** Whether `format` prints one machine document on stdout rather than lines for a person. */ -export function isMachine(format: OutputFormat): boolean { - return format === 'json' || format === 'yaml' -} - /** * The `diagnostics` a source command's result carries in a machine format, so the one document on * stdout holds every finding: errors and warnings, and info only with `verbose` (a new workflow @@ -167,7 +162,7 @@ function resultDiagnostics( diagnostics: readonly Diagnostic[], verbose = false ): { diagnostics?: ResultDiagnostic[] } { - if (!isMachine(format)) return {} + if (!isMachineFormat(format)) return {} const hidden = (finding: Diagnostic) => !verbose && finding.severity === 'info' && finding.code !== 'I_FINDINGS_TRUNCATED' const hiddenCount = diagnostics.filter(hidden).length @@ -257,7 +252,7 @@ export function findingsOutput( dir?: string ): FindingsOutput { const printed = new Set() - const machine = isMachine(format) + const machine = isMachineFormat(format) return { machine, print(diagnostics) { @@ -418,26 +413,36 @@ const DETAILS_REFERENCE = / See details\.diagnostics\.$/ export function printRefusal( error: unknown, format: OutputFormat, - options: { ifAnswerLost?: string; verbose?: boolean } = {} + options: { + ifAnswerLost?: string + verbose?: boolean + /** The `--folder` a create named, which the server answers "Folder not found" for. */ + folder?: string + } = {} ): never { - const { ifAnswerLost, verbose = false } = options + const { ifAnswerLost, verbose = false, folder } = options if (!(error instanceof SimApiError)) throw error const details = toRecord(error.details) const diagnostics = details.diagnostics const printed = isDiagnosticList(diagnostics) - const machine = isMachine(format) + const machine = isMachineFormat(format) if (printed && !machine) printDiagnostics(diagnostics) const message = machine ? error.message : error.message.replace(DETAILS_REFERENCE, printed ? ' Each finding is printed above.' : '') const nameTaken = error.status === 409 && details.code === SOURCE_REFUSAL_CODES.nameTaken + const folderMissing = folder !== undefined && /\bfolder not found\b/i.test(error.message) const hint = nameTaken ? 'Pass --name to create it under another name, or apply to that workflow.' - : ifAnswerLost && answerLost(error) - ? ifAnswerLost - : null + : folderMissing + ? `Create it with \`sim workflows folders create ${shellWord(folder)}\`, then create the workflow again.` + : ifAnswerLost && answerLost(error) + ? ifAnswerLost + : null throw new SimApiError( - hint ? `${message} ${hint}` : message, + hint + ? `${folderMissing && !/[.!?]$/.test(message) ? `${message}.` : message} ${hint}` + : message, error.status, error.code, printed ? refusalDetails(format, details, diagnostics, verbose) : error.details, diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 0dc4a6945da..17fdf65918b 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -21,6 +21,7 @@ import { SDK_GUIDE_FILE, SOURCE_COMPILER_OPTIONS } from '@sim/workflow-sdk/codeg import { SOURCE_PLANNED_EXIT_CODE, SOURCE_STALE_EXIT_CODE } from '../../exit-codes' import type { ApplyWorkflowSourceBody, GetWorkflowSourceResponse } from '../../generated/v2-api' import type { OperationClient } from '../../runtime/called-operations' +import { invokedSim } from '../../runtime/run-next' import { SourceDirError } from './local-errors' import { assertSourceDirKind, @@ -52,7 +53,7 @@ import { WORKSPACE_TYPES_FILE, type WorkspaceTypes, } from './source-tree' -import type { Diagnostic } from './source-ui' +import { type Diagnostic, shellWord } from './source-ui' import { compilePrinted, runFailingFindings, storedEdgesOf } from './stored-edges' type SourceBase = ApplyWorkflowSourceBody['base'] @@ -181,9 +182,12 @@ export async function readSourceFiles( return files } -/** The create command for `dir` in `workspaceId`, as the next step a starter prints. */ -export function createCommand(dir: string, workspaceId: string): string { - return `sim workflows source create --dir ${dir} --workspace ${workspaceId}` +/** + * The create command for `dir` in `workspaceId`, as the next step a starter prints; `sim` carries + * the server options the caller typed (by default, those of the running command's invocation). + */ +export function createCommand(dir: string, workspaceId: string, sim = invokedSim()): string { + return `${sim} workflows source create --dir ${shellWord(dir)} --workspace ${workspaceId}` } /** The public guide to workflow source, which AGENTS.md points an agent at. */ @@ -279,7 +283,7 @@ function advancedGuide(surface: PrimerSurface): string { ## Edit loop in detail -${batch} Each non-zero exit stops the chain. Step 3 (with its \`apply --dry\`, which only plans) is for a person, CI, or a change you want reviewed first. The test run (${testRun}) is another thing than \`apply --dry\`: it executes the saved draft, while a run without \`--dry\`, \`--draft\` or a flag that implies the draft (\`--trigger\`, \`--sample\`, \`--stop-after\`, \`--from-block\`) runs the active deployment (\`--deployment-version \`: that deployed version). A dry run answers every tool call not declared read (sends, table writes, HTTP requests other than GET, HEAD or OPTIONS, custom and MCP tools) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, when present (each list keeps a bounded number of entries and counts the rest in \`sideEffects.omitted\`, so check it before treating a list as complete); check those payloads instead of reading back or cleaning up data. Placeholders are distinctive (\`dry_run_row_1\`, numbers above 900000000), and a read that would send one (a tool read, an API GET, a Function's fetch, its headers included) is not sent either and is listed with \`reason: 'placeholder'\`. An MCP tool is stubbed even when its server declares it read-only, which Sim cannot verify: that entry has \`reason: 'mcp-read-only'\`, and \`--allow \` sends it. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, code an Agent's model writes) runs: its GET, HEAD and OPTIONS fetches are sent (an API that writes on a GET is not stubbed, so point those at a test resource), and any other fetch, or one carrying a method-override header, gets an empty 200 and is listed under \`sideEffects.stubbed\`; code in a remote sandbox (shell, Python, imports) is listed under \`sideEffects.unchecked\`, so check that list too. Child workflows run dry too, and custom, Human in the loop and Wait blocks are answered whole. \`--mock ='{…}'\` answers a block with fixed output to steer a branch; a bare \`--mock \` with \`--mock-from \` replays that block's output from the recorded run (this workflow's blocks, not a child's; not inside a loop or parallel unless that run mocked it). \`--allow \` sends that block's writes for real (a Function's fetches included) and \`--draft\` runs the draft with every write sent, so point both at test resources. \`--allow\` and \`--mock\` name a child workflow's block as \`.\`. +${batch} Each non-zero exit stops the chain. Step 3 (with its \`apply --dry\`, which only plans) is for a person, CI, or a change you want reviewed first. The test run (${testRun}) is another thing than \`apply --dry\`: it executes the saved draft, while a run without \`--dry\`, \`--draft\` or a flag that implies the draft (\`--trigger\`, \`--sample\`, \`--stop-after\`, \`--from-block\`) runs the active deployment (\`--deployment-version \`: that deployed version). A dry run answers every tool call not declared read (sends, table writes, HTTP requests other than GET, HEAD or OPTIONS, custom and MCP tools) with a placeholder and lists it under \`sideEffects.stubbed\` with the request it would have sent, when present (each list keeps a bounded number of entries and counts the rest in \`sideEffects.omitted\`, so check it before treating a list as complete); check those payloads instead of reading back or cleaning up data. Placeholders are distinctive (\`dry_run_row_1\`, numbers above 900000000), and a read that would send one (a tool read, an API GET, a Function's fetch, its headers included) is not sent either and is listed with \`reason: 'placeholder'\`. An MCP tool is stubbed even when its server declares it read-only, which Sim cannot verify: that entry has \`reason: 'mcp-read-only'\`, and \`--allow \` sends it. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, code an Agent's model writes) runs: its GET, HEAD and OPTIONS fetches are sent (an API that writes on a GET is not stubbed, so point those at a test resource), and any other fetch, or one carrying a method-override header, gets an empty 200 and is listed under \`sideEffects.stubbed\`; code in a remote sandbox (shell, Python, imports) really runs, its network requests included, and is listed under \`sideEffects.unchecked\`, so check that list too. Child workflows run dry too, and custom, Human in the loop and Wait blocks are answered whole. \`--mock ='{…}'\` answers a block with fixed output to steer a branch; a bare \`--mock \` with \`--mock-from \` replays that block's output from the recorded run (this workflow's blocks, not a child's; not inside a loop or parallel unless that run mocked it). \`--allow \` sends that block's writes for real (a Function's fetches included) and \`--draft\` runs the draft with every write sent, so point both at test resources. \`--allow\` and \`--mock\` name a child workflow's block as \`.\`. 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. 2. \`sim workflows source check --dir .\`: compiles with the server's compiler, in milliseconds and without a request. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It then adds the blocks the source now uses to \`tsconfig.json\` and type-checks with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings). That catches what the compile and \`apply --dry\` do not, such as a reference to a start input the trigger does not declare. Offline before that install, it warns \`W_TYPES_UNCHECKED\` and passes on the compile alone; \`--no-types\` skips it. \`apply --dry\` is the authority: a type error on a printed line you did not edit that it accepts can be skipped with \`--no-types\`. 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 0f4cd3c0d9c..cbbd19f9cb9 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -18,6 +18,7 @@ import { buildRequest, readArgumentSource } from '../../runtime/request' import { renderResult } from '../../runtime/result' import { selectorOf, shellArgument, typedCommandLine, withRunNext } from '../../runtime/run-next' import type { OperationSpec } from '../../runtime/types' +import { CliUsageError } from './local-errors' import { printRunFailureSite } from './run-source-location' import { BLOCK_ID } from './workflow-run-get' import { @@ -493,7 +494,7 @@ export interface TestRun { * workflow's output, the side effects the dry run held back and, for a run that failed in a * block, the dry rerun from where the server says a rerun can start (none when it names none). */ -export function testRunResult(record: Record): TestRun { +function testRunResult(record: Record): TestRun { const { next } = toRecord(withRunNext('executeWorkflow', record)) return { runId: record.runId, @@ -510,7 +511,7 @@ export function testRunResult(record: Record): TestRun { * 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. */ -export async function dryRunDraft( +async function dryRunDraft( client: OperationClient<'executeWorkflow'>, workflowId: string, input: string | undefined, @@ -543,6 +544,62 @@ export async function dryRunDraft( } } +/** + * A `--run` input read as `--input` reads it (JSON, or `@file`) and checked to parse, so a bad one + * is refused with `notJson` before anything is written rather than after. + */ +export async function readRunInput(raw: string, notJson: string): Promise { + const { text } = await readArgumentSource(raw, 'run') + try { + JSON.parse(text) + } catch { + throw new CliUsageError(notJson) + } + return text +} + +/** A source write's `--run` test of its saved draft, as {@link testRunDraft} reports it. */ +export interface DraftTest { + /** The run as the write's result shows it. */ + run: TestRun + /** Why the run did not complete; unset when it did. */ + failure?: string + /** Whether the server refused the run before it started (an input the trigger does not take). */ + refused?: boolean +} + +/** + * 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. + */ +export async function testRunDraft( + client: OperationClient<'executeWorkflow'>, + sourceDir: string, + workflowId: string, + input: string | undefined, + workspaceId: string | null +): Promise { + let record: Record + try { + record = await dryRunDraft(client, workflowId, input, workspaceId) + } catch (error) { + if (!(error instanceof SimApiError) || error.status !== 400) throw error + return { + run: { runId: null, status: 'failed', error: error.message, output: null }, + failure: `the server refused it before it started: ${error.message}`, + refused: true, + } + } + const run = testRunResult(record) + if (record.status === 'completed') return { run } + await printRunFailureSite(sourceDir, workflowId, record.error) + return { + run, + failure: runFailureMessage('executeWorkflow', record) ?? `it ended ${String(record.status)}`, + } +} + /** * Runs synchronously while keeping idle-limited HTTP paths active. * @@ -947,7 +1004,8 @@ placeholder (ids like dry_run_row_1, numbers above 900000000) and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. A read that would send a placeholder is held back too (reason placeholder), and an MCP call its server calls read-only says so (reason mcp-read-only). Reads, model calls and code run for real; code in a -remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked. Child workflows run +remote sandbox (shell, Python, imports) runs for real too, its network requests included, and is +listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. --allow sends that block's writes for real (use a test resource). --mock = answers a block with fixed output, to steer a branch; --mock-from with a bare @@ -1007,7 +1065,7 @@ export function attachWorkflowRunFollow(workflows: Command): void { ) .option( '--allow ', - "Send this block's writes for real during a dry run (its id, display name or key, or . for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls.; repeatable", + "Send this block's writes for real during a dry run (its id, display name or key, or . for a workflow it calls); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable", collectRepeated ) .option( diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-get.ts b/packages/sim-cli/src/commands/protocol/workflow-run-get.ts index b412fa8b0da..6fe28e3594d 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-get.ts @@ -4,6 +4,7 @@ import type { Command } from 'commander' import { CLI_CONTRACT } from '../../contract/commands' import { V2_OPERATIONS } from '../../generated/v2-api' import { SimApiError } from '../../http/client' +import { heldAction } from '../../runtime/build' import { type Connection, callsOperations, @@ -215,13 +216,12 @@ async function readRunByName( */ export function attachWorkflowRunGet(runs: Command): void { const get = runs.commands.find((command) => command.name() === 'get') - const held = (get as (Command & { _actionHandler?: unknown }) | undefined)?._actionHandler - if (!get || typeof held !== 'function') { + const previous = heldAction(get) + if (!get || !previous) { throw new Error( 'workflows runs get must be registered before block names can be attached to it' ) } - const previous = held as (args: unknown[]) => unknown const connectGet = callsOperations(get, ['getWorkflowRun', 'getWorkflowState']) get.action(async (runId: string, _options: unknown, command: Command): Promise => { 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 78dbf8f49c2..56635cf818d 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 @@ -104,7 +104,11 @@ function outcome(overrides: { dry?: boolean; diagnostics?: unknown[]; notes?: st } function program(): Command { + // The root's server options, as the CLI's program declares them. const root = new Command('sim') + .option('-P, --profile ') + .option('--endpoint ') + .option('-w, --workspace ') for (const command of buildGeneratedCommands()) root.addCommand(command) const workflows = root.commands.find((command) => command.name() === 'workflows') const sourceGroup = workflows?.commands.find((command) => command.name() === 'source') @@ -150,6 +154,19 @@ beforeEach(() => { vi.spyOn(process.stderr, 'write').mockImplementation(() => true) }) +afterEach(() => { + // A printed `next.command` is run as printed: a `{…}` placeholder belongs in its reason. + for (const [line] of vi.mocked(console.log).mock.calls) { + let printed: { next?: { command?: unknown } } | undefined + try { + printed = JSON.parse(String(line)) + } catch { + continue + } + expect(String(printed?.next?.command ?? '')).not.toContain('…') + } +}) + afterEach(() => { Object.defineProperty(process.stdin, 'isTTY', { value: stdinTty, configurable: true }) Object.defineProperty(process.stderr, 'isTTY', { value: stderrTty, configurable: true }) @@ -181,6 +198,34 @@ function dryRunFlags() { } describe('sim workflows source apply', () => { + it('keeps the root --profile and --endpoint the caller typed in the next command, not --workspace', async () => { + setTerminal(false) + request.mockResolvedValue(outcome({ dry: true })) + + await program().parseAsync([ + 'node', + 'sim', + '--profile', + 'staging', + '--endpoint', + 'https://sim.example.test', + '-w', + 'ws_other', + 'workflows', + 'source', + 'apply', + WORKFLOW_ID, + '--dir', + dir, + ]) + + expect(stdoutJson()).toMatchObject({ + next: { + command: `sim --profile staging --endpoint 'https://sim.example.test' workflows source apply --dir ${dir} --yes`, + }, + }) + }) + it('without --yes and nobody at a terminal, prints the plan, writes nothing and exits 14', async () => { setTerminal(false) request.mockResolvedValue(outcome({ dry: true })) @@ -1130,7 +1175,7 @@ describe('sim workflows source apply', () => { const failure = apply(WORKFLOW_ID, '--dir', dir, '--yes', '--run', '{}', '--deploy') await expect(failure).rejects.toThrow( - /test run failed: score is not a number.*Nothing was deployed/ + /test run failed: score is not a number\. Nothing was deployed\./ ) expect(request.mock.calls.map((call) => call[0])).toEqual([APPLY_PATH]) expect(readFileSync(join(dir, 'workflow.ts'), 'utf8')).toBe(`${ENTRY}// stored\n`) @@ -1141,6 +1186,79 @@ describe('sim workflows source apply', () => { }) }) + it('maps an input the server refuses like a failed run: saved, nothing deployed, a runnable next', async () => { + setTerminal(false) + serveDeploy() + const refusal = + 'workflow_input does not match trigger "Start" (email: Invalid input: expected string, received undefined)' + contextMockFns.mockRequestRaw.mockRejectedValue( + new SimApiError(refusal, 400, 'BAD_REQUEST') + ) + + const failure = apply(WORKFLOW_ID, '--dir', dir, '--yes', '--run', '{}', '--deploy') + + await expect(failure).rejects.toThrow( + /^The apply was saved into .*, but the test run failed: the server refused it before it started: workflow_input does not match trigger "Start" .*\. Nothing was deployed\. Fix the --run input, then run `sim workflows source apply --dir .* --run '\{\}' --deploy --yes`\.$/ + ) + expect(request.mock.calls.map((call) => call[0])).toEqual([APPLY_PATH]) + expect(stdoutJson()).toMatchObject({ + applied: true, + run: { status: 'failed', error: refusal }, + next: { + command: `sim workflows source apply --dir ${dir} --run '{}' --deploy --yes`, + reason: 'applies again and tests it with your fixed --run input', + }, + }) + }) + + it('says nothing changed when the source matched the draft and its test run fails', async () => { + setTerminal(false) + const unchanged = outcome() + unchanged.data.applied = false + unchanged.data.diff.noop = true + request.mockResolvedValue(unchanged) + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ status: 'failed', error: { message: 'score is not a number' } }) + ) + + await expect(apply(WORKFLOW_ID, '--dir', dir, '--yes', '--run', '{}')).rejects.toThrow( + /^Nothing changed: the draft already matched .*, and the test run failed: score is not a number\. Fix the source/ + ) + }) + + it("prints the run's side effects before the result, so the output still ends with it", async () => { + setTerminal(false) + contextMockState.output = 'table' + serveDeploy() + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ + status: 'completed', + output: {}, + sideEffects: { + stubbed: [{ blockId: 'b-1', block: 'Send', tool: 'slack_message', count: 1 }], + allowed: [], + unchecked: [], + }, + }) + ) + const printed: Array<{ to: 'stdout' | 'stderr'; text: string }> = [] + vi.mocked(console.log).mockImplementation((...line: unknown[]) => { + printed.push({ to: 'stdout', text: line.join(' ') }) + }) + vi.mocked(process.stderr.write).mockImplementation((chunk: unknown) => { + printed.push({ to: 'stderr', text: String(chunk) }) + return true + }) + + await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--run', '{}') + + const sideEffects = printed.findIndex((entry) => entry.text.includes('slack_message')) + const result = printed.findIndex((entry) => entry.to === 'stdout') + expect(sideEffects).toBeGreaterThanOrEqual(0) + expect(sideEffects).toBeLessThan(result) + expect(printed.at(-1)?.to).toBe('stdout') + }) + 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/ @@ -1811,6 +1929,24 @@ describe('sim workflows source create on a directory with no workflow.ts', () => expect(printed.files).toBeGreaterThan(0) }) + it("names a starter's create with the --name and --folder the caller chose", async () => { + setTerminal(false) + vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config')) + const empty = join(dir, 'new') + request.mockImplementation(async (path: string) => { + if (path.endsWith('/workflows/source/catalog')) return { data: CATALOG } + if (path.endsWith('/workflows/source/resources')) return MANIFEST + throw new Error(`unexpected request ${path}`) + }) + + await create('--dir', empty, '--name', 'Lead Router', '--folder', 'Sales/Q4', '--run', '{}') + + const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') + expect(printed.next.command).toBe( + `sim workflows source create --dir ${empty} --workspace ${WORKSPACE_ID} --name 'Lead Router' --folder Sales/Q4 --run '{}' --yes` + ) + }) + /** Answers the starter's catalog and manifest reads, and a create with a stored workflow. */ function answerStarterAndCreate() { request.mockImplementation(async (path: string, init: { query?: { dry?: boolean } }) => { @@ -1827,6 +1963,28 @@ describe('sim workflows source create on a directory with no workflow.ts', () => .filter((path) => path.endsWith('/workflows/source')) } + it('names the command that creates a --folder the server does not find', async () => { + setTerminal(false) + vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config')) + const empty = join(dir, 'new') + answerStarterAndCreate() + await create('--dir', empty) + request.mockImplementation(async (path: string) => { + if (path.endsWith('/workflows/source/catalog')) return { data: CATALOG } + if (path.endsWith('/workflows/source/resources')) return MANIFEST + throw new SimApiError('Folder not found', 404) + }) + + await expect(create('--dir', empty, '--folder', 'Reports/Q4', '--dry')).rejects.toThrow( + /^Folder not found\. Create it with `sim workflows folders create '?Reports\/Q4'?`, then create the workflow again\.$/ + ) + // The command the hint names is one the CLI has. + const folders = program() + .commands.find((command) => command.name() === 'workflows') + ?.commands.find((command) => command.name() === 'folders') + expect(folders?.commands.map((command) => command.name())).toContain('create') + }) + it('plans a starter without reading or rewriting its workspace types', async () => { setTerminal(false) vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config')) 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 4ea768dc846..def1f5fbce6 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -4,6 +4,7 @@ import type { Command } from 'commander' import { publishSummary } from '#sim-cli/output/github-actions' import { printError } from '#sim-cli/output/io' import type { NextStep } from '#sim-cli/output/next-step' +import { isMachineFormat } from '../../config/index' import { setSoftExitCode } from '../../embed-context' import type { ApplyWorkflowSourceBody, @@ -20,8 +21,7 @@ import { liveAgainstDraft, liveDeploymentStatus, } from '../../runtime/deployment-live' -import { runFailureMessage } from '../../runtime/execute' -import { readArgumentSource } from '../../runtime/request' +import { simInvocation } from '../../runtime/run-next' import { searchTasks } from '../search' import { type DeployedUrl, @@ -33,7 +33,6 @@ import { import { gitProvenance } from './git-provenance' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' -import { printRunFailureSite } from './run-source-location' import { folderChildResults } from './source-check' import { absoluteDirOption, @@ -58,7 +57,6 @@ import { type FindingsOutput, findingsOutput, fresh, - isMachine, markdownCell, printRefusal, refusedExitCode, @@ -82,7 +80,7 @@ import { writeSourceDirectory, writeSourceScaffold, } from './workflow-dir' -import { dryRunDraft, printSideEffects, type TestRun, testRunResult } from './workflow-run-follow' +import { printSideEffects, readRunInput, type TestRun, testRunDraft } from './workflow-run-follow' type SourceApplyData = ApplyWorkflowSourceResponse['data'] @@ -184,6 +182,8 @@ async function writeWorkflowSource(args: save: (data: SourceApplyData) => Promise /** The next step when the write's answer never came back, so it may have been stored. */ ifAnswerLost: string + /** The folder a create puts the workflow in (`--folder`). */ + folder?: string /** This write as a command, without `--yes`: what a `plan` run names next with it. */ command: string /** @@ -212,6 +212,7 @@ async function writeWorkflowSource(args: return printRefusal(error, args.output, { ...(dry ? {} : { ifAnswerLost: args.ifAnswerLost }), verbose: options.verbose === true, + ...(args.folder !== undefined ? { folder: args.folder } : {}), }) } } @@ -245,13 +246,14 @@ async function writeWorkflowSource(args: ...(live ? { live } : {}), ...(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) + } printProtocolResult(args.output, result, { ...(details.created ? { created: createdText(details.created) } : {}), ...(outcome.urls?.length ? { urls: deployedUrlsText(outcome.urls) } : {}), }) - if (run?.sideEffects && !findings.machine) { - printSideEffects(run.sideEffects, undefined, data.workflowId) - } } const hasErrors = (data: SourceApplyData) => countOf(data, 'error') > 0 /** Whether a committed answer stored the write: not refused, and a create that applied. */ @@ -302,21 +304,23 @@ async function writeWorkflowSource(args: } if (options.run !== undefined) { const input = options.run === true ? undefined : options.run - const record = await afterWrite(() => - dryRunDraft(args.client, data.workflowId, input, args.workspaceId) + const test = await afterWrite(() => + testRunDraft(args.client, options.dir, data.workflowId, input, args.workspaceId) ) - run = testRunResult(record) - if (record.status !== 'completed') { - await printRunFailureSite(options.dir, data.workflowId, record.error) + run = test.run + if (test.failure !== undefined) { const next = { command: `${args.savedCommand} --yes`, - reason: 'applies your fix and tests it again', + reason: test.refused + ? 'applies again and tests it with your fixed --run input' + : 'applies your fix and tests it again', } report(data, { next }, run) - const why = - runFailureMessage('executeWorkflow', record) ?? `it ended ${String(record.status)}` + const written = data.applied + ? `The ${verb} was saved into ${options.dir}, but` + : `Nothing changed: the draft already matched ${options.dir}, and` throw new SimApiError( - `The ${verb} was saved into ${options.dir}, but the test run ${String(record.status)}: ${why}${options.deploy ? ' Nothing was deployed.' : ''} Fix the source, then run \`${args.savedCommand} --yes\`.`, + `${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}\`.`, 0 ) } @@ -336,6 +340,11 @@ async function writeWorkflowSource(args: report(data, deployment, run) } +/** `text` ending as a sentence, so a sentence can follow it. */ +function asSentence(text: string): string { + return /[.!?]$/.test(text) ? text : `${text}.` +} + /** How many of a write's findings have `severity`. */ function countOf(data: SourceApplyData, severity: 'error' | 'warning'): number { return data.diagnostics.filter((diagnostic) => diagnostic.severity === severity).length @@ -557,9 +566,12 @@ function deployFailure( ) } -/** `sim workflows source apply` with the write flags `options` holds, without `--yes`. */ -function applyCommand(options: SourceWriteOptions): string { - return `sim workflows source apply --dir ${shellWord(options.dir)}${options.allowDelete ? ' --allow-delete' : ''}${runFlag(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}` +/** + * `sim workflows source apply` with the write flags `options` holds, without `--yes`; `sim` is the + * 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)}` } /** @@ -579,13 +591,10 @@ async function checkedWriteOptions(options: SourceWriteOptions): Promise { + .action(async (named: string | undefined, options: SourceWriteOptions, invoked: Command) => { const mode = writeMode(options) + const sim = simInvocation(invoked) await withSourceCommandLock( options.dir, async () => { @@ -663,8 +673,8 @@ export function attachWorkflowSourceApply(source: Command): void { mode, creating: false, question: `Apply these changes to workflow ${workflowId}?`, - command: applyCommand(options), - savedCommand: applyCommand(options), + command: applyCommand(options, sim), + savedCommand: applyCommand(options, sim), output: profile.output, client, workspaceId: base.workspaceId, @@ -685,7 +695,7 @@ export function attachWorkflowSourceApply(source: Command): void { await writeBack(options.dir, data, lock, { write: edges ? [edges] : [] }) await refreshWorkflowTsconfigs(options.dir, data) }, - ifAnswerLost: `It may have been saved. Run \`sim workflows source apply ${workflowId} --dir ${options.dir} --dry\`: exit 5 (stale) means the draft changed since this directory was read, by this apply or by someone else. Run \`sim workflows source get ${workflowId} --dir \` and compare it with ${options.dir}: if it holds your edit, \`sim workflows source get ${workflowId} --dir ${options.dir} --force\` brings this directory up to date; if not, reapply your edit in the fresh directory. Any other outcome means it was not saved: apply again.`, + ifAnswerLost: `It may have been saved. Run \`${sim} workflows source apply ${workflowId} --dir ${shellWord(options.dir)} --dry\`: exit 5 (stale) means the draft changed since this directory was read, by this apply or by someone else. Run \`${sim} workflows source get ${workflowId} --dir \` and compare it with ${options.dir}: if it holds your edit, \`${sim} workflows source get ${workflowId} --dir ${shellWord(options.dir)} --force\` brings this directory up to date; if not, reapply your edit in the fresh directory. Any other outcome means it was not saved: apply again.`, }) }, { readOnly: isReadOnly(mode) } @@ -731,79 +741,91 @@ export function attachWorkflowSourceCreate(source: Command): void { .allowExcessArguments(false) .description('Create a workflow from a workflow source directory') .addHelpText('after', sourceExitCodesHelp('workflows source create')) - .action(async (options: SourceWriteOptions & { name?: string; folder?: string }) => { - const mode = writeMode(options) - await withSourceCommandLock( - options.dir, - async () => { - await assertSourceDirKind(options.dir, 'workflow') - const checked = await checkedWriteOptions(options) - if ((await readSourceText(options.dir, ENTRY_FILE)) === null) { - if (options.dry || options.yes) { - throw new SourceDirError( - `${options.dir} has no ${ENTRY_FILE}, so there is nothing to ${options.dry ? 'check' : 'create'}. Write ${ENTRY_FILE} there, or run \`sim workflows source create --dir ${options.dir}\` without --dry and --yes to write a starter.` - ) + .action( + async ( + options: SourceWriteOptions & { name?: string; folder?: string }, + invoked: Command + ) => { + const mode = writeMode(options) + 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)}` + await withSourceCommandLock( + options.dir, + async () => { + await assertSourceDirKind(options.dir, 'workflow') + const checked = await checkedWriteOptions(options) + if ((await readSourceText(options.dir, ENTRY_FILE)) === null) { + if (options.dry || options.yes) { + throw new SourceDirError( + `${options.dir} has no ${ENTRY_FILE}, so there is nothing to ${options.dry ? 'check' : 'create'}. Write ${ENTRY_FILE} there, or run \`${sim} workflows source create --dir ${shellWord(options.dir)}\` without --dry and --yes to write a starter.` + ) + } + const { client, profile } = connectCreate() + const workspaceId = client.requireWorkspace() + const tree = await writeSourceScaffold(client, options.dir, workspaceId) + const next: NextStep = { + command: `${createLine(workspaceId)} --yes`, + reason: `${options.dir} had no ${ENTRY_FILE}, so a starter, the SDK types for workspace ${workspaceId}, tsconfig.json, .sim/AGENTS.md and the examples in .sim/examples/ were written and nothing was created. Edit ${ENTRY_FILE}, check it, then create it.`, + } + const machine = isMachineFormat(profile.output) + if (!machine) printError(`${next.reason} Next: ${next.command}`) + printTreeResult(profile.output, { + created: false, + scaffolded: true, + ...tree, + ...(machine ? { next } : {}), + }) + return } const { client, profile } = connectCreate() - const workspaceId = client.requireWorkspace() - const tree = await writeSourceScaffold(client, options.dir, workspaceId) - const next: NextStep = { - command: `${createCommand(shellWord(options.dir), workspaceId)} --yes${runFlag(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`, - reason: `${options.dir} had no ${ENTRY_FILE}, so a starter, the SDK types for workspace ${workspaceId}, tsconfig.json, .sim/AGENTS.md and the examples in .sim/examples/ were written and nothing was created. Edit ${ENTRY_FILE}, check it, then create it.`, + // A directory is bound to the workspace it records: a starter to the one its types were + // written for (--workspace still chooses another), a workspace folder to its workspace. + const recorded = directoryWorkspace( + options.dir, + await recordedWorkspace(options.dir, profile), + profile, + (from, _named, setting) => `Run it without ${setting} to create it in ${from}.` + ) + const workspaceId = client.requireWorkspace(recorded ?? undefined) + const files = await readSourceFiles(options.dir, null) + if (!isReadOnly(mode)) { + await refreshWorkflowWorkspaceTypes(client, options.dir, workspaceId) } - const machine = isMachine(profile.output) - if (!machine) printError(`${next.reason} Next: ${next.command}`) - printTreeResult(profile.output, { - created: false, - scaffolded: true, - ...tree, - ...(machine ? { next } : {}), + const childResults = isReadOnly(mode) + ? undefined + : await folderChildResults(options.dir) + await writeWorkflowSource<'createWorkflowFromSource'>({ + options: checked, + mode, + creating: true, + question: 'Create this workflow?', + command: createLine(workspaceId), + savedCommand: applyCommand(options, sim), + output: profile.output, + client, + operation: 'createWorkflowFromSource', + params: { workspaceId }, + workspaceId, + ...(options.folder !== undefined ? { folder: options.folder } : {}), + ifAnswerLost: `It may have been created. Run this command again: a SOURCE_NAME_TAKEN refusal means it was, so find its id with \`sim workflows list\` and run \`${sim} workflows source get --dir ${shellWord(options.dir)} --force\`.`, + save: async (data) => { + await writeSourceDirectory(client, options.dir, data, [], childResults) + await updateSourceDir(options.dir, { write: [], remove: [SOURCE_STARTER_FILE] }) + }, + body: { + files, + ...(options.name !== undefined ? { name: options.name } : {}), + ...(options.folder !== undefined ? { folderPath: options.folder } : {}), + provenance: { client: 'cli', ...(await gitProvenance(options.dir)) }, + }, }) - return - } - const { client, profile } = connectCreate() - // A directory is bound to the workspace it records: a starter to the one its types were - // written for (--workspace still chooses another), a workspace folder to its workspace. - const recorded = directoryWorkspace( - options.dir, - await recordedWorkspace(options.dir, profile), - profile, - (from, _named, setting) => `Run it without ${setting} to create it in ${from}.` - ) - const workspaceId = client.requireWorkspace(recorded ?? undefined) - const files = await readSourceFiles(options.dir, null) - if (!isReadOnly(mode)) { - await refreshWorkflowWorkspaceTypes(client, options.dir, workspaceId) - } - const childResults = isReadOnly(mode) ? undefined : await folderChildResults(options.dir) - await writeWorkflowSource<'createWorkflowFromSource'>({ - options: checked, - mode, - creating: true, - question: 'Create this workflow?', - command: `${createCommand(shellWord(options.dir), workspaceId)}${options.name !== undefined ? ` --name ${shellWord(options.name)}` : ''}${options.folder !== undefined ? ` --folder ${shellWord(options.folder)}` : ''}${runFlag(options.run)}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`, - savedCommand: applyCommand(options), - output: profile.output, - client, - operation: 'createWorkflowFromSource', - params: { workspaceId }, - workspaceId, - ifAnswerLost: `It may have been created. Run this command again: a SOURCE_NAME_TAKEN refusal means it was, so find its id with \`sim workflows list\` and run \`sim workflows source get --dir ${options.dir} --force\`.`, - save: async (data) => { - await writeSourceDirectory(client, options.dir, data, [], childResults) - await updateSourceDir(options.dir, { write: [], remove: [SOURCE_STARTER_FILE] }) - }, - body: { - files, - ...(options.name !== undefined ? { name: options.name } : {}), - ...(options.folder !== undefined ? { folderPath: options.folder } : {}), - provenance: { client: 'cli', ...(await gitProvenance(options.dir)) }, - }, - }) - }, - { readOnly: isReadOnly(mode) } - ) - }) + }, + { readOnly: isReadOnly(mode) } + ) + } + ) } /** Whether a diff adds, removes or changes any workflow variable. */ 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 28ed6586f13..c10decb894a 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 @@ -376,7 +376,22 @@ describe('sim workflows source check', () => { }) }) - it('with --output json, prints each finding in the JSON, ending stderr with the first error on one line and no frame', async () => { + it('with --output json, prints each finding in the JSON and nothing on stderr, so 2>&1 stays one document', async () => { + cacheCatalog() + writeFileSync( + join(dir, 'workflow.ts'), + CLEAN.replace('{ body: { received: start.message } }', '{ bdy: { received: start.message } }') + ) + + await check() + + expect(stdoutJson()).toMatchObject({ diagnostics: [{ code: 'E_UNKNOWN_PARAM' }] }) + expect(vi.mocked(console.error)).not.toHaveBeenCalled() + expect(process.exitCode).toBe(1) + }) + + it('inside Mothership, whose shell checks with the default JSON output, ends stderr with the first error on one line and no frame', async () => { + vi.stubEnv('SIM_CLI_HOST', 'mothership') cacheCatalog() writeFileSync( join(dir, 'workflow.ts'), @@ -428,10 +443,7 @@ describe('sim workflows source check', () => { expect(stdoutJson()).toMatchObject({ diagnostics: [{ code: 'E_UNKNOWN_PARAM' }] }) const stderr = vi.mocked(console.error).mock.calls.map((call) => call.join(' ')) - expect(stderr).toEqual([ - expect.stringMatching(/^::error file=.*,title=E_UNKNOWN_PARAM::/), - expect.stringMatching(/^Error: workflow\.ts:6:\d+ error E_UNKNOWN_PARAM: /), - ]) + expect(stderr).toEqual([expect.stringMatching(/^::error file=.*,title=E_UNKNOWN_PARAM::/)]) }) it('leaves stored() to the server, which holds the stored values', async () => { 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 c6fbaf87637..6971b3187f6 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 @@ -114,6 +114,29 @@ describe('sim workflows source find', () => { expect(contextMockFns.mockRequest).not.toHaveBeenCalled() }) + it('names the line that reads the block, not the first line of a field or block that spans several, nor a property of that name', async () => { + const multiline = WORKFLOW_TS.replace( + "const gate = condition('Gate', { if: js`${fetchPolicy.status} === 200`, else: true })", + [ + "const gate = condition('Gate', {", + ' if: js`metadata.fetchPolicy &&', + ' ${fetchPolicy.status} === 200`,', + ' else: true,', + ' })', + ].join('\n') + ) + expect(multiline).not.toBe(WORKFLOW_TS) + writeFileSync(join(dir, 'workflow.ts'), multiline) + + await find('Fetch Policy') + + const readsAt = + multiline.split('\n').findIndex((line) => line.includes('${fetchPolicy.status} === 200')) + 1 + expect(stdoutJson().blocks[0].readers).toContainEqual( + expect.objectContaining({ block: 'Gate', file: 'workflow.ts', line: readsAt }) + ) + }) + it('takes a key or identifier, and prints every block a part of a name matches', async () => { await find('fetchPolicy') expect(stdoutJson().blocks.map((block) => block.name)).toEqual(['Fetch Policy']) 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 b536ddd465c..1cc5223cacd 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-find.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-find.ts @@ -1,4 +1,4 @@ -import { compareStrings } from '@sim/utils/string' +import { compareStrings, escapeRegExp } from '@sim/utils/string' import { collectStringLeaves } from '@sim/utils/workflow-references' import { type BlockKey, @@ -18,12 +18,12 @@ import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import type { Command } from 'commander' import { printLine } from '#sim-cli/output/io' +import { isMachineFormat } from '../../config/index' import { actingProfileFrom } from '../../context' import { CliUsageError } from './local-errors' import { printProtocolResult } from './result' import { compileWorkflowDir } from './source-check' import { assertSourceDirKind, sourceRelativePath } from './source-dir' -import { isMachine } from './source-ui' import { lookupCatalog } from './workflow-source-params' /** The most blocks one find prints, so a broad match stays readable. */ @@ -163,13 +163,22 @@ function readersByKey(index: SourceIndex): Map { const at = index.span({ kind: 'param', block: readerKey, param: field }) ?? index.span({ kind: 'block', block: readerKey }) + const lines = at ? (index.linesOf(at.file)?.lines ?? []) : [] for (const head of heads) { - add(head, { - block: block.name, - field, - file: at?.file ?? SOURCE_ENTRY_FILE, - line: at?.line ?? 0, - }) + // The line of the field that names the block (`quote.data`, `...quote`, ``, + // ``), not the field's first line: a long field or block spans many. A + // property access (`metadata.quote`) names something else. + const reads = new RegExp( + `(?[])` + ) + let line = at?.line ?? 0 + for (let candidate = line; at && candidate <= at.endLine; candidate += 1) { + if (reads.test(lines[candidate - 1] ?? '')) { + line = candidate + break + } + } + add(head, { block: block.name, field, file: at?.file ?? SOURCE_ENTRY_FILE, line }) } } } @@ -294,7 +303,7 @@ export function attachWorkflowSourceFind(source: Command): void { .argument('', 'Block name, key or identifier; a part of a name matches every block') .option('--dir ', 'Workflow source directory to read', '.') .allowExcessArguments(false) - .description("Print a block's code, edges and readers with line numbers (offline)") + .description("Print a block's declaration, edges and readers with line numbers (offline)") .addHelpText('after', FIND_HELP) .action(async (query: string, options: { dir: string }, command: Command) => { const profile = actingProfileFrom(command) @@ -313,7 +322,7 @@ export function attachWorkflowSourceFind(source: Command): void { .map((key) => describeBlock(index, readers, key)) .sort(byLine) const more = keys.length - found.length - if (isMachine(profile.output)) { + if (isMachineFormat(profile.output)) { printProtocolResult(profile.output, { blocks: found, compiles: compiled.workflow !== null, 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 ca6d4be1c02..cdf80b49b1a 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 @@ -332,16 +332,27 @@ describe('sim workflows source get --dir', () => { const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') expect(printed).not.toHaveProperty('primer') expect(printed.guide).toBe('.sim/AGENTS.md') - expect(printed.editLoop).toEqual([ - expect.stringMatching( - /^sim workflows source check --dir (\S+) && sim workflows source apply --dir \1 --yes$/ - ), - ]) const agents = readFileSync(join(outDir, '.sim/AGENTS.md'), 'utf8') expect(agents).toContain('- `gmail.sendEmail` (Gmail: Send Email)') expect(agents).not.toContain('`slack.sendMessage`') }) + 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[]) => { + await get('--dir', outDir, ...args) + return JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}').editLoop + } + + expect(await editLoop()).toEqual([ + `sim workflows source check --dir ${outDir} && sim workflows source apply --dir ${outDir} --yes --run '{…}' --deploy`, + ]) + vi.stubEnv('SIM_CLI_HOST', 'mothership') + expect(await editLoop('--force')).toEqual([ + `sim workflows source check --dir ${outDir} && sim workflows source apply --dir ${outDir} --yes`, + ]) + }) + it('names the tables the workflow uses and the output paths its runs fail on, which the read does not', async () => { const workflow = [ '// @sim-sdk 1', diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts index a992a686d04..a70e327de6c 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -3,9 +3,11 @@ import { toRecord } from '@sim/utils/object' import { SOURCE_BASE_FILE } from '@sim/workflow-code/limits' import type { Command } from 'commander' import type { GetWorkflowSourceResponse, ListWorkflowsResponse } from '../../generated/v2-api' +import { heldAction } from '../../runtime/build' import { callsOperations, type OperationClient } from '../../runtime/called-operations' import { DEFAULT_PAGE_SIZE } from '../../runtime/options' import { buildRequest } from '../../runtime/request' +import { simInvocation } from '../../runtime/run-next' import { CliUsageError, SourceDirError } from './local-errors' import { folderChildResults } from './source-check' import { @@ -125,11 +127,10 @@ async function resolveWorkflow( */ export function attachWorkflowSourceGet(source: Command): void { const get = source.commands.find((command) => command.name() === 'get') - const held = (get as (Command & { _actionHandler?: unknown }) | undefined)?._actionHandler - if (!get || typeof held !== 'function') { + const previous = heldAction(get) + if (!get || !previous) { throw new Error('workflows source get must be registered before --dir can be attached to it') } - const previous = held as (args: unknown[]) => unknown const connectGet = callsOperations(get, [ 'getWorkflowSource', 'getSourceCatalog', @@ -214,7 +215,7 @@ export function attachWorkflowSourceGet(source: Command): void { workflowId: workflowSource.workflowId, dir, ...tree, - editLoop: editLoop('workflow', dir), + editLoop: editLoop('workflow', dir, simInvocation(command)), fingerprint: workflowSource.base.fingerprint, ...findings.result(diagnostics), }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts index 047f6d03aa5..1eb43699744 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts @@ -7,13 +7,12 @@ import { } from '@sim/workflow-sdk/codegen' import type { Command } from 'commander' import { printLine } from '#sim-cli/output/io' -import type { ResolvedProfile } from '../../config/index' +import { isMachineFormat, type ResolvedProfile } from '../../config/index' import { actingProfileFrom } from '../../context' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' import { recordedWorkspace } from './source-dir' import { cachedCatalog, cachedSourceCatalog } from './source-tree' -import { isMachine } from './source-ui' const PARAMS_HELP = ` Prints a builder in brief (an example call, the required params with types, the optional ones by @@ -69,7 +68,7 @@ export function attachWorkflowSourceParams(source: Command): void { const profile = actingProfileFrom(command) const catalog = await lookupCatalog(options.dir, profile) const found = lookupBuilder(catalog, query) - const machine = isMachine(profile.output) + const machine = isMachineFormat(profile.output) switch (found.kind) { case 'builder': if (machine) { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts index bdf0cac0591..e2c635ef127 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts @@ -5,6 +5,7 @@ import { Command } from 'commander' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { SOURCE_BUSY_EXIT_CODE } from '../../exit-codes' import { REQUEST_CANCELLED, SimApiError } from '../../http/client' +import { runActionsInvoked } from '../../runtime/build' import { contextMockFns, contextMockState, mockedProfile } from '../../test/context-mock' import { digest } from './source-dir' import { attachWorkflowSourceDiff, attachWorkflowSourceStatus } from './workflow-source-status' @@ -118,19 +119,47 @@ afterEach(() => { describe('workflows source status', () => { it.each(['status', 'diff'] as const)( - 'on a starter no workflow was created from, %s names the create to run, not a get', + 'on a starter no workflow was created from, %s names the create to run, not a get, quoting its directory', async (command) => { - const starter = join(root, 'starter') + const starter = join(root, 'my starter') write(starter, 'workflow.ts', GOT['workflow.ts']) write(starter, '.sim/starter.json', JSON.stringify({ workspaceId: WORKSPACE_ID })) await expect(run(starter, command)).rejects.toThrow( - `It holds a starter no workflow was created from yet: run \`sim workflows source create --dir ${starter} --workspace ${WORKSPACE_ID} --dry\`` + `It holds a starter no workflow was created from yet: run \`sim workflows source create --dir '${starter}' --workspace ${WORKSPACE_ID} --dry\`` ) expect(mockRequest).not.toHaveBeenCalled() } ) + it("names the starter's create with the root --profile the caller typed", async () => { + const starter = join(root, 'starter') + write(starter, 'workflow.ts', GOT['workflow.ts']) + write(starter, '.sim/starter.json', JSON.stringify({ workspaceId: WORKSPACE_ID })) + const program = new Command('sim').option('-P, --profile ').option('--endpoint ') + const source = new Command('source') + attachWorkflowSourceStatus(source) + program.addCommand(source) + runActionsInvoked(program) + program.exitOverride() + for (const each of source.commands) each.exitOverride() + + await expect( + program.parseAsync([ + 'node', + 'sim', + '--profile', + 'staging', + 'source', + 'status', + '--dir', + starter, + ]) + ).rejects.toThrow( + `run \`sim --profile staging workflows source create --dir ${starter} --workspace ${WORKSPACE_ID} --dry\`` + ) + }) + it('refuses while another command holds the directory, asking the server nothing', async () => { mkdirSync(join(root, '.sim/command.lock')) writeFileSync( diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts index 66729a61675..3f371724c57 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts @@ -22,6 +22,7 @@ import { setSoftExitCode } from '../../embed-context' import type { GetWorkflowSourceResponse, PlanWorkflowSourceResponse } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { apiCommand } from '../../runtime/called-operations' +import { simInvocation } from '../../runtime/run-next' import { absoluteDirOption, digest, @@ -56,8 +57,6 @@ import { codeFilePaths, readBase, readLock, readSourceFiles } from './workflow-d type PlanData = PlanWorkflowSourceResponse['data'] -const PREFIX = 'sim workflows source' - /** The workflow directory as a status reads it, once. */ interface LocalWorkflow { base: Awaited> @@ -236,7 +235,7 @@ export function attachWorkflowSourceStatus(source: Command): void { ...(local.unnamed.length > 0 ? { unnamed: local.unnamed } : {}), plan, next: nextStep(status, { - prefix: PREFIX, + prefix: `${simInvocation(invoked)} workflows source`, dir: options.dir, getArgs: `${workflowId} `, server, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index 6098e0b684d..53b0a150798 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -156,13 +156,37 @@ beforeEach(() => { vi.spyOn(console, 'error').mockImplementation(() => {}) }) +afterEach(() => { + // A printed `next.command` is run as printed: a `{…}` placeholder belongs in its reason. + for (const [line] of vi.mocked(console.log).mock.calls) { + let printed: { next?: { command?: unknown } } | undefined + try { + printed = JSON.parse(String(line)) + } catch { + continue + } + expect(String(printed?.next?.command ?? '')).not.toContain('…') + } +}) + afterEach(() => { process.exitCode = undefined rmSync(dir, { recursive: true, force: true }) }) +/** Stderr of an apply in human output, where its plan prints: a machine result carries it. */ +async function humanPlan(...argv: string[]): Promise { + vi.mocked(console.error).mockClear() + contextMockState.output = 'table' + await apply(...argv) + return vi + .mocked(console.error) + .mock.calls.map((call) => call.join(' ')) + .join('\n') +} + describe('workspaces source apply', () => { - it('without --yes and nobody at a terminal, prints the plan, writes nothing and exits 14', async () => { + it('without --yes and nobody at a terminal, prints the plan in the JSON alone, writes nothing and exits 14', async () => { request.mockResolvedValue( answer({ dry: true, plan: [{ kind: 'table', key: 'leads', action: 'create' }] }) ) @@ -177,7 +201,8 @@ describe('workspaces source apply', () => { created: [{ kind: 'table', key: 'leads' }], next: { command: `sim workspaces source apply --dir ${dir} --allow-delete --yes` }, }) - expect(vi.mocked(console.error).mock.calls.flat().join('\n')).toContain('+ leads') + // The JSON carries the plan, so `2>&1` stays one document. + expect(vi.mocked(console.error).mock.calls.flat().join('\n')).not.toContain('leads') }) it('with --yes, prints the plan it applied', async () => { @@ -188,6 +213,7 @@ describe('workspaces source apply', () => { }) ) + contextMockState.output = 'table' await apply('--yes') expect(request).toHaveBeenCalledTimes(1) @@ -219,15 +245,15 @@ describe('workspaces source apply', () => { await apply('--dry') - const stderr = vi.mocked(console.error).mock.calls.flat().join('\n') - expect(stderr).toContain('skills: 1 changed on the server') - expect(stderr).toContain('files: 1 unchanged, 1 deleted on the server') - expect(stderr).toContain(' ! partial.txt (deleted on the server; kept as the server has it)') const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) expect(printed.diagnostics.map((finding: { code: string }) => finding.code)).toEqual([ 'W_SERVER_CHANGED', 'W_SERVER_DELETED', ]) + const stderr = await humanPlan('--dry') + expect(stderr).toContain('skills: 1 changed on the server') + expect(stderr).toContain('files: 1 unchanged, 1 deleted on the server') + expect(stderr).toContain(' ! partial.txt (deleted on the server; kept as the server has it)') }) it('puts each finding of a dry run in the JSON on stdout', async () => { @@ -454,11 +480,20 @@ describe('workspaces source apply', () => { const summary = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) expect(summary).toMatchObject({ deleted: 1, destructive: 2 }) - const stderr = vi - .mocked(console.error) - .mock.calls.map((call) => call.join(' ')) - .join('\n') - expect(stderr).toContain('2 change(s) delete data that applying an older directory') + // The JSON names each change and what it loses, as the printed plan does. + expect(summary.plan).toEqual([ + { + kind: 'table', + key: 'leads', + action: 'update', + destructive: { what: 'rows', counts: { rows: 40 } }, + }, + { kind: 'skill', key: 'tone', action: 'delete', destructive: { what: 'skill', counts: {} } }, + { kind: 'workflow', key: 'ingest', action: 'update' }, + ]) + expect(await humanPlan('--dry')).toContain( + '2 change(s) delete data that applying an older directory' + ) }) it('prints a delete refused for want of --allow-delete as refused, not unchanged', async () => { @@ -481,9 +516,7 @@ describe('workspaces source apply', () => { }) ) - await apply('--dry') - - const stderr = vi.mocked(console.error).mock.calls.flat().join('\n') + const stderr = await humanPlan('--dry') expect(stderr).toContain('skills: 1 delete refused, 1 unchanged') expect(stderr).toContain(' - tone — refused, needs --allow-delete') }) @@ -638,7 +671,15 @@ describe('workspaces source apply', () => { expect(stale.hint).not.toContain('.sim/targets/ws_prod.json first') const [drifted] = byCode('W_SERVER_CHANGED') expect(drifted.hint).toContain('sim workspaces source get --workspace ws_prod') - const stderr = vi.mocked(console.error).mock.calls.flat().join('\n') + const stderr = await humanPlan( + '--to', + 'ws_prod', + '--only', + 'tables', + '--allow-delete', + '--delete-target-only', + '--dry' + ) expect(stderr).toContain(' ! gone (deleted on the server; kept as the server has it)') expect(stderr).toContain(' ! leads (changed on the server; your edit is refused as stale)') expect(stderr).not.toContain('resource(s) that only workspace ws_prod holds') @@ -2298,9 +2339,11 @@ describe('workspaces source apply', () => { ) expect(applies()).toHaveLength(1) const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) - expect(printed.next.command).toBe( - `sim workspaces source apply --dir ${dir} --run 'ingest={}' --run 'other={…}' --yes` - ) + expect(printed.next).toEqual({ + command: `sim workspaces source apply --dir ${dir} --run 'ingest={}' --run other --yes`, + reason: + "tests every draft deployments/ publishes, then deploys them; give a run its input with --run other='{…}'", + }) }) it('exits as written in part when the deployments write holds every deployment back', async () => { @@ -2360,8 +2403,9 @@ describe('workspaces source apply', () => { it('applies no deployments when a workflow file changed between the first write and the runs', async () => { serveApplies() - // The first write's plan prints after its save and before the read ahead of the runs: the - // edit lands in that window. + // The first write's plan prints (in human output) after its save and before the read ahead + // of the runs: the edit lands in that window. + contextMockState.output = 'table' let edited = false vi.mocked(console.error).mockImplementation((line: unknown) => { if (edited || !String(line).startsWith('workflows:')) return @@ -2419,6 +2463,64 @@ describe('workspaces source apply', () => { expect(out).not.toContain('W_DEPLOYED_DRAFT_CHANGED') }) + it('maps an input the server refuses like a failed run: written, deployments/ held, a runnable next', async () => { + serveApplies() + const refusal = 'workflow_input does not match trigger "Start" (email: Invalid input)' + contextMockFns.mockRequestRaw.mockRejectedValue(new SimApiError(refusal, 400, 'BAD_REQUEST')) + + await expect(apply('--yes', '--run', 'ingest={}')).rejects.toThrow( + /but the test run of ingest failed: the server refused it before it started: workflow_input does not match trigger "Start" .* deployments\/ was not applied\. Fix the source or the refused --run input, then run `sim workspaces source apply --dir .* --run 'ingest=\{\}' --yes`\.$/ + ) + expect(applies()).toHaveLength(1) + const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + expect(printed).toMatchObject({ + runs: [{ workflow: 'ingest', status: 'failed' }], + next: { reason: 'applies again and tests it with your fixed --run input' }, + }) + }) + + it("prints no workflow finding of the deployments write, which the apply's result drops too", async () => { + contextMockState.output = 'table' + const finding = (message: string) => ({ + code: 'W_UNRESOLVED_REF', + severity: 'warning', + message, + kind: 'workflow', + key: 'ingest', + }) + request.mockImplementation(async (path: string, options: { body?: { kinds?: string[] } }) => { + if (path === '/api/v2/workflows/wf_1/deployment') return deploymentStatus(1) + const base = { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } } + return options.body?.kinds?.includes('deployment') + ? answer({ + plan: [ + { kind: 'workflow', key: 'ingest', action: 'noop' }, + { kind: 'deployment', key: 'ingest', action: 'update' }, + ], + applied: [{ kind: 'deployment', key: 'ingest', action: 'update' }], + base, + diagnostics: [finding('ingest, as the deployments write read it.')], + }) + : answer({ + plan: [{ kind: 'workflow', key: 'ingest', action: 'update' }], + applied: [{ kind: 'workflow', key: 'ingest', action: 'update' }], + files: { 'workflows/ingest/workflow.ts': `${INGEST}// stored\n` }, + base, + diagnostics: [finding('ingest, as the first write read it.')], + }) + }) + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ status: 'completed', output: {} }) + ) + + await apply('--yes', '--run', 'ingest={}') + + expect(applies()).toHaveLength(2) + const stderr = vi.mocked(console.error).mock.calls.flat().join('\n') + expect(stderr).toContain('ingest, as the first write read it.') + expect(stderr).not.toContain('ingest, as the deployments write read it.') + }) + it('refuses a key with no workflow folder, naming the keys there, before sending anything', async () => { await expect(apply('--yes', '--run', 'ingset={}')).rejects.toThrow( /--run ingset: no such folder under workflows\/ .* Its workflow keys: ingest\./ @@ -2427,6 +2529,13 @@ describe('workspaces source apply', () => { expect(contextMockFns.mockRequestRaw).not.toHaveBeenCalled() }) + it('refuses an input with no key, naming the = form and the keys there', async () => { + await expect(apply('--yes', '--run', '{"email":"a@b.co"}')).rejects.toThrow( + /--run takes ='\{…\}', where is the workflow's folder under workflows\/ .* Its workflow keys: ingest\./ + ) + expect(request).not.toHaveBeenCalled() + }) + it('refuses an input that is not JSON before sending anything', async () => { await expect(apply('--yes', '--run', 'ingest={email:')).rejects.toThrow( /--run ingest: its input is not JSON/ diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 5d5b5e3bec6..1992e5b9e97 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -41,15 +41,13 @@ import { isRequestCancelled, SimApiError } from '../../http/client' import { sanitize } from '../../output/render' import { apiCommand, type OperationClient } from '../../runtime/called-operations' import { liveDeploymentStatus } from '../../runtime/deployment-live' -import { runFailureMessage } from '../../runtime/execute' import { collectRepeated } from '../../runtime/options' -import { readArgumentSource } from '../../runtime/request' +import { simInvocation } from '../../runtime/run-next' import { searchTasks } from '../search' import { type DeployedUrl, deployedUrlsText, lockBlockNames, namedUrls } from './deployed-urls' import { gitProvenance } from './git-provenance' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' -import { printRunFailureSite } from './run-source-location' import { absoluteDirOption, directoryWorkspace, @@ -89,7 +87,7 @@ import { unrecordedFoldersWarning, workflowFolderRecords, } from './stored-edges' -import { dryRunDraft, printSideEffects, type TestRun, testRunResult } from './workflow-run-follow' +import { printSideEffects, readRunInput, type TestRun, testRunDraft } from './workflow-run-follow' import { appliedBlobDigests, assertBlobsFetched, @@ -738,13 +736,14 @@ export function attachWorkspaceSourceApply(source: Command): void { ) .option( '--run ', - "After the apply, dry-run workflows//'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place", + "After the apply, dry-run workflows//'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked", collectRepeated ) .allowExcessArguments(false) .description('Apply a workspace source directory') .addHelpText('after', sourceExitCodesHelp('workspaces source apply')) - .action(async (options: ApplyOptions) => { + .action(async (options: ApplyOptions, invoked: Command) => { + const sim = simInvocation(invoked) assertTargetOnlyDeletable(options) const mode = writeMode(options) const only = parseKinds(options.only) @@ -831,7 +830,7 @@ export function attachWorkspaceSourceApply(source: Command): void { } } return printRefusal(promotion ? rehinted(refusal, promotion) : refusal, profile.output, { - ...(dry ? {} : { ifAnswerLost: answerLostHint(options.dir) }), + ...(dry ? {} : { ifAnswerLost: answerLostHint(options.dir, sim) }), verbose: options.verbose === true, }) } @@ -905,8 +904,19 @@ export function attachWorkspaceSourceApply(source: Command): void { () => planMarkdown({ ...data, diagnostics }, options.to ?? workspaceId), { file: options.summaryFile, marker: summaryMarker(options.dir) } ) + // Before the result, so its errors, warnings and next stay the last lines printed. + if (!findings.machine) { + for (const run of tested) { + if (run.sideEffects) printSideEffects(run.sideEffects, undefined, run.workflowId) + } + } const result = { ...summarize({ ...data, diagnostics }), + // The changes the printed plan lists, for a machine result, which prints no plan: + // an unchanged resource only counts, and its drift is a finding. + ...(findings.machine + ? { plan: data.plan.filter((change) => change.action !== 'noop') } + : {}), ...(workflows.length > 0 ? { workflows } : {}), ...(urls.length > 0 ? { urls } : {}), ...(tested.length > 0 ? { runs: tested } : {}), @@ -922,10 +932,6 @@ export function attachWorkspaceSourceApply(source: Command): void { ...(tested.length > 0 ? { runs: testRunsText(tested) } : {}), } ) - if (findings.machine) return - for (const run of tested) { - if (run.sideEffects) printSideEffects(run.sideEffects, undefined, run.workflowId) - } } /** * The write of `commit` after a preview of the whole submission, saved into the @@ -939,7 +945,9 @@ export function attachWorkspaceSourceApply(source: Command): void { mode, preview: async () => reported(await send(submission, true)), show: (preview) => { - printPlan(preview.plan, preview.diagnostics) + // A machine result carries the plan, so `2>&1` stays one document; a person asked + // to confirm still reads it. + if (!findings.machine || mode === 'ask') printPlan(preview.plan, preview.diagnostics) findings.print(preview.diagnostics) }, refuses: (preview) => preview.refuses === true, @@ -951,7 +959,13 @@ export function attachWorkspaceSourceApply(source: Command): void { const sent = reported( await send(commit, false, commit === submission ? only : commit.kinds) ) - const answer = commit === firstWrite && gated ? withoutDeferredWarnings(sent) : sent + if (commit !== firstWrite) { + // The deployments write: the first write already printed its workflows' findings, + // which mergedApply drops from the result too. + findings.print(sent.diagnostics.filter((finding) => finding.kind !== 'workflow')) + return sent + } + const answer = gated ? withoutDeferredWarnings(sent) : sent findings.print(answer.diagnostics) return answer }, @@ -972,12 +986,12 @@ export function attachWorkspaceSourceApply(source: Command): void { }, report, question: `Apply these changes to workspace ${workspaceId}?`, - command: applyCommand(options), + command: applyCommand(options, sim), interrupt: { verb: 'apply', dir: options.dir, noun: 'workspace', - ifAnswerLost: answerLostHint(options.dir), + ifAnswerLost: answerLostHint(options.dir, sim), }, }) /** @@ -988,7 +1002,7 @@ export function attachWorkspaceSourceApply(source: Command): void { if (data.failed) { printError('The apply stopped part-way; each planned change:') printPlan(data.plan, data.diagnostics, data) - } else if (mode === 'write') printPlan(data.plan, data.diagnostics) + } else if (mode === 'write' && !findings.machine) printPlan(data.plan, data.diagnostics) const held = data.plan.filter((change) => change.held) if (held.length > 0) { printError( @@ -1054,16 +1068,20 @@ export function attachWorkspaceSourceApply(source: Command): void { await afterWrite(() => testRuns(client, options.dir, workspaceId, data, runs, tested)) const failedRuns = tested.filter((run) => run.status !== 'completed') if (failedRuns.length > 0) { + // A run the server refused before it started has no id: its fix is the --run input. + const refused = failedRuns.some((run) => run.runId === null) const next = { - command: `${applyCommand(options)} --yes`, - reason: 'applies your fix and tests it again', + command: `${applyCommand(options, sim)} --yes`, + reason: refused + ? 'applies again and tests it with your fixed --run input' + : 'applies your fix and tests it again', } await finish(data, next) const why = failedRuns .map((run) => `the test run of ${run.workflow} ${String(run.status)}: ${run.error}`) .join('; ') throw new SimApiError( - `The apply was written into ${options.dir}, but ${why}.${gated ? ' deployments/ was not applied.' : ''} Fix the source, then run \`${next.command}\`.`, + `The apply was written into ${options.dir}, but ${why}.${gated ? ' deployments/ was not applied.' : ''} Fix the ${refused ? 'source or the refused --run input' : 'source'}, then run \`${next.command}\`.`, 0 ) } @@ -1073,8 +1091,8 @@ export function attachWorkspaceSourceApply(source: Command): void { ) if (untested.length > 0) { const next = { - command: `${applyCommand(options)}${untested.map((key) => ` --run ${shellWord(`${key}={…}`)}`).join('')} --yes`, - reason: 'tests every draft deployments/ publishes, then deploys them', + command: `${applyCommand(options, sim)}${untested.map((key) => ` --run ${shellWord(key)}`).join('')} --yes`, + reason: `tests every draft deployments/ publishes, then deploys them; give a run its input with ${untested.map((key) => `--run ${key}='{…}'`).join(' ')}`, } await finish(data, next) throw new SimApiError( @@ -1171,10 +1189,16 @@ async function assertRunKeys(dir: string, runs: readonly RunRequest[]): Promise< const keys = [...KIND_LAYOUTS.workflow.group(paths).groups.keys()].sort(compareStrings) const unknown = runs.filter((run) => !keys.includes(run.key)).map((run) => run.key) if (unknown.length === 0) return + const listed = + keys.length > 0 ? `Its workflow keys: ${keys.join(', ')}.` : 'It holds no workflows.' + // An input with no key (`--run '{…}'`, `--run @input.json`) reads as a key that names nothing. + if (unknown.some((key) => /^\s*[[{@]/.test(key))) { + throw new CliUsageError( + `--run takes ='{…}', where is the workflow's folder under ${KIND_DIRS.workflow}/ in ${dir}. ${listed}` + ) + } throw new CliUsageError( - `--run ${unknown.join(', ')}: no such folder under ${KIND_DIRS.workflow}/ in ${dir}. ${ - keys.length > 0 ? `Its workflow keys: ${keys.join(', ')}.` : 'It holds no workflows.' - }` + `--run ${unknown.join(', ')}: no such folder under ${KIND_DIRS.workflow}/ in ${dir}. ${listed}` ) } @@ -1186,13 +1210,10 @@ async function readRunInputs(runs: readonly RunRequest[]): Promise return Promise.all( runs.map(async (run) => { if (run.input === undefined) return run - const { text } = await readArgumentSource(run.input, 'run') - try { - JSON.parse(text) - } catch { - throw new CliUsageError(`--run ${run.key}: its input is not JSON.`) + return { + ...run, + input: await readRunInput(run.input, `--run ${run.key}: its input is not JSON.`), } - return { ...run, input: text } }) ) } @@ -1320,14 +1341,19 @@ async function testRuns( } for (const { key, input, workflowId } of targets) { if (!workflowId) continue - const record = await dryRunDraft(client, workflowId, input, workspaceId) - const run = { workflow: key, workflowId, ...testRunResult(record) } - if (record.status !== 'completed') { - await printRunFailureSite(join(dir, workflowFolder(key)), workflowId, record.error) - run.error = - runFailureMessage('executeWorkflow', record) ?? `it ended ${String(record.status)}` - } - tested.push(run) + const test = await testRunDraft( + client, + join(dir, workflowFolder(key)), + workflowId, + input, + workspaceId + ) + tested.push({ + workflow: key, + workflowId, + ...test.run, + ...(test.failure !== undefined ? { error: test.failure } : {}), + }) } } @@ -1478,11 +1504,11 @@ async function writtenWorkflows( /** * This apply as a command, without `--yes` or `--dry`: what a plan run or a failed test run - * names next. + * names next. `sim` carries the server options the caller typed. */ -function applyCommand(options: ApplyOptions): string { +function applyCommand(options: ApplyOptions, sim: string): string { return [ - `sim workspaces source apply --dir ${shellWord(options.dir)}`, + `${sim} workspaces source apply --dir ${shellWord(options.dir)}`, ...(options.only ? [`--only ${shellWord(options.only)}`] : []), ...(options.to ? [`--to ${shellWord(options.to)}`] : []), ...(options.allowDelete ? ['--allow-delete'] : []), @@ -1529,8 +1555,8 @@ function notSentFindings(paths: readonly string[]): ApplyData['diagnostics'] { * The next step for an apply write whose answer never came back (a timeout, a dropped connection, * an interrupt): it may or may not have been written. */ -function answerLostHint(dir: string): string { - return `It may have been written. Run \`sim workspaces source apply --dir ${dir} --dry\`: no changes, or only the workflows you edited refused as stale (exit 5), means it may have been, or someone else changed those resources. Run \`sim workspaces source get --dir \` and compare it with ${dir}: if it holds your edits, \`sim workspaces source get --dir ${dir} --force\` brings this directory up to date; if not, reapply your edits in the fresh directory. Any other outcome means it was not written: apply again.` +function answerLostHint(dir: string, sim: string): string { + return `It may have been written. Run \`${sim} workspaces source apply --dir ${shellWord(dir)} --dry\`: no changes, or only the workflows you edited refused as stale (exit 5), means it may have been, or someone else changed those resources. Run \`${sim} workspaces source get --dir \` and compare it with ${dir}: if it holds your edits, \`${sim} workspaces source get --dir ${shellWord(dir)} --force\` brings this directory up to date; if not, reapply your edits in the fresh directory. Any other outcome means it was not written: apply again.` } /** diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts index d74fb43360d..4f63d65fc96 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts @@ -200,7 +200,9 @@ describe('workspaces source get', () => { const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') expect(printed).not.toHaveProperty('primer') - expect(printed.editLoop[0]).toMatch(/^sim workspaces source check --dir /) + expect(printed.editLoop).toEqual([ + `sim workspaces source check --dir ${dir} && sim workspaces source apply --dir ${dir} --yes --run ='{…}'`, + ]) }) it('writes the workspace primer atop the guide, and the deep dives to the advanced guide it names', async () => { diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts index f4a40196681..67ad158400d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -10,6 +10,7 @@ import { printError } from '#sim-cli/output/io' import type { GetWorkspaceSourceResponse } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { apiCommand } from '../../runtime/called-operations' +import { simInvocation } from '../../runtime/run-next' import { searchTasks } from '../search' import { removeStagingOnSignal } from './files-get' import { SourceDirError } from './local-errors' @@ -345,7 +346,7 @@ export function attachWorkspaceSourceGet(source: Command): void { .allowExcessArguments(false) .description('Write a workspace as a source directory') .addHelpText('after', GET_HELP) - .action(async (options: { dir: string; only?: string; force?: boolean }) => { + .action(async (options: { dir: string; only?: string; force?: boolean }, invoked: Command) => { const kinds = parseKinds(options.only) const { client, profile } = connect() await withSourceDirLock(options.dir, async () => { @@ -389,7 +390,7 @@ export function attachWorkspaceSourceGet(source: Command): void { removed: result.removed, skipped: data.skipped.length, guide: result.guide, - editLoop: editLoop('workspace', options.dir), + editLoop: editLoop('workspace', options.dir, simInvocation(invoked)), ...findings.result(diagnostics), }) }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts index 3586f929a09..c349732f218 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -35,6 +35,7 @@ import type { PlanWorkspaceSourceResponse, } from '../../generated/v2-api' import { apiCommand, type Connection } from '../../runtime/called-operations' +import { simInvocation } from '../../runtime/run-next' import { SourceDirError } from './local-errors' import { absoluteDirOption, @@ -69,7 +70,7 @@ import { unreachableReason, } from './source-status' import { withSourceExitCode } from './source-tree' -import { type Diagnostic, summaryFileOption } from './source-ui' +import { type Diagnostic, shellWord, summaryFileOption } from './source-ui' import { assertWorkspaceDir, ONLY_KINDS_HELP, @@ -318,14 +319,15 @@ function unmanagedNext( status: SourceStatus, managed: readonly WorkspaceKind[], dir: string, - workspaceScope: string + workspaceScope: string, + prefix: string ): NextStep | null { if (status.conflicts.length > 0 || status.local.length === 0) return null if (status.local.some((entry) => managed.includes(entry.kind))) return null const folders = [...new Set(status.local.map((entry) => KIND_DIRS[entry.kind]))] const named = folders.join(', ') return { - command: `${PREFIX} get --dir ${dir} --only ${folders.join(',')} --force${workspaceScope}`, + command: `${prefix} get --dir ${shellWord(dir)} --only ${folders.join(',')} --force${workspaceScope}`, reason: `${named} ${folders.length === 1 ? 'is' : 'are'} gone, so this directory no longer manages ${folders.length === 1 ? 'that kind' : 'those kinds'} and an apply leaves their resources alone: this get writes ${folders.length === 1 ? 'it' : 'them'} back. To delete the resources instead, recreate ${folders.length === 1 ? 'it' : 'them'} without them (an emptied folder keeps a .gitkeep) and apply with --allow-delete.`, } } @@ -356,6 +358,7 @@ export function attachWorkspaceSourceStatus(source: Command): void { .description('Show what changed locally and on the server since the directory was read') .addHelpText('after', statusHelp('workspaces source status')) .action(async (options: StatusOptions, invoked: Command) => { + const nextPrefix = `${simInvocation(invoked)} workspaces source` const only = parseKinds(options.only) const output = options.json ? 'json' : profileFrom(invoked).output // A status or diff only reads, but holds the directory's lock so it never reports a @@ -437,9 +440,15 @@ export function attachWorkspaceSourceStatus(source: Command): void { next: (login ? null - : unmanagedNext(status, local.submission.kinds, options.dir, workspaceScope)) ?? + : unmanagedNext( + status, + local.submission.kinds, + options.dir, + workspaceScope, + nextPrefix + )) ?? nextStep(status, { - prefix: PREFIX, + prefix: nextPrefix, dir: options.dir, getArgs: '', server, diff --git a/packages/sim-cli/src/config/index.ts b/packages/sim-cli/src/config/index.ts index e1227fd7471..6469fe54f3e 100644 --- a/packages/sim-cli/src/config/index.ts +++ b/packages/sim-cli/src/config/index.ts @@ -6,6 +6,7 @@ export { deleteProfile, explicitWorkspaceSetting, FORBIDDEN_IN_VALUE, + isMachineFormat, listAuthenticationDependents, listProfiles, normalizeEndpoint, diff --git a/packages/sim-cli/src/config/profile.ts b/packages/sim-cli/src/config/profile.ts index 066e8e2b0a6..2b8164f399d 100644 --- a/packages/sim-cli/src/config/profile.ts +++ b/packages/sim-cli/src/config/profile.ts @@ -50,6 +50,11 @@ export const DEFAULT_ENDPOINT = 'https://www.sim.ai' export const OUTPUT_FORMATS = ['table', 'json', 'yaml', 'text'] as const export type OutputFormat = (typeof OUTPUT_FORMATS)[number] +/** Whether `format` prints one parseable document on stdout rather than lines for a person. */ +export function isMachineFormat(format: OutputFormat): boolean { + return format === 'json' || format === 'yaml' +} + /** * JSON unless the flag, `SIM_OUTPUT`, or the profile says otherwise: agents and * scripts are the main callers and parse it directly, and a person who prefers diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 2514551eece..7ab0bd4ce07 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -339,6 +339,11 @@ export const CLI_CONTRACT: CliContract = { filter: { json: true, describe: TABLE_FILTER_HELP }, }, confirm: 'This deletes every matching row and cannot be undone.', + confirmListed: { + field: 'rowIds', + text: (count) => + `This deletes ${count === null ? 'the listed rows' : count === 1 ? 'this row' : `these ${count} rows`} and cannot be undone.`, + }, }, updateRowsByFilter: { command: 'tables rows batch-update', diff --git a/packages/sim-cli/src/contract/types.ts b/packages/sim-cli/src/contract/types.ts index e2ecc71ad81..cd14babf6c6 100644 --- a/packages/sim-cli/src/contract/types.ts +++ b/packages/sim-cli/src/contract/types.ts @@ -344,6 +344,12 @@ export interface CommandSpec { * the point is that the caller can tell whether they meant it. */ confirm?: string + /** + * The `confirm` text when the caller listed what the command acts on (`--row a --row b`), so the + * refusal says what it is about to destroy: `field` is the list's request field, and `text` + * takes how many entries it holds (`null` when they are read from a file). + */ + confirmListed?: { field: string; text: (count: number | null) => string } /** * Accept `-y/--yes` without a `confirm` gate, as a no-op: a write callers run beside confirmed * ones (a deploy after `workflows source apply --yes`) takes the flag they pass there. diff --git a/packages/sim-cli/src/embed-isolation.test.ts b/packages/sim-cli/src/embed-isolation.test.ts index 7dd0175beca..abe65d58ca4 100644 --- a/packages/sim-cli/src/embed-isolation.test.ts +++ b/packages/sim-cli/src/embed-isolation.test.ts @@ -118,6 +118,45 @@ describe('embedded CLI output ownership', () => { expect(noOptions.stderr).not.toContain('Options for') }) + it('words the --yes refusal of listed rows by their count, and prints one document when none was deleted', async () => { + const sent: unknown[] = [] + const transport = async (_input: unknown, init?: RequestInit) => { + sent.push(init?.body) + return new Response(JSON.stringify({ data: { deletedCount: 0, requestedCount: 2 } }), { + headers: { 'content-type': 'application/json' }, + }) + } + const unconfirmed = await runEmbeddedCli( + ['tables', 'rows', 'batch-delete', 'tbl_1', '--row-ids', 'row_1,row_2'], + { ...identity, transport } + ) + expect(unconfirmed.exitCode).toBe(1) + expect(unconfirmed.stderr).toContain( + 'This deletes these 2 rows and cannot be undone. Re-run with --yes to confirm.' + ) + expect(sent).toEqual([]) + const asJson = await runEmbeddedCli( + ['tables', 'rows', 'batch-delete', 'tbl_1', '--row', '["row_1","row,2","row_3"]'], + { ...identity, transport } + ) + expect(asJson.stderr).toContain('This deletes these 3 rows and cannot be undone.') + const escaped = await runEmbeddedCli( + ['tables', 'rows', 'batch-delete', 'tbl_1', '--row', '@@row_1'], + { ...identity, transport } + ) + expect(escaped.stderr).toContain('This deletes this row and cannot be undone.') + + const missing = await runEmbeddedCli( + ['tables', 'rows', 'batch-delete', 'tbl_1', '--row', 'row_1', 'row_2', '--yes'], + { ...identity, transport } + ) + expect(missing.exitCode).toBe(1) + expect(missing.stdout).toBe('') + expect(missing.stderr).toMatch( + /^Error: Deleted nothing: none of the 2 requested rows were deleted\.\n.*requestedCount/s + ) + }) + it('names the command a guessed flag belongs to one group down, by any spelling it answers to', async () => { const guessed = await runEmbeddedCli( ['tables', 'batch-delete', 'tbl_1', '--row-ids', 'row_1', '--yes'], @@ -178,32 +217,42 @@ describe('embedded CLI output ownership', () => { const transport = async () => { throw new Error('a parse error must not reach the API') } - const [positionalInput, swallowed, rootSwallowed, negated, fromFile] = await Promise.all([ - runEmbeddedCli(['workflows', 'run', 'wf_1', '--dry', '{"email":"a@b.co"}'], { - ...identity, - transport, - }), - runEmbeddedCli( - ['workflows', 'run', 'wf_1', '--draft', '--allow', '--input', '{"email":"a@b.co"}'], - { ...identity, transport } - ), - runEmbeddedCli(['workflows', 'run', 'wf_1', '--workspace', '--input', '{"a":1}'], { - ...identity, - transport, - }), - runEmbeddedCli(['workflows', 'run', 'wf_1', '--dry', '--include-file-base64', '{"a":1}'], { - ...identity, - transport, - }), - runEmbeddedCli(['workflows', 'run', 'wf_1', '@input.json'], { ...identity, transport }), - ]) + const [positionalInput, swallowed, mockSwallowed, rootSwallowed, negated, fromFile] = + await Promise.all([ + runEmbeddedCli(['workflows', 'run', 'wf_1', '--dry', '{"email":"a@b.co"}'], { + ...identity, + transport, + }), + runEmbeddedCli( + ['workflows', 'run', 'wf_1', '--draft', '--allow', '--input', '{"email":"a@b.co"}'], + { ...identity, transport } + ), + runEmbeddedCli( + ['workflows', 'run', 'wf_1', '--mock', 'Fetch={}', '--mock', '--input', '{"a":1}'], + { ...identity, transport } + ), + runEmbeddedCli(['workflows', 'run', 'wf_1', '--workspace', '--input', '{"a":1}'], { + ...identity, + transport, + }), + runEmbeddedCli(['workflows', 'run', 'wf_1', '--dry', '--include-file-base64', '{"a":1}'], { + ...identity, + transport, + }), + runEmbeddedCli(['workflows', 'run', 'wf_1', '@input.json'], { ...identity, transport }), + ]) expect(positionalInput.exitCode).toBe(1) expect(positionalInput.stderr).toContain( `Example: sim workflows run wf_1 --dry --input '{"email":"a@b.co"}'` ) expect(swallowed.exitCode).toBe(1) expect(swallowed.stderr).toContain('--allow took --input as its value; write --allow :') - expect(swallowed.stderr).not.toContain('--input \'{"email"') + expect(swallowed.stderr).toContain( + `Example: sim workflows run wf_1 --draft --allow '' --input '{"email":"a@b.co"}'` + ) + expect(mockSwallowed.stderr).toContain( + `Example: sim workflows run wf_1 --mock 'Fetch={}' --mock '=' --input '{"a":1}'` + ) expect(rootSwallowed.stderr).toContain('--workspace took --input as its value') expect(fromFile.stderr).toContain("Example: sim workflows run wf_1 --input '@input.json'") expect(negated.stderr).toContain( diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 6e15e1238b5..34563ccf469 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -898,6 +898,7 @@ export type ApplyWorkflowSourceResponse = { | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' | 'W_CODE_FILE_REF_SYNTAX' + | 'W_CODE_FILE_REF_QUOTED' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -1404,6 +1405,7 @@ export type ApplyWorkspaceSourceResponse = { | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' | 'W_CODE_FILE_REF_SYNTAX' + | 'W_CODE_FILE_REF_QUOTED' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -1701,6 +1703,7 @@ export type ApplyWorkspaceSourceResponse = { | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' | 'W_CODE_FILE_REF_SYNTAX' + | 'W_CODE_FILE_REF_QUOTED' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -5378,6 +5381,7 @@ export type CreateWorkflowFromSourceResponse = { | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' | 'W_CODE_FILE_REF_SYNTAX' + | 'W_CODE_FILE_REF_QUOTED' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -10607,6 +10611,7 @@ export type GetWorkflowSourceResponse = { | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' | 'W_CODE_FILE_REF_SYNTAX' + | 'W_CODE_FILE_REF_QUOTED' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -11305,6 +11310,7 @@ export type GetWorkspaceSourceResponse = { | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' | 'W_CODE_FILE_REF_SYNTAX' + | 'W_CODE_FILE_REF_QUOTED' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -14640,6 +14646,7 @@ export type PlanWorkflowSourceResponse = { | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' | 'W_CODE_FILE_REF_SYNTAX' + | 'W_CODE_FILE_REF_QUOTED' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -15101,6 +15108,7 @@ export type PlanWorkspaceSourceResponse = { | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' | 'W_CODE_FILE_REF_SYNTAX' + | 'W_CODE_FILE_REF_QUOTED' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -15398,6 +15406,7 @@ export type PlanWorkspaceSourceResponse = { | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' | 'W_CODE_FILE_REF_SYNTAX' + | 'W_CODE_FILE_REF_QUOTED' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' diff --git a/packages/sim-cli/src/http/client.ts b/packages/sim-cli/src/http/client.ts index dc0d8bcfb5a..b1eaba7034e 100644 --- a/packages/sim-cli/src/http/client.ts +++ b/packages/sim-cli/src/http/client.ts @@ -3,7 +3,12 @@ import { backoffWithJitter, parseRetryAfter } from '@sim/utils/retry' import { truncate } from '@sim/utils/string' import { writeStderr } from '#sim-cli/output/io' import { hasProgressTerminal, styles } from '#sim-cli/output/presentation' -import type { ResolvedProfile, StoredCredential, StoredOAuthCredential } from '../config/index' +import { + isMachineFormat, + type ResolvedProfile, + type StoredCredential, + type StoredOAuthCredential, +} from '../config/index' import { AUTH_REQUIRED_CODE, AUTH_REQUIRED_EXIT_CODE, RATE_LIMITED_EXIT_CODE } from '../exit-codes' import { identityHeaders } from '../telemetry/client-info' import { warnIfCredentialOverCleartext, warnIfProxyIgnored } from './environment' @@ -791,7 +796,7 @@ export class SimClient { // capture of a request that then succeeds, and one whose retries run out is its error. // On a terminal, a `fetched N…` paging line is cleared first. const terminal = hasProgressTerminal() - if (terminal || (this.profile.output !== 'json' && this.profile.output !== 'yaml')) { + if (terminal || !isMachineFormat(this.profile.output)) { writeStderr( `${terminal ? '\r\u001b[K' : ''}${styles().dim(`Rate limited (HTTP 429); retrying in ${Math.ceil(waitMs / 1000)}s (retry ${rateLimitResends + 1} of ${RATE_LIMIT_RETRIES}).`)}\n` ) diff --git a/packages/sim-cli/src/output/trace.ts b/packages/sim-cli/src/output/trace.ts index f0517da698f..06589cb349f 100644 --- a/packages/sim-cli/src/output/trace.ts +++ b/packages/sim-cli/src/output/trace.ts @@ -1,6 +1,6 @@ import { printLine } from '#sim-cli/output/io' import { styles } from '#sim-cli/output/presentation' -import type { OutputFormat } from '../config/index' +import { isMachineFormat, type OutputFormat } from '../config/index' import { duration, sanitize } from './render' type TraceSpan = Record @@ -107,7 +107,7 @@ function renderSpan(value: unknown, depth: number): string[] { /** Prints the complete recursive run trace for an explicitly expanded log. */ export function printTraceSpans(format: OutputFormat, traceSpans: unknown[]): void { - if (format === 'json' || format === 'yaml') return + if (isMachineFormat(format)) return printLine('') printLine(format === 'table' ? styles().dim('trace:') : 'trace:') if (traceSpans.length === 0) { diff --git a/packages/sim-cli/src/program.ts b/packages/sim-cli/src/program.ts index 10f0218c26d..d8d0c0ab99d 100644 --- a/packages/sim-cli/src/program.ts +++ b/packages/sim-cli/src/program.ts @@ -14,6 +14,7 @@ import { assertNoReservedProgramFlags, buildGeneratedCommands, refuseHelpAfterUnknownCommand, + runActionsInvoked, } from './runtime/build' import { detectCodingAgent } from './telemetry/coding-agent' import { announceUpdateIfAvailable } from './update/check' @@ -238,6 +239,7 @@ export function buildProgram( refuseHelpAfterUnknownCommand(program) addParseErrorGuidanceToTree(program) assertNoReservedProgramFlags(program) + runActionsInvoked(program) return program } diff --git a/packages/sim-cli/src/runtime/build.ts b/packages/sim-cli/src/runtime/build.ts index d359a137b41..3db9d96a65a 100644 --- a/packages/sim-cli/src/runtime/build.ts +++ b/packages/sim-cli/src/runtime/build.ts @@ -16,7 +16,7 @@ import { RESERVED_PROGRAM_FLAGS, trailingListField, } from './request' -import { shellArgument, typedCommandLine } from './run-next' +import { runInvoked, shellArgument, typedCommandLine } from './run-next' import type { OperationSpec } from './types' const GROUP_ALIASES: Readonly> = { @@ -92,12 +92,39 @@ function looksLikeAnId(token: string): boolean { } /** - * Whether the command runs an action of its own rather than only dispatching - * to subcommands. Commander keeps the handler off its typings, and the tree - * mixes generated commands with hand-written ones, so the contract cannot say. + * The action `command` holds, if any. Commander keeps the handler off its + * typings and offers no way to read it, so a command that wraps a generated + * leaf's handler (`workflows source get --dir`, `workflows runs get`) reads it + * here, and the tree, which mixes generated and hand-written commands, asks it + * whether a command acts on its own. */ +export function heldAction( + command: Command | undefined +): ((args: unknown[]) => void | Promise) | undefined { + const held = (command as (Command & { _actionHandler?: unknown }) | undefined)?._actionHandler + return typeof held === 'function' + ? (held as (args: unknown[]) => void | Promise) + : undefined +} + +/** + * Runs every action of the assembled program as its command's (`runInvoked`), so a hint printed + * deep below one (a directory reader's refusal) keeps the root options the caller typed. + */ +export function runActionsInvoked(program: Command): void { + const walk = (command: Command): void => { + const held = heldAction(command) + // Commander hands the wrapper the positionals, options and command it hands the action; the + // held handler reads the positionals from the front of that list as it does from argv's. + if (held) command.action((...args: unknown[]) => runInvoked(command, () => held(args))) + for (const child of command.commands) walk(child) + } + walk(program) +} + +/** Whether the command runs an action of its own rather than only dispatching to subcommands. */ function hasOwnAction(command: Command): boolean { - return Boolean((command as Command & { _actionHandler?: unknown })._actionHandler) + return heldAction(command) !== undefined } function longFlagSyntax(option: Option): string { @@ -145,34 +172,78 @@ function misplacedFlagValue(command: Command): { option: Option; value: string } return extra.length === 1 ? { option: missing[0], value: extra[0] } : undefined } +/** An option of this command or a group above it that took another of its flags as its value. */ +interface SwallowedFlag { + owner: Command + option: Option + /** The flag it took, as typed (`--input`, or `--input=…`). */ + taken: string + /** The option the taken flag names. */ + takenOption: Option +} + /** * Each option of this command or a group above it (the root's `--workspace` too) that took a flag - * as its value, with what the option is for: `run --allow --input '{…}'` gives `--allow` the value `--input` and - * leaves the JSON over as a positional, so the excess is a symptom of the missing value and the - * JSON is not misplaced. + * as its value: `run --allow --input '{…}'` gives `--allow` the value `--input` and leaves the + * JSON over as a positional, so the excess is a symptom of the missing value and the JSON is not + * misplaced. */ -function swallowedFlags(command: Command): string[] { +function swallowedFlags(command: Command): SwallowedFlag[] { const owned: { owner: Command; option: Option }[] = [] for (let owner: Command | null = command; owner; owner = owner.parent) { for (const option of owner.options) owned.push({ owner, option }) } return owned.flatMap(({ owner, option }) => { const value = owner.getOptionValue(option.attributeName()) - const taken = (Array.isArray(value) ? value : [value]).find( - (given) => - typeof given === 'string' && - owned.some(({ option: other }) => - [other.long, other.short].includes(given.split('=', 1)[0]) - ) - ) - if (taken === undefined) return [] - const purpose = option.description.split(/[;(]/, 1)[0].trim() - return [ - `${option.long ?? option.short} took ${taken} as its value; write ${option.flags}: ${purpose}.`, - ] + for (const given of Array.isArray(value) ? value : [value]) { + if (typeof given !== 'string') continue + const takenOption = owned.find(({ option: other }) => + [other.long, other.short].includes(given.split('=', 1)[0]) + )?.option + if (takenOption) return [{ owner, option, taken: given, takenOption }] + } + return [] }) } +/** What a swallowing option is for, and how to write it. */ +function swallowedLine({ option, taken }: SwallowedFlag): string { + const purpose = option.description.split(/[;(]/, 1)[0].trim() + return `${option.long ?? option.short} took ${taken} as its value; write ${option.flags}: ${purpose}.` +} + +/** + * The command line with the one leaf option that took a flag given a placeholder value of its own, + * and the flag it took given the operand left over: `run --allow '' --input '{…}'`. + * The typed positionals and options are kept. Null when the reading is not the only one: several + * swallowed flags, one owned by a group above the leaf, or operands that do not fit the taken flag. + */ +function swallowedExample(command: Command, swallowed: readonly SwallowedFlag[]): string | null { + if (swallowed.length !== 1) return null + const [{ owner, option, taken, takenOption }] = swallowed + if (owner !== command || !option.long || !takenOption.long) return null + const extra = command.args.slice(command.registeredArguments.length) + const takesValue = (takenOption.required || takenOption.optional) && !taken.includes('=') + if (extra.length !== (takesValue ? 1 : 0)) return null + const placeholder = option.flags.slice(option.flags.lastIndexOf(' ') + 1) + const value = command.getOptionValue(option.attributeName()) + const kept = (Array.isArray(value) ? value : []).filter( + (given): given is string => typeof given === 'string' && given !== taken + ) + const words = [ + typedCommandLine( + command, + command.args.slice(0, command.registeredArguments.length), + new Set([option.attributeName()]) + ), + ...kept.map((given) => `${option.long} ${shellArgument(given)}`), + `${option.long} ${shellArgument(placeholder)}`, + taken.includes('=') ? shellArgument(taken) : takenOption.long, + ...extra.map(shellArgument), + ] + return `Example: ${words.join(' ')}` +} + /** * A JSON operand typed where one of the command's JSON flags (`--input `) was meant, * as the line that moves it there with the positionals and the options typed kept. Null when no operand opens like @@ -243,9 +314,10 @@ function parseErrorGuidance(command: Command, code: string | undefined): string[ case 'commander.excessArguments': { const swallowed = swallowedFlags(command) const moved = swallowed.length === 0 ? misplacedJson(command) : null + const corrected = swallowedExample(command, swallowed) return [ - ...swallowed, - ...(moved ?? [`Example: ${usageExample(command)}`]), + ...swallowed.map(swallowedLine), + ...(moved ?? [corrected ?? `Example: ${usageExample(command)}`]), optionList(command), ] } @@ -296,28 +368,6 @@ export function addParseErrorGuidanceToTree(program: Command): void { walk(program) } -/** - * Refuses a leaf option the root program would swallow. - * - * A collision is invisible at runtime — either the root's handler answers and - * exits `0`, or the root simply keeps the value and the leaf reads `undefined`. - * Either way the command reports success while doing nothing the caller asked - * for. Raising here means the CLI cannot start with one, which the command-tree - * tests exercise on every operation, so a contract that introduces one fails in - * CI rather than in somebody's pipeline. - */ -function assertNoReservedFlags(command: Command, operation: V2OperationName): void { - for (const option of command.options) { - for (const flag of [option.long, option.short]) { - if (flag && RESERVED_PROGRAM_FLAGS.has(flag)) { - throw new Error( - `${operation} declares ${flag}, which the root program already owns; give the flag another name` - ) - } - } - } -} - /** * Commands allowed to re-declare a flag the root owns, by full command path. * @@ -330,12 +380,17 @@ function assertNoReservedFlags(command: Command, operation: V2OperationName): vo const RESERVED_FLAG_EXEMPTIONS: ReadonlySet = new Set(['profiles add']) /** - * Sweeps the assembled program for a flag the root already owns. + * Refuses, across the assembled program, a leaf option the root would swallow: + * generated leaves, commands attached by hand (`attachSecretCommands`, + * `attachProtocolCommands`, `attachCredentialCommands`) and options added to a + * leaf after it is built. * - * `assertNoReservedFlags` runs while a generated leaf is configured, so it sees - * nothing that is attached by hand (`attachSecretCommands`, - * `attachProtocolCommands`, `attachCredentialCommands`) or added to a leaf - * after it is built. Walking the finished tree is what covers those. + * A collision is invisible at runtime — either the root's handler answers and + * exits `0`, or the root simply keeps the value and the leaf reads `undefined`. + * Either way the command reports success while doing nothing the caller asked + * for. Raising here means the CLI cannot start with one, which the command-tree + * tests exercise on every operation, so a contract that introduces one fails in + * CI rather than in somebody's pipeline. */ export function assertNoReservedProgramFlags(program: Command): void { const walk = (command: Command, prefix: string[]): void => { @@ -520,7 +575,6 @@ function configureOperation( ) if (spec.helpText) command.addHelpText('after', spec.helpText) addOperationOptions(command, operation, spec, operationSpec) - assertNoReservedFlags(command, operation) // The last frame that still knows which operation ran, and so the only one // that can say `--include-job-runs` where the server said `includeJobRuns`. command.action((...invocation: unknown[]) => @@ -629,20 +683,12 @@ function addLeafCommand( ): void { const [groupName, ...rest] = segments if (rest.length === 0) throw new Error(`${operation} leaf command must include a verb`) - const group = groupFor(groups, groupName) - if (rest.length > 1) { - let parent = group - for (const segment of rest.slice(0, -1)) { - parent = nestedGroup(parent, segment) - } - parent.addCommand(configureOperation(new Command(rest[rest.length - 1]), operation, spec), { - isDefault: spec.defaultSubcommand === true, - }) - return + let parent = groupFor(groups, groupName) + for (const segment of rest.slice(0, -1)) { + parent = nestedGroup(parent, segment) } - - group.addCommand(configureOperation(new Command(rest[0]), operation, spec), { + parent.addCommand(configureOperation(new Command(rest[rest.length - 1]), operation, spec), { isDefault: spec.defaultSubcommand === true, }) } diff --git a/packages/sim-cli/src/runtime/execute.test.ts b/packages/sim-cli/src/runtime/execute.test.ts index 9bf6b8afbe7..2f7694b9aab 100644 --- a/packages/sim-cli/src/runtime/execute.test.ts +++ b/packages/sim-cli/src/runtime/execute.test.ts @@ -11,6 +11,7 @@ import { import { SimApiError } from '../http/client' import { callsOperations } from './called-operations' import { BULK_OUTCOME_CHECKS, executeOperation } from './execute' +import { warnRenamedCommand, writeRenameWarnings } from './renamed' import type { OperationSpec } from './types' const { request, output, workspaceSource } = vi.hoisted(() => ({ @@ -442,6 +443,35 @@ describe('a bulk call that changed nothing', () => { ) }) + it('fails a machine result as one document: the refusal carries the result and the warnings owed', async () => { + const payload = { + deleted: [], + skipped: [], + notFound: [{ kind: 'table', id: 'tbl_nope' }], + failed: [], + deletedItems: { tables: 0, folders: 0 }, + } + request.mockResolvedValue({ data: payload }) + const host = leaf('bulkDeleteTables') + warnRenamedCommand(host, 'tables remove', 'tables batch-delete') + const written = vi.spyOn(process.stderr, 'write').mockImplementation(() => true) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + const failure = await executeOperation('bulkDeleteTables', {}, BULK_DELETE_TABLES, [ + {}, + host, + ]).catch((error: unknown) => error) + writeRenameWarnings(host) + + expect(failure).toBeInstanceOf(SimApiError) + expect((failure as SimApiError).details).toEqual({ + ...payload, + note: 'command "sim tables remove" has been renamed to "sim tables batch-delete". The old name still works.', + }) + expect(console.log).not.toHaveBeenCalled() + expect(written).not.toHaveBeenCalled() + }) + /** * The scoping guard. Some items really were deleted, so the call did work; * failing here would break every caller sweeping a list that legitimately @@ -513,24 +543,32 @@ describe('workspace invitation batch outcomes', () => { vi.spyOn(console, 'log').mockImplementation(() => {}) }) - it.each([false, true])( - 'prints every result and exits nonzero on a partial=%s failure', - async (partial) => { - const payload = { - ...empty, - success: false, - successful: partial ? ['first@example.com'] : [], - invitations: partial ? [receipt] : [], - failed: [{ email: 'second@example.com', error: 'Unable to invite this recipient' }], - } - request.mockResolvedValue({ data: payload }) - await expect(invite()).rejects.toThrow( - 'Invitation batch failed for 1 recipient. Successful results remain committed; inspect failed recipients before retrying.' - ) - expect(JSON.parse(vi.mocked(console.log).mock.calls[0][0])).toEqual(payload) - expect(request).toHaveBeenCalledTimes(1) - } - ) + const failedBatch = (partial: boolean) => ({ + ...empty, + success: false, + successful: partial ? ['first@example.com'] : [], + invitations: partial ? [receipt] : [], + failed: [{ email: 'second@example.com', error: 'Unable to invite this recipient' }], + }) + const BATCH_FAILED = + 'Invitation batch failed for 1 recipient. Successful results remain committed; inspect failed recipients before retrying.' + + it('prints the committed part of a failed batch, then exits nonzero', async () => { + request.mockResolvedValue({ data: failedBatch(true) }) + await expect(invite()).rejects.toThrow(BATCH_FAILED) + expect(JSON.parse(vi.mocked(console.log).mock.calls[0][0])).toEqual(failedBatch(true)) + expect(request).toHaveBeenCalledTimes(1) + }) + + it('fails a batch that committed nothing as one document, the refusal carrying the result', async () => { + request.mockResolvedValue({ data: failedBatch(false) }) + await expect(invite()).rejects.toMatchObject({ + message: BATCH_FAILED, + details: failedBatch(false), + }) + expect(console.log).not.toHaveBeenCalled() + expect(request).toHaveBeenCalledTimes(1) + }) it('preserves HTTP failures without reporting a successful batch or retrying', async () => { const failure = new SimApiError('Organization access denied', 403) diff --git a/packages/sim-cli/src/runtime/execute.ts b/packages/sim-cli/src/runtime/execute.ts index bbfda844072..c9a50dd0d0f 100644 --- a/packages/sim-cli/src/runtime/execute.ts +++ b/packages/sim-cli/src/runtime/execute.ts @@ -7,7 +7,7 @@ import { waitWorkspaceOperation, workspaceWaitTimeout, } from '../commands/protocol/workspace-operation-wait' -import type { ResolvedProfile } from '../config/index' +import { isMachineFormat, type ResolvedProfile } from '../config/index' import type { CommandSpec } from '../contract/types' import type { GetWorkspaceOperationResponse, V2OperationName } from '../generated/v2-api' import { assertCursorAdvances, pageProgress, SimApiError, type V2Page } from '../http/client' @@ -15,16 +15,19 @@ import { safeOneLine } from '../output/render' import { connect } from './called-operations' import { camel } from './derive' import { DEFAULT_PAGE_SIZE, defaultListLimit } from './options' -import { deliveredRenameWarnings, owedRenameWarnings, warnRenamedFlag } from './renamed' +import { renameWarningOptions, warnRenamedFlag } from './renamed' import { type BuiltRequest, buildRequest, cursorSlot, flagNameFor, + flagSpecFor, inlineShapeRefusal, isProfileWorkspacePath, + namesFile, otherSpellings, PROFILE_INJECTED_FIELD, + readListFlag, trailingListField, } from './request' import { foldPageEnvelope, renderPage, renderResult } from './result' @@ -253,13 +256,42 @@ const RESULT_NOTES: Readonly< }, } -/** The operation's result note, when it has one and the result calls for it. */ -function resultNote( +/** + * What a `confirm` command is about to do: its `confirmListed` text when the caller listed the + * entries, counted as the request reads the list (a comma list or a JSON array too; a file is read + * only once confirmed, so its count is unknown), else `confirm`. A list the request would refuse + * keeps `confirm`, for the request to name the mistake. + */ +async function confirmText( operation: V2OperationName, - payload: unknown, - request: BuiltRequest -): string | undefined { - return RESULT_NOTES[operation]?.(toRecord(payload), request) + spec: CommandSpec, + flags: Record +): Promise { + const listed = spec.confirmListed + const flagName = listed ? flagNameFor(operation, listed.field) : undefined + const raw = flagName ? flags[camel(flagName)] : undefined + if (!listed || !flagName || raw === undefined) return spec.confirm + const values = Array.isArray(raw) ? raw : [raw] + if (values.some((value) => typeof value === 'string' && namesFile(value))) { + return listed.text(null) + } + try { + return listed.text( + (await readListFlag(raw, flagSpecFor(operation, listed.field), flagName)).length + ) + } catch { + return spec.confirm + } +} + +/** + * Whether a bulk call its check failed still committed part of its batch. Only an invitation + * batch fails a partial success; every other check fails a total miss alone. + */ +function committedPart(operation: V2OperationName, payload: unknown): boolean { + if (operation !== 'createWorkspaceInvitations') return false + const { successful, added, invitations } = toRecord(payload) + return lengthOf(successful) + lengthOf(added) + lengthOf(invitations) > 0 } /** The one-line explanation of a bulk call that changed nothing, or `null`. */ @@ -479,10 +511,11 @@ export async function executeOperation( */ if (commandSpec.confirm && !requestFlags.yes && requestFlags.dry !== true) { const misshapen = inlineShapeRefusal(operation, requestFlags) + const confirm = await confirmText(operation, commandSpec, requestFlags) throw new SimApiError( misshapen - ? `${misshapen} Also pass --yes: ${commandSpec.confirm}` - : `${commandSpec.confirm} Re-run with --yes to confirm.`, + ? `${misshapen} Also pass --yes: ${confirm}` + : `${confirm} Re-run with --yes to confirm.`, 0 ) } @@ -590,8 +623,7 @@ export async function executeOperation( progress.finish() } renderPage(profile.output, { data: rows, nextCursor: cursor }, commandSpec, envelope, { - warnings: owedRenameWarnings(host), - warningsDelivered: () => deliveredRenameWarnings(host), + ...renameWarningOptions(host), }) return } @@ -674,12 +706,22 @@ export async function executeOperation( )) payload = report renderResult(operation, profile.output, payload, commandSpec, { - warnings: owedRenameWarnings(host), - warningsDelivered: () => deliveredRenameWarnings(host), + ...renameWarningOptions(host), }) assertWorkspaceOperationOutcome(report, timedOut) return } + const bulkFailure = bulkFailureMessage(operation, payload, request.body) + // A failure that committed nothing prints one document in a machine format: the refusal, + // carrying the result that explains it and the invocation's warnings as the result's `note` + // would. A batch that committed part prints its result first, as a failed run does. + if (bulkFailure && isMachineFormat(profile.output) && !committedPart(operation, payload)) { + const { warnings, warningsDelivered } = renameWarningOptions(host) + const details = + warnings.length > 0 ? { ...toRecord(payload), note: warnings.join('\n') } : payload + warningsDelivered() + throw new SimApiError(bulkFailure, 0, null, details) + } renderResult( operation, profile.output, @@ -687,9 +729,8 @@ export async function executeOperation( commandSpec, { expandedTrace: requestFlags.trace === true, - note: resultNote(operation, payload, request), - warnings: owedRenameWarnings(host), - warningsDelivered: () => deliveredRenameWarnings(host), + note: RESULT_NOTES[operation]?.(toRecord(payload), request), + ...renameWarningOptions(host), }, // The envelope, not just the payload: a list that does not paginate states // its own truncation there, and unwrapping `data` discarded it. @@ -700,7 +741,6 @@ export async function executeOperation( // carries the block outputs that explain *why* the run failed, and exiting // before writing it would leave a piped consumer an exit code and nothing to // read. - const failure = - runFailureMessage(operation, payload) ?? bulkFailureMessage(operation, payload, request.body) + const failure = runFailureMessage(operation, payload) ?? bulkFailure if (failure) throw new SimApiError(failure, 0) } diff --git a/packages/sim-cli/src/runtime/renamed.ts b/packages/sim-cli/src/runtime/renamed.ts index 5b5c09b9f7b..1eeef4ff81e 100644 --- a/packages/sim-cli/src/runtime/renamed.ts +++ b/packages/sim-cli/src/runtime/renamed.ts @@ -36,21 +36,25 @@ export function warnRenamedFlag(command: Command, from: string, to: string): voi owe(command, 'flag', `--${from}`, `--${to}`) } -/** The rename warnings `command` owes, for its result to carry. */ -export function owedRenameWarnings(command: Command): readonly string[] { - return OWED.get(command) ?? [] -} - /** - * Settles what `command` owed once its warnings have reached the reader: a render that throws - * first leaves them owed, for {@link writeRenameWarnings}. + * The rename warnings `command` owes, for its result to carry, and `warningsDelivered`, which + * settles them once they have reached the reader: a render that throws first leaves them owed, for + * {@link writeRenameWarnings}. */ -export function deliveredRenameWarnings(command: Command): void { - OWED.delete(command) +export function renameWarningOptions(command: Command): { + warnings: readonly string[] + warningsDelivered: () => void +} { + return { + warnings: OWED.get(command) ?? [], + warningsDelivered: () => { + OWED.delete(command) + }, + } } /** Writes on stderr the rename warnings no printed result delivered. */ export function writeRenameWarnings(command: Command): void { - for (const warning of owedRenameWarnings(command)) writeStderr(`warning: ${warning}\n`) + for (const warning of OWED.get(command) ?? []) writeStderr(`warning: ${warning}\n`) OWED.delete(command) } diff --git a/packages/sim-cli/src/runtime/request.ts b/packages/sim-cli/src/runtime/request.ts index 26a9b76520b..8df91bd1d10 100644 --- a/packages/sim-cli/src/runtime/request.ts +++ b/packages/sim-cli/src/runtime/request.ts @@ -328,14 +328,18 @@ function literalAtHint(error: unknown, path: string): string { : '' } +/** Whether an argument names a file (`@path`, `@-`) rather than a value: `@@x` is the literal `@x`. */ +export function namesFile(raw: string): boolean { + return raw.startsWith('@') && !raw.startsWith('@@') +} + export async function readArgumentSource( raw: string, flagName: string ): Promise<{ text: string; from: string }> { if (Buffer.byteLength(raw, 'utf8') > MAX_JSON_ARGUMENT_BYTES) throw new SimApiError(`--${flagName} exceeds the 10 MiB JSON input limit`, 0) - if (raw.startsWith('@@')) return { text: raw.slice(1), from: '' } - if (!raw.startsWith('@')) return { text: raw, from: '' } + if (!namesFile(raw)) return { text: raw.startsWith('@@') ? raw.slice(1) : raw, from: '' } // An embedded run executes in-process on the hosting server, so a raw file // path here would read the SERVER's filesystem with argv the model controls. diff --git a/packages/sim-cli/src/runtime/result.ts b/packages/sim-cli/src/runtime/result.ts index dc84eb3417e..0441852c193 100644 --- a/packages/sim-cli/src/runtime/result.ts +++ b/packages/sim-cli/src/runtime/result.ts @@ -2,7 +2,7 @@ import { isRecordLike, omit, toRecord, toRecordOrNull } from '@sim/utils/object' import { writeStderr } from '#sim-cli/output/io' import { styles } from '#sim-cli/output/presentation' import { truncationMetadata } from '#sim-cli/output/truncation' -import type { OutputFormat } from '../config/index' +import { isMachineFormat, type OutputFormat } from '../config/index' import type { ColumnSpec, CommandSpec } from '../contract/types' import type { V2OperationName } from '../generated/v2-api' import { nextStepText } from '../output/next-step' @@ -532,11 +532,6 @@ function clippedSubject(flag: string): string { return subject ? `the ${spellOut(subject)} it returned` : 'this result' } -/** Whether `format` prints one parseable document rather than lines for a person. */ -function isMachineFormat(format: OutputFormat): boolean { - return format === 'json' || format === 'yaml' -} - /** A result whose `next` a person reads: its command, then why ({@link nextStepText}). */ function withNextText(data: unknown): unknown { if (!isRecordLike(data)) return data diff --git a/packages/sim-cli/src/runtime/run-next.ts b/packages/sim-cli/src/runtime/run-next.ts index c4ca50a089d..e56632f215a 100644 --- a/packages/sim-cli/src/runtime/run-next.ts +++ b/packages/sim-cli/src/runtime/run-next.ts @@ -1,3 +1,4 @@ +import { AsyncLocalStorage } from 'node:async_hooks' import { isRecordLike, toArray, toRecordOrNull } from '@sim/utils/object' import type { Command } from 'commander' import type { V2OperationName } from '../generated/v2-api' @@ -54,6 +55,46 @@ export function typedCommandLine( return words.join(' ') } +/** The command whose action is running, for code below it that holds no `Command`. */ +const invoked = new AsyncLocalStorage() + +/** Runs `work` as `command`'s action, so {@link invokedSim} reads the options it was given. */ +export function runInvoked(command: Command, work: () => T): T { + return invoked.run(command, work) +} + +/** + * {@link simInvocation} of the command whose action is running, for a hint printed far from it + * (a directory reader's refusal); bare `sim` outside one. + */ +export function invokedSim(): string { + const command = invoked.getStore() + return command ? simInvocation(command) : 'sim' +} + +/** The root options that choose the server, which a command printed to run next keeps. */ +const SERVER_OPTIONS: ReadonlySet = new Set(['profile', 'endpoint']) + +/** + * `sim` with the root `--profile` and `--endpoint` the caller typed, so a command printed for the + * caller to run next reaches the server this one did. `--workspace` is left out: the source + * commands that print one act on a directory that pins its workspace. + */ +export function simInvocation(command: Command): string { + let root = command + while (root.parent) root = root.parent + const words = ['sim'] + for (const option of root.options) { + const key = option.attributeName() + if (!option.long || !SERVER_OPTIONS.has(key) || root.getOptionValueSource(key) !== 'cli') { + continue + } + const value = root.getOptionValue(key) + if (typeof value === 'string') words.push(option.long, shellArgument(value)) + } + return words.join(' ') +} + function resumeCommand(runId: string, workflowId: string, contextId: string): string { return `sim workflows runs resume ${shellArgument(runId)} --workflow ${shellArgument(workflowId)} --context ${shellArgument(contextId)}` } diff --git a/packages/sim-cli/src/terminal.ts b/packages/sim-cli/src/terminal.ts index f8caedde599..a59e671987f 100644 --- a/packages/sim-cli/src/terminal.ts +++ b/packages/sim-cli/src/terminal.ts @@ -3,7 +3,7 @@ import { dump } from 'js-yaml' import { styles } from '#sim-cli/output/presentation' import { CliUpdateError } from '#sim-cli/update/install' import { enclosingWorkspace } from './commands/protocol/source-dir' -import { ProfileConfigError } from './config/index' +import { isMachineFormat, ProfileConfigError } from './config/index' import { profileFrom, setWorkingDirectoryWorkspace } from './context' import { CliExit } from './embed-context' import { @@ -44,7 +44,7 @@ function explainFailure(error: unknown, program: Command): number | null { } catch { /** Preserve the original error when configuration is invalid. */ } - if (output === 'json' || output === 'yaml') { + if (isMachineFormat(output)) { const payload = { error: { code: error.code ?? 'CLI_ERROR', diff --git a/packages/utils/src/workflow-references.ts b/packages/utils/src/workflow-references.ts index 86934598108..081ae21f0c6 100644 --- a/packages/utils/src/workflow-references.ts +++ b/packages/utils/src/workflow-references.ts @@ -14,6 +14,18 @@ export interface WorkflowReferenceToken { end: number } +/** + * Whether `` reads a file's path in a Function's sandbox: three or more segments, + * the last `path`. The run splices that path into code raw, even inside a string literal (it can + * hold no quote), where any other reference is spliced as a literal of its value. + */ +export function isFilePathReference(reference: string): boolean { + const segments = reference + .slice(REFERENCE_START.length, -REFERENCE_END.length) + .split(REFERENCE_PATH_DELIMITER) + return segments.length >= 3 && segments.at(-1) === 'path' +} + /** Separates comparison characters before the final `` segment. */ export function splitWorkflowReferenceSegment( segment: string diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index 025d1a794f1..28a4322c0b3 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -282,7 +282,10 @@ changes how an unedited field stores it. `E_CODE_FILE_MISSING`. JavaScript files use `$ref.block.path` for `` and `$env.NAME` for `{{NAME}}`, rewritten back on compile; Python and shell files are verbatim, so they write `` and `{{NAME}}` themselves, and a `$ref` or `$env` in one is -`W_CODE_FILE_REF_SYNTAX` (the apply refuses it in a file the edit changed). A `` tag in +`W_CODE_FILE_REF_SYNTAX` (the apply refuses it in a file the edit changed). The run substitutes a +tag in a Python file as a Python literal, so a tag between quotes of its own (`""`) +gets its quotes twice: `W_CODE_FILE_REF_QUOTED`; write it unquoted (a file's `.path` is spliced raw, +so it stays quoted). A `` tag in any code file (a JavaScript string included) is checked like a `$ref` chain. `$ref` names a block by its key (`$ref.triageagent.content`), not its ident; a chain that names no block or variable is `W_UNRESOLVED_REF` at the file location (the hint names the key when the head is an ident or a @@ -457,6 +460,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `E_CODE_FILE_PATH` | A code file path outside the directory, or with the wrong extension. | | `W_CODE_FILE_INLINED` | Print: the code could not round-trip through a file and was inlined. | | `W_CODE_FILE_REF_SYNTAX` | `$ref.key.path` or `$env.NAME` in a Python or shell code file, which runs as text; the hint names the `` or `{{NAME}}` form. Refused as `E_APPLY_CODE_FILE_REF_SYNTAX` in a file the edit changed. | +| `W_CODE_FILE_REF_QUOTED` | A `` tag between quotes of its own in a Python code file (`""`): the run substitutes it as a Python literal, so a string value arrives with its quotes in it. Remove the quotes. A file's path (`open('')`), spliced raw, is not reported. | | `W_UNRESOLVED_REF` | Print: a stored `` token that resolves to nothing. Compile: a code file `$ref` chain that does. Either is kept as text. | | `W_FORWARD_REF_LITERALIZED` | Print: a ref in a cycle printed as text. | | `W_COMMENT_MOVED` | A comment hoisted to the nearest anchor. | diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 22ffa30d0c6..7bc14648ed5 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -4,6 +4,7 @@ import { isRecordLike } from '@sim/utils/object' import { utf8ByteLength } from '@sim/utils/paste' import { findWorkflowReferenceTokens, + isFilePathReference, isLikelyWorkflowReferenceSegment, } from '@sim/utils/workflow-references' import { @@ -41,7 +42,13 @@ import { } from '../catalog/surface' import type { CatalogBlock, CatalogSubBlock } from '../catalog/types' import { catalogBuildersOfType } from '../catalog/view' -import { type CodeFileLanguage, codeFileLanguage, codeFileRefs, fromCodeFile } from '../code-files' +import { + type CodeFileLanguage, + type CodeFileRef, + codeFileLanguage, + codeFileRefs, + fromCodeFile, +} from '../code-files' import { isIdentifierName, LOOP_PROPERTIES, parseStoredPath } from '../code-files/ref-path' import { branchesAtTopLevel, ELSE_KEY, isElseTrue } from '../forms/condition' import { compileResponseParam, usesResponseForm } from '../forms/response' @@ -459,6 +466,7 @@ function parseCodeFile( } if (language !== 'javascript') reportScriptRefSyntax(ctx, path, text, language, decl.key) const refs = codeFileRefs(back.refs, text) + if (language === 'python') reportQuotedScriptRefs(ctx, path, text, refs, decl.key) if (refs.length > 0) ctx.codeFiles.chains.push({ path, blockKey: decl.key, refs }) return back.code } @@ -519,6 +527,39 @@ function reportScriptRefSyntax( } } +/** + * `W_CODE_FILE_REF_QUOTED` on each `` tag a Python file writes between quotes of its own + * (`""`, `''`): the run substitutes a tag as a Python literal (inside + * a string, as its JSON text), so the value arrives with its quotes in it. A tag inside longer text + * (a JSON body a string builds) reads that JSON text on purpose, a file's path is spliced raw + * (`isFilePathReference`), and a shell file quotes a tag in quotes correctly, so none is reported. + */ +function reportQuotedScriptRefs( + ctx: CompileContext, + path: string, + text: string, + refs: readonly CodeFileRef[], + blockKey: BlockKey +): void { + for (const ref of refs) { + if (ref.kind !== 'ref' || !ref.tag) continue + const quote = text[ref.start - 1] + if ((quote !== '"' && quote !== "'") || text[ref.end] !== quote) continue + const tag = text.slice(ref.start, ref.end) + // A file's path is spliced raw into its quotes: `open('')` is right. + if (isFilePathReference(tag)) continue + ctx.reporter.report( + 'W_CODE_FILE_REF_QUOTED', + `${quote}${tag}${quote} quotes a reference the run already substitutes as a Python literal, so a string value arrives with its quotes in it.`, + { file: path, start: ref.start - 1, end: ref.end + 1 }, + { + hint: `References are substituted as language literals: remove the quotes and write ${tag}.`, + blockKey, + } + ) + } +} + interface WrittenParam { property: ObjectProperty param: string diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 2e672e1c4b1..5efabcfedf8 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1893,6 +1893,59 @@ describe('reference tags written in a code file', () => { }) }) +describe('a quoted tag in a Python code file', () => { + const quoted = (result: CompileResult) => + result.diagnostics + .filter((d) => d.code === 'W_CODE_FILE_REF_QUOTED') + .map((d) => ({ hint: d.hint, file: d.span.file, line: d.span.line, column: d.span.column })) + const withFile = (language: 'python' | 'shell', file: string, text: string) => + run( + source( + [ + START, + `const f = fn('F', { language: '${language}', code: codeFile('./functions/${file}') })`, + 'start.to(f)', + ].join('\n') + ), + { [`workflows/functions/${file}`]: text } + ) + + it('reports a tag between quotes of its own, which the run substitutes already quoted', () => { + const result = withFile( + 'python', + 'f.py', + 'country = ""\ncity = \'\'\nreturn [country, city]' + ) + expect(quoted(result)).toEqual([ + { + hint: 'References are substituted as language literals: remove the quotes and write .', + file: 'workflows/functions/f.py', + line: 1, + column: 11, + }, + { + hint: 'References are substituted as language literals: remove the quotes and write .', + file: 'workflows/functions/f.py', + line: 2, + column: 8, + }, + ]) + }) + + it("leaves an unquoted tag, a tag inside a longer string, a quoted file's path and a shell file alone", () => { + expect( + quoted( + withFile( + 'python', + 'f.py', + "country = \nbody = '{\"country\": }'\nwith open('') as f:\n return [country, body, f.read()]" + ) + ) + ).toEqual([]) + expect(quoted(withFile('shell', 'f.sh', 'echo ""'))).toEqual([]) + }) +}) + describe('$ref and $env in a Python or shell code file', () => { const syntax = (result: CompileResult) => result.diagnostics diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index d1c772a1414..2540cdc1f3e 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -300,6 +300,14 @@ const CODE_FILE_CODES = [ * round-trips; refused as `E_APPLY_CODE_FILE_REF_SYNTAX` in a file the edit changed. */ 'W_CODE_FILE_REF_SYNTAX', + /** + * A `` tag a Python code file writes between quotes of its own (`""`): + * the run substitutes a tag as a Python literal (inside a string, as its JSON text), so a string + * value arrives with its quotes in it; a file's `.path`, spliced raw, is not reported. A warning: + * an object's JSON text is a reading someone may want, and stored code written in the editor + * may hold the form. + */ + 'W_CODE_FILE_REF_QUOTED', ] as const /** References and comments, shared by compile and print. */ diff --git a/scripts/check-unused-exports.baseline.json b/scripts/check-unused-exports.baseline.json index 88015bd478d..14ede70f66c 100644 --- a/scripts/check-unused-exports.baseline.json +++ b/scripts/check-unused-exports.baseline.json @@ -3662,7 +3662,6 @@ "apps/sim/lib/api/contracts/v2/workflows.ts#v2ActivateWorkflowVersionDataSchema", "apps/sim/lib/api/contracts/v2/workflows.ts#v2AgentToolInputSchema", "apps/sim/lib/api/contracts/v2/workflows.ts#v2AgentToolSchema", - "apps/sim/lib/api/contracts/v2/workflows.ts#v2ApplyWorkflowOperationsBodySchema", "apps/sim/lib/api/contracts/v2/workflows.ts#v2ApplyWorkflowVariablesBodySchema", "apps/sim/lib/api/contracts/v2/workflows.ts#v2ApplyWorkflowVariablesDataSchema", "apps/sim/lib/api/contracts/v2/workflows.ts#v2ArchivedWorkflowMcpToolSchema",