diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 5a97559c6ed..6af6e3e02ea 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -10145,7 +10145,7 @@ sim workspaces source apply [options] | `--delete-target-only` | No | With --to and --allow-delete, also delete the target's resources this directory never declared and no promotion from it left there (prod-only tables and their rows, skills made in prod). Without it a promotion keeps them, naming each with a warning. | | `--only ` | No | Apply only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--to ` | No | Promote the directory to another workspace (dev to prod): its resources bind by key to that workspace's own and are updated in place. Only .sim/targets/<workspaceId>.json changes, the record the next promotion compares with: a resource changed there since is kept, or refused as stale (exit 5) when the directory changed it too. | -| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked. | +| `--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). In a workflow with several triggers, name the one the run enters through after a period (its const, block key or id): `--run 'orders.shopWebhook={…}'`. Repeat it to test more workflows, or more triggers of one. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked. | | `--json` | No | Print machine-readable JSON (same as --output json). | diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 994577a7f38..6f8907b375b 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -760,7 +760,7 @@ sim workspaces source apply [options] | `--delete-target-only` | No | With --to and --allow-delete, also delete the target's resources this directory never declared and no promotion from it left there (prod-only tables and their rows, skills made in prod). Without it a promotion keeps them, naming each with a warning. | | `--only ` | No | Apply only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--to ` | No | Promote the directory to another workspace (dev to prod): its resources bind by key to that workspace's own and are updated in place. Only .sim/targets/<workspaceId>.json changes, the record the next promotion compares with: a resource changed there since is kept, or refused as stale (exit 5) when the directory changed it too. | -| `--run ` | No | After the apply, dry-run workflows/<key>/'s saved draft with this input (JSON or @file, as `sim workflows run --dry --input` takes it; `--run ` alone: no input). Repeat it to test more workflows. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked. | +| `--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). In a workflow with several triggers, name the one the run enters through after a period (its const, block key or id): `--run 'orders.shopWebhook={…}'`. Repeat it to test more workflows, or more triggers of one. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked. | | `--json` | No | Print machine-readable JSON (same as --output json). | diff --git a/apps/docs/content/docs/workflows/code/workspace.mdx b/apps/docs/content/docs/workflows/code/workspace.mdx index ed45d132c86..6cd3141a72b 100644 --- a/apps/docs/content/docs/workflows/code/workspace.mdx +++ b/apps/docs/content/docs/workflows/code/workspace.mdx @@ -56,9 +56,9 @@ The dry run prints the plan (`+` create, `~` update, `=` adopt an existing resou 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. +`--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. A workflow with more than one trigger (an API trigger and a webhook, say) needs the trigger each run enters through, named after a period by its const, block key or id: `--run two.apiIn='{…}' --run two.hook='{…}'` tests both paths in one apply. 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`. +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. It is also applied only when every draft it publishes was test-run in this apply: if it would publish a workflow no `--run` tested, `deployments/` is skipped, the apply exits non-zero, and its `next` adds the `--run` for each untested workflow. 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. 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 8997d2388ee..d387fa542bf 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -105,9 +105,10 @@ and writes the workspace; --run ='{…}' (one per workflow, its workf 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 really ran, network requests included, and .omitted counts entries left -out. Use --run when the apply changes a workflow. A workflow deploys on apply when -deployments/.ts declares it; with --run, deployments/ is applied only after every run -completed. +out. A workflow with several triggers takes one --run '.={…}' per trigger (its +const, block key or id). 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, and only when every draft it publishes was test-run. --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 2319e24a6f1..d607d5d4dec 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -127,7 +127,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 (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. +**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; several triggers: \`--run '.={…}'\` each) and deploys only if all complete and every draft it deploys was tested. \`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. diff --git a/packages/sim-cli/src/commands/protocol/workflow-test-runs.ts b/packages/sim-cli/src/commands/protocol/workflow-test-runs.ts index 7f0c4d13c8f..fc2fd38d979 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-test-runs.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-test-runs.ts @@ -21,10 +21,16 @@ export interface RunRequest { /** A `--run` test as a write's result shows it: the trigger it named, then the run. */ export type NamedTestRun = TestRun & { trigger?: string } +/** + * A run's `--run` value as a command writes it, from its `raw` and the trigger it names: a + * workspace apply puts the workflow's key in front. + */ +type RunFlag = (run: Pick) => string + /** A `--run` run in turn: its result, why it did not complete, and the `--run` to repeat next. */ export interface RunOutcome extends DraftTest { run: NamedTestRun - /** The `--run` value the next command repeats: a trigger the refusal pointed at, else `raw`. */ + /** The `--run` the next command repeats: a trigger the refusal pointed at, else `raw` (as `flag` writes it). */ next: string } @@ -107,6 +113,14 @@ function triggerId(blocks: readonly LockBlock[], name: string): string { return match?.id ?? name } +/** + * The id of the trigger block `name` (its const, block key or id) is in the saved `lock`, so two + * names of one block compare equal; a name the lock does not hold comes back as written. + */ +export function lockTriggerId(lock: unknown, name: string): string { + return triggerId(lockBlocks(lock), name) +} + /** The consts of the triggers a refusal lists by id, in its order, but the block `refusedId`. */ function listedTriggers( message: string, @@ -128,22 +142,29 @@ function triggerRefusal( request: RunRequest, message: string, blocks: readonly LockBlock[], - refusedId: string | undefined + refusedId: string | undefined, + flag: RunFlag ): { failure: string; next: string } | undefined { const triggers = listedTriggers(message, blocks, refusedId) if (triggers.length === 0) return undefined if (request.trigger === undefined && SEVERAL_TRIGGERS.test(message)) { const [first, ...others] = triggers - const next = `${first}=${request.raw}` + const next = flag({ + trigger: first, + raw: request.raw === '' ? first : `${first}=${request.raw}`, + }) return { - failure: `the workflow has more than one trigger (${triggers.join(', ')}), so name the one each --run enters through: --run ${shellWord(next)}${others.length > 0 ? ` (or ${others.map((other) => `${other}=`).join(', ')})` : ''}`, + failure: `the workflow has more than one trigger (${triggers.join(', ')}), so name the one each --run enters through: --run ${shellWord(next)}${others.length > 0 ? ` (or ${others.map((other) => flag({ trigger: other, raw: `${other}=` })).join(', ')})` : ''}`, next, } } if (request.trigger !== undefined && NOT_A_TRIGGER.test(message)) { return { failure: `${request.trigger} is not a trigger of this workflow; name one of ${triggers.join(', ')} before = in --run`, - next: `${triggers[0]}${request.raw.slice(request.trigger.length)}`, + next: flag({ + trigger: triggers[0], + raw: `${triggers[0]}${request.raw.slice(request.trigger.length)}`, + }), } } return undefined @@ -163,9 +184,12 @@ export async function runTests( workspaceId: string lock: unknown runs: readonly RunRequest[] - onRun: (run: NamedTestRun) => void + onRun?: (run: NamedTestRun) => void + /** How this command writes a run's `--run` value; unset: its `raw`. */ + flag?: RunFlag } ): Promise { + const flag = args.flag ?? ((run: Pick) => run.raw) const blocks = lockBlocks(args.lock) const outcomes: RunOutcome[] = [] for (const request of args.runs) { @@ -180,7 +204,7 @@ export async function runTests( ) const named = request.trigger === undefined ? {} : { trigger: request.trigger } const refusal = test.refused - ? triggerRefusal(request, String(test.run.error), blocks, entryId) + ? triggerRefusal(request, String(test.run.error), blocks, entryId, flag) : undefined const outcome: RunOutcome = refusal ? { @@ -189,9 +213,9 @@ export async function runTests( failure: `the server refused it before it started: ${refusal.failure}`, next: refusal.next, } - : { ...test, run: { ...named, ...test.run }, next: request.raw } + : { ...test, run: { ...named, ...test.run }, next: flag(request) } outcomes.push(outcome) - args.onRun(outcome.run) + args.onRun?.(outcome.run) } return outcomes } 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 81b959e4374..2e860c3e083 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 @@ -1946,6 +1946,77 @@ describe('workspaces source apply', () => { }) }) + it('reads no deployment of a workflow it created without a deployments/ change', async () => { + const keys = Array.from({ length: 60 }, (_, index) => `flow-${index}`) + const created = keys.map((key, index) => ({ + kind: 'workflow', + key, + action: 'create', + id: `wf_${index}`, + })) + request.mockImplementation(async () => + answer({ + plan: created, + applied: created, + base: { + ...BASE, + resources: Object.fromEntries( + keys.map((key, index) => [`workflow:${key}`, { id: `wf_${index}` }]) + ), + }, + }) + ) + + await apply('--yes') + + expect( + request.mock.calls.filter(([path]) => String(path).endsWith('/deployment')) + ).toHaveLength(0) + expect(printedJson().workflows).toHaveLength(60) + expect(printedJson().workflows[0]).toEqual({ + key: 'flow-0', + workflowId: 'wf_0', + deployedVersion: null, + needsRedeployment: false, + live: 'not deployed', + }) + }) + + it('still reads the deployment of a workflow whose folder was renamed, a new key in the base', async () => { + const changes = [ + { kind: 'workflow', key: 'ingest', action: 'update', fields: ['key'] }, + { kind: 'workflow', key: 'fresh', action: 'create', id: 'wf_2' }, + ] + request.mockImplementation(async (path: string) => + path === '/api/v2/workflows/wf_1/deployment' + ? deploymentStatus(3) + : answer({ + plan: changes, + applied: changes, + base: { + ...BASE, + resources: { 'workflow:ingest': { id: 'wf_1' }, 'workflow:fresh': { id: 'wf_2' } }, + }, + }) + ) + + await apply('--yes') + + expect( + request.mock.calls + .map(([path]) => String(path)) + .filter((path) => path.endsWith('/deployment')) + ).toEqual(['/api/v2/workflows/wf_1/deployment']) + expect(printedJson().workflows).toEqual([ + expect.objectContaining({ + key: 'ingest', + deployedVersion: 3, + live: 'version 3, matches the draft', + }), + expect.objectContaining({ key: 'fresh', deployedVersion: null, live: 'not deployed' }), + ]) + }) + it('reports a workflow whose deployment it deleted as not deployed', async () => { request.mockImplementation(async (path: string) => path === '/api/v2/workflows/wf_1/deployment' @@ -2490,11 +2561,11 @@ describe('workspaces source apply', () => { it('maps an input the server refuses like a failed run: written, deployments/ held, a runnable next', async () => { serveApplies() - const refusal = 'workflow_input does not match trigger "Start" (email: Invalid input)' + const refusal = 'workflow_input does not match trigger "Start" (email: Invalid input).' contextMockFns.mockRequestRaw.mockRejectedValue(new SimApiError(refusal, 400, 'BAD_REQUEST')) await expect(apply('--yes', '--run', 'ingest={}')).rejects.toThrow( - /but the test run of ingest failed: the server refused it before it started: workflow_input does not match trigger "Start" .* deployments\/ was not applied\. Fix the source or the refused --run input, then run `sim workspaces source apply --dir .* --run 'ingest=\{\}' --yes`\.$/ + /but the test run of ingest failed: the server refused it before it started: workflow_input does not match trigger "Start" \(email: Invalid input\)\. deployments\/ was not applied\. Fix the source or the refused --run input, then run `sim workspaces source apply --dir .* --run 'ingest=\{\}' --yes`\.$/ ) expect(applies()).toHaveLength(1) const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) @@ -2520,6 +2591,114 @@ describe('workspaces source apply', () => { }) }) + describe('in a workflow with an API and a webhook trigger', () => { + beforeEach(() => { + write( + 'workflows/ingest/.sim/lock.json', + JSON.stringify({ + version: 1, + blocks: { + apiin: { id: 'b-api', parent: null, ident: 'apiIn', order: 0 }, + hook: { id: 'b-hook', parent: null, ident: 'hook', order: 1 }, + }, + variables: {}, + }) + ) + }) + + it('tests each trigger named as ., then applies deployments/', async () => { + serveApplies() + contextMockFns.mockRequestRaw + .mockResolvedValueOnce(runAnswer({ status: 'completed', output: { via: 'api' } })) + .mockResolvedValueOnce(runAnswer({ status: 'completed', output: { via: 'hook' } })) + + await apply('--yes', '--run', 'ingest.apiIn={"x":1}', '--run', 'ingest.hook={"y":2}') + + const sent = contextMockFns.mockRequestRaw.mock.calls.map(([, request]) => request.body) + expect(sent).toEqual([ + expect.objectContaining({ + input: { x: 1 }, + run: { source: 'draft', dry: true, entry: { type: 'trigger', blockId: 'b-api' } }, + }), + expect.objectContaining({ + input: { y: 2 }, + run: { source: 'draft', dry: true, entry: { type: 'trigger', blockId: 'b-hook' } }, + }), + ]) + expect(applies()).toHaveLength(2) + expect(process.exitCode).toBeUndefined() + const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + expect(printed.runs).toMatchObject([ + { workflow: 'ingest', trigger: 'apiIn', status: 'completed' }, + { workflow: 'ingest', trigger: 'hook', status: 'completed' }, + ]) + }) + + it('names the triggers and a next that picks one when a --run names none', async () => { + serveApplies() + contextMockFns.mockRequestRaw.mockRejectedValue( + new SimApiError( + 'This workflow has multiple runnable triggers. Pass run.entry.blockId to choose one: b-api (Api In), b-hook (Hook In).', + 400, + 'BAD_REQUEST' + ) + ) + + const failure = apply('--yes', '--run', 'ingest={"x":1}') + + await expect(failure).rejects.toThrow( + /more than one trigger \(apiIn, hook\).*--run 'ingest\.apiIn=\{"x":1\}' \(or ingest\.hook=\)\. deployments\/ was not applied\./ + ) + await expect(failure).rejects.not.toThrow(/run\.entry\.blockId|\.\./) + expect(applies()).toHaveLength(1) + const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + expect(printed.next.command).toBe( + `sim workspaces source apply --dir ${dir} --run 'ingest.apiIn={"x":1}' --yes` + ) + }) + + it('retries a bare --run through a trigger with no input, once beside an explicit run of it', async () => { + serveApplies() + contextMockFns.mockRequestRaw + .mockRejectedValueOnce( + new SimApiError( + 'This workflow has multiple runnable triggers. Pass run.entry.blockId to choose one: b-api (Api In), b-hook (Hook In).', + 400, + 'BAD_REQUEST' + ) + ) + .mockResolvedValueOnce(runAnswer({ status: 'completed', output: {} })) + + await expect(apply('--yes', '--run', 'ingest', '--run', 'ingest.apiIn')).rejects.toThrow( + /more than one trigger/ + ) + + const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + expect(printed.next.command).toBe( + `sim workspaces source apply --dir ${dir} --run ingest.apiIn --yes` + ) + }) + + it('refuses the same workflow and trigger twice before sending anything', async () => { + await expect( + apply('--yes', '--run', 'ingest.hook={}', '--run', 'ingest.hook={"y":2}') + ).rejects.toThrow(/--run names ingest\.hook twice/) + expect(request).not.toHaveBeenCalled() + }) + + it('refuses two names of one trigger (its const and block key) before running either', async () => { + serveApplies() + + await expect( + apply('--yes', '--run', 'ingest.apiIn={"x":1}', '--run', 'ingest.apiin={"x":2}') + ).rejects.toThrow( + /--run names ingest\.apiIn and ingest\.apiin, one trigger of workflows\/ingest\/, so nothing was test-run/ + ) + expect(contextMockFns.mockRequestRaw).not.toHaveBeenCalled() + expect(applies()).toHaveLength(1) + }) + }) + it("prints no workflow finding of the deployments write, which the apply's result drops too", async () => { contextMockState.output = 'table' const finding = (message: string) => ({ 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 7bf20fb76d8..e0b889312c3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -87,7 +87,8 @@ import { unrecordedFoldersWarning, workflowFolderRecords, } from './stored-edges' -import { printSideEffects, readRunInput, type TestRun, testRunDraft } from './workflow-run-follow' +import { printSideEffects, readRunInput } from './workflow-run-follow' +import { lockTriggerId, type NamedTestRun, type RunRequest, runTests } from './workflow-test-runs' import { appliedBlobDigests, assertBlobsFetched, @@ -735,8 +736,8 @@ export function attachWorkspaceSourceApply(source: Command): void { "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, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked", + '--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). In a workflow with several triggers, name the one the run enters through after a period (its const, block key or id): `--run 'orders.shopWebhook={…}'`. Repeat it to test more workflows, or more triggers of one. deployments/ is applied only after every run completed, and only when every draft it publishes was test-run; a run that does not complete exits 1 and leaves the applied drafts in place. Sandboxed code (Python, shell, imports) really runs in it, network requests included, and is listed in runs[].sideEffects.unchecked", collectRepeated ) .allowExcessArguments(false) @@ -1076,24 +1077,38 @@ export function attachWorkspaceSourceApply(source: Command): void { } // 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 nextRuns = await afterWrite(() => + testRuns(client, options.dir, workspaceId, data, runs, tested) + ) const failedRuns = tested.filter((run) => run.status !== 'completed') if (failedRuns.length > 0) { // A run the server refused before it started has no id: its fix is the --run input, - // unless it was only rate limited, which waiting fixes. + // or the trigger its refusal named, which the next command already enters through; a run + // only rate limited needs waiting instead. const rateLimited = failedRuns.every((run) => run.rateLimited) const refused = failedRuns.some((run) => run.runId === null && !run.rateLimited) + const named = nextRuns.some((value, index) => value !== options.run?.[index]) + // A refused run's trigger can be one another --run already names: it runs once. + const nextNames = nextRuns.map((value) => runName(parseRunValue(value))) + const retried = nextRuns.filter( + (_, index) => nextNames.indexOf(nextNames[index]) === index + ) const next = { - command: `${applyCommand(options, sim)} --yes`, + command: `${applyCommand({ ...options, run: retried }, sim)} --yes`, reason: rateLimited ? 'runs the tests again once the rate limit allows' - : refused - ? 'applies again and tests it with your fixed --run input' - : 'applies your fix and tests it again', + : named + ? 'applies again and tests each workflow through the trigger its --run names' + : refused + ? 'applies again and tests it with your fixed --run input' + : 'applies your fix and tests it again', } await finish(data, next) const why = failedRuns - .map((run) => `the test run of ${run.workflow} ${String(run.status)}: ${run.error}`) + .map( + (run) => + `the test run of ${testRunName(run)} ${String(run.status)}: ${String(run.error).replace(/[.!?]$/, '')}` + ) .join('; ') throw new SimApiError( `The apply was written into ${options.dir}, but ${why}.${gated ? ' deployments/ was not applied.' : ''} ${rateLimited ? 'Wait a minute' : `Fix the ${refused ? 'source or the refused --run input' : 'source'}`}, then run \`${next.command}\`.`, @@ -1144,39 +1159,74 @@ export function attachWorkspaceSourceApply(source: Command): void { }) } -/** One `--run`: the workflow folder's key, and its input as `--input` takes it (JSON or `@file`). */ -interface RunRequest { +/** + * One `--run`: the workflow folder's key, and the run as `sim workflows source apply --run` + * takes it: `raw` is `[=]`, without the key. + */ +interface WorkspaceRun { key: string - input?: string + request: RunRequest } -/** `--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) +/** A run's `--run` value as a workspace apply writes it for `key`. */ +function workspaceRunFlag(key: string, run: Pick): string { + if (run.trigger !== undefined) return `${key}.${run.raw}` + return run.raw === '' ? key : `${key}=${run.raw}` +} + +/** + * `--run [.][=]`: a workflow key holds no period, so the first one ends the + * key and starts the trigger (its const, block key or id). Each workflow once per trigger. + */ +function parseRuns(values: readonly string[] | undefined): WorkspaceRun[] { + const runs = (values ?? []).map(parseRunValue) + const names = runs.map(runName) + const repeated = names.find((name, index) => names.indexOf(name) !== index) if (repeated !== undefined) { - throw new CliUsageError(`--run names ${repeated} twice: test each workflow once per apply.`) + throw new CliUsageError( + `--run names ${repeated} twice: test each workflow once per trigger in an apply.` + ) } return runs } +/** One `--run [.][=]` value, as {@link parseRuns} reads it. */ +function parseRunValue(value: string): WorkspaceRun { + const at = value.indexOf('=') + const head = at === -1 ? value : value.slice(0, at) + const input = at === -1 ? undefined : value.slice(at + 1) + const dot = head.indexOf('.') + const key = dot === -1 ? head : head.slice(0, dot) + const trigger = dot === -1 ? undefined : head.slice(dot + 1) + if (key.length === 0) { + throw new CliUsageError( + `--run ${value} names no workflow: write --run ='{…}', where is its folder under ${KIND_DIRS.workflow}/.` + ) + } + if (trigger === '') { + throw new CliUsageError( + `--run ${value} names no trigger after the period: write --run ${key}.='{…}', where is its const, block key or id.` + ) + } + if (trigger === undefined) { + return { key, request: input === undefined ? { raw: '' } : { raw: input, input } } + } + const raw = input === undefined ? trigger : `${trigger}=${input}` + return { key, request: input === undefined ? { raw, trigger } : { raw, trigger, input } } +} + +/** A run as `--run` names it: its key, and its trigger after a period when it names one. */ +function runName({ key, request }: WorkspaceRun): string { + return request.trigger === undefined ? key : `${key}.${request.trigger}` +} + /** * 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[], + runs: readonly WorkspaceRun[], only: readonly WorkspaceKind[] | undefined ): void { if (runs.length === 0) return @@ -1198,7 +1248,7 @@ function assertRunnable( } /** Refuses a `--run` key with no `workflows//` folder in `dir`, naming the keys it has. */ -async function assertRunKeys(dir: string, runs: readonly RunRequest[]): Promise { +async function assertRunKeys(dir: string, runs: readonly WorkspaceRun[]): Promise { if (runs.length === 0) return const { paths } = await kindFolders(dir, ['workflow']) const keys = [...KIND_LAYOUTS.workflow.group(paths).groups.keys()].sort(compareStrings) @@ -1221,13 +1271,17 @@ async function assertRunKeys(dir: string, runs: readonly RunRequest[]): Promise< * 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 { +async function readRunInputs(runs: readonly WorkspaceRun[]): Promise { return Promise.all( runs.map(async (run) => { - if (run.input === undefined) return run + const { input } = run.request + if (input === undefined) return run return { ...run, - input: await readRunInput(run.input, `--run ${run.key}: its input is not JSON.`), + request: { + ...run.request, + input: await readRunInput(input, `--run ${runName(run)}: its input is not JSON.`), + }, } }) ) @@ -1312,39 +1366,45 @@ function mergedApply(first: ApplyData, deployed: ApplyData): ApplyData { } /** A `--run` test run in an apply's result: the workflow's key and id, then the run. */ -interface WorkflowTestRun extends TestRun { +type WorkflowTestRun = NamedTestRun & { workflow: string workflowId: string /** Still rate limited after the client's resends, so it never started. */ rateLimited?: true } -/** The test runs as one display line: `ingest completed; score failed: …`. */ +/** A test run as `--run` named it: `ingest`, or `ingest.hook` through a trigger. */ +function testRunName(run: WorkflowTestRun): string { + return run.trigger === undefined ? run.workflow : `${run.workflow}.${run.trigger}` +} + +/** The test runs as one display line: `ingest completed; score.hook 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)}` + ? `${testRunName(run)} completed` + : `${testRunName(run)} ${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. + * Dry-runs each `--run` workflow's saved draft, one at a time and through the trigger it names + * (found in the lock the apply saved), as `sim workflows source apply --run` 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. A key the written base binds to no workflow + * is refused before any run. Returns each `--run` value a next command repeats, in order: a refused + * run's names the trigger its refusal listed. */ async function testRuns( client: OperationClient<'executeWorkflow'>, dir: string, workspaceId: string, data: ApplyData, - runs: readonly RunRequest[], + runs: readonly WorkspaceRun[], tested: WorkflowTestRun[] -): Promise { +): Promise { const base = parseWorkspaceBase(data.base).base const targets = runs.map((run) => ({ ...run, @@ -1356,23 +1416,46 @@ async function testRuns( `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) { + const locks = new Map() + for (const { key } of targets) { + if (!locks.has(key)) { + locks.set(key, await readSourceText(dir, `${workflowFolder(key)}/${SOURCE_LOCK_FILE}`)) + } + } + // parseRuns compares names as written; the saved lock tells a const from its block key or id. + const entered = new Map() + for (const target of targets) { + if (target.request.trigger === undefined) continue + const entry = `${target.key}\0${lockTriggerId(locks.get(target.key), target.request.trigger)}` + const earlier = entered.get(entry) + if (earlier) { + throw new SourceDirError( + `The apply was written, but --run names ${runName(earlier)} and ${runName(target)}, one trigger of ${workflowFolder(target.key)}/, so nothing was test-run: keep one of them, then apply again.` + ) + } + entered.set(entry, target) + } + const next: string[] = [] + for (const { key, request, workflowId } of targets) { if (!workflowId) continue - const test = await testRunDraft( - client, - join(dir, workflowFolder(key)), + const [outcome] = await runTests(client, { + dir: join(dir, workflowFolder(key)), workflowId, - input, - workspaceId - ) + workspaceId, + lock: locks.get(key), + runs: [request], + flag: (run) => workspaceRunFlag(key, run), + }) tested.push({ workflow: key, workflowId, - ...test.run, - ...(test.failure !== undefined ? { error: test.failure } : {}), - ...(test.rateLimited ? { rateLimited: true as const } : {}), + ...outcome.run, + ...(outcome.failure !== undefined ? { error: outcome.failure } : {}), + ...(outcome.rateLimited ? { rateLimited: true as const } : {}), }) + next.push(outcome.next) } + return next } /** @@ -1481,9 +1564,25 @@ async function writtenWorkflows( .filter((change) => change.kind === 'deployment' && change.action !== 'delete') .map((change) => change.key) ) + const createdKeys = new Set( + written + .filter((change) => change.kind === 'workflow' && change.action === 'create') + .map((change) => change.key) + ) const read = await mapWithConcurrency(keys, DEPLOYMENT_READ_CONCURRENCY, async (key) => { const workflowId = base?.resources[resourceAddress('workflow', key)]?.id if (!workflowId) return null + // A workflow this apply created is deployed only by a deployments/ change of the same apply. + if (createdKeys.has(key) && !deployedKeys.has(key)) { + const workflow: WrittenWorkflow = { + key, + workflowId, + deployedVersion: null, + needsRedeployment: false, + live: 'not deployed', + } + return { workflow, urls: [] } + } const status = await client .request('getWorkflowDeployment', { params: { workflowId } }) .then( 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 b191b88fe76..f1eaadd460d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -167,7 +167,7 @@ Batch it: write every file first, then run steps 2 and 4 (with a test run of eac 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). \`--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. +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; a workflow with several triggers takes one \`--run '.={…}'\` per trigger, \`\` its const, block key or id) 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 and every draft it publishes was test-run, so a deployment with \`live: 'draft'\` publishes only a tested draft; without \`--run\` it is applied with everything else. ## Good to know