diff --git a/apps/docs/content/docs/cli/index.mdx b/apps/docs/content/docs/cli/index.mdx index 8f9b51a27a1..51227641aa7 100644 --- a/apps/docs/content/docs/cli/index.mdx +++ b/apps/docs/content/docs/cli/index.mdx @@ -77,7 +77,7 @@ b8c0d247-9e13-4a86-97f5-2ad4e1638c09 Weekly digest /Reporting no 18 sim workflows run 3a9e21d8-5f47-4c0b-b2ea-91d7c6034ef8 --input '{"ticketId":"T-4821"}' ``` -Ordinary execution runs the active deployment. Deploy from the workflow builder or with `sim workflows deploy `; its first line, `live`, says which version serves, and while a new version activates it names the version still serving. To run an earlier deployed version, pass `--deployment-version `; it needs workspace write access, through a full-access API key or an OAuth token with `api:write`, and child workflows still run their own active deployment. To execute the current saved workflow state, use `sim workflows run --draft`. To test it without sending its writes, use `--dry`: each write is answered with a placeholder and listed with its request under `sideEffects` in the result. +Ordinary execution runs the active deployment. Deploy from the workflow builder or with `sim workflows deploy `; its `live` line (last, before any `next`) says which version serves, and while a new version activates it names the version still serving. To run an earlier deployed version, pass `--deployment-version `; it needs workspace write access, through a full-access API key or an OAuth token with `api:write`, and child workflows still run their own active deployment. To execute the current saved workflow state, use `sim workflows run --draft`. To test it without sending its writes, use `--dry`: each write is answered with a placeholder and listed with its request under `sideEffects` in the result. ## How commands are shaped diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index e4125d50b5b..6513b966498 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8617,7 +8617,7 @@ API request and response schemas: [getSourceResources](/api-reference/workflows/ Show a workflow’s draft as TypeScript source with its identity lock ```bash -sim workflows source get [options] +sim workflows source get [options] ``` **Arguments** @@ -8626,7 +8626,7 @@ sim workflows source get [options] | Argument | Required | Description | | --- | --- | --- | -| `workflowId` | Yes | Unique workflow identifier. | +| `workflow` | Yes | Workflow id, or its exact name | @@ -8642,7 +8642,7 @@ sim workflows source get [options] -Exit codes with --dir: 0 written; 1 the command failed, the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force); 7 the workflow is too large to print as source; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. +Exit codes with --dir: 0 written; 1 the command failed, no workflow or several are named exactly the name given (WORKFLOW_NOT_FOUND, WORKFLOW_NAME_AMBIGUOUS: each candidate is listed with its id), the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force); 7 the workflow is too large to print as source; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. API request and response schemas: [getWorkflowSource](/api-reference/workflows/getWorkflowSource). @@ -8675,14 +8675,15 @@ 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. | -| `--deploy` | No | After the write is saved, deploy the workflow (as `sim workflows deploy ` does). | +| `--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. | +| `--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. | -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), the --run test run did not complete (the draft is saved; nothing was deployed), or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. -API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [getSourceResources](/api-reference/workflows/getSourceResources). +API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [getSourceResources](/api-reference/workflows/getSourceResources), [executeWorkflow](/api-reference/workflows/executeWorkflowV2). ### sim workflows source create @@ -8705,13 +8706,14 @@ 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. | -| `--deploy` | No | After the write is saved, deploy the workflow (as `sim workflows deploy ` does). | +| `--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. | +| `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). | -Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), the --run test run did not complete (the workflow is created; nothing was deployed), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. -API request and response schemas: [createWorkflowFromSource](/api-reference/workflows/createWorkflowFromSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). +API request and response schemas: [createWorkflowFromSource](/api-reference/workflows/createWorkflowFromSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [executeWorkflow](/api-reference/workflows/executeWorkflowV2). ### sim workflows source check diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 725eb959c08..2c7111d150e 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1374,7 +1374,7 @@ API request and response schemas: [createWorkflowFolder](/api-reference/workflow ### Show a workflow’s draft as TypeScript source with its identity lock ```bash -sim workflows source get [options] +sim workflows source get [options] ``` **Arguments** @@ -1383,7 +1383,7 @@ sim workflows source get [options] | Argument | Required | Description | | --- | --- | --- | -| `workflowId` | Yes | Unique workflow identifier. | +| `workflow` | Yes | Workflow id, or its exact name | @@ -1399,7 +1399,7 @@ sim workflows source get [options] -Exit codes with --dir: 0 written; 1 the command failed, the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force); 7 the workflow is too large to print as source; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. +Exit codes with --dir: 0 written; 1 the command failed, no workflow or several are named exactly the name given (WORKFLOW_NOT_FOUND, WORKFLOW_NAME_AMBIGUOUS: each candidate is listed with its id), the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force); 7 the workflow is too large to print as source; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. API request and response schemas: [getWorkflowSource](/api-reference/workflows/getWorkflowSource). @@ -1447,13 +1447,14 @@ 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. | -| `--deploy` | No | After the write is saved, deploy the workflow (as `sim workflows deploy ` does). | +| `--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. | +| `--deploy` | No | After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does). | -Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), the --run test run did not complete (the workflow is created; nothing was deployed), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. -API request and response schemas: [createWorkflowFromSource](/api-reference/workflows/createWorkflowFromSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). +API request and response schemas: [createWorkflowFromSource](/api-reference/workflows/createWorkflowFromSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [executeWorkflow](/api-reference/workflows/executeWorkflowV2). ### Apply a workflow source directory to a workflow draft @@ -1482,14 +1483,15 @@ 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. | -| `--deploy` | No | After the write is saved, deploy the workflow (as `sim workflows deploy ` does). | +| `--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. | +| `--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. | -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), the --run test run did not complete (the draft is saved; nothing was deployed), or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. -API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [getSourceResources](/api-reference/workflows/getSourceResources). +API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [getSourceResources](/api-reference/workflows/getSourceResources), [executeWorkflow](/api-reference/workflows/executeWorkflowV2). ### Show the block catalog workflow source is checked against diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx index b90191e1eed..95a4cbb2861 100644 --- a/apps/docs/content/docs/workflows/code/coding-agents.mdx +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -16,17 +16,19 @@ Point the agent at `.sim/AGENTS.md` before it edits. ## The loop -1. `sim workflows source get --dir ` writes the workflow and the guide. +1. `sim workflows source get --dir && cat /.sim/AGENTS.md` writes the workflow and the guide and reads the guide's primer in the same call. `` is the workflow's id or its exact name. 2. Write every file the change needs. 3. Run one chained command, then fix whatever it reports in the next step: ```bash - sim workflows source check --dir && sim workflows source apply --dir --yes && sim workflows run --dry --input '{...}' + sim workflows source check --dir && sim workflows source apply --dir --yes --run '{...}' --deploy ``` A non-zero exit code stops the chain at the first failure. `apply` compiles the source and compares it with the saved draft again, so an agent can skip `--dry`. `check` also type-checks the directory, so the chain needs no separate `tsc`. People and CI use `apply --dry` to review the plan, and `status` shows what changed and what to run next. - `run --dry` tests the saved draft without sending its writes: each write returns a placeholder and is listed under `sideEffects` with the request it would have sent, so the agent checks payloads instead of cleaning up rows or messages. `--allow ` sends one block's writes for real against a test resource, and `--draft` runs everything for real. + `--run` dry-runs the saved draft with that input, and `--deploy` deploys only if the run completed; a run that fails exits 1, deploys nothing, and maps the failing block to its file and line. Drop `--deploy` to keep the change a draft. The result opens with a one-line `summary` and ends with `errors`, `warnings`, `live` and `next`, so a `| head` or `| tail` of it still shows the outcome. + + The dry run (also `sim workflows run --dry`) tests the saved draft without sending its writes: each write returns a placeholder and is listed under `sideEffects` with the request it would have sent, so the agent checks payloads instead of cleaning up rows or messages. `--allow ` sends one block's writes for real against a test resource, and `--draft` runs everything for real. For a whole workspace, use `sim workspaces source` with the same steps; see [Manage a workspace as code](/workflows/code/workspace). diff --git a/apps/docs/content/docs/workflows/code/edit.mdx b/apps/docs/content/docs/workflows/code/edit.mdx index f648b90ab02..853237a8973 100644 --- a/apps/docs/content/docs/workflows/code/edit.mdx +++ b/apps/docs/content/docs/workflows/code/edit.mdx @@ -76,7 +76,7 @@ Editing the name or description in `workflow('…')` renames or redescribes the ### Deploy -Saving writes the draft. Add `--deploy` to deploy right after the save, which also prints the URL of each webhook the workflow now serves. Without it, a deployed workflow whose draft now differs prints the `sim workflows deploy` command to run. +Saving writes the draft. Add `--deploy` to deploy right after the save, which also prints the URL of each webhook the workflow now serves. Add `--run ''` to dry-run the saved draft with that input first: with `--deploy`, it deploys only if the run completed. Without `--deploy`, a deployed workflow whose draft now differs prints the `sim workflows deploy` command to run, pinned to the draft this apply saved; after an apply without `--run`, it also names the apply that tests and deploys in one step. ### Deletes diff --git a/apps/docs/content/docs/workflows/code/exit-codes.mdx b/apps/docs/content/docs/workflows/code/exit-codes.mdx index 5b16b21f531..2be5221a26c 100644 --- a/apps/docs/content/docs/workflows/code/exit-codes.mdx +++ b/apps/docs/content/docs/workflows/code/exit-codes.mdx @@ -31,7 +31,7 @@ The table for the kind of directory you work in. Both are built from the table ` | Code | Meaning | What to do | | --- | --- | --- | | `0` | Applied or created, a dry run or check with no errors, or a clean status | Go on | - | `1` | The source has errors (each printed as `file:line:column` with a hint), a locked block (`E_APPLY_LOCKED_BLOCK`), a name another workflow holds (`SOURCE_NAME_TAKEN`), a cancelled prompt, or the command failed | Fix what it printed and run it again | + | `1` | The source has errors (each printed as `file:line:column` with a hint), a locked block (`E_APPLY_LOCKED_BLOCK`), a name another workflow holds (`SOURCE_NAME_TAKEN`), a `--run` test run that did not complete, a cancelled prompt, or the command failed | Fix what it printed and run it again | | `5` | Stale (`SOURCE_STALE`, or `E_APPLY_STALE` on a dry run): the server changed what this directory was read from, and nothing was written | `sim workflows source get --dir `, reapply your edit there, dry-run, apply | | `6` | A workflow or its folder is locked (`E_APPLY_LOCKED`); a locked block exits 1 instead | Ask someone to unlock it in the workflow builder | | `7` | The source is over the size limits (on a get, status or diff too) | Split function code, or remove blocks or resources | diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index a9802c358a0..5d5b767e1ae 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -13171,7 +13171,7 @@ { "lang": "bash", "meta": null, - "sha256": "29cc30facfddd548aa5873383ac3d90a6b392cf120894fd73a735f266196540d", + "sha256": "6428ea92c442ec004f650fa6da178d53c3163dcd4895e1a24beb07bb93da1928", "bytes": null, "line": null }, @@ -17750,7 +17750,7 @@ { "lang": "bash", "meta": null, - "sha256": "29cc30facfddd548aa5873383ac3d90a6b392cf120894fd73a735f266196540d", + "sha256": "6428ea92c442ec004f650fa6da178d53c3163dcd4895e1a24beb07bb93da1928", "bytes": null, "line": null }, diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts index c3f02b5ed65..4200ceb9ac8 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -100,15 +100,15 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo }, { code: 1, - meaning: `The source has errors (each printed as \`file:line:column\` with a hint), a locked block (\`E_APPLY_LOCKED_BLOCK\`), ${prefix === 'sim workspaces source' ? 'a name another resource holds (`E_NAME_TAKEN`)' : 'a name another workflow holds (`SOURCE_NAME_TAKEN`)'}, a cancelled prompt, or the command failed`, + meaning: `The source has errors (each printed as \`file:line:column\` with a hint), a locked block (\`E_APPLY_LOCKED_BLOCK\`), ${prefix === 'sim workspaces source' ? 'a name another resource holds (`E_NAME_TAKEN`)' : 'a name another workflow holds (`SOURCE_NAME_TAKEN`), a `--run` test run that did not complete'}, a cancelled prompt, or the command failed`, next: 'Fix what it printed and run it again', help: { 'workflows source apply': - "the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), or the command failed", + "the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), the --run test run did not complete (the draft is saved; nothing was deployed), or the command failed", 'workflows source create': - 'the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another)', + 'the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), the --run test run did not complete (the workflow is created; nothing was deployed), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another)', 'workflows source get': - "the command failed, the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force)", + "the command failed, no workflow or several are named exactly the name given (WORKFLOW_NOT_FOUND, WORKFLOW_NAME_AMBIGUOUS: each candidate is listed with its id), the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force)", 'workflows source status': 'the command failed', 'workspaces source apply': 'the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace or SIM_WORKSPACE names (SOURCE_OTHER_WORKSPACE: drop it, or promote it with --to; without either an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed', diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.test.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.test.ts deleted file mode 100644 index 25f8c1c48a5..00000000000 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { WORKFLOW_SOURCE_LOOP_HELP } from './source-loop-help' -import { sourcePrimer } from './source-primer' - -describe('the edit loop of sim workflows source --help', () => { - it('chains the same test run the primer does', () => { - const primerRun = sourcePrimer('workflow').match(/&& (sim workflows run [^`]+)`/)?.[1] - expect(primerRun).toBeDefined() - expect(WORKFLOW_SOURCE_LOOP_HELP).toContain(`&& ${primerRun}`) - }) -}) 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 289599bcf34..bcf25b792a9 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -5,85 +5,64 @@ import { SOURCE_DRIFT_EXIT_CODE, SOURCE_LOCAL_CHANGES_EXIT_CODE } from '../../exit-codes' import { SOURCE_AGENTS_FILE } from './source-dir' -/** The loop's steps as aligned `command what it does` rows. */ -function loopRows(rows: ReadonlyArray): string { - const width = Math.max(...rows.map(([command]) => command.length)) + 3 - return rows.map(([command, what]) => ` ${command.padEnd(width)}${what}`.trimEnd()).join('\n') -} - /** Where the commands of either group find their workspace. */ -const WORKSPACE_LINE = `Workspace: a directory records it (.sim/base.json, or a starter's .sim/starter.json); any other -command takes -w , SIM_WORKSPACE or the profile's (export SIM_WORKSPACE once, or keep only the -ID in a variable: one holding "--workspace " is one argument, an unknown option alone and the -whole ID after -w).` +const WORKSPACE_LINE = `Workspace: a directory records it (.sim/base.json, or a starter's .sim/starter.json); other +commands take -w or SIM_WORKSPACE (a variable holding "--workspace " is one argument: keep +only the ID in it).` /** Where an author reads a run's result after running the workflow the source defines. */ -const RUN_LOGS_LINE = `Test a run: \`sim workflows run --dry\` runs the saved draft without sending its writes -and lists each one, with the request it would have sent, under sideEffects (--allow sends -one block's for real; --draft runs everything for real). Debug it with \`sim logs list --workflow -\` and \`sim logs get --trace --no-include-workflow-state\` (each block's -resolved inputs and errors).` +const RUN_LOGS_LINE = `Rerun or debug: \`sim workflows run --dry --input '{…}'\` (writes stubbed, listed +under sideEffects; --allow sends one block's, --draft sends all); \`sim logs get +--trace --no-include-workflow-state\` shows each block's resolved inputs and errors (\`sim logs list +--workflow \` lists runs).` /** The status line both groups end with, for a directory at `dir`. */ function statusLine(group: string, dir: string): string { - return `\`${group} status --dir ${dir}\` shows what applying would do and -whether the server changed since the get (exit 0 clean, ${SOURCE_LOCAL_CHANGES_EXIT_CODE} your edits only, ${SOURCE_DRIFT_EXIT_CODE} the server changed). -Every exit code, and the rules for editing: ${SOURCE_AGENTS_FILE} in the directory.` + return `\`${group} status --dir ${dir}\`: what applying would do and whether the server changed +(exit 0 clean, ${SOURCE_LOCAL_CHANGES_EXIT_CODE} your edits only, ${SOURCE_DRIFT_EXIT_CODE} the server changed). Exit codes and editing rules: ${SOURCE_AGENTS_FILE}.` } /** * The top of `sim workflows source --help`, above the usage line: what a workflow's source leaves * out, so a task that changes a table starts in the directory that holds it. */ -export const WORKFLOW_SOURCE_SCOPE_HELP = `A workflow's source holds that workflow alone. A table's columns and rows, and every other -workspace resource, are edited with \`sim workspaces source get --dir \` (tables/.ts), -or read with \`sim tables rows list \`. \`workflows source get\` names the tables a -workflow uses (\`tables\`). +export const WORKFLOW_SOURCE_SCOPE_HELP = `A workflow's source holds that workflow alone: edit a table's columns and rows with +\`sim workspaces source get --dir \` (tables/.ts), read rows with \`sim tables rows +list
\`. \`workflows source get\` names the tables a workflow uses (\`tables\`). ` -/** `sim workflows source --help`, after the command list. */ +/** + * `sim workflows source --help`, after the command list. The get reads the primer in the same + * shell call, so the agent edits without a turn spent opening it. + */ export const WORKFLOW_SOURCE_LOOP_HELP = ` -The loop: -${loopRows([ - ['sim workflows source get --dir ./wf', 'write workflow.ts, functions/* and .sim/'], - ['edit ./wf/workflow.ts', 'every file first, then the one command below'], - ['sim workflows source check --dir ./wf', 'compile + types: each error as file:line:column'], - [' && sim workflows source apply --dir ./wf --yes', 'save the draft (it re-checks)'], - [" && sim workflows run --dry --input '{…}'", 'test the draft, sending no writes'], -])} -Run those three as one chained command: a non-zero exit stops it at the first failure, and the next -step fixes what it reported. Check also type-checks with TypeScript (installed once, on its first -run; --no-types skips it). For review, \`apply --dry\` prints the plan and writes nothing. +The loop, two shell calls (: its id or exact name): + sim workflows source get --dir ./wf && cat ./wf/${SOURCE_AGENTS_FILE} + edit every file, then: sim workflows source check --dir ./wf && sim workflows source apply --dir ./wf --yes --run '{…}' --deploy +A non-zero exit stops the chain at the first failure; fix what it reported and run it again. check +compiles and type-checks (TypeScript installs on first run; --no-types skips it); apply re-checks, +saves the draft and rewrites the files; --run dry-runs that input on the saved draft (writes +stubbed, listed under run.sideEffects); --deploy deploys only if that run completed (without it the +draft stays undeployed). --allow-delete lets an edit remove a block or variable; apply --dry only +prints the plan; get --force replaces unapplied edits or another workflow's source. A new workflow: \`sim workflows source create --dir ./new --workspace \` writes a -starter that records its workspace; edit and check it, then \`create --dir ./new --yes\` creates the -workflow there, and the loop above goes on from there. +starter; edit and check it, then \`create --dir ./new --yes --run '{…}' --deploy\`. ${WORKSPACE_LINE} ${RUN_LOGS_LINE} - -Flags the loop needs: --allow-delete (apply: an edit that removes a block or variable is refused -without it), --deploy (apply, create: also deploy the saved draft), --force (get: replace another -workflow's source, or edits no apply has saved). ${statusLine('sim workflows source', './wf')}` /** `sim workspaces source --help`, after the command list. */ export const WORKSPACE_SOURCE_LOOP_HELP = ` -The loop: -${loopRows([ - ['sim workspaces source get --dir ./ws', 'write tables/, workflows//, … and .sim/'], - ['edit the files', 'every file first; a new workflow: workflows//workflow.ts'], - ['sim workspaces source check --dir ./ws', 'compile + types: each error as file:line:column'], - [' && sim workspaces source apply --dir ./ws --yes', 'write it to the workspace (it re-checks)'], -])} -Run those two as one chained command: a non-zero exit stops it at the first failure, and the next -step fixes what it reported. Check also type-checks with TypeScript (installed once, on its first -run; --no-types skips it). For review, \`apply --dry\` prints the plan and writes nothing. -Promote dev to prod: \`sim workspaces source apply --dir ./ws --to --dry\`, then ---yes. +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 +A non-zero exit stops the chain at the first failure; fix what it reported and run it again. check +compiles and type-checks (TypeScript installs on first run; --no-types skips it); apply re-checks +and writes the workspace; a workflow deploys on apply when deployments/.ts declares it. +--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. ${WORKSPACE_LINE} ${RUN_LOGS_LINE} - -Flags the loop needs: --allow-delete (apply: removing a resource, a column, rows or a document, -or a workflow's block or variable, is refused without it), --force (get: replace edits no apply -has saved). A workflow deploys on apply when -deployments/.ts declares it. ${statusLine('sim workspaces source', './ws')}` diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index f70c7639558..66d0cf9384c 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -43,26 +43,25 @@ function sharedRules(group: string, extra: { renames?: string; patterns?: string ${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\` (a Function's \`shape.errorMessage\`: message only). - - Retry: block meta, the 3rd argument, \`{ retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } }\`; an \`api\` block's \`retries: 3\`, \`retryDelayMs: 500\` resend only its request. - - Child: \`workflowId: childWorkflow('enrich-lead')\`, \`inputMapping: { email: start.email }\`; read \`enrich.result.data.\`. + - 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 } }\`. + - 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 (\`sim workflows run --deployment-version \`: that version); \`--draft\` runs the draft for real (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders; a read given one too: \`placeholder\`); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--allow \` sends its writes (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 (\`--deployment-version \`: that version); \`--draft\` runs the draft for real (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders; a read given one too: \`placeholder\`); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--allow \` sends its writes (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 \`. - **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo in a fresh \`${group} 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.` } const WORKFLOW_PRIMER = `# Sim workflow source: primer -\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and 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 ends in \`sim workflows source create --dir . --yes\`). +\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and 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, and its loop runs \`create\` where the loop below runs \`apply\`: no workflow exists until then). -**Edit loop**: write every file, then run one chained command; fix what it reports: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`. \`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites \`${SOURCE_ENTRY_FILE}\`: reread it before the next edit. +**Edit loop**: write every file, then run one chained command; fix what it reports: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes --run '{…}' --deploy\` applies, dry-runs that input on the draft, and deploys only if the run completed (no \`--deploy\`: stays a draft). \`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites \`${SOURCE_ENTRY_FILE}\`: reread it before the next edit. - **Scope**: the workflow alone. A table's columns and rows: \`sim workspaces source get --dir \`. - **Deletes**: removing a block or variable needs \`apply --allow-delete\`. -- **Deploy**: \`apply --deploy\`, or later \`sim workflows deploy \`. ${sharedRules('sim workflows source')} ` @@ -102,7 +101,7 @@ export function agentsPointer(kind: PrimerKind): string { ${kind === 'workflow' ? '`workflow.ts` is a Sim workflow as TypeScript that Sim compiles' : 'This directory is a Sim workspace as files that Sim applies'}; nothing in it runs. Read \`${SOURCE_AGENTS_FILE}\` before editing: the rules, the edit loop, patterns and exit codes. -Loop: write every file, then one chained command: \`${group} check --dir . && ${group} apply --dir . --yes\`; fix what it reports next. +Loop: write every file, then one chained command: \`${group} check --dir . && ${group} apply --dir . --yes${kind === 'workflow' ? " --run '{…}' --deploy" : ''}\`; fix what it reports next.${kind === 'workflow' ? ` A starter (\`${SOURCE_STARTER_FILE}\`, no workflow yet) runs \`create\` in place of \`apply\`.` : ''} Exit codes: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (get a fresh copy and redo the edit), ${SOURCE_DRIFT_EXIT_CODE} \`status\`: the server changed. ` } diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index f53017e0b30..31999489f5c 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -250,12 +250,12 @@ const ADVANCED_GUIDE = `# Sim workflow source: advanced ## Edit loop in detail -Batch it: write every file first, then run steps 2 and 4 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --dry --input '{…}'\`, and fix what it reports in the next step. 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's \`run --dry\` is another thing: it executes the saved draft, while a run without \`--dry\` or \`--draft\` 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; 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 it: write every file first, then run steps 2 and 4 (with a test run and the deploy) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes --run '{…}' --deploy\`, and fix what it reports in the next step. 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 (\`--run\`, or \`sim workflows run --dry --input '{…}'\`) 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 \`.\`. 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\`. 3. \`sim workflows source status --dir .\`: the files you changed (\`sim workflows source diff --dir .\` shows the edits), whether the workflow changed on the server since the get, and the command to run next (\`--offline\`: skip the server). Then \`sim workflows source apply --dir . --dry\` until it exits 0. -4. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). \`--deploy\` also deploys it; without it, a deployed workflow's next \`sim workflows deploy --expected-draft-fingerprint \` is printed, which deploys only the draft this apply saved. Its first line, \`live\`, says what serves: \`not deployed\`, \`version N, matches the draft\`, \`version N, draft has undeployed changes\`, or after \`--deploy\` \`version N still serving; version M activating\` until the deploy is live (\`sim workflows deployment status \` shows when). It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). +4. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). \`--run '{…}'\` then dry-runs that input on the saved draft (\`run\` in the result: status, output, side effects; a failed run exits 1 and maps the failing block to file:line), and \`--deploy\` deploys it only if that run completed (alone, it deploys right after the apply). Without \`--deploy\`, a deployed workflow's next is \`sim workflows deploy --expected-draft-fingerprint \`, which deploys only the draft this apply saved; after an apply without \`--run\` its reason names the same apply with \`--run '{…}' --deploy\`, which tests and deploys in one step. Its first line, \`summary\`, gives the counts, findings, test run and what is live; its last lines repeat \`errors\`, \`warnings\` and \`live\`, which says what serves: \`not deployed\`, \`version N, matches the draft\`, \`version N, draft has undeployed changes\`, or after \`--deploy\` \`version N still serving; version M activating\` until the deploy is live (\`sim workflows deployment status \` shows when). It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). 5. Exit ${SOURCE_STALE_EXIT_CODE} (\`SOURCE_STALE\`, HTTP 409, or \`E_APPLY_STALE\` on a dry run): the workflow changed and nothing was saved. Run \`sim workflows source get --dir \`, reapply your edit there, dry-run, apply. A get into this directory refuses to overwrite your unapplied edits unless you pass \`--force\`. Exit ${SOURCE_STALE_EXIT_CODE} right after an apply that ended without an answer (a timeout, a dropped connection) means the draft changed, by that apply or by someone else: get into a fresh directory and compare. Only when it holds your edit, run \`sim workflows source get --dir . --force\`; otherwise reapply your edit in the fresh directory. Editing the \`workflow('…')\` name or description renames or redescribes the workflow; a name another workflow in its folder holds is refused with \`E_NAME_TAKEN\`. Lines starting \`note:\` explain something the write did differently than the source says; read them. 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 2599bed7d8a..1b79a6c27ca 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -10,7 +10,7 @@ import { V2_OPERATIONS } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { readNdjson } from '../../http/ndjson' import { safeOneLine, sanitize } from '../../output/render' -import { callsOperations, connect } from '../../runtime/called-operations' +import { callsOperations, connect, type OperationClient } from '../../runtime/called-operations' import { runFailureMessage } from '../../runtime/execute' import { retypeApiError } from '../../runtime/naming' import { collectRepeated } from '../../runtime/options' @@ -274,7 +274,11 @@ async function resolveWorkflowRunSelection( * `overrides` name it: by id, a child's as `.`. The request payloads are in * the result itself (`--output json`). */ -function printSideEffects(sideEffects: unknown, overrides: unknown, workflowId: unknown): void { +export function printSideEffects( + sideEffects: unknown, + overrides: unknown, + workflowId: unknown +): void { if (!isRecordLike(sideEffects)) return const list = (key: string) => toArray(sideEffects[key]).filter(isRecordLike) const stubbed = list('stubbed') @@ -447,6 +451,63 @@ function stillRunning(runId: string, workflowId: string, waitedSeconds: number) `Run ${runId} is still ${snapshot.status} after ${waitedSeconds}s and continues in the background. Keep waiting: sim workflows runs wait ${runId} --workflow ${workflowId} --wait-timeout ${waitedSeconds}. Stop it: sim workflows runs cancel ${runId} --workflow ${workflowId}` } +/** Sends a run this command waits for and reads its answer over the heartbeat transport. */ +async function sendWaitedRun( + client: OperationClient<'executeWorkflow'>, + workflowId: string, + flags: Record, + workspaceId: string | null, + selection: WorkflowRunSelection | undefined, + waitTimeoutSeconds?: number +): Promise { + const request = await runRequest(workflowId, flags, workspaceId, selection, true) + const response = await client.requestRaw('executeWorkflow', { + params: request.params, + query: request.query, + body: waitTimeoutSeconds === undefined ? request.body : { ...request.body, waitTimeoutSeconds }, + headers: { ...request.headers, accept: WORKFLOW_RESULT_STREAM_CONTENT_TYPE }, + }) + return readWorkflowResult(response) +} + +/** + * The run record of `sim workflows run --dry --input `: the saved draft run + * with its writes stubbed, waited for. `input` is read as `--input` reads it (JSON, or `@file`). + * A failed run is returned, not thrown: the caller decides what it stops. + */ +export async function dryRunDraft( + client: OperationClient<'executeWorkflow'>, + workflowId: string, + input: string | undefined, + workspaceId: string | null +): Promise> { + const commandSpec = CLI_CONTRACT.executeWorkflow ?? {} + try { + const result = await sendWaitedRun( + client, + workflowId, + input === undefined ? {} : { input }, + workspaceId, + { source: 'draft', dry: true } + ) + // A dry run is never detached (it cannot take --wait-timeout); a server that did is reported. + if ('detachedRunId' in result) { + throw new SimApiError( + `The test run ${result.detachedRunId} continued in the background: sim workflows runs wait ${result.detachedRunId} --workflow ${workflowId}`, + 0 + ) + } + return result.settled + } catch (error) { + throw retypeApiError( + error, + 'executeWorkflow', + commandSpec, + V2_OPERATIONS.executeWorkflow as OperationSpec + ) + } +} + /** * Runs synchronously while keeping idle-limited HTTP paths active. * @@ -467,15 +528,14 @@ async function runWithResultStream( const commandSpec = CLI_CONTRACT.executeWorkflow ?? {} try { - const request = await runRequest(workflowId, flags, profile.workspaceId, selection, true) - const response = await client.requestRaw('executeWorkflow', { - params: request.params, - query: request.query, - body: - waitTimeoutSeconds === undefined ? request.body : { ...request.body, waitTimeoutSeconds }, - headers: { ...request.headers, accept: WORKFLOW_RESULT_STREAM_CONTENT_TYPE }, - }) - const result = await readWorkflowResult(response) + const result = await sendWaitedRun( + client, + workflowId, + flags, + profile.workspaceId, + selection, + waitTimeoutSeconds + ) if ('detachedRunId' in result) { // The server already spent the wait, so the run is read once and reported. const now = Date.now() 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 2da7593a8fc..c73be919692 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 @@ -11,6 +11,7 @@ import { import { hostname, tmpdir } from 'node:os' import { join } from 'node:path' import { toRecord } from '@sim/utils/object' +import { escapeRegExp } from '@sim/utils/string' import { compileWorkflow } from '@sim/workflow-code' import { fingerprintOf } from '@sim/workspace-code' import { Command } from 'commander' @@ -135,6 +136,7 @@ let stderrTty: boolean | undefined beforeEach(() => { contextMockState.output = 'json' request.mockReset() + contextMockFns.mockRequestRaw.mockReset() prompt.question.mockReset() stdinTty = process.stdin.isTTY stderrTty = process.stderr.isTTY @@ -621,7 +623,7 @@ describe('sim workflows source apply', () => { const printed = vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '' expect(JSON.parse(printed)).toMatchObject({ blocksModified: 1, - modified: [{ block: 'eachticket', fields: ['subflow'] }], + modified: ['eachticket (subflow)'], }) }) @@ -640,8 +642,8 @@ describe('sim workflows source apply', () => { expect(stderrLines().some((line) => line.includes('Removed: boom (function)'))).toBe(true) const printed = vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '' expect(JSON.parse(printed)).toMatchObject({ - added: [{ block: 'bang', type: 'function' }], - removed: [{ block: 'boom', type: 'function' }], + added: ['bang (function)'], + removed: ['boom (function)'], }) }) @@ -679,7 +681,7 @@ describe('sim workflows source apply', () => { const lines = vi.mocked(console.log).mock.calls.map((call) => call.join(' ')) expect(lines.find((line) => line.startsWith('modified\t'))).toBe( - 'modified\t[{"block":"eachticket","fields":["subflow"]}]' + 'modified\teachticket (subflow)' ) }) @@ -1075,6 +1077,79 @@ describe('sim workflows source apply', () => { ) }) + describe('--run', () => { + const RUN_PATH = `/api/v2/workflows/${WORKFLOW_ID}/execute` + const runAnswer = (record: Record) => + new Response( + JSON.stringify({ data: { workflowId: WORKFLOW_ID, runId: 'run-1', ...record } }), + { + headers: { 'content-type': 'application/json' }, + } + ) + const serveDeploy = () => + request.mockImplementation(async (path: string) => + path === DEPLOY_PATH ? deployed : path === STATUS_PATH ? liveStatus : outcome() + ) + + it('applies, dry-runs the saved draft with the input, then deploys, in one result', async () => { + setTerminal(false) + serveDeploy() + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ status: 'completed', output: { tier: 'A' } }) + ) + + await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--run', '{"email":"a@b.co"}', '--deploy') + + const [path, sent] = contextMockFns.mockRequestRaw.mock.calls[0] + expect(path).toBe(RUN_PATH) + expect(sent.body).toMatchObject({ + input: { email: 'a@b.co' }, + run: { source: 'draft', dry: true }, + }) + expect(request.mock.calls.map((call) => call[0])).toEqual([ + APPLY_PATH, + DEPLOY_PATH, + STATUS_PATH, + ]) + const result = stdoutJson() + expect(result).toMatchObject({ + applied: true, + run: { runId: 'run-1', status: 'completed', output: { tier: 'A' } }, + live: 'version 4, serving (this deploy)', + }) + expect(String(result.summary)).toContain('test run completed') + }) + + it('deploys nothing when the test run fails, exits 1, and keeps the saved draft', async () => { + setTerminal(false) + serveDeploy() + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ status: 'failed', error: { message: 'score is not a number' } }) + ) + + 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/ + ) + expect(request.mock.calls.map((call) => call[0])).toEqual([APPLY_PATH]) + expect(readFileSync(join(dir, 'workflow.ts'), 'utf8')).toBe(`${ENTRY}// stored\n`) + expect(stdoutJson()).toMatchObject({ + applied: true, + run: { status: 'failed', error: 'score is not a number' }, + next: { command: `sim workflows source apply --dir ${dir} --run '{}' --deploy --yes` }, + }) + }) + + it('refuses beside --dry, before sending anything', async () => { + await expect(apply(WORKFLOW_ID, '--dir', dir, '--dry', '--run', '{}')).rejects.toThrow( + /--run test-runs what the write saves, and --dry saves nothing/ + ) + expect(request).not.toHaveBeenCalled() + expect(contextMockFns.mockRequestRaw).not.toHaveBeenCalled() + }) + }) + it('deploys through the deploy operation once the apply is saved', async () => { setTerminal(false) request.mockImplementation(async (path: string) => @@ -1166,19 +1241,22 @@ describe('sim workflows source apply', () => { ]) }) - it('without --deploy, names the deploy command when the deployed workflow now differs', async () => { + it('without --deploy, names the pinned deploy when the deployed workflow now differs, and the tested one in its reason', async () => { setTerminal(false) request.mockResolvedValue(outcome()) await apply(WORKFLOW_ID, '--dir', dir, '--yes') expect(request.mock.calls.map((call) => call[0])).toEqual([APPLY_PATH]) - expect(stdoutJson()).toMatchObject({ + const result = stdoutJson() + // `next.command` runs as printed: no placeholder an agent would have to fill in. + expect(result).toMatchObject({ needsRedeployment: true, - next: { - command: `sim workflows deploy ${WORKFLOW_ID} --expected-draft-fingerprint sf1:b`, - }, + next: { command: `sim workflows deploy ${WORKFLOW_ID} --expected-draft-fingerprint sf1:b` }, }) + expect(toRecord(result.next).reason).toContain( + `\`sim workflows source apply --dir ${dir} --yes --run '{…}' --deploy\` tests and deploys it in one step` + ) }) it.each([ @@ -1200,7 +1278,9 @@ describe('sim workflows source apply', () => { vi.mocked(console.log).mockClear() contextMockState.output = 'text' await apply(WORKFLOW_ID, '--dir', dir, '--yes') - expect(vi.mocked(console.log).mock.calls[0].join(' ')).toBe(`live\t${live}`) + const lines = vi.mocked(console.log).mock.calls.map((call) => call.join(' ')) + expect(lines[0]).toMatch(new RegExp(`^summary\tapplied: .*; live: ${escapeRegExp(live)}$`)) + expect(lines).toContain(`live\t${live}`) } ) @@ -1262,7 +1342,11 @@ describe('sim workflows source apply', () => { contextMockState.output = 'text' await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--deploy') const lines = vi.mocked(console.log).mock.calls.map((call) => call.join(' ')) - expect(lines[0]).toBe('live\tversion 3 still serving; version 4 activating') + expect(lines[0]).toMatch(/; live: version 3 still serving; version 4 activating$/) + expect(lines.slice(-2)).toEqual([ + 'live\tversion 3 still serving; version 4 activating', + `next\tsim workflows deployment status ${WORKFLOW_ID} # shows when version 4 is live`, + ]) // The admitted version is never printed as if it were deployed. expect(lines.some((line) => line.startsWith('deployed\t'))).toBe(false) }) @@ -1780,6 +1864,37 @@ describe('sim workflows source create on a directory with no workflow.ts', () => } }) + it('after a create whose test run fails, names the apply of the created workflow, not a second create', async () => { + setTerminal(false) + vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config')) + const starter = join(dir, 'new') + answerStarterAndCreate() + await create('--dir', starter) + vi.mocked(console.log).mockClear() + contextMockFns.mockRequestRaw.mockResolvedValue( + new Response( + JSON.stringify({ + data: { + workflowId: WORKFLOW_ID, + runId: 'run-1', + status: 'failed', + error: { message: 'bad' }, + }, + }), + { headers: { 'content-type': 'application/json' } } + ) + ) + + await expect(create('--dir', starter, '--yes', '--run', '{}', '--deploy')).rejects.toThrow( + `run \`sim workflows source apply --dir ${starter} --run '{}' --deploy --yes\`` + ) + + expect(existsSync(join(starter, '.sim/base.json'))).toBe(true) + expect(stdoutJson()).toMatchObject({ + next: { command: `sim workflows source apply --dir ${starter} --run '{}' --deploy --yes` }, + }) + }) + it.each(['--dry', '--yes'])('refuses %s instead of scaffolding', async (flag) => { 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 efdb145420a..9a74ad4c6b7 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -20,6 +20,8 @@ import { liveAgainstDraft, liveDeploymentStatus, } from '../../runtime/deployment-live' +import { runFailureMessage } from '../../runtime/execute' +import { withRunNext } from '../../runtime/run-next' import { searchTasks } from '../search' import { type DeployedUrl, @@ -31,6 +33,7 @@ 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, @@ -78,6 +81,7 @@ import { writeSourceDirectory, writeSourceScaffold, } from './workflow-dir' +import { dryRunDraft, printSideEffects } from './workflow-run-follow' type SourceApplyData = ApplyWorkflowSourceResponse['data'] @@ -88,9 +92,17 @@ interface SourceWriteOptions { allowDelete?: boolean verbose?: boolean deploy?: boolean + /** `--run [input]`: the test run's input as `--input` takes it, or `true` for none. */ + run?: string | true summaryFile?: string } +/** The `--run` flag as written in a next command. */ +function runFlag(run: SourceWriteOptions['run']): string { + if (run === undefined) return '' + return run === true ? ' --run' : ` --run ${shellWord(run)}` +} + /** * Prints a write's diagnostics and, in a display format, its notes (such as a custom tool the * save could not store; a machine result lists them), each once: after a terminal preview, the @@ -114,24 +126,29 @@ function variableChangeList(variables: SourceApplyData['diff']['variables']): st ] } +type BlockDiff = SourceApplyData['diff']['blocks'] + +/** An added or removed block as a person and a JSON result name it: `key (type)`. */ +const typedBlock = ({ key, type }: BlockDiff['added'][number]) => `${key} (${type})` + +/** A modified block and the fields that changed: `key (field, …)`. */ +const modifiedBlock = ({ key, fields }: BlockDiff['modified'][number]) => + `${key} (${fields.join(', ')})` + +/** How many blocks a diff adds, removes, renames and modifies, as one clause. */ +function blockCounts(blocks: BlockDiff): string { + return `${blocks.added.length} added, ${blocks.removed.length} removed, ${blocks.renamed.length} renamed, ${blocks.modified.length} modified` +} + /** One line naming what the apply changes, shown before asking to confirm it. */ function diffSummary(data: SourceApplyData): string { const { blocks, edges, variables } = data.diff if (data.diff.noop) return 'No graph changes (names, order or comments may still be saved).' - const parts = [ - `${blocks.added.length} added`, - `${blocks.removed.length} removed`, - `${blocks.renamed.length} renamed`, - `${blocks.modified.length} modified`, - ] const variableChanges = variableChangeList(variables) - const modified = blocks.modified.map(({ key, fields }) => `${key} (${fields.join(', ')})`) - const typed = (list: ReadonlyArray<{ key: string; type: string }>) => - list.map(({ key, type }) => `${key} (${type})`).join('; ') - return `Blocks: ${parts.join(', ')}. Connections: +${edges.added} -${edges.removed}.${ - blocks.added.length > 0 ? `\nAdded: ${typed(blocks.added)}` : '' - }${blocks.removed.length > 0 ? `\nRemoved: ${typed(blocks.removed)}` : ''}${ - modified.length > 0 ? `\nModified: ${modified.join('; ')}` : '' + return `Blocks: ${blockCounts(blocks)}. Connections: +${edges.added} -${edges.removed}.${ + blocks.added.length > 0 ? `\nAdded: ${blocks.added.map(typedBlock).join('; ')}` : '' + }${blocks.removed.length > 0 ? `\nRemoved: ${blocks.removed.map(typedBlock).join('; ')}` : ''}${ + blocks.modified.length > 0 ? `\nModified: ${blocks.modified.map(modifiedBlock).join('; ')}` : '' }${variableChanges.length > 0 ? `\nVariables: ${variableChanges.join('; ')}` : ''}` } @@ -153,7 +170,11 @@ async function writeWorkflowSource(args: mode: WriteMode creating: boolean question: string - client: OperationClient + client: OperationClient< + Operation | 'deployWorkflow' | 'getWorkflowDeployment' | 'executeWorkflow' + > + /** The workspace the write is in, for the `--run` test run's request. */ + workspaceId: string operation: Operation params: Record body: ApplyWorkflowSourceBody | CreateWorkflowFromSourceBody @@ -164,6 +185,11 @@ async function writeWorkflowSource(args: ifAnswerLost: string /** This write as a command, without `--yes`: what a `plan` run names next with it. */ command: string + /** + * The write to run again once this one is saved, without `--yes`: an apply's own command; a + * create's is an apply of the workflow it created, whose name a second create finds taken. + */ + savedCommand: string }): Promise { const { options, creating } = args assertSendableCodeFiles(args.body.files) @@ -190,32 +216,43 @@ async function writeWorkflowSource(args: } const findings = findingsOutput(args.output, options.verbose, options.dir) const notes = new Set() - const report = (data: SourceApplyData, deployment: DeployOutcome = {}) => { - const { live: deployedLive, deployed, ...outcome } = deployment + /** + * Prints the result: a one-line `summary` first and `errors`, `warnings`, `live` and `next` + * last, so both `| head` and `| tail` of a long result (findings, many blocks) show the outcome. + */ + const report = (data: SourceApplyData, deployment: DeployOutcome = {}, run?: TestRun) => { + const { live: deployedLive, deployed, next, ...outcome } = deployment const live = deployedLive ?? liveAgainstDraft(data.deployedVersion, data.needsRedeployment) publishSummary(() => planMarkdown(data, creating, live), { file: options.summaryFile, marker: summaryMarker(options.dir), }) + const details = summarize(data, creating, findings.machine) + const errors = countOf(data, 'error') + const warnings = countOf(data, 'warning') // `deployed.version` is the version the deploy admitted, which may not be live yet: a person // reads `live` instead, and a machine result keeps the record. const result = { - ...(live ? { live } : {}), - ...summarize(data, creating, findings.machine), + summary: summaryLine(data, creating, { errors, warnings, run, live }), + ...details, + ...(run ? { run } : {}), ...(deployed && findings.machine ? { deployed } : {}), ...outcome, + ...findings.result(data.diagnostics), + errors, + warnings, + ...(live ? { live } : {}), + ...(next ? { next } : {}), + } + 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) } - printProtocolResult( - args.output, - { ...result, ...findings.result(data.diagnostics) }, - { - ...(result.created ? { created: createdText(result.created) } : {}), - ...(outcome.urls?.length ? { urls: deployedUrlsText(outcome.urls) } : {}), - } - ) } - const hasErrors = (data: SourceApplyData) => - data.diagnostics.some((diagnostic) => diagnostic.severity === 'error') + const hasErrors = (data: SourceApplyData) => countOf(data, 'error') > 0 /** Whether a committed answer stored the write: not refused, and a create that applied. */ const stored = (data: SourceApplyData) => !data.dry && !hasErrors(data) && (data.applied || !creating) @@ -248,21 +285,115 @@ async function writeWorkflowSource(args: if (!data) return if (mode === 'write' && stored(data) && !findings.machine) printError(diffSummary(data)) - let deployment: DeployOutcome = {} - if (stored(data)) { + if (!stored(data)) { + report(data) + return + } + let run: TestRun | undefined + /** Runs a step after the stored write; a failure prints the write's result first: it stands. */ + const afterWrite = async (step: () => Promise): Promise => { try { - deployment = await deployStep(args.client, data, { - ...options, - verb, - machine: findings.machine, - }) + return await step() } catch (error) { - // The write stands: its result prints before the deploy's failure. - report(data) + report(data, {}, run) throw error } } - report(data, deployment) + if (options.run !== undefined) { + const input = options.run === true ? undefined : options.run + const record = await afterWrite(() => + dryRunDraft(args.client, data.workflowId, input, args.workspaceId) + ) + run = testRunResult(record) + if (record.status !== 'completed') { + await printRunFailureSite(options.dir, data.workflowId, record.error) + const next = { + command: `${args.savedCommand} --yes`, + reason: 'applies your fix and tests it again', + } + report(data, { next }, run) + const why = + runFailureMessage('executeWorkflow', record) ?? `it ended ${String(record.status)}` + 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\`.`, + 0 + ) + } + } + const deployment = await afterWrite(() => + deployStep(args.client, data, { + ...options, + verb, + machine: findings.machine, + // Read only without --deploy: an untested draft's next names the tested deploy too. + testedDeploy: + run === undefined && !creating + ? `${args.savedCommand} --yes --run '{…}' --deploy` + : undefined, + }) + ) + report(data, deployment, run) +} + +/** What a write's result shows of its `--run` test run. */ +interface TestRun { + runId: unknown + status: unknown + error?: unknown + output: unknown + sideEffects?: unknown + next?: unknown +} + +/** + * A `--run` record as the write's result shows it: the run id, status, error message, the + * 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). + */ +function testRunResult(record: Record): TestRun { + const { next } = toRecord(withRunNext('executeWorkflow', record)) + return { + runId: record.runId, + status: record.status, + ...(record.error ? { error: toRecord(record.error).message ?? record.error } : {}), + output: record.output, + ...(record.sideEffects ? { sideEffects: record.sideEffects } : {}), + ...(next ? { next } : {}), + } +} + +/** 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 +} + +/** + * The write's outcome in one line: what it did (or would do), its findings, the test run and + * what is live, so the first line of a long result already answers whether it worked. + */ +function summaryLine( + data: SourceApplyData, + creating: boolean, + outcome: { errors: number; warnings: number; run?: TestRun; live?: string } +): string { + const { blocks, edges } = data.diff + const changes = data.diff.noop + ? 'no graph changes' + : `${blockCounts(blocks)}, connections +${edges.added} -${edges.removed}` + return [ + `${writeOutcome(data, creating, outcome.errors)}: ${changes}`, + `${outcome.errors} error(s), ${outcome.warnings} warning(s)`, + ...(outcome.run ? [`test run ${String(outcome.run.status)}`] : []), + ...(outcome.live ? [`live: ${outcome.live}`] : []), + ].join('; ') +} + +/** What a write did, in a word or two. */ +function writeOutcome(data: SourceApplyData, creating: boolean, errors: number): string { + if (data.dry) return 'plan' + if (errors > 0) return 'refused' + if (!data.applied) return 'not applied' + return creating ? 'created' : 'applied' } /** @@ -292,7 +423,7 @@ function planMarkdown(data: SourceApplyData, creating: boolean, live: string | u ] const variableChanges = variableChangeList(data.diff.variables) const errors = data.diagnostics.filter((finding) => finding.severity === 'error') - const warnings = data.diagnostics.filter((finding) => finding.severity === 'warning').length + const warnings = countOf(data, 'warning') return [ `### Sim workflow ${data.dry ? 'plan' : verb}: ${markdownCell(data.workflowId)}`, '', @@ -340,7 +471,14 @@ interface DeployOutcome { async function deployStep( client: OperationClient<'deployWorkflow' | 'getWorkflowDeployment'>, data: SourceApplyData, - options: { deploy?: boolean; dir: string; verb: string; machine: boolean } + options: { + deploy?: boolean + dir: string + verb: string + machine: boolean + /** The write again with a test run and the deploy, named in `next.reason` while the draft is untested. */ + testedDeploy?: string + } ): Promise { // Pinned to the draft this write stored, as `--deploy` is: an edit made since is never deployed. const deployCommand = `sim workflows deploy ${data.workflowId} --expected-draft-fingerprint ${data.base.fingerprint}` @@ -349,7 +487,7 @@ async function deployStep( return { next: { command: deployCommand, - reason: `The workflow is deployed and its draft now differs from the live version: deploy to make the change live (or ${options.verb} with --deploy).`, + reason: `The workflow is deployed and its draft now differs from the live version: deploy to make the change live (or ${options.verb} with --deploy).${options.testedDeploy ? ` The draft is untested: \`${options.testedDeploy}\` tests and deploys it in one step.` : ''}`, }, } } @@ -442,13 +580,37 @@ function deployFailure( ) } -/** Refuses `--deploy` beside `--dry`: a dry run stores nothing to deploy. */ -function assertDeployable(options: SourceWriteOptions): void { - if (options.deploy && options.dry) { +/** `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)}` +} + +/** Refuses `--deploy` or `--run` beside `--dry`: a dry run stores nothing to deploy or run. */ +function assertNotDry(options: SourceWriteOptions): void { + if (!options.dry) return + if (options.deploy) { throw new CliUsageError( '--deploy deploys what the write saves, and --dry saves nothing: drop one of them.' ) } + if (options.run !== undefined) { + throw new CliUsageError( + '--run test-runs what the write saves, and --dry saves nothing: drop one of them.' + ) + } +} + +/** `--run [input]` and `--deploy` on a write: test the saved draft, then deploy it. */ +function runAndDeployOptions(command: Command): Command { + return command + .option( + '--run [input]', + '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' + ) + .option( + '--deploy', + 'After the write is saved (and a --run completed), deploy the workflow (as `sim workflows deploy ` does)' + ) } const DIR_DESCRIPTION = @@ -470,6 +632,7 @@ export function attachWorkflowSourceApply(source: Command): void { 'deployWorkflow', 'getWorkflowDeployment', 'getSourceResources', + 'executeWorkflow', ]) absoluteDirOption(command) verboseFlag(command) @@ -482,10 +645,8 @@ export function attachWorkflowSourceApply(source: Command): void { .option('--dir ', DIR_DESCRIPTION, '.') .option('--dry', 'Check the source and show the outcome without saving or writing files') .option('-y, --yes', 'Apply without asking for confirmation') - .option( - '--deploy', - 'After the write is saved, deploy the workflow (as `sim workflows deploy ` does)' - ) + + runAndDeployOptions(command) .option( '--allow-delete', 'Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused' @@ -498,7 +659,7 @@ export function attachWorkflowSourceApply(source: Command): void { await withSourceCommandLock( options.dir, async () => { - assertDeployable(options) + assertNotDry(options) await assertSourceDirKind(options.dir, 'workflow') const { client, profile } = connectApply() const lock = await readLock(options.dir) @@ -514,9 +675,11 @@ export function attachWorkflowSourceApply(source: Command): void { mode, creating: false, question: `Apply these changes to workflow ${workflowId}?`, - command: `sim workflows source apply --dir ${shellWord(options.dir)}${options.allowDelete ? ' --allow-delete' : ''}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`, + command: applyCommand(options), + savedCommand: applyCommand(options), output: profile.output, client, + workspaceId: base.workspaceId, operation: 'applyWorkflowSource', params: { workflowId }, body: { @@ -555,6 +718,7 @@ export function attachWorkflowSourceCreate(source: Command): void { 'getSourceResources', 'deployWorkflow', 'getWorkflowDeployment', + 'executeWorkflow', ]) absoluteDirOption(command) verboseFlag(command) @@ -574,10 +738,8 @@ export function attachWorkflowSourceCreate(source: Command): void { .option('--name ', "The workflow name (default: the source's)") .option('--folder ', 'The folder to create it in (default: the root)') .option('-y, --yes', 'Create without asking for confirmation') - .option( - '--deploy', - 'After the write is saved, deploy the workflow (as `sim workflows deploy ` does)' - ) + + runAndDeployOptions(command) .allowExcessArguments(false) .description('Create a workflow from a workflow source directory') .addHelpText('after', sourceExitCodesHelp('workflows source create')) @@ -597,7 +759,7 @@ export function attachWorkflowSourceCreate(source: Command): void { const workspaceId = client.requireWorkspace() const tree = await writeSourceScaffold(client, options.dir, workspaceId) const next: NextStep = { - command: `${createCommand(shellWord(options.dir), workspaceId)} --yes${summaryFileFlag(options.summaryFile)}`, + 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.`, } const machine = isMachine(profile.output) @@ -610,7 +772,7 @@ export function attachWorkflowSourceCreate(source: Command): void { }) return } - assertDeployable(options) + assertNotDry(options) 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. @@ -631,11 +793,13 @@ export function attachWorkflowSourceCreate(source: Command): void { 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)}` : ''}${options.deploy ? ' --deploy' : ''}${summaryFileFlag(options.summaryFile)}`, + 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) @@ -693,23 +857,22 @@ function summarize(data: SourceApplyData, creating: boolean, machine: boolean) { dry: data.dry, noop: data.diff.noop, ...(created.length > 0 ? { created } : {}), + // One string per block (`key (type)`, `key (field, …)`): a line each in a JSON result. blocksAdded: data.diff.blocks.added.length, ...(data.diff.blocks.added.length > 0 && { - added: data.diff.blocks.added.map(({ key, type }) => ({ block: key, type })), + added: data.diff.blocks.added.map(typedBlock), }), blocksRemoved: data.diff.blocks.removed.length, ...(data.diff.blocks.removed.length > 0 && { - removed: data.diff.blocks.removed.map(({ key, type }) => ({ block: key, type })), + removed: data.diff.blocks.removed.map(typedBlock), }), blocksModified: data.diff.blocks.modified.length, ...(data.diff.blocks.modified.length > 0 && { - modified: data.diff.blocks.modified.map(({ key, fields }) => ({ block: key, fields })), + modified: data.diff.blocks.modified.map(modifiedBlock), }), edgesAdded: data.diff.edges.added, edgesRemoved: data.diff.edges.removed, ...(variablesChanged(data.diff.variables) && { variables: data.diff.variables }), - errors: data.diagnostics.filter((diagnostic) => diagnostic.severity === 'error').length, - warnings: data.diagnostics.filter((diagnostic) => diagnostic.severity === 'warning').length, notes: machine ? data.notes : data.notes.length, fingerprint: data.base.fingerprint, deployedVersion: data.deployedVersion, 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 1cb2ce38cba..77374e8cee5 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 @@ -165,6 +165,109 @@ afterEach(() => { rmSync(rootDir, { recursive: true, force: true }) }) +describe('sim workflows source get ', () => { + const LIST_PATH = '/api/v2/workflows' + const OTHER_ID = '00000000-0000-4000-8000-00000000000c' + const listed = + (...workflows: Array<{ id: string; name: string; folderPath?: string }>) => + () => ({ + data: workflows.map((workflow) => ({ folderPath: '', ...workflow })), + nextCursor: null, + }) + + async function getNamed(name: string): Promise { + return program() + .parseAsync(['node', 'sim', 'workflows', 'source', 'get', name, '--dir', outDir]) + .then( + () => null, + (error: unknown) => error + ) + } + + it('gets the one workflow whose name matches exactly, not one that only contains it', async () => { + serve({ + [LIST_PATH]: listed( + { id: OTHER_ID, name: 'Lead Scorer v2' }, + { id: WORKFLOW_ID, name: 'Lead Scorer' } + ), + }) + + expect(await getNamed('Lead Scorer')).toBeNull() + + expect(callsTo(LIST_PATH)[0][1].query).toMatchObject({ search: 'Lead Scorer' }) + expect(callsTo(SOURCE_PATH)).toHaveLength(1) + expect(JSON.parse(readFileSync(join(outDir, '.sim/base.json'), 'utf8')).workflowId).toBe( + WORKFLOW_ID + ) + }) + + it('reads every page of substring hits before deciding, so an exact match after the first is found', async () => { + const hits = Array.from({ length: 100 }, (_, index) => ({ + id: `00000000-0000-4000-8000-${String(index).padStart(12, '1')}`, + name: `Lead Scorer ${index}`, + folderPath: '', + })) + serve({ + [LIST_PATH]: () => { + const cursor = callsTo(LIST_PATH).at(-1)?.[1].query?.cursor + return cursor + ? { data: [{ id: WORKFLOW_ID, name: 'Lead Scorer', folderPath: '' }], nextCursor: null } + : { data: hits, nextCursor: 'page-2' } + }, + }) + + expect(await getNamed('Lead Scorer')).toBeNull() + + expect(callsTo(LIST_PATH)).toHaveLength(2) + expect(JSON.parse(readFileSync(join(outDir, '.sim/base.json'), 'utf8')).workflowId).toBe( + WORKFLOW_ID + ) + }) + + it("looks a name up in the workspace the directory was read from, not the profile's", async () => { + mkdirSync(join(outDir, '.sim'), { recursive: true }) + writeFileSync( + join(outDir, '.sim/base.json'), + JSON.stringify({ + version: 1, + workflowId: WORKFLOW_ID, + workspaceId: WORKSPACE_ID, + fingerprint: 'sf1:a', + catalogHash: 'h', + }) + ) + serve({ [LIST_PATH]: listed({ id: WORKFLOW_ID, name: 'Lead Scorer' }) }) + + expect(await getNamed('Lead Scorer')).toBeNull() + + expect(callsTo(LIST_PATH)[0][1].query).toMatchObject({ workspaceId: WORKSPACE_ID }) + }) + + it.each([ + [ + 'several workflows hold the name', + [ + { id: WORKFLOW_ID, name: 'Lead Scorer', folderPath: 'sales' }, + { id: OTHER_ID, name: 'Lead Scorer', folderPath: 'ops' }, + ], + 'WORKFLOW_NAME_AMBIGUOUS', + ], + ['none holds it exactly', [{ id: OTHER_ID, name: 'Lead Scorer v2' }], 'WORKFLOW_NOT_FOUND'], + ])( + 'refuses when %s, naming each candidate with its id, and reads no source', + async (_case, workflows, code) => { + serve({ [LIST_PATH]: listed(...workflows) }) + + const error = await getNamed('Lead Scorer') + + expect(error).toMatchObject({ code }) + for (const { id } of workflows) expect(String((error as Error).message)).toContain(id) + expect(callsTo(SOURCE_PATH)).toHaveLength(0) + expect(existsSync(join(outDir, '.sim/base.json'))).toBe(false) + } + ) +}) + describe('sim workflows source get --dir', () => { it('writes the source, lock, base, an agent guide and the declarations of the blocks it uses', async () => { serve({ 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 855f0923d6b..1f5bc161bbb 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -1,18 +1,22 @@ +import { isValidUuid } from '@sim/utils/id' import { toRecord } from '@sim/utils/object' import { SOURCE_BASE_FILE } from '@sim/workflow-code/limits' import type { Command } from 'commander' -import type { GetWorkflowSourceResponse } from '../../generated/v2-api' -import { callsOperations } from '../../runtime/called-operations' +import type { GetWorkflowSourceResponse, ListWorkflowsResponse } from '../../generated/v2-api' +import { callsOperations, type OperationClient } from '../../runtime/called-operations' +import { DEFAULT_PAGE_SIZE } from '../../runtime/options' import { buildRequest } from '../../runtime/request' -import { SourceDirError } from './local-errors' +import { CliUsageError, SourceDirError } from './local-errors' import { folderChildResults } from './source-check' import { absoluteDirOption, assertPrintedSourcePaths, assertSourceDirKind, + directoryWorkspace, locallyEditedFiles, readPreviousLock, readSourceJson, + recordedWorkspace, withSourceCommandLock, } from './source-dir' import { sourceExitCodesHelp } from './source-exit-codes' @@ -55,6 +59,43 @@ async function assertNoLocalEdits(dir: string, source: PrintedSource): Promise, + workflow: string, + /** The workspace to look in when not the command's own: a directory's recorded one. */ + inWorkspace?: string +): Promise { + if (isValidUuid(workflow)) return workflow + const workspaceId = client.requireWorkspace(inWorkspace) + // Every page: an exact match or a second one can sort after the first page of substring hits. + const found = await client.requestAllPages( + 'listWorkflows', + { query: { workspaceId, search: workflow }, pageSize: DEFAULT_PAGE_SIZE } + ) + const exact = found.filter(({ name }) => name === workflow) + if (exact.length === 1) return exact[0].id + const candidates = exact.length > 1 ? exact : found + const listed = candidates + .slice(0, NAMED_CANDIDATES) + .map(({ id, name, folderPath }) => `${name} (${id}${folderPath ? `, in ${folderPath}` : ''})`) + const more = candidates.length - listed.length + const named = `${listed.join('; ')}${more > 0 ? `; and ${more} more` : ''}` + throw new CliUsageError( + exact.length > 1 + ? `${exact.length} workflows are named "${workflow}": ${named}. Get one by its id.` + : `No workflow is named exactly "${workflow}"${listed.length > 0 ? `; names containing it: ${named}` : ' in this workspace'}. Pass its id or exact name (\`sim workflows list\` lists them).`, + { code: exact.length > 1 ? 'WORKFLOW_NAME_AMBIGUOUS' : 'WORKFLOW_NOT_FOUND' } + ) +} + /** * Teaches the generated `workflows source get` leaf `--dir `: instead of printing the * response, it writes `workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`, SDK @@ -77,7 +118,10 @@ export function attachWorkflowSourceGet(source: Command): void { 'getWorkflowSource', 'getSourceCatalog', 'getSourceResources', + 'listWorkflows', ]) + const [workflowArgument] = get.registeredArguments + if (workflowArgument) workflowArgument.description = 'Workflow id, or its exact name' get.option( `--${DIR_FLAG} `, @@ -89,12 +133,16 @@ export function attachWorkflowSourceGet(source: Command): void { ) absoluteDirOption(get) get.addHelpText('after', sourceExitCodesHelp('workflows source get', 'Exit codes with --dir')) - get.action(async (workflowId: string, _options: unknown, command: Command): Promise => { + get.action(async (workflow: string, _options: unknown, command: Command): Promise => { const flags = command.optsWithGlobals() as Record const dir = flags[DIR_FLAG] if (typeof dir !== 'string') { try { - await previous(command.processedArgs) + // An id needs no connection here: the generated handler connects on its own. + const workflowId = isValidUuid(workflow) + ? workflow + : await resolveWorkflow(connectGet().client, workflow) + await previous([workflowId, ...command.processedArgs.slice(1)]) } catch (error) { throw withSourceExitCode(error) } @@ -103,8 +151,20 @@ export function attachWorkflowSourceGet(source: Command): void { await withSourceCommandLock(dir, async () => { const force = flags[FORCE_FLAG] === true await assertSourceDirKind(dir, 'workflow') - if (!force) await assertSameWorkflow(dir, workflowId) const { client, profile } = connectGet() + // A name is looked up in the workspace the directory was read from, as its other commands + // act on it; --force gets into it from the command's own workspace instead. + const recorded = force + ? null + : directoryWorkspace( + dir, + await recordedWorkspace(dir, profile), + profile, + (_from, _named, setting) => + `Drop ${setting}, or pass --force to replace it with a workflow from ${setting}.` + ) + const workflowId = await resolveWorkflow(client, workflow, recorded ?? undefined) + if (!force) await assertSameWorkflow(dir, workflowId) const request = await buildRequest( 'getWorkflowSource', [workflowId], diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 61a1b256a42..888b7331202 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -716,6 +716,8 @@ export const CLI_CONTRACT: CliContract = { getWorkflowSource: { command: 'workflows source get', describe: 'Show a workflow’s draft as TypeScript source with its identity lock', + // `workflow-source-get.ts` resolves a name to its id before the request. + pathArgumentNames: { workflowId: 'workflow' }, }, /** `workflows source apply --dir ` reads and writes a source directory by hand. */ applyWorkflowSource: { hidden: true }, diff --git a/packages/sim-cli/src/program.ts b/packages/sim-cli/src/program.ts index 4bd7a20f26c..10f0218c26d 100644 --- a/packages/sim-cli/src/program.ts +++ b/packages/sim-cli/src/program.ts @@ -27,19 +27,17 @@ Profiles work like the AWS CLI: settings live in ~/.sim/config, keys in ~/.sim/credentials (0600), or under SIM_CONFIG_DIR when it is set. Select one with -P, --profile, or SIM_PROFILE. -A command's workspace is, first to last: -w (--workspace ), then -SIM_WORKSPACE, then the source directory it runs in (the nearest directory at -or above the working directory whose .sim/base.json or .sim/starter.json names -one, a workflow folder counting as its workspace directory), then the -profile's. A source command acts on the directory -its --dir names: a workflow directory on the workflow its .sim/base.json names, -a workspace directory on the workspace its base names, refusing a -w or -SIM_WORKSPACE naming another (SOURCE_OTHER_WORKSPACE), and a starter on the one -.sim/starter.json names unless -w or SIM_WORKSPACE names another. In a script, -export SIM_WORKSPACE= once, or keep only the ID in a variable and write --w "$WS". -A variable holding "--workspace " is one argument: alone it is an unknown -option, and after -w all of it is taken as the ID. +A command's workspace is, first to last: -w , SIM_WORKSPACE, the source +directory at or above the working directory whose .sim/base.json or +.sim/starter.json names one (a workflow folder counts as its workspace's), then +the profile's. A source command acts on what its --dir names: a workflow +directory on the workflow its .sim/base.json names, a workspace directory on the +workspace its base names (refusing a -w or SIM_WORKSPACE naming another, +SOURCE_OTHER_WORKSPACE), and a starter, until \`source create\` creates its +workflow, on the workspace .sim/starter.json names unless -w or SIM_WORKSPACE +names another. In a script, export SIM_WORKSPACE= once, or keep only +the ID in a variable and write -w "$WS" (one holding "--workspace " is a +single argument). Workflow, knowledge-base and workspace IDs are bare UUIDs. Table IDs carry a tbl_ prefix and file IDs a wf_ one, so wf_ never names a workflow. An audit-log diff --git a/packages/sim-cli/src/runtime/deployment-live.test.ts b/packages/sim-cli/src/runtime/deployment-live.test.ts index e0975235afb..d7fa05cfbaf 100644 --- a/packages/sim-cli/src/runtime/deployment-live.test.ts +++ b/packages/sim-cli/src/runtime/deployment-live.test.ts @@ -116,7 +116,11 @@ describe('withDeploymentLive after a deploy', () => { ])('$name', ({ response, live, next }) => { const payload = { id: ID, isDeployed: true, warnings: [], ...response } const shown = withDeploymentLive('deployWorkflow', payload) as Record - expect(Object.keys(shown)[0]).toBe('live') + expect( + Object.keys(shown) + .filter((key) => key !== 'next') + .at(-1) + ).toBe('live') expect(shown.live).toBe(live) expect(shown.next).toEqual(step(next)) }) diff --git a/packages/sim-cli/src/runtime/deployment-live.ts b/packages/sim-cli/src/runtime/deployment-live.ts index 6fcc45d66a6..ec271bade9a 100644 --- a/packages/sim-cli/src/runtime/deployment-live.ts +++ b/packages/sim-cli/src/runtime/deployment-live.ts @@ -184,9 +184,9 @@ function deploymentState(payload: Record): DeploymentState | nu } /** - * A deployment response with `live` first (the first line a person reads) and, when one follows, - * `next` last: for a deploy, rollback or activation, {@link liveAfterActivation}; for the status - * read, {@link liveDeploymentStatus}. Any other payload comes back as it was. + * A deployment response with `live` and, when one follows, `next` last, so the outcome survives a + * `| tail` of a long response: for a deploy, rollback or activation, {@link liveAfterActivation}; + * for the status read, {@link liveDeploymentStatus}. Any other payload comes back as it was. */ export function withDeploymentLive(operation: V2OperationName, payload: unknown): unknown { if (!isRecordLike(payload) || typeof payload.id !== 'string') return payload @@ -209,5 +209,5 @@ export function withDeploymentLive(operation: V2OperationName, payload: unknown) ? `sim workflows deploy ${shellArgument(payload.id)}` : undefined ) - return { live, ...payload, ...(next ? { next } : {}) } + return { ...payload, live, ...(next ? { next } : {}) } } diff --git a/packages/sim-cli/src/runtime/result.test.ts b/packages/sim-cli/src/runtime/result.test.ts index 9315fc2665e..e87ef3e1064 100644 --- a/packages/sim-cli/src/runtime/result.test.ts +++ b/packages/sim-cli/src/runtime/result.test.ts @@ -268,7 +268,7 @@ describe('a deploy result read by a person', () => { manualRunIssue: null, notes: [], } - const deployed = (lint: Record) => ({ + const deployed = (lint: Record | null) => ({ id: 'wf-1', isDeployed: true, version: 7, @@ -282,7 +282,7 @@ describe('a deploy result read by a person', () => { lint, }) - it('opens with what is live, and keeps only the lint findings', () => { + it('ends with what is live, and keeps only the lint findings', () => { const orphan = ref('b-3', 'Stray', 'function') renderResult( 'deployWorkflow', @@ -290,20 +290,24 @@ describe('a deploy result read by a person', () => { deployed({ ...clean, orphanBlocks: [orphan] }), CLI_CONTRACT.deployWorkflow ?? {} ) - expect(logged[0]).toBe('live\tversion 7, serving (this deploy)') + expect(logged.at(-1)).toBe('live\tversion 7, serving (this deploy)') expect(logged).toContain(`lint\t${JSON.stringify({ orphanBlocks: [orphan] })}`) }) - it('drops a report whose only entries are the graph sources and sinks, and keeps it whole for a machine', () => { + it('drops a report whose only entries are the graph sources and sinks, for a machine too', () => { renderResult('deployWorkflow', 'text', deployed(clean), CLI_CONTRACT.deployWorkflow ?? {}) expect(logged.some((line) => line.startsWith('lint\t'))).toBe(false) logged = [] renderResult('deployWorkflow', 'json', deployed(clean), CLI_CONTRACT.deployWorkflow ?? {}) - expect(JSON.parse(logged.join('\n'))).toMatchObject({ - live: 'version 7, serving (this deploy)', - lint: clean, - }) + const shown = JSON.parse(logged.join('\n')) + expect(shown).not.toHaveProperty('lint') + expect(Object.keys(shown).at(-1)).toBe('live') + + // A deploy that lints nothing answers `lint: null`: no report, so no field either. + logged = [] + renderResult('deployWorkflow', 'json', deployed(null), CLI_CONTRACT.deployWorkflow ?? {}) + expect(JSON.parse(logged.join('\n'))).not.toHaveProperty('lint') }) }) diff --git a/packages/sim-cli/src/runtime/result.ts b/packages/sim-cli/src/runtime/result.ts index e1372676033..83d40f8c7df 100644 --- a/packages/sim-cli/src/runtime/result.ts +++ b/packages/sim-cli/src/runtime/result.ts @@ -309,13 +309,14 @@ const LINT_GRAPH_FACTS: ReadonlySet = new Set(['sources', 'sinks']) /** * A record whose `lint` (the workflow lint report a deploy or a graph write returns) keeps only - * its findings, for the human formats: the report lists every category, almost all empty, plus - * every workflow's source and sink blocks, and the one JSON line that made pushed the rest of the - * result off a short terminal or a `| tail`. Without a finding the field is dropped. Machine - * formats keep the report whole, as the API sent it. + * its findings, in every format: the report lists every category, almost all empty, plus every + * source and sink block of the graph, which grows with the workflow and pushes the outcome off a + * short terminal or a `| tail`. Without a finding the field is dropped. The graph's shape is what + * `sim workflows outline` prints. */ function withLintFindingsOnly(data: unknown): unknown { - if (!isRecordLike(data) || !isRecordLike(data.lint)) return data + if (!isRecordLike(data) || !('lint' in data)) return data + if (!isRecordLike(data.lint)) return data.lint === null ? omit(data, ['lint']) : data const findings = Object.entries(data.lint).filter( ([key, value]) => !LINT_GRAPH_FACTS.has(key) && value !== null && !(Array.isArray(value) && value.length === 0) @@ -474,12 +475,13 @@ export function renderResult( // The single-key unwrap exists for the human table: `{ mcpServer: {...} }` rendered as-is // printed nothing. Machine formats print the API's data as the OpenAPI shape the docs and the - // agent reference card are generated from, plus the fields the CLI adds for a run or deploy: - // `live`, and `next` with `{ command, reason }` (a person reads it as the command, then why). + // agent reference card are generated from, except a lint report's graph facts, plus the fields + // the CLI adds for a run or deploy: `live`, and `next` with `{ command, reason }` (a person + // reads it as the command, then why). const machine = format === 'json' || format === 'yaml' const added = withRunNext( operation, - withDeploymentLive(operation, machine ? raw : withLintFindingsOnly(unwrapResource(raw))) + withDeploymentLive(operation, withLintFindingsOnly(machine ? raw : unwrapResource(raw))) ) const data = machine ? added : withNextText(added) if (spec.itemsPath) {