From 42cfc22fb081212e55575148c6039d867c0a2744 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 16:33:55 -0800 Subject: [PATCH 1/6] improvement(workflow-code): sim workspaces source apply --run tests workflows, gating deployments/ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `apply --yes --run =''` (repeatable, JSON or @file): after the apply, dry-run each named workflows// draft as `sim workflows run --dry --input` does; one `runs` entry each in the result; a run that does not complete exits 1, maps its failing block to file:line, and leaves the applied drafts in place. - With --run, deployments/ is applied in a second write only after every run completed, so a `live: 'draft'` deployment publishes only a tested draft. - Refused before anything is sent: beside --dry or --to, an --only without workflows, an unknown key (naming the keys there), a repeated key, or input that is not JSON. - Primer, AGENTS.md pointer, `source --help`, the advanced guide and docs teach the one-call loop `check && apply --yes --run ='{…}'`. --- apps/docs/content/docs/cli/reference.mdx | 5 +- apps/docs/content/docs/cli/workspaces.mdx | 5 +- .../docs/workflows/code/coding-agents.mdx | 2 +- .../docs/workflows/code/exit-codes.mdx | 2 +- .../content/docs/workflows/code/workspace.mdx | 10 + .../commands/protocol/source-exit-codes.ts | 4 +- .../src/commands/protocol/source-loop-help.ts | 7 +- .../src/commands/protocol/source-primer.ts | 8 +- .../commands/protocol/workflow-run-follow.ts | 29 +- .../protocol/workflow-source-apply.ts | 30 +- .../protocol/workspace-source-apply.test.ts | 141 +++++++ .../protocol/workspace-source-apply.ts | 375 ++++++++++++++++-- .../commands/protocol/workspace-source-dir.ts | 6 +- 13 files changed, 543 insertions(+), 81 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index e719c6ca84d..171fccd38e6 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -10125,12 +10125,13 @@ sim workspaces source apply [options] | `--delete-target-only` | No | With --to and --allow-delete, also delete the target's resources this directory never declared and no promotion from it left there (prod-only tables and their rows, skills made in prod). Without it a promotion keeps them, naming each with a warning. | | `--only ` | No | Apply only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--to ` | No | Promote the directory to another workspace (dev to prod): its resources bind by key to that workspace's own and are updated in place. Only .sim/targets/<workspaceId>.json changes, the record the next promotion compares with: a resource changed there since is kept, or refused as stale (exit 5) when the directory changed it too. | +| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed; a run that does not complete exits 1 and leaves the applied drafts in place. | -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), 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; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command 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); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 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), 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), a --run test run did not complete (the apply is written; deployments/ was not applied), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command 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); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 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: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). +API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [executeWorkflow](/api-reference/workflows/executeWorkflowV2). ### sim workspaces source check diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 9718d573495..becf7a09a34 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -759,12 +759,13 @@ sim workspaces source apply [options] | `--delete-target-only` | No | With --to and --allow-delete, also delete the target's resources this directory never declared and no promotion from it left there (prod-only tables and their rows, skills made in prod). Without it a promotion keeps them, naming each with a warning. | | `--only ` | No | Apply only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--to ` | No | Promote the directory to another workspace (dev to prod): its resources bind by key to that workspace's own and are updated in place. Only .sim/targets/<workspaceId>.json changes, the record the next promotion compares with: a resource changed there since is kept, or refused as stale (exit 5) when the directory changed it too. | +| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed; a run that does not complete exits 1 and leaves the applied drafts in place. | -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), 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; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command 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); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 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), 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), a --run test run did not complete (the apply is written; deployments/ was not applied), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command 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); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 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: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). +API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [executeWorkflow](/api-reference/workflows/executeWorkflowV2). ### Compile and type-check every workflow of a workspace source directory locally, without the server diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx index 95a4cbb2861..d76d8a07e23 100644 --- a/apps/docs/content/docs/workflows/code/coding-agents.mdx +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -30,7 +30,7 @@ Point the agent at `.sim/AGENTS.md` before it edits. 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). +For a whole workspace, use `sim workspaces source` with the same steps: its chained command is `sim workspaces source check --dir && sim workspaces source apply --dir --yes --run ='{...}'`, one `--run` per workflow folder (`workflows//`) to test, and `deployments/` is applied only if every run completed. See [Test workflows on apply](/workflows/code/workspace#test-workflows-on-apply). ## Look things up diff --git a/apps/docs/content/docs/workflows/code/exit-codes.mdx b/apps/docs/content/docs/workflows/code/exit-codes.mdx index 2be5221a26c..e6748c41ebd 100644 --- a/apps/docs/content/docs/workflows/code/exit-codes.mdx +++ b/apps/docs/content/docs/workflows/code/exit-codes.mdx @@ -51,7 +51,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 resource holds (`E_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 resource holds (`E_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 workspaces source get --dir `, reapply your edit there, dry-run, apply | | `6` | A resource is locked (`E_APPLY_LOCKED`): a workflow or its folder, or a table; a locked block exits 1 instead | Ask someone to unlock it: a workflow in the workflow builder, a table in its settings (the finding's hint names which) | | `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/content/docs/workflows/code/workspace.mdx b/apps/docs/content/docs/workflows/code/workspace.mdx index 3dd22794f5e..ed45d132c86 100644 --- a/apps/docs/content/docs/workflows/code/workspace.mdx +++ b/apps/docs/content/docs/workflows/code/workspace.mdx @@ -50,6 +50,16 @@ Unlike a workflow directory's `check`, it needs the block catalog but fetches it The dry run prints the plan (`+` create, `~` update, `=` adopt an existing resource with the same name, `-` delete) and every error with its file and line. `--only tables,workflows` limits a get or an apply to some kinds. +## Test workflows on apply + +```bash +sim workspaces source check --dir ./my-workspace && sim workspaces source apply --dir ./my-workspace --yes --run lead-intake='{"email":"a@b.co"}' +``` + +`--run =''` dry-runs the saved draft of `workflows//` with that input after the apply, as `sim workflows run --dry --input` does: writes return placeholders and are listed under each run's `sideEffects`. The input is JSON or `@file`; repeat `--run` to test several workflows. The result lists each run under `runs` with its workflow key and id, status and output. A run that does not complete exits `1` and prints the failing block's file and line in `workflows//`; the applied drafts stay in place, so fix the source and run the same command again. + +With `--run`, `deployments/` is applied only after every run completed, in a second write, so a deployment with `live: 'draft'` publishes only a draft that passed its test. Without `--run` it is applied with everything else. `--run` is refused with `--dry` (nothing is written to test), with `--to` (test in this workspace, then promote), and with an `--only` that leaves out `workflows`. + An apply adopts a resource it never read (one made in Sim under the name a new declaration gives) only when the declaration matches it, or only adds to it: a column, rows into an empty table, a document. An adopt that would change or remove anything the resource holds is refused with `E_APPLY_NO_BASE`, even with `--allow-delete`. Run `get` into a new directory to read the resource, then make your edit there, or give the declaration another name. `status` shows what would happen if you applied, without writing anything: the files you created, edited, or deleted, grouped by resource; what changed in Sim since the `get` (a resource edited, added, or deleted there, a workflow edited in the workflow builder included); the conflicts, where a resource changed on both sides; and the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unapplied, and `12` when something changed in Sim since the `get`, so a script or an agent can branch on it. Its JSON `plan` counts errors and warnings as the dry run of the apply it names next would, a conflict as an error. Without a connection it shows your edits only and says so; `--offline` skips the server. `diff [paths or kind:key…]` prints the edits as unified diffs (a binary file by its sizes), and `diff --server` compares the directory with what Sim holds now. Both take `--json` (or `--output json`). 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 4200ceb9ac8..57fc092e4e1 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -100,7 +100,7 @@ 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 `--run` test run that did not complete'}, 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': @@ -111,7 +111,7 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo "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', + '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), a --run test run did not complete (the apply is written; deployments/ was not applied), or the command failed', 'workspaces source get': 'the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace or SIM_WORKSPACE names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written)', 'workspaces source status': 'the command failed', 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 8088eda05e8..56491999b1d 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -95,10 +95,13 @@ export const WORKSPACE_SOURCE_LOOP_HELP = ` 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 + sim workspaces source check --dir ./ws && sim workspaces source apply --dir ./ws --yes --run ='{…}' A non-zero exit stops the chain at the first failure; fix what it reported and run it again. check 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. +and writes the workspace; --run ='{…}' (one per workflow, its workflows// folder) +dry-runs that input on the saved draft (writes stubbed, listed under runs[].sideEffects). A +workflow deploys on apply when deployments/.ts declares it; with --run, deployments/ is +applied only after every run completed. --allow-delete lets an edit remove a resource, column, rows, document, or a workflow's block or variable; apply --dry only prints the plan; get --force replaces edits no apply has saved. Promote dev to prod: \`sim workspaces source apply --dir ./ws --to --dry\`, then --yes. diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 41f31524e4e..bd0314b1e5f 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -77,7 +77,7 @@ const WORKFLOW_LOOP = 'sim workflows source check --dir . && sim workflows source apply --dir . --yes' const WORKSPACE_LOOP = - 'sim workspaces source check --dir . && sim workspaces source apply --dir . --yes' + "sim workspaces source check --dir . && sim workspaces source apply --dir . --yes --run ='{…}'" /** What a coding agent chains onto a workflow apply: the test run, then the deploy. */ const RUN_AND_DEPLOY = " --run '{…}' --deploy" @@ -119,11 +119,11 @@ const WORKSPACE_EXTRA = { const WORKSPACE_PRIMER = `# Sim workspace source: primer -A Sim workspace as files (\`tables/\`, \`workflows//\`); nothing here runs. Commands here (table ones too) act on the workspace \`${SOURCE_BASE_FILE}\` names. Every \`.ts\` file starts with \`// @sim-sdk ${SDK_MAJOR}\`. +A Sim workspace as files; nothing here runs. Commands here (table ones too) act on the workspace \`${SOURCE_BASE_FILE}\` names. Every \`.ts\` file starts with \`// @sim-sdk ${SDK_MAJOR}\`. -**Edit loop**: write every file, then run one chained command; fix what it reports: \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`; then \`sim workflows run --dry --input '{…}'\`. \`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites files: reread before editing. +**Edit loop**: write every file, then run one chained command; fix what it reports: \`${WORKSPACE_LOOP}\` dry-runs \`workflows//\`'s draft (repeatable) and deploys only if all complete. \`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites files: reread before editing. -- **Deletes**: removing a file, folder, column, block or variable needs \`apply --allow-delete\` and is permanent. +- **Deletes**: removing anything (file, column, block) needs \`apply --allow-delete\` and is permanent. - **Exit ${SOURCE_HELD_EXIT_CODE}**: partly written: what needs an unset secret or unbound credential waits; set it, reapply. ${sharedRules(WORKSPACE_EXTRA)} ` 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 1b79a6c27ca..e6a59a9e57f 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -16,7 +16,7 @@ import { retypeApiError } from '../../runtime/naming' import { collectRepeated } from '../../runtime/options' import { buildRequest, readArgumentSource } from '../../runtime/request' import { renderResult } from '../../runtime/result' -import { selectorOf, shellArgument } from '../../runtime/run-next' +import { selectorOf, shellArgument, withRunNext } from '../../runtime/run-next' import type { OperationSpec } from '../../runtime/types' import { printRunFailureSite } from './run-source-location' import { BLOCK_ID } from './workflow-run-get' @@ -470,6 +470,33 @@ async function sendWaitedRun( return readWorkflowResult(response) } +/** What a write's result shows of its `--run` test run. */ +export interface TestRun { + runId: unknown + status: unknown + error?: unknown + output: unknown + sideEffects?: unknown + next?: unknown +} + +/** + * A `--run` record as a source 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). + */ +export 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 } : {}), + } +} + /** * 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`). 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 9a74ad4c6b7..52fb0916c6a 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -21,7 +21,6 @@ import { liveDeploymentStatus, } from '../../runtime/deployment-live' import { runFailureMessage } from '../../runtime/execute' -import { withRunNext } from '../../runtime/run-next' import { searchTasks } from '../search' import { type DeployedUrl, @@ -81,7 +80,7 @@ import { writeSourceDirectory, writeSourceScaffold, } from './workflow-dir' -import { dryRunDraft, printSideEffects } from './workflow-run-follow' +import { dryRunDraft, printSideEffects, type TestRun, testRunResult } from './workflow-run-follow' type SourceApplyData = ApplyWorkflowSourceResponse['data'] @@ -335,33 +334,6 @@ async function writeWorkflowSource(args: 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 diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index b73022e98c9..a635e8d61ba 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -140,6 +140,7 @@ beforeEach(() => { contextMockState.workspaceSource = 'config' request.mockReset() mockRequest.mockReset() + contextMockFns.mockRequestRaw.mockReset() mockRequest.mockImplementation((path: string, options: { body?: unknown; form?: FormData }) => path.includes('/source/blobs') ? stagingAnswer(path, options) : request(path, options) ) @@ -2153,4 +2154,144 @@ describe('workspaces source apply', () => { .join('\n') expect(warned).toContain('could not fetch the block catalog of workflows/ingest') }) + + describe('--run', () => { + const APPLY_PATH = '/api/v2/workspaces/ws_local/source' + const DEPLOYMENT = "// @sim-sdk 1\nexport default defineDeployment({ live: 'draft' })\n" + const runAnswer = (record: Record) => + new Response(JSON.stringify({ data: { workflowId: 'wf_1', runId: 'run-1', ...record } }), { + headers: { 'content-type': 'application/json' }, + }) + const applies = () => request.mock.calls.filter((call) => call[0] === APPLY_PATH) + /** Answers the first write with the workflow saved, the second with the deployment. */ + const serveApplies = () => + request.mockImplementation(async (path: string, options: { body?: { kinds?: string[] } }) => { + if (path === '/api/v2/workflows/wf_1/deployment') return deploymentStatus(1) + const base = { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } } + return options.body?.kinds?.includes('deployment') + ? answer({ + plan: [ + { kind: 'workflow', key: 'ingest', action: 'noop' }, + { kind: 'deployment', key: 'ingest', action: 'update' }, + ], + applied: [{ kind: 'deployment', key: 'ingest', action: 'update' }], + base, + }) + : answer({ + plan: [{ kind: 'workflow', key: 'ingest', action: 'update' }], + applied: [{ kind: 'workflow', key: 'ingest', action: 'update' }], + files: { 'workflows/ingest/workflow.ts': `${INGEST}// stored\n` }, + base, + }) + }) + + beforeEach(() => { + write('deployments/ingest.ts', DEPLOYMENT) + }) + + it('applies, dry-runs the saved draft with the input, then applies deployments/, in one result', async () => { + serveApplies() + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ status: 'completed', output: { tier: 'A' } }) + ) + + await apply('--yes', '--run', 'ingest={"email":"a@b.co"}') + + const [first, second] = applies().map((call) => call[1].body) + expect(applies()).toHaveLength(2) + expect(first.kinds).not.toContain('deployment') + expect(first.options.only).not.toContain('deployment') + expect(Object.keys(first.files).some((path) => path.startsWith('deployments/'))).toBe(false) + expect(second.options.only).toEqual(['workflow', 'deployment']) + expect(second.files['deployments/ingest.ts']).toBe(DEPLOYMENT) + const [path, sent] = contextMockFns.mockRequestRaw.mock.calls[0] + expect(path).toBe('/api/v2/workflows/wf_1/execute') + expect(sent.body).toMatchObject({ + input: { email: 'a@b.co' }, + run: { source: 'draft', dry: true }, + }) + expect(process.exitCode).toBeUndefined() + const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + expect(printed).toMatchObject({ + applied: 2, + runs: [ + { + workflow: 'ingest', + workflowId: 'wf_1', + runId: 'run-1', + status: 'completed', + output: { tier: 'A' }, + }, + ], + }) + }) + + it('applies nothing of deployments/ when a run fails, exits 1 at its block, and keeps the applied draft', async () => { + write( + 'workflows/ingest/.sim/lock.json', + JSON.stringify({ + version: 1, + blocks: { score: { id: 'b-score', parent: null, ident: 'score', order: 0 } }, + variables: {}, + }) + ) + serveApplies() + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ + status: 'failed', + error: { message: 'score is not a number', blockId: 'b-score' }, + }) + ) + + const failure = apply('--yes', '--run', 'ingest={}') + + await expect(failure).rejects.toThrow( + /the test run of ingest failed: score is not a number\. deployments\/ was not applied/ + ) + expect(applies()).toHaveLength(1) + expect(applies()[0][1].body.kinds).not.toContain('deployment') + expect(vi.mocked(console.error).mock.calls.flat().join('\n')).toMatch( + /workflows\/ingest\/workflow\.ts: score is not a number \(block score\)/ + ) + expect(readFileSync(join(dir, 'workflows/ingest/workflow.ts'), 'utf8')).toBe( + `${INGEST}// stored\n` + ) + const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + expect(printed).toMatchObject({ + applied: 1, + runs: [{ workflow: 'ingest', status: 'failed', error: 'score is not a number' }], + next: { command: `sim workspaces source apply --dir ${dir} --run 'ingest={}' --yes` }, + }) + }) + + it('refuses a key with no workflow folder, naming the keys there, before sending anything', async () => { + await expect(apply('--yes', '--run', 'ingset={}')).rejects.toThrow( + /--run ingset: no such folder under workflows\/ .* Its workflow keys: ingest\./ + ) + expect(request).not.toHaveBeenCalled() + expect(contextMockFns.mockRequestRaw).not.toHaveBeenCalled() + }) + + it('refuses an input that is not JSON before sending anything', async () => { + await expect(apply('--yes', '--run', 'ingest={email:')).rejects.toThrow( + /--run ingest: its input is not JSON/ + ) + expect(request).not.toHaveBeenCalled() + }) + + it('refuses beside --to, before sending anything', async () => { + await expect(apply('--yes', '--to', 'ws_prod', '--run', 'ingest={}')).rejects.toThrow( + /--run tests the workflows of the workspace this directory was read from/ + ) + expect(request).not.toHaveBeenCalled() + }) + + it('refuses beside --dry, before sending anything', async () => { + await expect(apply('--dry', '--run', 'ingest={}')).rejects.toThrow( + /--run test-runs what the apply writes, and --dry writes nothing/ + ) + expect(request).not.toHaveBeenCalled() + expect(contextMockFns.mockRequestRaw).not.toHaveBeenCalled() + }) + }) }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 7ef930490dc..891ee69314c 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -3,6 +3,7 @@ import { join } from 'node:path' import { mapWithConcurrency } from '@sim/utils/concurrency' import { getErrorMessage } from '@sim/utils/errors' import { isRecordLike } from '@sim/utils/object' +import { compareStrings } from '@sim/utils/string' import { SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { APPLY_ORDER, @@ -40,11 +41,15 @@ import { isRequestCancelled, SimApiError } from '../../http/client' import { sanitize } from '../../output/render' import { apiCommand, type OperationClient } from '../../runtime/called-operations' import { liveDeploymentStatus } from '../../runtime/deployment-live' +import { runFailureMessage } from '../../runtime/execute' +import { collectRepeated } from '../../runtime/options' +import { readArgumentSource } from '../../runtime/request' import { searchTasks } from '../search' import { type DeployedUrl, deployedUrlsText, lockBlockNames, namedUrls } from './deployed-urls' import { gitProvenance } from './git-provenance' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' +import { printRunFailureSite } from './run-source-location' import { absoluteDirOption, directoryWorkspace, @@ -78,12 +83,13 @@ import { verboseFlag, writeMode, } from './source-ui' -import { runSourceWrite } from './source-write' +import { runSourceWrite, type SourceWriteFlow } from './source-write' import { removedWorkflowRecords, unrecordedFoldersWarning, workflowFolderRecords, } from './stored-edges' +import { dryRunDraft, printSideEffects, type TestRun, testRunResult } from './workflow-run-follow' import { appliedBlobDigests, assertBlobsFetched, @@ -94,6 +100,8 @@ import { import { assertWorkspaceDir, assertWorkspacePaths, + declaredKeys, + kindFolders, ONLY_KINDS_HELP, parseKinds, readWorkspaceDir, @@ -114,6 +122,8 @@ interface ApplyOptions { only?: string to?: string summaryFile?: string + /** Each `--run [=]`, as written. */ + run?: string[] } const SYMBOLS: Record = { @@ -699,6 +709,7 @@ export function attachWorkspaceSourceApply(source: Command): void { 'getWorkspaceSource', 'getSourceCatalog', 'getWorkflowDeployment', + 'executeWorkflow', ]) absoluteDirOption(command) verboseFlag(command) @@ -725,6 +736,11 @@ export function attachWorkspaceSourceApply(source: Command): void { '--to ', "Promote the directory to another workspace (dev to prod): its resources bind by key to that workspace's own and are updated in place. Only .sim/targets/.json changes, the record the next promotion compares with: a resource changed there since is kept, or refused as stale (exit 5) when the directory changed it too" ) + .option( + '--run ', + "After the apply, dry-run workflows//'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed; a run that does not complete exits 1 and leaves the applied drafts in place", + collectRepeated + ) .allowExcessArguments(false) .description('Apply a workspace source directory') .addHelpText('after', sourceExitCodesHelp('workspaces source apply')) @@ -732,6 +748,10 @@ export function attachWorkspaceSourceApply(source: Command): void { assertTargetOnlyDeletable(options) const mode = writeMode(options) const only = parseKinds(options.only) + const parsedRuns = parseRuns(options.run) + assertRunnable(options, parsedRuns, only) + await assertRunKeys(options.dir, parsedRuns) + const runs = await readRunInputs(parsedRuns) const { client, profile } = connect() const readFrom = baseWorkspaceOf(await readSourceJson(options.dir, WORKSPACE_BASE_FILE)) const workspaceId = @@ -746,7 +766,11 @@ export function attachWorkspaceSourceApply(source: Command): void { ) ?? undefined ) const provenance = await gitProvenance(options.dir) - const post = async (submission: WorkspaceSubmission, dry: boolean) => { + const post = async ( + submission: WorkspaceSubmission, + dry: boolean, + kinds: readonly WorkspaceKind[] | undefined + ) => { const body: ApplyWorkspaceSourceBody = { files: submission.files, kinds: submission.kinds, @@ -754,7 +778,7 @@ export function attachWorkspaceSourceApply(source: Command): void { ...(submission.base ? { base: submission.base } : {}), options: { ...(options.allowDelete ? { allowDelete: true } : {}), - ...(only ? { only } : {}), + ...(kinds ? { only: [...kinds] } : {}), }, provenance: { client: 'cli', ...provenance }, } @@ -782,14 +806,18 @@ export function attachWorkspaceSourceApply(source: Command): void { } } /** - * Sends the directory. A commit the server refuses only for blobs that are not staged (the - * CLI's guess from the base missed one) stages those and is sent once more. + * Sends the directory (as `kinds` limit it). A commit the server refuses only for blobs that + * are not staged (the CLI's guess from the base missed one) stages those and is sent once more. */ let promotion: Promotion | null = null - const send = async (submission: WorkspaceSubmission, dry: boolean): Promise => { + const send = async ( + submission: WorkspaceSubmission, + dry: boolean, + kinds: readonly WorkspaceKind[] | undefined = only + ): Promise => { let refusal: unknown try { - return await post(submission, dry) + return await post(submission, dry, kinds) } catch (error) { refusal = error } @@ -797,7 +825,7 @@ export function attachWorkspaceSourceApply(source: Command): void { if (missing && missing.length > 0) { await stage(submission, new Set(missing)) try { - return await post(submission, dry) + return await post(submission, dry, kinds) } catch (error) { refusal = error } @@ -829,6 +857,13 @@ export function attachWorkspaceSourceApply(source: Command): void { ) : null const submission = promotion?.submission ?? read + // With --run, deployments/ waits for the test runs: the first write leaves it out, and a + // second applies it once every run completed (the drafts the runs tested, vouched for by + // the workflow folders' bases the first write saved). + const deferred = new Set( + runs.length > 0 ? (declaredKeys('deployment', submission.files) ?? []) : [] + ) + const firstWrite = deferred.size > 0 ? withoutDeployments(submission) : submission /** `data` as this apply reports it: a promotion's own wording and warnings added. */ const reported = (data: ApplyData): ApplyData => promotion @@ -848,7 +883,8 @@ export function attachWorkspaceSourceApply(source: Command): void { const report = ( data: ApplyData, next?: NextStep, - { workflows, urls }: WrittenWorkflows = { workflows: [], urls: [] } + { workflows, urls }: WrittenWorkflows = { workflows: [], urls: [] }, + tested: readonly WorkflowTestRun[] = [] ) => { const diagnostics = [...notSent, ...data.diagnostics] publishSummary( @@ -859,6 +895,7 @@ export function attachWorkspaceSourceApply(source: Command): void { ...summarize({ ...data, diagnostics }), ...(workflows.length > 0 ? { workflows } : {}), ...(urls.length > 0 ? { urls } : {}), + ...(tested.length > 0 ? { runs: tested } : {}), ...(next ? { next } : {}), } printProtocolResult( @@ -868,10 +905,23 @@ export function attachWorkspaceSourceApply(source: Command): void { created: createdText(result.created), ...(workflows.length > 0 ? { workflows: writtenWorkflowsText(workflows) } : {}), ...(urls.length > 0 ? { urls: workflowUrlsText(urls) } : {}), + ...(tested.length > 0 ? { runs: testRunsText(tested) } : {}), } ) + if (findings.machine) return + for (const run of tested) { + if (run.sideEffects) printSideEffects(run.sideEffects, undefined, run.workflowId) + } } - const data = await runSourceWrite({ + /** + * The write of `commit` after a preview of the whole submission, saved into the + * directory against `held`, its `.sim/written.json`. A commit of part of the submission + * is sent as only its own kinds. + */ + const writeFlow = ( + commit: WorkspaceSubmission, + held: Written + ): SourceWriteFlow => ({ mode, preview: async () => reported(await send(submission, true)), show: (preview) => { @@ -882,9 +932,11 @@ export function attachWorkspaceSourceApply(source: Command): void { previewExitCode, // Without a preview, stage the blobs the base does not hold as they are. beforeCommit: (preview) => - stage(submission, preview ? new Set(preview.needBlobs) : blobsToStage(submission)), + stage(commit, preview ? new Set(preview.needBlobs) : blobsToStage(commit)), commit: async () => { - const answer = reported(await send(submission, false)) + const answer = reported( + await send(commit, false, commit === submission ? only : commit.kinds) + ) findings.print(answer.diagnostics) return answer }, @@ -899,7 +951,7 @@ export function attachWorkspaceSourceApply(source: Command): void { const { records, unrecorded } = workspaceCatalog ? await workflowFolderRecords(client, workspaceId, workspaceCatalog, answer.files) : { records: [], unrecorded: [] } - await saveApplied(options.dir, answer, submission, written, records) + await saveApplied(options.dir, answer, commit, held, records) const unrecordedWarning = unrecordedFoldersWarning(unrecorded) if (unrecordedWarning) printError(unrecordedWarning) }, @@ -913,38 +965,289 @@ export function attachWorkspaceSourceApply(source: Command): void { ifAnswerLost: answerLostHint(options.dir), }, }) + /** + * Prints how a written apply ended (its plan, what it held back, where it stopped) and + * sets its exit status. Returns whether it wrote every change it planned. + */ + const settle = (data: ApplyData): boolean => { + if (data.failed) { + printError('The apply stopped part-way; each planned change:') + printPlan(data.plan, data.diagnostics, data) + } else if (mode === 'write') printPlan(data.plan, data.diagnostics) + const held = data.plan.filter((change) => change.held) + if (held.length > 0) { + printError( + `Held back, not written: ${held.map((change) => `${change.kind} ${change.key}`).join(', ')}. Fix what each one's error names, then apply again.` + ) + // Written in part is not the same outcome as nothing written: a script must tell them apart. + setSoftExitCode(data.applied.length > 0 ? SOURCE_HELD_EXIT_CODE : 1) + } + if (data.failed) { + printError( + `Stopped at ${data.failed.kind} ${data.failed.key}: ${data.failed.message}` + ) + setSoftExitCode(failedExitCode(data.failed)) + } + return !data.failed && held.length === 0 + } + const tested: WorkflowTestRun[] = [] + /** Prints `data` as the result with its workflows' deployments and the test runs. */ + const finish = async (data: ApplyData, next?: NextStep) => + report( + data, + next, + await writtenWorkflows( + client, + data, + promotion ? undefined : (path) => readSourceText(options.dir, path) + ), + tested + ) + + const data = await runSourceWrite(writeFlow(firstWrite, written)) if (!data) return - if (data.failed) { - printError('The apply stopped part-way; each planned change:') - printPlan(data.plan, data.diagnostics, data) - } else if (mode === 'write') printPlan(data.plan, data.diagnostics) - const held = data.plan.filter((change) => change.held) - if (held.length > 0) { + // The first write declares no deployment file, so the server warns that each deferred + // deployment's workflow changed with none to deploy it (`warnDeployedDraftChanges`): + // the second write decides those. + const first = + deferred.size === 0 + ? data + : { + ...data, + diagnostics: data.diagnostics.filter( + (finding) => + finding.code !== 'W_DEPLOYED_DRAFT_CHANGED' || + !deferred.has(finding.key ?? '') + ), + } + const complete = settle(first) + if (runs.length === 0) return finish(first) + if (!complete) { printError( - `Held back, not written: ${held.map((change) => `${change.kind} ${change.key}`).join(', ')}. Fix what each one's error names, then apply again.` + `Not test-run${deferred.size > 0 ? ', and deployments/ not applied' : ''}: the apply did not write every change.` ) - // Written in part is not the same outcome as nothing written: a script must tell them apart. - setSoftExitCode(data.applied.length > 0 ? SOURCE_HELD_EXIT_CODE : 1) + return finish(first) } - if (data.failed) { - printError(`Stopped at ${data.failed.kind} ${data.failed.key}: ${data.failed.message}`) - setSoftExitCode(failedExitCode(data.failed)) + /** Runs a step after the write; a failure prints the write's result first: it stands. */ + const afterWrite = async (step: () => Promise): Promise => { + try { + return await step() + } catch (error) { + await finish(first) + throw error + } } - report( - data, - undefined, - await writtenWorkflows( - client, - data, - promotion ? undefined : (path) => readSourceText(options.dir, path) + await afterWrite(() => testRuns(client, options.dir, workspaceId, first, runs, tested)) + const failedRuns = tested.filter((run) => run.status !== 'completed') + if (failedRuns.length > 0) { + const next = { + command: `${applyCommand(options)} --yes`, + reason: 'applies your fix and tests it again', + } + await finish(first, next) + const why = failedRuns + .map((run) => `the test run of ${run.workflow} ${String(run.status)}: ${run.error}`) + .join('; ') + throw new SimApiError( + `The apply was written into ${options.dir}, but ${why}.${deferred.size > 0 ? ' deployments/ was not applied.' : ''} Fix the source, then run \`${next.command}\`.`, + 0 ) - ) + } + if (deferred.size === 0) return finish(first) + const deployed = await afterWrite(async () => { + const saved = await readWritten(options.dir) + const second = await readWorkspaceDir( + options.dir, + ['workflow', 'deployment'], + workspaceId, + saved + ) + return runSourceWrite({ ...writeFlow(second, saved), mode: 'write' }) + }) + if (!deployed) return + settle({ ...deployed, plan: deployed.plan.filter(isDeployment) }) + await finish(mergedApply(first, deployed)) }, { readOnly: mode === 'dry' || mode === 'plan' } ) }) } +/** One `--run`: the workflow folder's key, and its input as `--input` takes it (JSON or `@file`). */ +interface RunRequest { + key: string + input?: string +} + +/** `--run [=]`, each workflow once. */ +function parseRuns(values: readonly string[] | undefined): RunRequest[] { + const runs = (values ?? []).map((value): RunRequest => { + const at = value.indexOf('=') + const key = at === -1 ? value : value.slice(0, at) + if (key.length === 0) { + throw new CliUsageError( + `--run ${value} names no workflow: write --run ='{…}', where is its folder under ${KIND_DIRS.workflow}/.` + ) + } + return at === -1 ? { key } : { key, input: value.slice(at + 1) } + }) + const keys = runs.map((run) => run.key) + const repeated = keys.find((key, index) => keys.indexOf(key) !== index) + if (repeated !== undefined) { + throw new CliUsageError(`--run names ${repeated} twice: test each workflow once per apply.`) + } + return runs +} + +/** + * Refuses `--run` beside `--dry` (nothing is written to test), `--to` (a promotion writes another + * workspace than the one the directory tests in) and an `--only` without workflows. + */ +function assertRunnable( + options: ApplyOptions, + runs: readonly RunRequest[], + only: readonly WorkspaceKind[] | undefined +): void { + if (runs.length === 0) return + if (options.dry) { + throw new CliUsageError( + '--run test-runs what the apply writes, and --dry writes nothing: drop one of them.' + ) + } + if (options.to) { + throw new CliUsageError( + '--run tests the workflows of the workspace this directory was read from, and --to promotes to another one: test with an apply to this workspace, then promote without --run.' + ) + } + if (only && !only.includes('workflow')) { + throw new CliUsageError( + `--run tests the workflows this apply writes: add ${KIND_DIRS.workflow} to --only, or drop --run.` + ) + } +} + +/** Refuses a `--run` key with no `workflows//` folder in `dir`, naming the keys it has. */ +async function assertRunKeys(dir: string, runs: readonly RunRequest[]): Promise { + if (runs.length === 0) return + const { paths } = await kindFolders(dir, ['workflow']) + const keys = [...KIND_LAYOUTS.workflow.group(paths).groups.keys()].sort(compareStrings) + const unknown = runs.filter((run) => !keys.includes(run.key)).map((run) => run.key) + if (unknown.length === 0) return + throw new CliUsageError( + `--run ${unknown.join(', ')}: no such folder under ${KIND_DIRS.workflow}/ in ${dir}. ${ + keys.length > 0 ? `Its workflow keys: ${keys.join(', ')}.` : 'It holds no workflows.' + }` + ) +} + +/** + * Each `--run` input read as `--input` reads it (JSON, or `@file`) and checked to parse, so a bad + * one is refused before anything is written rather than after the apply. + */ +async function readRunInputs(runs: readonly RunRequest[]): Promise { + return Promise.all( + runs.map(async (run) => { + if (run.input === undefined) return run + const { text } = await readArgumentSource(run.input, 'run') + try { + JSON.parse(text) + } catch { + throw new CliUsageError(`--run ${run.key}: its input is not JSON.`) + } + return { ...run, input: text } + }) + ) +} + +const isDeployment = (change: Pick) => change.kind === 'deployment' + +/** `submission` without its deployment files: an apply of every other kind it sends. */ +function withoutDeployments(submission: WorkspaceSubmission): WorkspaceSubmission { + return { + ...submission, + kinds: submission.kinds.filter((kind) => kind !== 'deployment'), + files: Object.fromEntries( + Object.entries(submission.files).filter(([path]) => kindOfPath(path) !== 'deployment') + ), + } +} + +/** + * The first write of a `--run` apply and the deployments written after its runs, as one apply: + * the second's deployment changes and findings added to the first's. The second write sends the + * workflows only so their bases vouch for the drafts it deploys; the first already wrote them, so + * its findings on them repeat the first's. + */ +function mergedApply(first: ApplyData, deployed: ApplyData): ApplyData { + return { + ...deployed, + plan: [...first.plan, ...deployed.plan.filter(isDeployment)], + applied: [...first.applied, ...deployed.applied.filter(isDeployment)], + files: { ...first.files, ...deployed.files }, + diagnostics: [ + ...first.diagnostics, + ...deployed.diagnostics.filter((finding) => finding.kind !== 'workflow'), + ], + ...(first.applyId ? { applyId: first.applyId } : {}), + } +} + +/** A `--run` test run in an apply's result: the workflow's key and id, then the run. */ +interface WorkflowTestRun extends TestRun { + workflow: string + workflowId: string +} + +/** The test runs as one display line: `ingest completed; score failed: …`. */ +function testRunsText(tested: readonly WorkflowTestRun[]): string { + return tested + .map((run) => + run.status === 'completed' + ? `${run.workflow} completed` + : `${run.workflow} ${String(run.status)}: ${String(run.error)}` + ) + .join('; ') +} + +/** + * Dry-runs each `--run` workflow's saved draft, one at a time, as `sim workflows run --dry + * --input` does, adding each result to `tested`; a run that does not complete has its failing + * block mapped to file:line in its `workflows//` folder, and its `error` says why, as + * `sim workflows source apply --run` words it. A key the written base binds to no workflow is + * refused before any run. + */ +async function testRuns( + client: OperationClient<'executeWorkflow'>, + dir: string, + workspaceId: string, + data: ApplyData, + runs: readonly RunRequest[], + tested: WorkflowTestRun[] +): Promise { + const base = parseWorkspaceBase(data.base).base + const targets = runs.map((run) => ({ + ...run, + workflowId: base?.resources[resourceAddress('workflow', run.key)]?.id, + })) + const unbound = targets.filter((target) => !target.workflowId).map((target) => target.key) + if (unbound.length > 0) { + throw new SourceDirError( + `The apply was written, but ${WORKSPACE_BASE_FILE} binds no workflow to ${unbound.map((key) => `${workflowFolder(key)}/`).join(', ')}, so nothing was test-run: check that each holds a workflow.ts, then apply again.` + ) + } + for (const { key, input, workflowId } of targets) { + if (!workflowId) continue + const record = await dryRunDraft(client, workflowId, input, workspaceId) + const run = { workflow: key, workflowId, ...testRunResult(record) } + if (record.status !== 'completed') { + await printRunFailureSite(join(dir, workflowFolder(key)), workflowId, record.error) + run.error = + runFailureMessage('executeWorkflow', record) ?? `it ended ${String(record.status)}` + } + tested.push(run) + } +} + /** * The plan of a dry run or apply to `workspaceId` as the Markdown a GitHub Actions step summary * shows: each change and how it went, then each error. @@ -1090,7 +1393,10 @@ async function writtenWorkflows( } } -/** This apply as a command, without `--yes` or `--dry`: what a plan run names next. */ +/** + * This apply as a command, without `--yes` or `--dry`: what a plan run or a failed test run + * names next. + */ function applyCommand(options: ApplyOptions): string { return [ `sim workspaces source apply --dir ${shellWord(options.dir)}`, @@ -1098,6 +1404,7 @@ function applyCommand(options: ApplyOptions): string { ...(options.to ? [`--to ${shellWord(options.to)}`] : []), ...(options.allowDelete ? ['--allow-delete'] : []), ...(options.deleteTargetOnly ? ['--delete-target-only'] : []), + ...(options.run ?? []).map((run) => `--run ${shellWord(run)}`), ...(options.summaryFile ? [summaryFileFlag(options.summaryFile).trimStart()] : []), ].join(' ') } diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index be0e7166b59..2d75468b89c 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -159,12 +159,12 @@ Secrets never appear in source: a workflow reads an environment variable as \`en ## Edit loop in detail -Batch it: write every file first, then run steps 2 and 4 (and any test run) as one chained command, \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`, 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. +Batch it: write every file first, then run steps 2 and 4 (with a test run of each workflow you changed) as one chained command, \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes --run ='{…}'\`, 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. 1. Edit the files. 2. \`sim workspaces source check --dir .\`: compiles every workflow offline with the server's compiler, against what this directory declares: an unknown resource key (skills included) or table column, a child workflow's inputs, and an env name \`${KIND_DIRS.secret}\` lacks (a warning); and checks each \`${KIND_DIRS.table}/.rows.jsonl\` line against its table as the apply would. It fails (exit 1) on errors and on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block), regenerates \`.sim/sdk/workspace.d.ts\` from the files (so a resource or workflow input added since the get is typed) and adds the blocks the workflows now use to \`tsconfig.json\`, then type-checks every file 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 the dry run 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. In a workflow folder, \`sim workflows source check --dir .\` checks that one workflow the same way. Fix and rerun until it exits 0. 3. \`sim workspaces source status --dir .\` before applying: your changes by resource (\`sim workspaces source diff --dir .\` shows the edits), what changed on the server since the get (a workflow edited in the editor included), the conflicts, and the command to run next. Exit 0 nothing changed, ${SOURCE_LOCAL_CHANGES_EXIT_CODE} only your edits, ${SOURCE_DRIFT_EXIT_CODE} the server changed since (\`--offline\`: skip the server). Then \`sim workspaces source apply --dir . --dry\`: shows the plan (\`+\` create, \`~\` update, \`=\` adopt an existing resource of the same name, \`-\` delete) and every error; fix and rerun until it exits 0. -4. \`sim workspaces source apply --dir . --yes\`: writes it and rewrites this directory from what was stored; it prints the plan it applied (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}, writing nothing). +4. \`sim workspaces source apply --dir . --yes\`: writes it and rewrites this directory from what was stored; it prints the plan it applied (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}, writing nothing). \`--run ='{…}'\` (one per workflow, \`\` its \`${KIND_DIRS.workflow}//\` folder; the input is JSON or \`@file\`, as \`sim workflows run --dry --input\` takes it) then dry-runs that workflow's saved draft as that command does: \`runs\` in the result holds each run's status, output and side effects, and a run that does not complete exits 1, names its failing block's file:line and leaves the applied drafts in place. With \`--run\`, \`${KIND_DIRS.deployment}/\` is applied after the runs, and only when every one completed, so a deployment with \`live: 'draft'\` publishes only a tested draft; without \`--run\` it is applied with everything else. ## Good to know @@ -293,7 +293,7 @@ export async function writtenLocalDeclarations( * folder's paths group into. `null` for a root file that is absent or does not read, whose keys * are unknown. */ -function declaredKeys( +export function declaredKeys( kind: WorkspaceKind, files: Readonly> ): string[] | null { From 0506f1f8cf6054995efe9141903b332858c494e0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 16:41:41 -0800 Subject: [PATCH 2/6] fix(workflow-code): review round 1 for workspace apply --run - Gate a managed deployments/ on the runs even when no deployment file is left, so a failed run never undeploys a workflow. - Read the deployments write before the runs and refuse it when a workflow or deployment file changed while they ran, so only tested drafts deploy. - Drop the first write's W_DEPLOYED_DRAFT_CHANGED for deferred deployments before it prints. - Help names runs[].sideEffects.unchecked and .omitted. --- .../src/commands/protocol/source-loop-help.ts | 3 +- .../protocol/workspace-source-apply.test.ts | 68 +++++++++++ .../protocol/workspace-source-apply.ts | 109 +++++++++++------- 3 files changed, 140 insertions(+), 40 deletions(-) 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 56491999b1d..9a29ca54acc 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -99,7 +99,8 @@ The loop, two shell calls: 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; --run ='{…}' (one per workflow, its workflows// folder) -dry-runs that input on the saved draft (writes stubbed, listed under runs[].sideEffects). A +dry-runs that input on the saved draft: writes are stubbed and listed under runs[].sideEffects, +whose .unchecked lists sandboxed code that ran unchecked and .omitted counts entries left out. A workflow deploys on apply when deployments/.ts declares it; with --run, deployments/ is applied only after every run completed. --allow-delete lets an edit remove a resource, column, rows, document, or a workflow's block or diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index a635e8d61ba..277b9e573e4 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -2264,6 +2264,74 @@ describe('workspaces source apply', () => { }) }) + it('holds back a managed deployments/ with no files left (its undeploys) until the runs complete', async () => { + unlinkSync(join(dir, 'deployments/ingest.ts')) + write('deployments/.gitkeep', '') + serveApplies() + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ status: 'failed', error: { message: 'score is not a number' } }) + ) + + await expect(apply('--yes', '--allow-delete', '--run', 'ingest={}')).rejects.toThrow( + /deployments\/ was not applied/ + ) + expect(applies()).toHaveLength(1) + expect(applies()[0][1].body.kinds).not.toContain('deployment') + }) + + it('applies no deployments when a workflow file changed while the runs ran', async () => { + serveApplies() + contextMockFns.mockRequestRaw.mockImplementation(async () => { + write('workflows/ingest/workflow.ts', `${INGEST}// edited during the run\n`) + return runAnswer({ status: 'completed', output: {} }) + }) + + await expect(apply('--yes', '--run', 'ingest={}')).rejects.toThrow( + /workflows\/ingest\/workflow\.ts changed in .* while they ran, so deployments\/ was not applied/ + ) + expect(applies()).toHaveLength(1) + }) + + it("never prints the first write's warning that a deferred deployment's workflow is not deployed", async () => { + request.mockImplementation(async (path: string, options: { body?: { kinds?: string[] } }) => { + if (path === '/api/v2/workflows/wf_1/deployment') return deploymentStatus(1) + const base = { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } } + if (options.body?.kinds?.includes('deployment')) { + return answer({ + plan: [{ kind: 'deployment', key: 'ingest', action: 'update' }], + applied: [{ kind: 'deployment', key: 'ingest', action: 'update' }], + base, + }) + } + return answer({ + plan: [{ kind: 'workflow', key: 'ingest', action: 'update' }], + applied: [{ kind: 'workflow', key: 'ingest', action: 'update' }], + files: { 'workflows/ingest/workflow.ts': `${INGEST}// stored\n` }, + base, + diagnostics: [ + { + code: 'W_DEPLOYED_DRAFT_CHANGED', + severity: 'warning', + message: 'workflow ingest is deployed: the live version keeps running the old one.', + kind: 'workflow', + key: 'ingest', + }, + ], + }) + }) + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ status: 'completed', output: {} }) + ) + + await apply('--yes', '--run', 'ingest={}') + + expect(applies()).toHaveLength(2) + const out = [...vi.mocked(console.error).mock.calls, ...vi.mocked(console.log).mock.calls] + .flat() + .join('\n') + expect(out).not.toContain('W_DEPLOYED_DRAFT_CHANGED') + }) + it('refuses a key with no workflow folder, naming the keys there, before sending anything', async () => { await expect(apply('--yes', '--run', 'ingset={}')).rejects.toThrow( /--run ingset: no such folder under workflows\/ .* Its workflow keys: ingest\./ diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 891ee69314c..4a38ff3c9cc 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -857,13 +857,27 @@ export function attachWorkspaceSourceApply(source: Command): void { ) : null const submission = promotion?.submission ?? read - // With --run, deployments/ waits for the test runs: the first write leaves it out, and a - // second applies it once every run completed (the drafts the runs tested, vouched for by - // the workflow folders' bases the first write saved). + // With --run, a managed deployments/ (its deploys, and the undeploys of files removed + // from it) waits for the test runs: the first write leaves it out, and a second applies + // it once every run completed (the drafts the runs tested, vouched for by the workflow + // folders' bases the first write saved). + const gated = runs.length > 0 && submission.kinds.includes('deployment') const deferred = new Set( - runs.length > 0 ? (declaredKeys('deployment', submission.files) ?? []) : [] + gated ? (declaredKeys('deployment', submission.files) ?? []) : [] ) - const firstWrite = deferred.size > 0 ? withoutDeployments(submission) : submission + const firstWrite = gated ? withoutDeployments(submission) : submission + /** + * The first write declares no deployment file, so the server warns that each deferred + * deployment's workflow changed with none to deploy it (`warnDeployedDraftChanges`): the + * second write decides those. + */ + const withoutDeferredWarnings = (data: ApplyData): ApplyData => ({ + ...data, + diagnostics: data.diagnostics.filter( + (finding) => + finding.code !== 'W_DEPLOYED_DRAFT_CHANGED' || !deferred.has(finding.key ?? '') + ), + }) /** `data` as this apply reports it: a promotion's own wording and warnings added. */ const reported = (data: ApplyData): ApplyData => promotion @@ -934,9 +948,10 @@ export function attachWorkspaceSourceApply(source: Command): void { beforeCommit: (preview) => stage(commit, preview ? new Set(preview.needBlobs) : blobsToStage(commit)), commit: async () => { - const answer = reported( + const sent = reported( await send(commit, false, commit === submission ? only : commit.kinds) ) + const answer = commit === firstWrite && gated ? withoutDeferredWarnings(sent) : sent findings.print(answer.diagnostics) return answer }, @@ -1006,67 +1021,63 @@ export function attachWorkspaceSourceApply(source: Command): void { const data = await runSourceWrite(writeFlow(firstWrite, written)) if (!data) return - // The first write declares no deployment file, so the server warns that each deferred - // deployment's workflow changed with none to deploy it (`warnDeployedDraftChanges`): - // the second write decides those. - const first = - deferred.size === 0 - ? data - : { - ...data, - diagnostics: data.diagnostics.filter( - (finding) => - finding.code !== 'W_DEPLOYED_DRAFT_CHANGED' || - !deferred.has(finding.key ?? '') - ), - } - const complete = settle(first) - if (runs.length === 0) return finish(first) + const complete = settle(data) + if (runs.length === 0) return finish(data) if (!complete) { printError( - `Not test-run${deferred.size > 0 ? ', and deployments/ not applied' : ''}: the apply did not write every change.` + `Not test-run${gated ? ', and deployments/ not applied' : ''}: the apply did not write every change.` ) - return finish(first) + return finish(data) } - /** Runs a step after the write; a failure prints the write's result first: it stands. */ + /** Runs a step after the write; a failure prints the write's result data: it stands. */ const afterWrite = async (step: () => Promise): Promise => { try { return await step() } catch (error) { - await finish(first) + await finish(data) throw error } } - await afterWrite(() => testRuns(client, options.dir, workspaceId, first, runs, tested)) + /** What the deployments write sends: the workflows the first write saved, and deployments/. */ + const readDeploymentWrite = async () => { + const saved = await readWritten(options.dir) + const read = await readWorkspaceDir( + options.dir, + ['workflow', 'deployment'], + workspaceId, + saved + ) + return { saved, read } + } + // Read before the runs, so the deploys publish only what they tested. + const before = gated ? await afterWrite(readDeploymentWrite) : null + await afterWrite(() => testRuns(client, options.dir, workspaceId, data, runs, tested)) const failedRuns = tested.filter((run) => run.status !== 'completed') if (failedRuns.length > 0) { const next = { command: `${applyCommand(options)} --yes`, reason: 'applies your fix and tests it again', } - await finish(first, next) + await finish(data, next) const why = failedRuns .map((run) => `the test run of ${run.workflow} ${String(run.status)}: ${run.error}`) .join('; ') throw new SimApiError( - `The apply was written into ${options.dir}, but ${why}.${deferred.size > 0 ? ' deployments/ was not applied.' : ''} Fix the source, then run \`${next.command}\`.`, + `The apply was written into ${options.dir}, but ${why}.${gated ? ' deployments/ was not applied.' : ''} Fix the source, then run \`${next.command}\`.`, 0 ) } - if (deferred.size === 0) return finish(first) + if (!before) return finish(data) const deployed = await afterWrite(async () => { - const saved = await readWritten(options.dir) - const second = await readWorkspaceDir( - options.dir, - ['workflow', 'deployment'], - workspaceId, - saved - ) - return runSourceWrite({ ...writeFlow(second, saved), mode: 'write' }) + assertUnchangedSinceRuns(options.dir, before.read, (await readDeploymentWrite()).read) + return runSourceWrite({ + ...writeFlow(before.read, before.saved), + mode: 'write', + }) }) if (!deployed) return settle({ ...deployed, plan: deployed.plan.filter(isDeployment) }) - await finish(mergedApply(first, deployed)) + await finish(mergedApply(data, deployed)) }, { readOnly: mode === 'dry' || mode === 'plan' } ) @@ -1159,6 +1170,26 @@ async function readRunInputs(runs: readonly RunRequest[]): Promise ) } +/** + * Refuses the deployments write of a `--run` apply when its workflow or deployment files changed + * while the runs ran (`before` was read ahead of them, `after` once they completed): deploying + * then would publish a draft, or settings, no run tested. + */ +function assertUnchangedSinceRuns( + dir: string, + before: WorkspaceSubmission, + after: WorkspaceSubmission +): void { + const paths = new Set([...Object.keys(before.files), ...Object.keys(after.files)]) + const changed = [...paths] + .filter((path) => before.files[path] !== after.files[path]) + .sort(compareStrings) + if (changed.length === 0) return + throw new SourceDirError( + `The apply was written and every test run completed, but ${changed.join(', ')} changed in ${dir} while they ran, so ${KIND_DIRS.deployment}/ was not applied: apply again to test and deploy what is there now.` + ) +} + const isDeployment = (change: Pick) => change.kind === 'deployment' /** `submission` without its deployment files: an apply of every other kind it sends. */ From b251fe18c78f8f224cf05a80a588bdb9515f30b0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 16:49:15 -0800 Subject: [PATCH 3/6] fix(workflow-code): review round 2: judge a held deployments write against the whole apply --- .../protocol/workspace-source-apply.test.ts | 27 +++++++++++++++++++ .../protocol/workspace-source-apply.ts | 7 +++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index 277b9e573e4..f543565e2b3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -2264,6 +2264,33 @@ describe('workspaces source apply', () => { }) }) + it('exits as written in part when the deployments write holds every deployment back', async () => { + request.mockImplementation(async (path: string, options: { body?: { kinds?: string[] } }) => { + if (path === '/api/v2/workflows/wf_1/deployment') return deploymentStatus(1) + const base = { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } } + return options.body?.kinds?.includes('deployment') + ? answer({ + plan: [{ kind: 'deployment', key: 'ingest', action: 'update', held: true }], + applied: [], + base, + }) + : answer({ + plan: [{ kind: 'workflow', key: 'ingest', action: 'update' }], + applied: [{ kind: 'workflow', key: 'ingest', action: 'update' }], + files: { 'workflows/ingest/workflow.ts': `${INGEST}// stored\n` }, + base, + }) + }) + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ status: 'completed', output: {} }) + ) + + await apply('--yes', '--run', 'ingest={}') + + expect(applies()).toHaveLength(2) + expect(process.exitCode).toBe(15) + }) + it('holds back a managed deployments/ with no files left (its undeploys) until the runs complete', async () => { unlinkSync(join(dir, 'deployments/ingest.ts')) write('deployments/.gitkeep', '') diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 4a38ff3c9cc..287fc2b5b87 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -1076,8 +1076,11 @@ export function attachWorkspaceSourceApply(source: Command): void { }) }) if (!deployed) return - settle({ ...deployed, plan: deployed.plan.filter(isDeployment) }) - await finish(mergedApply(data, deployed)) + const merged = mergedApply(data, deployed) + // Judged against the whole apply: held deployments after written workflows are a + // partial write, not nothing written. + settle({ ...merged, plan: deployed.plan.filter(isDeployment) }) + await finish(merged) }, { readOnly: mode === 'dry' || mode === 'plan' } ) From 388013d0cc0cf01ffd863274df5013a74b62d600 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 16:56:25 -0800 Subject: [PATCH 4/6] fix(workflow-code): review round 3: refuse deploying a workflow edited between the first write and the runs --- .../protocol/workspace-source-apply.test.ts | 23 ++++++++++- .../protocol/workspace-source-apply.ts | 39 ++++++++++++------- 2 files changed, 47 insertions(+), 15 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index f543565e2b3..df5e7a3afa3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -2314,11 +2314,32 @@ describe('workspaces source apply', () => { }) await expect(apply('--yes', '--run', 'ingest={}')).rejects.toThrow( - /workflows\/ingest\/workflow\.ts changed in .* while they ran, so deployments\/ was not applied/ + /workflows\/ingest\/workflow\.ts changed in .* since the apply read it, so deployments\/ was not applied/ ) expect(applies()).toHaveLength(1) }) + it('applies no deployments when a workflow file changed between the first write and the runs', async () => { + serveApplies() + // The first write's plan prints after its save and before the read ahead of the runs: the + // edit lands in that window. + let edited = false + vi.mocked(console.error).mockImplementation((line: unknown) => { + if (edited || !String(line).startsWith('workflows:')) return + edited = true + write('workflows/ingest/workflow.ts', `${INGEST}// edited after the save\n`) + }) + contextMockFns.mockRequestRaw.mockResolvedValue( + runAnswer({ status: 'completed', output: {} }) + ) + + await expect(apply('--yes', '--run', 'ingest={}')).rejects.toThrow( + /workflows\/ingest\/workflow\.ts changed in .* since the apply read it/ + ) + expect(edited).toBe(true) + expect(applies()).toHaveLength(1) + }) + it("never prints the first write's warning that a deferred deployment's workflow is not deployed", async () => { request.mockImplementation(async (path: string, options: { body?: { kinds?: string[] } }) => { if (path === '/api/v2/workflows/wf_1/deployment') return deploymentStatus(1) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 287fc2b5b87..a878d8f9310 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -1069,7 +1069,17 @@ export function attachWorkspaceSourceApply(source: Command): void { } if (!before) return finish(data) const deployed = await afterWrite(async () => { - assertUnchangedSinceRuns(options.dir, before.read, (await readDeploymentWrite()).read) + const after = (await readDeploymentWrite()).read + const tested = before.read.files + assertUnchangedSinceRuns(options.dir, [ + // The read ahead of the runs against what the first write saved (else read); its + // pruned workflow folders were never sent whole, so only its own paths count. + ...changedPaths({ ...submission.files, ...data.files }, tested, Object.keys(tested)), + ...changedPaths(tested, after.files, [ + ...Object.keys(tested), + ...Object.keys(after.files), + ]), + ]) return runSourceWrite({ ...writeFlow(before.read, before.saved), mode: 'write', @@ -1173,23 +1183,24 @@ async function readRunInputs(runs: readonly RunRequest[]): Promise ) } +/** The `paths` whose text in `actual` is not the text in `expected`. */ +function changedPaths( + expected: Readonly>, + actual: Readonly>, + paths: readonly string[] +): string[] { + return paths.filter((path) => expected[path] !== actual[path]) +} + /** - * Refuses the deployments write of a `--run` apply when its workflow or deployment files changed - * while the runs ran (`before` was read ahead of them, `after` once they completed): deploying - * then would publish a draft, or settings, no run tested. + * Refuses the deployments write of a `--run` apply when a workflow or deployment file it sends + * `changed` since the apply read it: deploying then would publish a draft, or settings, no run + * tested. */ -function assertUnchangedSinceRuns( - dir: string, - before: WorkspaceSubmission, - after: WorkspaceSubmission -): void { - const paths = new Set([...Object.keys(before.files), ...Object.keys(after.files)]) - const changed = [...paths] - .filter((path) => before.files[path] !== after.files[path]) - .sort(compareStrings) +function assertUnchangedSinceRuns(dir: string, changed: readonly string[]): void { if (changed.length === 0) return throw new SourceDirError( - `The apply was written and every test run completed, but ${changed.join(', ')} changed in ${dir} while they ran, so ${KIND_DIRS.deployment}/ was not applied: apply again to test and deploy what is there now.` + `The apply was written and every test run completed, but ${[...new Set(changed)].sort(compareStrings).join(', ')} changed in ${dir} since the apply read it, so ${KIND_DIRS.deployment}/ was not applied: apply again to test and deploy what is there now.` ) } From a23291a92a69493aace9b7c684c68ee3a4c6d569 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 17:19:27 -0800 Subject: [PATCH 5/6] fix(workflow-code): review round 4: repair a kept chat when an earlier apply's draft goes live - A stored chat output reads by the block's name in the draft, else in the live version it serves, so a chat whose output block an earlier apply re-created is rewritten when that draft deploys (the apply --run deployments write), instead of keeping the deleted block id. - Help says the test run executes code and sends GET fetches; the primer and pointer say one --run per changed workflow. --- .../application/deployments.integration.ts | 36 ++++++++++++++++++ .../application/kinds/deployment/adapter.ts | 37 ++++++++++++------- .../application/kinds/deployment/stored.ts | 27 ++++++++++++-- .../src/commands/protocol/source-loop-help.ts | 6 ++- .../src/commands/protocol/source-primer.ts | 4 +- packages/workspace-code/DESIGN.md | 6 ++- 6 files changed, 94 insertions(+), 22 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/deployments.integration.ts b/apps/sim/lib/workspace-source/application/deployments.integration.ts index 1091ccce697..8035136eb88 100644 --- a/apps/sim/lib/workspace-source/application/deployments.integration.ts +++ b/apps/sim/lib/workspace-source/application/deployments.integration.ts @@ -624,6 +624,42 @@ describe('workspace source: deployments', () => { } ) + check( + 'rewrites a kept chat whose output block an earlier apply re-created, when its draft goes live', + async () => { + const deployed = await deployedWorkspace(answerChat('recreated-earlier-chat')) + const { workspaceId, id, base } = deployed + const files: Files = deployed.files + const [oldOutput] = toArray((await deployState(id)).chat?.outputConfigs) + + // The workflow alone first, as `apply --run` writes it before its test runs: the retyped + // Answer block gets a new id while the chat still answers from the old one. + const workflowOnly = await apply( + workspaceId, + { ...files, [WORKFLOW]: RETYPED }, + { base, allowDelete: true, kinds: ['workflow'], only: ['workflow'] } + ) + expect(workflowOnly.failed).toBeUndefined() + const newId = await answerBlockId(id) + expect(newId).not.toEqual(toRecord(oldOutput).blockId) + + // Then the deployment beside the unchanged workflow: its draft goes live, chat repaired. + const deploying = await apply( + workspaceId, + { ...files, ...workflowOnly.files, [DEPLOYMENT]: files[DEPLOYMENT] }, + { base: workflowOnly.base } + ) + expect(deploymentCodes(deploying.diagnostics, 'error')).toEqual([]) + expect(deploying.plan.find((change) => change.kind === 'deployment')?.fields).toContain( + 'chat outputs' + ) + expect(deploying.failed).toBeUndefined() + const after = await deployState(id) + expect(after.versions).toBe(2) + expect(after.chat?.outputConfigs).toEqual([{ blockId: newId, path: 'content' }]) + } + ) + check( 'renames a chat output block and the chat naming it in one apply, keeping the block id', async () => { diff --git a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts index 4ccf679ecc4..c52bcb2891b 100644 --- a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts @@ -347,12 +347,21 @@ async function checkChat( } } +/** The stored draft's blocks of workflow `workflowId`, as an edit's `blocks`: id to normalized name. */ +async function draftBlocks( + ctx: PlanContext, + workflowId: string +): Promise> { + const { nameOf } = await readBlockNames(ctx, workflowId) + return new Map([...nameOf].map(([id, name]) => [id, normalizeWorkflowBlockName(name)])) +} + /** - * Checks a chat this apply keeps unchanged against the graph an edit leaves: the chat stores its - * outputs by block id, so an edit that deletes a block and adds one under the same name leaves - * it answering from a block that no longer exists. Every output whose block is still there is - * fine. One whose block is gone is re-created when exactly one block of the edited graph has its - * name: counted, so the chat is written again, its outputs resolved to that block. When several + * Checks a chat this apply keeps unchanged against the draft going live (the graph an edit leaves, + * or a stored draft an earlier edit left): the chat stores its outputs by block id, so an edit + * that deletes a block and adds one under the same name leaves it answering from a block that no + * longer exists. Every output whose block is still there is fine. One whose block is gone is + * re-created when exactly one block of that draft has its name: counted, so the chat is written again, its outputs resolved to that block. When several * share it, it refuses (`E_DEPLOY_CHAT_OUTPUT`). A kept chat declares the names it stores, so one * no block has is refused by {@link checkChat}'s name check, which runs as well; both before * anything goes live. @@ -606,15 +615,15 @@ async function planDeployment( } } if (next.action === 'noop') return next - if ( - state?.chat && - decl.chat && - detail.chat === undefined && - detail.deploy && - draftEdited && - workflowChange?.blocks - ) { - if (checkKeptOutputs(next, state.chat.outputs, workflowChange.blocks) > 0) { + // A kept chat going live with a new draft: the one this apply's edit leaves, or a stored draft + // that differs from the live version (an earlier apply's edit, deployed now). + if (state?.chat && decl.chat && detail.chat === undefined && detail.deploy) { + const blocks = draftEdited + ? workflowChange?.blocks + : workflowId + ? await draftBlocks(ctx, workflowId) + : undefined + if (blocks && checkKeptOutputs(next, state.chat.outputs, blocks) > 0) { detail.chat = 'replace' next.fields = [...(next.fields ?? []), 'chat outputs'] } diff --git a/apps/sim/lib/workspace-source/application/kinds/deployment/stored.ts b/apps/sim/lib/workspace-source/application/kinds/deployment/stored.ts index f4d2648e93a..397eb57eacf 100644 --- a/apps/sim/lib/workspace-source/application/kinds/deployment/stored.ts +++ b/apps/sim/lib/workspace-source/application/kinds/deployment/stored.ts @@ -19,13 +19,20 @@ import { } from '@/lib/chat-deployments/application/workflow-chat-deployment' import { readWorkflowDeploymentStatus } from '@/lib/workflows/application/deployments' import { readWorkflowGraph } from '@/lib/workflows/application/read-workflow-graph' +import { + loadDeployedWorkflowState, + NoActiveDeploymentError, +} from '@/lib/workflows/persistence/utils' import type { SourceContext } from '@/lib/workspace-source/application/types' -/** A chat output as stored: a block id and a path, with the block's name when the draft has it. */ +/** + * A chat output as stored: a block id and a path, with the block's name: in the draft, else in the + * live version the chat serves (a draft that re-created or dropped the block since). + */ interface StoredChatOutput { blockId: string path: string - /** The block's name in the draft; absent when the draft no longer holds the block. */ + /** The block's name; absent when neither the draft nor the live version holds the block. */ block?: string } @@ -97,6 +104,17 @@ export async function readBlockNames( return { nameOf, idOf } } +/** The live version's block names by id, or `null` when nothing is deployed. */ +async function liveBlockNames(workflowId: string): Promise | null> { + try { + const { blocks } = await loadDeployedWorkflowState(workflowId) + return new Map(Object.entries(blocks).map(([id, block]) => [id, block.name])) + } catch (error) { + if (error instanceof NoActiveDeploymentError) return null + throw error + } +} + /** The chat workflow `workflowId` serves, or `null` when it serves none. */ async function readChat(ctx: SourceContext, workflowId: string): Promise { const { principal } = ctx @@ -111,6 +129,9 @@ async function readChat(ctx: SourceContext, workflowId: string): Promise 0 ? await readBlockNames(ctx, workflowId) : { nameOf: null } + const live = outputs.some((output) => !nameOf?.has(output.blockId)) + ? await liveBlockNames(workflowId) + : null return { identifier: deployment.identifier, title: deployment.title, @@ -119,7 +140,7 @@ async function readChat(ctx: SourceContext, workflowId: string): Promise { - const block = nameOf?.get(output.blockId) + const block = nameOf?.get(output.blockId) ?? live?.get(output.blockId) return block === undefined ? output : { ...output, block } }), customizations: customizationsOf(deployment.customizations), 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 9a29ca54acc..f268786f01f 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -99,8 +99,10 @@ The loop, two shell calls: 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; --run ='{…}' (one per workflow, its workflows// folder) -dry-runs that input on the saved draft: writes are stubbed and listed under runs[].sideEffects, -whose .unchecked lists sandboxed code that ran unchecked and .omitted counts entries left out. A +dry-runs that input on the saved draft: code runs and GET fetches are sent (point them at test +resources); writes are stubbed and listed under runs[].sideEffects, whose .unchecked lists +sandboxed code that ran unchecked and .omitted counts entries left out. Use --run when the apply +changes a workflow. A workflow deploys on apply when deployments/.ts declares it; with --run, deployments/ is applied only after every run completed. --allow-delete lets an edit remove a resource, column, rows, document, or a workflow's block or diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index bd0314b1e5f..8a3a8fa5544 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -121,7 +121,7 @@ const WORKSPACE_PRIMER = `# Sim workspace source: primer A Sim workspace as files; nothing here runs. Commands here (table ones too) act on the workspace \`${SOURCE_BASE_FILE}\` names. Every \`.ts\` file starts with \`// @sim-sdk ${SDK_MAJOR}\`. -**Edit loop**: write every file, then run one chained command; fix what it reports: \`${WORKSPACE_LOOP}\` dry-runs \`workflows//\`'s draft (repeatable) and deploys only if all complete. \`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites files: reread before editing. +**Edit loop**: write every file, then run one chained command; fix what it reports: \`${WORKSPACE_LOOP}\` dry-runs \`workflows//\`'s draft (one \`--run\` per workflow you changed; drop it when you changed none) and deploys only if all complete. \`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites files: reread before editing. - **Deletes**: removing anything (file, column, block) needs \`apply --allow-delete\` and is permanent. - **Exit ${SOURCE_HELD_EXIT_CODE}**: partly written: what needs an unset secret or unbound credential waits; set it, reapply. @@ -137,7 +137,7 @@ export const AGENTS_POINTER_MARKER = const STARTER_LOOP = ` A starter (\`${SOURCE_STARTER_FILE}\`, no workflow yet) runs \`create\` in place of \`apply\`.` -const WORKSPACE_POINTER_LOOP = `\`${WORKSPACE_LOOP}\`; fix what it reports next.` +const WORKSPACE_POINTER_LOOP = `\`${WORKSPACE_LOOP}\` (one \`--run\` per workflow you changed); fix what it reports next.` /** The loop line of the pointer, after its lead, by directory kind and surface. */ const POINTER_LOOPS: Record> = { diff --git a/packages/workspace-code/DESIGN.md b/packages/workspace-code/DESIGN.md index cfd68ec347b..39e963cfa7a 100644 --- a/packages/workspace-code/DESIGN.md +++ b/packages/workspace-code/DESIGN.md @@ -239,7 +239,11 @@ write is refused as stale rather than published. A deploy's idempotency key hash fingerprint and the live version it replaces. The flag, the deploy and the chat are separate writes, so the apply checks what the chat write refuses (an identifier another chat holds, `E_DEPLOY_CHAT_IDENTIFIER`, at plan time and again before the first write; the password, the -outputs, the auth mode) before it writes any of them. The base records each part's fingerprint +outputs, the auth mode) before it writes any of them. A chat stores its outputs by block id, and +a stored output reads by the block's name in the draft, else in the live version it serves: a kept +chat whose output block the going-live draft re-created (by this apply's edit, or an earlier +apply's, as \`apply --run\` writes deployments after its test runs) is rewritten to the block of +that name (\`checkKeptOutputs\`). The base records each part's fingerprint (`x-parts`: `api`, `chat`), so a re-run after an apply stopped between them finds every part either the base's or the directory's and finishes the write (`partway` in `three-way.ts`), while a part that matches neither is still `E_APPLY_STALE`. A first deploy that stopped before its chat leaves a deployment with no From b597aeafe52326b10749a67c9e74a2bf8157d375 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 17:33:21 -0800 Subject: [PATCH 6/6] fix(workflow-code): review round 5: check a kept chat's outputs against every draft a deploy publishes --- .../application/deployments.integration.ts | 30 +++++++++++++++++++ .../application/kinds/deployment/adapter.ts | 6 ++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/deployments.integration.ts b/apps/sim/lib/workspace-source/application/deployments.integration.ts index 8035136eb88..8312c5588c5 100644 --- a/apps/sim/lib/workspace-source/application/deployments.integration.ts +++ b/apps/sim/lib/workspace-source/application/deployments.integration.ts @@ -660,6 +660,36 @@ describe('workspace source: deployments', () => { } ) + check( + 'refuses to deploy a draft an earlier apply left with no block of the name a kept chat declares', + async () => { + const deployed = await deployedWorkspace(answerChat('dropped-earlier-chat')) + const { workspaceId, id, base } = deployed + const files: Files = deployed.files + const before = await deployState(id) + + // The workflow alone first: the Answer block is renamed away, so no block has the name. + const workflowOnly = await apply( + workspaceId, + { ...files, [WORKFLOW]: files[WORKFLOW].replace("agent('Answer'", "agent('Responder'") }, + { base, kinds: ['workflow'], only: ['workflow'] } + ) + expect(workflowOnly.failed).toBeUndefined() + + const refused = await refusal( + apply( + workspaceId, + { ...files, ...workflowOnly.files, [DEPLOYMENT]: files[DEPLOYMENT] }, + { base: workflowOnly.base } + ) + ) + expect(deploymentCodes(refused.diagnostics, 'error')).toEqual(['E_DEPLOY_CHAT_OUTPUT']) + const after = await deployState(id) + expect(after.versions).toBe(before.versions) + expect(after.chat?.outputConfigs).toEqual(before.chat?.outputConfigs) + } + ) + check( 'renames a chat output block and the chat naming it in one apply, keeping the block id', async () => { diff --git a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts index c52bcb2891b..986029a8ae1 100644 --- a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts @@ -639,9 +639,9 @@ async function planDeployment( }), } } - // A chat the apply keeps goes live with the edited draft all the same. - const publishesEditedDraft = detail.deploy && draftEdited - if (decl.chat && (writesChat || publishesEditedDraft)) { + // A chat the apply keeps goes live with the published draft all the same, edited by this apply + // or an earlier one: its outputs must name blocks that draft has. + if (decl.chat && (writesChat || detail.deploy)) { await checkChat(next, decl.chat, ctx, { workflowId, writesChat,