diff --git a/apps/docs/content/docs/cli/index.mdx b/apps/docs/content/docs/cli/index.mdx index f8e60ffd8b6..c47d6e05945 100644 --- a/apps/docs/content/docs/cli/index.mdx +++ b/apps/docs/content/docs/cli/index.mdx @@ -77,7 +77,7 @@ b8c0d247-9e13-4a86-97f5-2ad4e1638c09 Weekly digest /Reporting no 18 sim workflows run 3a9e21d8-5f47-4c0b-b2ea-91d7c6034ef8 --input '{"ticketId":"T-4821"}' ``` -Ordinary execution runs the active deployment. Deploy from the workflow builder or with `sim workflows deploy `. To execute the current saved workflow state, use `sim workflows run --manual`. To test it without sending its writes, use `--dry`: each write is answered with a placeholder and listed with its request under `sideEffects` in the result. +Ordinary execution runs the active deployment. Deploy from the workflow builder or with `sim workflows deploy `; its first line, `live`, says which version serves, and while a new version activates it names the version still serving. To run an earlier deployed version, pass `--deployment-version `; it needs workspace write access, through a full-access API key or an OAuth token with `api:write`, and child workflows still run their own active deployment. To execute the current saved workflow state, use `sim workflows run --manual`. To test it without sending its writes, use `--dry`: each write is answered with a placeholder and listed with its request under `sideEffects` in the result. ## How commands are shaped diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index edbee1d5ca8..2a47296c9bb 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8516,6 +8516,7 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | +| `--deployment-version ` | No | Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --manual or any flag that runs the draft. | | `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | | `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | | `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, so a rerun passes it again (its log shows the output like any other block’s); repeatable. | @@ -8532,7 +8533,7 @@ sim workflows run [options] -Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. +Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead, as a pin for comparing or reproducing (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --manual runs the saved draft, as the source loop leaves it. --dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index d87fd3e7cf6..db5506f94e8 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -833,6 +833,7 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | +| `--deployment-version ` | No | Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --manual or any flag that runs the draft. | | `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | | `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | | `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, so a rerun passes it again (its log shows the output like any other block’s); repeatable. | @@ -849,7 +850,7 @@ sim workflows run [options] -Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. +Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead, as a pin for comparing or reproducing (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --manual runs the saved draft, as the source loop leaves it. --dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 49c481780de..7cedaea64e7 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -6197,6 +6197,7 @@ }, "mintedIds": {}, "notes": [], + "deployedVersion": 3, "needsRedeployment": false } } @@ -6393,6 +6394,7 @@ }, "mintedIds": {}, "notes": [], + "deployedVersion": 3, "needsRedeployment": false } } @@ -6583,6 +6585,7 @@ "start": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77" }, "notes": [], + "deployedVersion": null, "needsRedeployment": false } } @@ -20468,9 +20471,22 @@ }, "description": "Non-fatal notes about the write." }, + "deployedVersion": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "The live deployment version `needsRedeployment` compares the draft against, or null when the workflow is not deployed." + }, "needsRedeployment": { "type": "boolean", - "description": "Whether the draft now differs from the live deployment; apply never deploys." + "description": "Whether the draft now differs from the live deployment; apply never deploys. False when nothing is deployed, so read it beside `deployedVersion`." } }, "required": [ @@ -20485,6 +20501,7 @@ "base", "mintedIds", "notes", + "deployedVersion", "needsRedeployment" ], "additionalProperties": false, @@ -20546,6 +20563,7 @@ }, "mintedIds": {}, "notes": [], + "deployedVersion": 3, "needsRedeployment": false } } @@ -21435,9 +21453,22 @@ }, "description": "Non-fatal notes about the write." }, + "deployedVersion": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "The live deployment version `needsRedeployment` compares the draft against, or null when the workflow is not deployed." + }, "needsRedeployment": { "type": "boolean", - "description": "Whether the draft now differs from the live deployment; apply never deploys." + "description": "Whether the draft now differs from the live deployment; apply never deploys. False when nothing is deployed, so read it beside `deployedVersion`." } }, "required": [ @@ -21452,6 +21483,7 @@ "base", "mintedIds", "notes", + "deployedVersion", "needsRedeployment" ], "additionalProperties": false, @@ -21513,6 +21545,7 @@ }, "mintedIds": {}, "notes": [], + "deployedVersion": 3, "needsRedeployment": false } } @@ -22378,9 +22411,22 @@ }, "description": "Non-fatal notes about the write." }, + "deployedVersion": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "The live deployment version `needsRedeployment` compares the draft against, or null when the workflow is not deployed." + }, "needsRedeployment": { "type": "boolean", - "description": "Whether the draft now differs from the live deployment; apply never deploys." + "description": "Whether the draft now differs from the live deployment; apply never deploys. False when nothing is deployed, so read it beside `deployedVersion`." } }, "required": [ @@ -22395,6 +22441,7 @@ "base", "mintedIds", "notes", + "deployedVersion", "needsRedeployment" ], "additionalProperties": false, @@ -22464,6 +22511,7 @@ "start": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77" }, "notes": [], + "deployedVersion": null, "needsRedeployment": false } } diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts index 429e10ff8b6..b2c0b554846 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.test.ts @@ -205,6 +205,7 @@ const applied = { base: source.base, mintedIds: {}, notes: [], + deployedVersion: 3, needsRedeployment: true, sdkMajor: 1, } diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.test.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.test.ts index d7b65348312..507c06752b1 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.test.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/route.test.ts @@ -74,6 +74,7 @@ const created = { }, mintedIds: { start: 'b-1' }, notes: [], + deployedVersion: null, needsRedeployment: false, sdkMajor: 1, } diff --git a/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts b/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts index eab446626c4..d400a826e9c 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts @@ -129,6 +129,7 @@ export const workflowSourceOpenApiRoutes = [ base: WORKFLOW_SOURCE_EXAMPLE.base, mintedIds: {}, notes: [], + deployedVersion: 3, needsRedeployment: false, }, }, @@ -192,6 +193,7 @@ export const workflowSourceOpenApiRoutes = [ base: WORKFLOW_SOURCE_EXAMPLE.base, mintedIds: {}, notes: [], + deployedVersion: 3, needsRedeployment: false, }, }, @@ -259,6 +261,7 @@ export const workflowSourceOpenApiRoutes = [ base: WORKFLOW_SOURCE_EXAMPLE.base, mintedIds: { start: BLOCK_ID }, notes: [], + deployedVersion: null, needsRedeployment: false, }, }, diff --git a/apps/sim/lib/api/contracts/v2/workflow-source.ts b/apps/sim/lib/api/contracts/v2/workflow-source.ts index 6fdb06a3b03..d89a676ef85 100644 --- a/apps/sim/lib/api/contracts/v2/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/workflow-source.ts @@ -253,9 +253,19 @@ const applyWorkflowSourceDataSchema = z 'Block key → id for new blocks whose id was minted rather than taken from the lock.' ), notes: z.array(z.string()).describe('Non-fatal notes about the write.'), + deployedVersion: z + .number() + .int() + .positive() + .nullable() + .describe( + 'The live deployment version `needsRedeployment` compares the draft against, or null when the workflow is not deployed.' + ), needsRedeployment: z .boolean() - .describe('Whether the draft now differs from the live deployment; apply never deploys.'), + .describe( + 'Whether the draft now differs from the live deployment; apply never deploys. False when nothing is deployed, so read it beside `deployedVersion`.' + ), }) .describe('The outcome of applying workflow source.') diff --git a/apps/sim/lib/workflows/api/source-presenters.ts b/apps/sim/lib/workflows/api/source-presenters.ts index 9a1539a5672..2134f98151d 100644 --- a/apps/sim/lib/workflows/api/source-presenters.ts +++ b/apps/sim/lib/workflows/api/source-presenters.ts @@ -24,6 +24,7 @@ export function presentSourceOutcome(outcome: SourceOutcome): SourceOutcomeData base: outcome.base, mintedIds: outcome.mintedIds, notes: outcome.notes, + deployedVersion: outcome.deployedVersion, needsRedeployment: outcome.needsRedeployment, } } diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts index 6fc2bb44d27..8c57bd6a7cf 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -81,9 +81,9 @@ vi.mock('@/lib/workflows/deployment-status', async (importOriginal) => { const actual = await importOriginal() return { ...actual, - checkNeedsRedeployment: (workflowId: string) => { + readDeploymentDrift: (workflowId: string) => { draftDeploymentChecks.count += 1 - return actual.checkNeedsRedeployment(workflowId) + return actual.readDeploymentDrift(workflowId) }, } }) @@ -2530,7 +2530,7 @@ export default workflow('Fresh', {}, () => { await db.insert(workflowDeploymentVersion).values({ id: generateId(), workflowId, - version: 1, + version: 2, state: deployed, isActive: true, }) @@ -2546,17 +2546,37 @@ export default workflow('Fresh', {}, () => { expect(draftDeploymentChecks.count).toBe(1) const applied = await apply(source, changed) - expect(unchangedDryRun.needsRedeployment).toBe(false) - expect(changedDryRun.needsRedeployment).toBe(true) - expect(applied.needsRedeployment).toBe(true) + // Each answer names the live version it compared the draft against. + expect(unchangedDryRun).toMatchObject({ deployedVersion: 2, needsRedeployment: false }) + expect(changedDryRun).toMatchObject({ deployedVersion: 2, needsRedeployment: true }) + expect(applied).toMatchObject({ deployedVersion: 2, needsRedeployment: true }) const edited = await getSource(workflowId) const reverted = edit(edited.files, 'return 2', 'return 1') const revertDryRun = await apply(edited, reverted, { dryRun: true }) const revert = await apply(edited, reverted) - expect(revertDryRun.needsRedeployment).toBe(false) - expect(revert.needsRedeployment).toBe(false) + expect(revertDryRun).toMatchObject({ deployedVersion: 2, needsRedeployment: false }) + expect(revert).toMatchObject({ deployedVersion: 2, needsRedeployment: false }) + } + ) + + check( + 'a workflow never deployed reports no live version, which is not a draft matching one', + async () => { + const start = seedBlock('start_trigger', 'Start') + const score = seedBlock('function', 'Score', { code: ['code', 'return 1'] }) + const workflowId = await seedGraph([start, score]) + const source = await getSource(workflowId) + const changed = edit(source.files, 'return 1', 'return 2') + + for (const answer of [ + await apply(source, source.files, { dryRun: true }), + await apply(source, changed, { dryRun: true }), + await apply(source, changed), + ]) { + expect(answer).toMatchObject({ deployedVersion: null, needsRedeployment: false }) + } } ) diff --git a/apps/sim/lib/workflows/application/source-pipeline/commit.ts b/apps/sim/lib/workflows/application/source-pipeline/commit.ts index d4105b3bf13..251b05fe908 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/commit.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/commit.ts @@ -22,7 +22,7 @@ import { PlanBindingError, type PlannedSource, } from '@/lib/workflows/application/source-pipeline/plan' -import { checkNeedsRedeployment } from '@/lib/workflows/deployment-status' +import { readDeploymentDrift, UNDEPLOYED } from '@/lib/workflows/deployment-status' const logger = createLogger('ApplyWorkflowSource') @@ -67,7 +67,7 @@ export async function commitSource( diff: plan.diff, diagnostics: plan.diagnostics, wroteSourceMeta: sourceMetaChanged, - needsRedeployment: await checkNeedsRedeployment(workflowId), + ...(await readDeploymentDrift(workflowId)), }) } @@ -95,7 +95,7 @@ export async function commitSource( mintedIds: plan.mintedIds, workflowName: committed.name, notes: committed.warnings, - needsRedeployment: target.kind === 'new' ? false : await checkNeedsRedeployment(workflowId), + ...(target.kind === 'new' ? UNDEPLOYED : await readDeploymentDrift(workflowId)), }) }) } diff --git a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts index cef70da652a..70f529afb93 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts @@ -16,8 +16,10 @@ import { type CommitTarget, targetIds } from '@/lib/workflows/application/source import type { PlannedSource, RefusedSource } from '@/lib/workflows/application/source-pipeline/plan' import { type PrintedSource, printStoredSource } from '@/lib/workflows/code/print-stored' import { - checkDraftNeedsRedeployment, - checkNeedsRedeployment, + type DeploymentDrift, + readDeploymentDrift, + readDraftDeploymentDrift, + UNDEPLOYED, } from '@/lib/workflows/deployment-status' const logger = createLogger('ApplyWorkflowSource') @@ -43,6 +45,8 @@ export interface SourceOutcome { /** Source key → id for every new block whose id was minted rather than taken from the lock. */ mintedIds: Record notes: string[] + /** The live deployment version, or null when none: what `needsRedeployment` compared against. */ + deployedVersion: number | null needsRedeployment: boolean sdkMajor: number } @@ -57,7 +61,8 @@ interface OutcomeFrame { } /** What an outcome reports beyond its frame and the printed source; the rest default to empty. */ -type OutcomeFields = Pick & +type OutcomeFields = Pick & + DeploymentDrift & Partial> /** The one outcome shape: what is (or would be) stored, printed, and what the write did. */ @@ -131,12 +136,12 @@ export function printWritten( } /** - * Whether the draft as it is differs from its deployment, for a dry run that leaves it so (a no-op - * or a refusal); a new workflow has none. Run only once the plan says so: a dry run that would - * change the draft compares what it would write instead. + * The live version and whether the draft as it is differs from it, for a dry run that leaves it so + * (a no-op or a refusal); a new workflow has none. Run only once the plan says so: a dry run that + * would change the draft compares what it would write instead. */ -async function draftNeedsRedeployment(target: CommitTarget): Promise { - return target.kind === 'new' ? false : checkNeedsRedeployment(target.context.workflowId) +async function storedDraftDrift(target: CommitTarget): Promise { + return target.kind === 'new' ? UNDEPLOYED : readDeploymentDrift(target.context.workflowId) } /** @@ -163,7 +168,7 @@ export async function previewSource( workflowName: plan.meta.name, diff: plan.diff, diagnostics: plan.diagnostics, - needsRedeployment: await draftNeedsRedeployment(target), + ...(await storedDraftDrift(target)), }) } const preview = await previewSourceCommit(planned.workflowId, plan) @@ -174,12 +179,12 @@ export async function previewSource( }) return shapeOutcome(frame, printWritten(planned, preview.state), { applied: false, - needsRedeployment: - !isNew && - (await checkDraftNeedsRedeployment(planned.workflowId, { - ...preview.state, - variables: plan.storedVariables, - })), + ...(isNew + ? UNDEPLOYED + : await readDraftDeploymentDrift(planned.workflowId, { + ...preview.state, + variables: plan.storedVariables, + })), diff: plan.diff, diagnostics: plan.diagnostics, mintedIds: plan.mintedIds, @@ -212,7 +217,7 @@ export async function refusedOutcome( applied: false, diff: emptyDiffSummary(), diagnostics: refused.diagnostics, - needsRedeployment: await draftNeedsRedeployment(target), + ...(await storedDraftDrift(target)), } ) } diff --git a/apps/sim/lib/workflows/deployment-status.ts b/apps/sim/lib/workflows/deployment-status.ts index 62e345dc458..3521c108f7d 100644 --- a/apps/sim/lib/workflows/deployment-status.ts +++ b/apps/sim/lib/workflows/deployment-status.ts @@ -10,8 +10,19 @@ import { } from '@/lib/workflows/persistence/utils' import type { WorkflowState } from '@/stores/workflows/workflow/types' +/** The active deployment's version, and whether the draft has diverged from it. */ +export interface DeploymentDrift { + /** The live version, or `null` when nothing is deployed. */ + deployedVersion: number | null + /** False when nothing is deployed: read it beside {@link deployedVersion}. */ + needsRedeployment: boolean +} + +/** What a workflow with no active deployment reports: no live version, so nothing to redeploy. */ +export const UNDEPLOYED: DeploymentDrift = { deployedVersion: null, needsRedeployment: false } + /** - * Reports whether the durable draft has diverged from the active deployment. + * Reports the active deployment's version and whether the durable draft has diverged from it. * * Owns both loads deliberately. The two operands are only comparable once each * has been through its own projection: the draft picks up handle canonicalization @@ -25,37 +36,46 @@ import type { WorkflowState } from '@/stores/workflows/workflow/types' * All reads share one REPEATABLE READ snapshot; the CPU-only diff runs after * commit so the connection is not held idle in transaction. */ -export async function checkNeedsRedeployment(workflowId: string): Promise { +export async function readDeploymentDrift(workflowId: string): Promise { const snapshot = await db.transaction(async (tx) => { await tx.execute(sql`SET TRANSACTION ISOLATION LEVEL REPEATABLE READ`) - const deployedState = await loadActiveDeployedState(tx, workflowId) - if (!deployedState) return null - - const currentState = await loadWorkflowDeploymentSnapshot(workflowId, tx) - if (!currentState) return null - - return { currentState, deployedState } + const deployed = await loadActiveDeployedState(tx, workflowId) + if (!deployed) return null + return { deployed, currentState: await loadWorkflowDeploymentSnapshot(workflowId, tx) } }) - if (!snapshot) return false - return differsFromDeployed(snapshot.currentState, snapshot.deployedState) + if (!snapshot) return UNDEPLOYED + const { deployed, currentState } = snapshot + return { + deployedVersion: deployed.version, + needsRedeployment: currentState !== null && differsFromDeployed(currentState, deployed.state), + } +} + +/** Whether the durable draft has diverged from the active deployment; false when none is active. */ +export async function checkNeedsRedeployment(workflowId: string): Promise { + return (await readDeploymentDrift(workflowId)).needsRedeployment } /** - * Reports whether `draft`, a draft not written yet, would diverge from the active deployment: what - * a dry run answers, since it stores nothing for {@link checkNeedsRedeployment} to load. `draft` - * must be in the shape a write stores (`prepareWorkflowStateForPersistence`, with the variables - * the write leaves), built from the stored draft as loaded, so the two compare as stored states do. + * {@link readDeploymentDrift} for `draft`, a draft not written yet: what a dry run answers, since + * it stores nothing for the stored draft to be loaded from. `draft` must be in the shape a write + * stores (`prepareWorkflowStateForPersistence`, with the variables the write leaves), built from + * the stored draft as loaded, so the two compare as stored states do. */ -export async function checkDraftNeedsRedeployment( +export async function readDraftDeploymentDrift( workflowId: string, draft: WorkflowState -): Promise { - const deployedState = await db.transaction(async (tx) => { +): Promise { + const deployed = await db.transaction(async (tx) => { await tx.execute(sql`SET TRANSACTION ISOLATION LEVEL REPEATABLE READ`) return loadActiveDeployedState(tx, workflowId) }) - return deployedState !== null && differsFromDeployed(draft, deployedState) + if (!deployed) return UNDEPLOYED + return { + deployedVersion: deployed.version, + needsRedeployment: differsFromDeployed(draft, deployed.state), + } } /** {@link hasWorkflowChanged} against a deployed state, whose variables are untyped JSON. */ @@ -64,8 +84,8 @@ function differsFromDeployed(draft: WorkflowState, deployed: DeployedWorkflowDat } /** - * The active deployment's state, through the same projection the draft load applies; `null` when - * the workflow has no usable active deployment. + * The active deployment's version and state, through the same projection the draft load applies; + * `null` when the workflow has no usable active deployment. * * `workspaceId` is selected here, in the caller's transaction, rather than left for * `materializeDeploymentState` to look up: resolving an absent one goes through @@ -75,10 +95,11 @@ function differsFromDeployed(draft: WorkflowState, deployed: DeployedWorkflowDat async function loadActiveDeployedState( tx: DbOrTx, workflowId: string -): Promise { +): Promise<{ version: number; state: DeployedWorkflowData } | null> { const [active] = await tx .select({ id: workflowDeploymentVersion.id, + version: workflowDeploymentVersion.version, state: workflowDeploymentVersion.state, workspaceId: workflowTable.workspaceId, }) @@ -95,5 +116,8 @@ async function loadActiveDeployedState( /* The inner join guarantees a workspace row; a null id means unusable data. */ if (!active?.state || !active.workspaceId) return null - return materializeDeploymentState(workflowId, active, active.workspaceId, tx) + return { + version: active.version, + state: await materializeDeploymentState(workflowId, active, active.workspaceId, tx), + } } diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 910bfdcd87e..f545cd94e46 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -221,7 +221,7 @@ Batch it: write every file first, then run steps 2 and 4 (and a test run) as one 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. 2. \`sim workflows source check --dir .\`: compiles with the server's compiler, in milliseconds and without a request. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It then adds the blocks the source now uses to \`tsconfig.json\` and type-checks with it, using the TypeScript release the declarations are built for (installed once into the CLI's cache, on the first check; \`E_TYPE\` findings). That catches what the compile and \`apply --dry-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. \`apply --dry-run\` is the authority: a type error on a printed line you did not edit that it accepts can be skipped with \`--no-types\`. 3. \`sim workflows source status --dir .\`: the files you changed (\`sim workflows source diff --dir .\` shows the edits), whether the workflow changed on the server since the get, and the command to run next (\`--offline\`: skip the server). Then \`sim workflows source apply --dir . --dry-run\` until it exits 0. -4. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). \`--deploy\` also deploys it; without it, a deployed workflow's next \`sim workflows deploy --expected-draft-fingerprint \` is printed, which deploys only the draft this apply saved. It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). +4. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). \`--deploy\` also deploys it; without it, a deployed workflow's next \`sim workflows deploy --expected-draft-fingerprint \` is printed, which deploys only the draft this apply saved. Its first line, \`live\`, says what serves: \`not deployed\`, \`version N, matches the draft\`, \`version N, draft has undeployed changes\`, or after \`--deploy\` \`version N still serving; version M activating\` until the deploy is live (\`sim workflows deployment status \` shows when). It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). 5. Exit ${SOURCE_STALE_EXIT_CODE} (\`SOURCE_STALE\`, HTTP 409, or \`E_APPLY_STALE\` on a dry run): the workflow changed and nothing was saved. Run \`sim workflows source get --dir \`, reapply your edit there, dry-run, apply. A get into this directory refuses to overwrite your unapplied edits unless you pass \`--force\`. Exit ${SOURCE_STALE_EXIT_CODE} right after an apply that ended without an answer (a timeout, a dropped connection) means the draft changed, by that apply or by someone else: get into a fresh directory and compare. Only when it holds your edit, run \`sim workflows source get --dir . --force\`; otherwise reapply your edit in the fresh directory. Editing the \`workflow('…')\` name or description renames or redescribes the workflow; a name another workflow in its folder holds is refused with \`E_NAME_TAKEN\`. Lines starting \`note:\` explain something the write did differently than the source says; read them. diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index 88106183d98..0d048e3463a 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -429,6 +429,49 @@ describe('sim workflows run --follow', () => { expect(requestRaw).not.toHaveBeenCalled() }) + it('runs a pinned deployment version, synchronously and queued', async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + request.mockResolvedValue({ data: { runId: 'run-2', statusUrl: '/runs/run-2' } }) + + await run(WORKFLOW_ID, '--deployment-version', '6') + await run(WORKFLOW_ID, '--deployment-version', '6', '--async', '--input', '{"a":1}') + + expect(requestRaw.mock.calls[0][1].body).toEqual({ run: { source: 'deployment', version: 6 } }) + expect(request.mock.calls[0][1].body).toEqual({ + async: true, + input: { a: 1 }, + run: { source: 'deployment', version: 6 }, + }) + }) + + it.each(['0', '-1', '1.5', 'v6', '06'])( + 'refuses --deployment-version %s, which is not a version number', + async (version) => { + await expect(run(WORKFLOW_ID, '--deployment-version', version)).rejects.toThrow( + '--deployment-version must be a positive integer' + ) + expect(requestRaw).not.toHaveBeenCalled() + } + ) + + it.each([ + ['--manual'], + ['--dry'], + ['--trigger', 'slack-trigger'], + ['--mock-payload'], + ['--stop-after', 'agent-1'], + ['--from-block', 'agent-1', '--source-run', 'run-1'], + ['--source-run', 'run-1'], + ['--allow', 'agent-1'], + ['--mock', 'agent-1={}'], + ])('refuses --deployment-version beside %s, which runs the draft', async (...flags) => { + await expect(run(WORKFLOW_ID, '--deployment-version', '6', ...flags)).rejects.toThrow( + `--deployment-version runs a deployed version; ${flags[0]} runs the draft: drop one` + ) + expect(requestRaw).not.toHaveBeenCalled() + expect(request).not.toHaveBeenCalled() + }) + it('selects a run only through its flags, not as raw JSON', async () => { await expect(run(WORKFLOW_ID, '--run', '{"source":"manual"}')).rejects.toThrow( "unknown option '--run'" 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 9468f8ca118..b3d0ee84c93 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -11,7 +11,7 @@ import { SimApiError } from '../../http/client' import { readNdjson } from '../../http/ndjson' import { safeOneLine, sanitize } from '../../output/render' import { callsOperations, connect } from '../../runtime/called-operations' -import { executeOperation, runFailureMessage } from '../../runtime/execute' +import { runFailureMessage } from '../../runtime/execute' import { retypeApiError } from '../../runtime/naming' import { collectRepeated } from '../../runtime/options' import { buildRequest, readArgumentSource } from '../../runtime/request' @@ -55,15 +55,54 @@ export interface FollowOptions { stderr: CommentaryWriter } -type WorkflowRunSelection = { - source: 'manual' - entry?: - | { type: 'trigger'; blockId?: string; useMockPayload?: boolean } - | { type: 'block'; blockId: string; sourceRunId: string } - stopAfterBlockId?: string - dry?: true - allowBlocks?: string[] - mocks?: Record> +type WorkflowRunSelection = + | { source: 'deployment'; version: number } + | { + source: 'manual' + entry?: + | { type: 'trigger'; blockId?: string; useMockPayload?: boolean } + | { type: 'block'; blockId: string; sourceRunId: string } + stopAfterBlockId?: string + dry?: true + allowBlocks?: string[] + mocks?: Record> + } + +/** The flags that run the saved draft, which a pinned deployment version never runs. */ +const DRAFT_RUN_FLAGS = [ + ['manual', '--manual'], + ['dry', '--dry'], + ['trigger', '--trigger'], + ['mockPayload', '--mock-payload'], + ['stopAfter', '--stop-after'], + ['fromBlock', '--from-block'], + ['sourceRun', '--source-run'], + ['allow', '--allow'], + ['mock', '--mock'], +] as const + +/** + * `--deployment-version ` as the deployment selector it names, or undefined when it is not + * given. Refused unless it is a positive integer, and beside any flag that runs the draft. + */ +function pinnedDeployment( + flags: Record +): { source: 'deployment'; version: number } | undefined { + const given = flags.deploymentVersion + if (given === undefined) return undefined + const version = typeof given === 'string' && /^[1-9]\d*$/.test(given) ? Number(given) : Number.NaN + if (!Number.isSafeInteger(version)) { + throw new SimApiError('--deployment-version must be a positive integer, like 7', 0) + } + for (const [key, flag] of DRAFT_RUN_FLAGS) { + if (flags[key] === undefined || flags[key] === false) continue + if (Array.isArray(flags[key]) && flags[key].length === 0) continue + throw new SimApiError( + `--deployment-version runs a deployed version; ${flag} runs the draft: drop one`, + 0 + ) + } + return { source: 'deployment', version } } /** `--mock =` values as the block selector each names and its output object. */ @@ -102,6 +141,8 @@ async function readBlockMocks(values: string[]): Promise ): Promise { + const pinned = pinnedDeployment(flags) + if (pinned) return pinned const trigger = typeof flags.trigger === 'string' ? flags.trigger : undefined const useMockPayload = flags.mockPayload === true const stopAfter = typeof flags.stopAfter === 'string' ? flags.stopAfter : undefined @@ -305,14 +346,20 @@ async function readWorkflowResult(response: Response): Promise { } /** - * The request body: the generated one, the run selection the friendly flags make (the contract - * omits `run` as a flag of its own), and file references for an embedded run. + * The `workflows run` request: the generated one, with the run selection the run flags make (the + * contract omits `run` as a flag of its own) and, for a run this command waits on, an embedded + * run's file references ({@link withEmbeddedFileReferences}; a queued run rejects the field). */ -function runBody( - body: Record | undefined, - selection: WorkflowRunSelection | undefined -): Record | undefined { - return withEmbeddedFileReferences(selection ? { ...body, run: selection } : body) +async function runRequest( + workflowId: string, + flags: Record, + workspaceId: string | null, + selection: WorkflowRunSelection | undefined, + waits: boolean +) { + const request = await buildRequest('executeWorkflow', [workflowId], flags, workspaceId) + const body = selection ? { ...request.body, run: selection } : request.body + return { ...request, body: waits ? withEmbeddedFileReferences(body) : body } } /** @@ -355,12 +402,12 @@ async function runWithResultStream( const commandSpec = CLI_CONTRACT.executeWorkflow ?? {} try { - const request = await buildRequest('executeWorkflow', [workflowId], flags, profile.workspaceId) - const body = runBody(request.body, selection) + const request = await runRequest(workflowId, flags, profile.workspaceId, selection, true) const response = await client.requestRaw('executeWorkflow', { params: request.params, query: request.query, - body: waitTimeoutSeconds === undefined ? body : { ...body, waitTimeoutSeconds }, + body: + waitTimeoutSeconds === undefined ? request.body : { ...request.body, waitTimeoutSeconds }, headers: { ...request.headers, accept: WORKFLOW_RESULT_STREAM_CONTENT_TYPE }, }) const result = await readWorkflowResult(response) @@ -578,13 +625,13 @@ async function followRun( const { client, profile } = connect(command, ['executeWorkflow']) const operation = V2_OPERATIONS.executeWorkflow as OperationSpec - const request = await buildRequest('executeWorkflow', [workflowId], flags, profile.workspaceId) + const request = await runRequest(workflowId, flags, profile.workspaceId, selection, true) const response = await client.requestRaw('executeWorkflow', { params: request.params, query: request.query, body: { - ...runBody(request.body, selection), + ...request.body, stream: true, ...(includeThinking ? { includeThinking: true } : {}), ...(includeToolCalls ? { includeToolCalls: true } : {}), @@ -637,95 +684,102 @@ function stopBlockSelection( selection: WorkflowRunSelection | undefined, flags: Record ): string[] | null { - const stopAfter = selection?.stopAfterBlockId + const stopAfter = selection?.source === 'manual' ? selection.stopAfterBlockId : undefined if (stopAfter === undefined) return null if (Array.isArray(flags.selectOutput) && flags.selectOutput.length > 0) return null return [BLOCK_ID.test(stopAfter) ? stopAfter : normalizeWorkflowBlockName(stopAfter)] } -/** - * The handler Commander invokes for the generated `run` leaf, given the handler - * it is replacing. - */ -function followOrDelegate(previous: ((args: unknown[]) => unknown) | null) { - return async (workflowId: string, _options: unknown, command: Command): Promise => { - const initialFlags = command.optsWithGlobals() as Record - const waitTimeoutSeconds = - typeof initialFlags.waitTimeout === 'string' - ? Math.ceil(parseWaitTimeout(initialFlags.waitTimeout)) - : undefined - if (waitTimeoutSeconds !== undefined && initialFlags.async === true) { - throw new SimApiError( - '--wait-timeout bounds how long a synchronous run is waited for, and --async never waits; pass one, not both', - 0 - ) - } - if (waitTimeoutSeconds !== undefined && initialFlags.follow === true) { +/** Queues an `--async` run and prints its receipt: the run id and where to poll it. */ +async function queueRun( + workflowId: string, + command: Command, + selection: WorkflowRunSelection | undefined +): Promise { + const flags = command.optsWithGlobals() as Record + const { client, profile } = connect(command, ['executeWorkflow']) + const operation = V2_OPERATIONS.executeWorkflow as OperationSpec + const commandSpec = CLI_CONTRACT.executeWorkflow ?? {} + try { + const request = await runRequest(workflowId, flags, profile.workspaceId, selection, false) + const { data } = await client.request<{ data: unknown }>('executeWorkflow', request) + renderResult('executeWorkflow', profile.output, data, commandSpec) + } catch (error) { + throw retypeApiError(error, 'executeWorkflow', commandSpec, operation) + } +} + +/** The action of the `workflows run` leaf: validates the flags, then runs, follows or queues. */ +async function runWorkflow(workflowId: string, _options: unknown, command: Command): Promise { + const initialFlags = command.optsWithGlobals() as Record + const waitTimeoutSeconds = + typeof initialFlags.waitTimeout === 'string' + ? Math.ceil(parseWaitTimeout(initialFlags.waitTimeout)) + : undefined + if (waitTimeoutSeconds !== undefined && initialFlags.async === true) { + throw new SimApiError( + '--wait-timeout bounds how long a synchronous run is waited for, and --async never waits; pass one, not both', + 0 + ) + } + if (waitTimeoutSeconds !== undefined && initialFlags.follow === true) { + throw new SimApiError( + '--wait-timeout cannot be combined with --follow, which streams the run until it ends', + 0 + ) + } + if ( + typeof initialFlags.dir === 'string' && + (initialFlags.follow === true || initialFlags.async === true) + ) { + throw new SimApiError( + '--dir maps the failure of a run this command waits for; --follow and --async do not report the block that failed. Drop --dir, or run without them', + 0 + ) + } + const selection = await resolveWorkflowRunSelection(initialFlags) + const stopBlock = stopBlockSelection(selection, initialFlags) + if (stopBlock) command.setOptionValue('selectOutput', stopBlock) + const flags = command.optsWithGlobals() as Record + + if (flags.follow !== true) { + // A queued run has produced nothing to select from, so the server would + // answer 400; failing locally names the recovery: the finished run is read + // with `runs get`, which takes the same block names (`workflow-run-get.ts`). + if ( + Array.isArray(flags.selectOutput) && + flags.selectOutput.length > 0 && + flags.async === true + ) { throw new SimApiError( - '--wait-timeout cannot be combined with --follow, which streams the run until it ends', + '--select-output names outputs of a completed run, and --async returns as soon as the run is queued. Drop one of them, or read the finished run with: sim workflows runs get --workflow --select-output [.path] — that resource takes the same selectors --select-output takes here.', 0 ) } - if ( - typeof initialFlags.dir === 'string' && - (initialFlags.follow === true || initialFlags.async === true) - ) { + if (flags.includeThinking === true || flags.includeToolCalls === true) { throw new SimApiError( - '--dir maps the failure of a run this command waits for; --follow and --async do not report the block that failed. Drop --dir, or run without them', + '--include-thinking and --include-tool-calls describe a stream; add --follow', 0 ) } - const selection = await resolveWorkflowRunSelection(initialFlags) - const stopBlock = stopBlockSelection(selection, initialFlags) - if (stopBlock) command.setOptionValue('selectOutput', stopBlock) - const flags = command.optsWithGlobals() as Record - - if (flags.follow !== true) { - // A queued run has produced nothing to select from, so the server would - // answer 400; failing locally names the recovery: the finished run is read - // with `runs get`, which takes the same block names (`workflow-run-get.ts`). - if ( - Array.isArray(flags.selectOutput) && - flags.selectOutput.length > 0 && - flags.async === true - ) { - throw new SimApiError( - '--select-output names outputs of a completed run, and --async returns as soon as the run is queued. Drop one of them, or read the finished run with: sim workflows runs get --workflow --select-output [.path] — that resource takes the same selectors --select-output takes here.', - 0 - ) - } - if (flags.includeThinking === true || flags.includeToolCalls === true) { - throw new SimApiError( - '--include-thinking and --include-tool-calls describe a stream; add --follow', - 0 - ) - } - if (flags.async !== true) { - await runWithResultStream(workflowId, command, selection, waitTimeoutSeconds) - return - } - - if (previous) { - await previous(command.processedArgs) - return - } - await executeOperation( - 'executeWorkflow', - CLI_CONTRACT.executeWorkflow ?? {}, - V2_OPERATIONS.executeWorkflow as OperationSpec, - [workflowId, command.opts(), command] - ) + if (flags.async !== true) { + await runWithResultStream(workflowId, command, selection, waitTimeoutSeconds) return } - - await followRun(workflowId, command, selection) + await queueRun(workflowId, command, selection) + return } + + await followRun(workflowId, command, selection) } /** `sim workflows run --help`, after the options: which version runs, what it prints, how it exits. */ const RUN_HELP = ` Without --manual (or a flag that implies it) this runs the active deployment; a workflow never -deployed has none. --manual runs the saved draft, as the source loop leaves it. +deployed has none. --deployment-version runs that deployed version instead, as a pin for +comparing or reproducing (it needs workspace write access, through a full-access API key or an +OAuth token with api:write); the child workflows it calls still run their own active deployment. +--manual runs the saved draft, as the source loop leaves it. --dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in @@ -764,9 +818,10 @@ elapsed.` * output-selection, and `--async` flags all still apply, and a second command * would have to restate every one of them and then drift. * - * Commander offers no way to read the action it already holds, so the existing - * handler is captured for async execution. Synchronous execution uses the same - * generated request and result builders with a heartbeat-capable response. + * Every mode builds its request with the same generated request builder: the + * run selection the run flags make is added to the body by hand, since the + * generated leaf omits `run`. Synchronous execution reads a heartbeat-capable + * response. */ export function attachWorkflowRunFollow(workflows: Command): void { const run = workflows.commands.find((command) => command.name() === 'run') @@ -774,13 +829,15 @@ export function attachWorkflowRunFollow(workflows: Command): void { throw new Error('workflows run must be registered before --follow can be attached to it') } - const held = (run as Command & { _actionHandler?: unknown })._actionHandler - const previous = typeof held === 'function' ? (held as (args: unknown[]) => unknown) : null // A run that outlasts --wait-timeout is read back from the runs resource. callsOperations(run, ['executeWorkflow', 'getWorkflowRun'], { runs: 'executeWorkflow' }) run .option('--manual', 'Run the current saved workflow state instead of the active deployment') + .option( + '--deployment-version ', + "Run this deployed version instead of the active one (a version number from `sim workflows versions list`); a Workflow block in it still runs its child workflow's active deployment. Needs workspace write access, through a full-access API key or an OAuth token with api:write. Not with --manual or any flag that runs the draft" + ) .option( '--dry', 'Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout' @@ -830,5 +887,5 @@ export function attachWorkflowRunFollow(workflows: Command): void { .option('--include-thinking', 'Show model reasoning while following (requires --follow)') .option('--include-tool-calls', 'Show tool calls while following (requires --follow)') .addHelpText('after', RUN_HELP) - .action(followOrDelegate(previous)) + .action(runWorkflow) } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts index 18fa6df5fe4..dd0f8be8ed3 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts @@ -96,6 +96,7 @@ function outcome(overrides: { dryRun?: boolean; diagnostics?: unknown[]; notes?: base: { ...BASE, fingerprint: 'sf1:b' }, mintedIds: {}, notes: overrides.notes ?? [], + deployedVersion: 3 as number | null, needsRedeployment: true, }, } @@ -236,7 +237,7 @@ describe('sim workflows source apply', () => { expect(markdown).toContain('1 to add, 0 to remove, 0 to modify, 0 renamed; connections +1 -0') expect(markdown).toContain('| + | start (start_trigger) | added |') expect(markdown).toContain('- `E_UNKNOWN_IDENTIFIER` workflow.ts:4: Nothing \\| named x.') - expect(markdown).toContain('The live deployment now differs from the draft.') + expect(markdown).toContain('Live: version 3, draft has undeployed changes') }) it('names variable changes in --summary-file, which no block or connection count shows', async () => { @@ -1019,7 +1020,11 @@ describe('sim workflows source apply', () => { isDeployed: true, deployedAt: null, warnings: [], - activeDeployment: null, + activeDeployment: { + deploymentVersionId: 'dv-4', + version: 4, + deployedAt: '2026-11-20T00:00:00Z', + } as { deploymentVersionId: string; version: number; deployedAt: string } | null, latestDeploymentAttempt: null, version: 4, lint: null, @@ -1101,6 +1106,7 @@ describe('sim workflows source apply', () => { noop.data.applied = false noop.data.diff.noop = true noop.data.needsRedeployment = false + let attempt: Record | null = null const status = (isDeployed: boolean) => ({ data: { ...deployed.data, @@ -1111,6 +1117,7 @@ describe('sim workflows source apply', () => { activeDeployment: isDeployed ? { deploymentVersionId: 'dv-7', version: 7, deployedAt: '2026-11-20T00:00:00Z' } : null, + latestDeploymentAttempt: attempt, }, }) let live = true @@ -1136,6 +1143,27 @@ describe('sim workflows source apply', () => { DEPLOY_PATH, STATUS_PATH, ]) + + // A version still activating is about to replace the one that matches: the draft is deployed. + live = true + attempt = { + id: 'op-5', + deploymentVersionId: 'dv-5', + version: 5, + action: 'rollback', + status: 'activating', + isCurrent: true, + readiness: { webhooks: 'pending', schedules: 'ready', mcp: 'ready' }, + requestedAt: '2026-11-20T00:00:00Z', + } + request.mockClear() + await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--deploy') + expect(request.mock.calls.map((call) => call[0])).toEqual([ + APPLY_PATH, + STATUS_PATH, + DEPLOY_PATH, + STATUS_PATH, + ]) }) it('without --deploy, names the deploy command when the deployed workflow now differs', async () => { @@ -1153,6 +1181,89 @@ describe('sim workflows source apply', () => { }) }) + it.each([ + [null, false, 'not deployed'], + [3, false, 'version 3, matches the draft'], + [3, true, 'version 3, draft has undeployed changes'], + ])( + 'without --deploy, a workflow live at %s (draft differs: %s) reads as %s', + async (deployedVersion, needsRedeployment, live) => { + setTerminal(false) + const answer = outcome() + answer.data.deployedVersion = deployedVersion + answer.data.needsRedeployment = needsRedeployment + request.mockResolvedValue(answer) + + await apply(WORKFLOW_ID, '--dir', dir, '--yes') + + expect(stdoutJson()).toMatchObject({ live, deployedVersion, needsRedeployment }) + vi.mocked(console.log).mockClear() + contextMockState.output = 'text' + await apply(WORKFLOW_ID, '--dir', dir, '--yes') + expect(vi.mocked(console.log).mock.calls[0].join(' ')).toBe(`live\t${live}`) + } + ) + + it('prints no live line against a server that does not report deployedVersion', async () => { + setTerminal(false) + const answer = outcome() + answer.data.needsRedeployment = false + Reflect.deleteProperty(answer.data, 'deployedVersion') + request.mockResolvedValue(answer) + contextMockState.output = 'text' + + await apply(WORKFLOW_ID, '--dir', dir, '--yes') + + const lines = vi.mocked(console.log).mock.calls.map((call) => call.join(' ')) + expect(lines.some((line) => line.startsWith('live\t'))).toBe(false) + expect(lines.join('\n')).not.toContain('undefined') + }) + + it('says the version it deployed is still activating, not that it is live', async () => { + setTerminal(false) + const activating = { + data: { + ...deployed.data, + activeDeployment: { + deploymentVersionId: 'dv-3', + version: 3, + deployedAt: '2026-11-20T00:00:00Z', + }, + latestDeploymentAttempt: { + id: 'op-4', + deploymentVersionId: 'dv-4', + version: 4, + action: 'deploy', + status: 'activating', + isCurrent: true, + readiness: { webhooks: 'pending', schedules: 'ready', mcp: 'ready' }, + requestedAt: '2026-11-20T00:00:00Z', + }, + }, + } + request.mockImplementation(async (path: string) => + path === DEPLOY_PATH ? activating : path === STATUS_PATH ? liveStatus : outcome() + ) + + await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--deploy') + + expect(stdoutJson()).toMatchObject({ + live: 'version 3 still serving; version 4 activating', + deployedVersion: 3, + // Version 3 serves, and the draft is version 4: the live version is not the draft yet. + needsRedeployment: true, + next: { command: `sim workflows deployment status ${WORKFLOW_ID}` }, + }) + + vi.mocked(console.log).mockClear() + contextMockState.output = 'text' + await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--deploy') + const lines = vi.mocked(console.log).mock.calls.map((call) => call.join(' ')) + expect(lines[0]).toBe('live\tversion 3 still serving; version 4 activating') + // The admitted version is never printed as if it were deployed. + expect(lines.some((line) => line.startsWith('deployed\t'))).toBe(false) + }) + it('deploys nothing after a refused apply, and refuses beside --dry-run', async () => { setTerminal(false) request.mockResolvedValue(outcome({ diagnostics: [STALE] })) 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 1f4e3320582..c467782645e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -13,6 +13,12 @@ import type { } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { apiCommand, type OperationClient } from '../../runtime/called-operations' +import { + draftIsLive, + liveAfterActivation, + liveAgainstDraft, + liveDeploymentStatus, +} from '../../runtime/deployment-live' import { searchTasks } from '../search' import { type DeployedUrl, @@ -184,21 +190,27 @@ async function writeWorkflowSource(args: const findings = findingsOutput(args.output, options.verbose, options.dir) const notes = new Set() const report = (data: SourceApplyData, deployment: DeployOutcome = {}) => { - publishSummary(() => planMarkdown(data, creating, deployment), { + const { live: deployedLive, deployed, ...outcome } = deployment + const live = deployedLive ?? liveAgainstDraft(data.deployedVersion, data.needsRedeployment) + publishSummary(() => planMarkdown(data, creating, live), { file: options.summaryFile, marker: summaryMarker(options.dir), }) - const result = { ...summarize(data, creating, findings.machine), ...deployment } + // `deployed.version` is the version the deploy admitted, which may not be live yet: a person + // reads `live` instead, and a machine result keeps the record. + const result = { + ...(live ? { live } : {}), + ...summarize(data, creating, findings.machine), + ...(deployed && findings.machine ? { deployed } : {}), + ...outcome, + } printProtocolResult( args.output, { ...result, ...findings.result(data.diagnostics) }, { ...(result.created ? { created: createdText(result.created) } : {}), - ...(deployment.next ? { next: deployment.next.command } : {}), - ...(deployment.deployed - ? { deployed: `version ${deployment.deployed.version ?? '?'}` } - : {}), - ...(deployment.urls?.length ? { urls: deployedUrlsText(deployment.urls) } : {}), + ...(outcome.next ? { next: outcome.next.command } : {}), + ...(outcome.urls?.length ? { urls: deployedUrlsText(outcome.urls) } : {}), } ) } @@ -255,9 +267,9 @@ async function writeWorkflowSource(args: /** * The plan of a dry run or write as the Markdown a step summary or `--summary-file` holds: the - * counts, each block changed, each error, and whether the live deployment is now behind the draft. + * counts, each block changed, each error, and what is live. */ -function planMarkdown(data: SourceApplyData, creating: boolean, deployment: DeployOutcome): string { +function planMarkdown(data: SourceApplyData, creating: boolean, live: string | undefined): string { const { blocks, edges } = data.diff const [added, removed, modified] = data.dryRun ? ['to add', 'to remove', 'to modify'] @@ -281,7 +293,6 @@ function planMarkdown(data: SourceApplyData, creating: boolean, deployment: Depl const variableChanges = variableChangeList(data.diff.variables) const errors = data.diagnostics.filter((finding) => finding.severity === 'error') const warnings = data.diagnostics.filter((finding) => finding.severity === 'warning').length - const needsRedeployment = deployment.needsRedeployment ?? data.needsRedeployment return [ `### Sim workflow ${data.dryRun ? 'plan' : verb}: ${markdownCell(data.workflowId)}`, '', @@ -304,13 +315,16 @@ function planMarkdown(data: SourceApplyData, creating: boolean, deployment: Depl ] : []), ...(errors.length > 0 ? ['', '**Errors**', '', ...errorBullets(errors)] : []), - ...(needsRedeployment ? ['', 'The live deployment now differs from the draft.'] : []), + ...(live ? ['', `Live: ${markdownCell(live)}`] : []), ].join('\n') } /** What a write adds to its result about deploying: the deploy it ran, or the one to run. */ interface DeployOutcome { + /** What is live after the deploy step, when it deployed or read the deployment. */ + live?: string deployed?: { version?: number; isDeployed: boolean; warnings?: string[] } + deployedVersion?: number | null needsRedeployment?: boolean /** The URL of each webhook the live deployment serves. */ urls?: DeployedUrl[] @@ -340,8 +354,8 @@ async function deployStep( } } if (!data.applied && !data.needsRedeployment) { - // A no-op write changed no draft: when the live version already matches it, a deploy would - // only publish the same version again. + // A no-op write changed no draft: when the live version already matches it and no other + // version is activating to replace it, a deploy would only publish the same version again. const status = await client .request('getWorkflowDeployment', { params: { workflowId: data.workflowId }, @@ -352,14 +366,16 @@ async function deployStep( throw deployFailure(error, options, deployCommand) } ) - if (status.isDeployed && !status.needsRedeployment) { + if (draftIsLive(status)) { if (!options.machine) printError('The live version already matches the draft; nothing was deployed.') return { + live: liveDeploymentStatus(status, data.workflowId).live, deployed: { ...(status.activeDeployment ? { version: status.activeDeployment.version } : {}), isDeployed: true, }, + deployedVersion: status.activeDeployment?.version ?? null, needsRedeployment: false, urls: namedUrls(status.webhooks, lockBlockNames(data.lock)), } @@ -380,13 +396,25 @@ async function deployStep( if (!options.machine) { for (const warning of deployed.warnings) printError(`deploy warning: ${warning}`) } + const { live, next } = liveAfterActivation( + deployed, + data.workflowId, + deployed.version, + 'this deploy', + deployCommand + ) + const liveVersion = deployed.activeDeployment?.version ?? null return { + live, + ...(next ? { next } : {}), deployed: { ...(deployed.version !== undefined ? { version: deployed.version } : {}), isDeployed: deployed.isDeployed, ...(options.machine && deployed.warnings.length > 0 ? { warnings: deployed.warnings } : {}), }, - needsRedeployment: false, + deployedVersion: liveVersion, + // The draft is live only once the version this deploy admitted is the one serving. + needsRedeployment: deployed.version === undefined || liveVersion !== deployed.version, ...(deployed.isDeployed ? { urls: await deployedUrls(client, data.workflowId, lockBlockNames(data.lock)) } : {}), @@ -680,6 +708,7 @@ function summarize(data: SourceApplyData, creating: boolean, machine: boolean) { warnings: data.diagnostics.filter((diagnostic) => diagnostic.severity === 'warning').length, notes: machine ? data.notes : data.notes.length, fingerprint: data.base.fingerprint, + deployedVersion: data.deployedVersion, needsRedeployment: data.needsRedeployment, ...(creating && data.applied && !data.dryRun ? { guide: SOURCE_AGENTS_FILE } : {}), } 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 2ca12ac0e12..05ba321823e 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 @@ -93,6 +93,30 @@ function answer(overrides: Record = {}) { } } +/** A deployment status of `wf_1`, live at `version` (none when null), serving `webhooks`. */ +function deploymentStatus( + version: number | null, + overrides: Record = {} +): { data: Record } { + return { + data: { + id: 'wf_1', + isDeployed: version !== null, + deployedAt: null, + warnings: [], + activeDeployment: + version === null + ? null + : { deploymentVersionId: `dv-${version}`, version, deployedAt: '2026-11-20T00:00:00Z' }, + latestDeploymentAttempt: null, + needsRedeployment: false, + isPublicApi: false, + webhooks: [], + ...overrides, + }, + } +} + let dir: string function write(path: string, text: string | Buffer) { @@ -1678,13 +1702,9 @@ describe('workspaces source apply', () => { } request.mockImplementation(async (path: string) => path === '/api/v2/workflows/wf_1/deployment' - ? { - data: { - id: 'wf_1', - isDeployed: true, - webhooks: [{ blockId: 'b-hook', provider: 'generic', url: hookUrl }], - }, - } + ? deploymentStatus(1, { + webhooks: [{ blockId: 'b-hook', provider: 'generic', url: hookUrl }], + }) : answer({ plan: [{ kind: 'deployment', key: 'ingest', action: 'create' }], applied: [{ kind: 'deployment', key: 'ingest', action: 'create' }], @@ -1715,13 +1735,9 @@ describe('workspaces source apply', () => { writeFileSync(join(dir, 'workflows/ingest/.sim/lock.json'), JSON.stringify(lock)) request.mockImplementation(async (path: string) => path === '/api/v2/workflows/wf_1/deployment' - ? { - data: { - id: 'wf_1', - isDeployed: true, - webhooks: [{ blockId: 'b-hook', provider: 'generic', url: hookUrl }], - }, - } + ? deploymentStatus(1, { + webhooks: [{ blockId: 'b-hook', provider: 'generic', url: hookUrl }], + }) : answer({ plan: [{ kind: 'deployment', key: 'ingest', action: 'update' }], applied: [{ kind: 'deployment', key: 'ingest', action: 'update' }], @@ -1759,7 +1775,7 @@ describe('workspaces source apply', () => { .mocked(console.error) .mock.calls.map(([line]) => String(line)) .join('\n') - expect(warned).toContain('its webhook URLs could not be read (gateway cleared)') + expect(warned).toContain('the deployment of ingest could not be read (gateway cleared)') expect(warned).not.toContain('\u001b') }) @@ -1779,6 +1795,135 @@ describe('workspaces source apply', () => { expect(vi.mocked(console.log)).not.toHaveBeenCalled() }) + describe('names each workflow it wrote with its id and what is live', () => { + const wrote = answer({ + plan: [ + { kind: 'workflow', key: 'draft-only', action: 'create', id: 'wf_new' }, + { kind: 'workflow', key: 'ingest', action: 'update', id: 'wf_1' }, + { kind: 'deployment', key: 'ingest', action: 'update' }, + ], + applied: [ + { kind: 'workflow', key: 'draft-only', action: 'create', id: 'wf_new' }, + { kind: 'workflow', key: 'ingest', action: 'update', id: 'wf_1' }, + { kind: 'deployment', key: 'ingest', action: 'update' }, + ], + base: { + ...BASE, + resources: { 'workflow:draft-only': { id: 'wf_new' }, 'workflow:ingest': { id: 'wf_1' } }, + }, + }) + const respond = (ingest: ReturnType) => + request.mockImplementation(async (path: string) => + path === '/api/v2/workflows/wf_new/deployment' + ? deploymentStatus(null, { id: 'wf_new' }) + : path === '/api/v2/workflows/wf_1/deployment' + ? ingest + : wrote + ) + const printedJson = () => + JSON.parse( + vi + .mocked(console.log) + .mock.calls.map(([line]) => String(line)) + .join('\n') + ) + + it('tells a workflow never deployed apart from one whose live version is the draft', async () => { + respond(deploymentStatus(4)) + + await apply('--yes') + + expect(printedJson().workflows).toEqual([ + { + key: 'draft-only', + workflowId: 'wf_new', + deployedVersion: null, + liveMatchesDraft: false, + live: 'not deployed', + }, + { + key: 'ingest', + workflowId: 'wf_1', + deployedVersion: 4, + liveMatchesDraft: true, + live: 'version 4, matches the draft', + }, + ]) + }) + + it('says the draft is not live while the version it deployed is still activating', async () => { + respond( + deploymentStatus(4, { + latestDeploymentAttempt: { + id: 'op-5', + deploymentVersionId: 'dv-5', + version: 5, + action: 'deploy', + status: 'activating', + isCurrent: true, + readiness: { webhooks: 'pending', schedules: 'ready', mcp: 'ready' }, + requestedAt: '2026-11-20T00:00:00Z', + }, + }) + ) + + await apply('--yes') + + expect(printedJson().workflows[1]).toEqual({ + key: 'ingest', + workflowId: 'wf_1', + deployedVersion: 4, + liveMatchesDraft: false, + live: 'version 4 still serving; version 5 activating', + }) + }) + + it('reports a workflow whose deployment it deleted as not deployed', async () => { + request.mockImplementation(async (path: string) => + path === '/api/v2/workflows/wf_1/deployment' + ? deploymentStatus(null) + : answer({ + plan: [{ kind: 'deployment', key: 'ingest', action: 'delete' }], + applied: [{ kind: 'deployment', key: 'ingest', action: 'delete' }], + base: { ...BASE, resources: { 'workflow:ingest': { id: 'wf_1' } } }, + }) + ) + + await apply('--yes', '--allow-delete') + + expect(printedJson()).toMatchObject({ + workflows: [ + { + key: 'ingest', + workflowId: 'wf_1', + deployedVersion: null, + liveMatchesDraft: false, + live: 'not deployed', + }, + ], + }) + expect(printedJson()).not.toHaveProperty('urls') + }) + + it('shows each id and live version to a person, and reads nothing on a dry run', async () => { + respond(deploymentStatus(4, { needsRedeployment: true })) + contextMockState.output = 'text' + + await apply('--yes') + + expect(vi.mocked(console.log).mock.calls.map((call) => call.join(' '))).toContain( + 'workflows\tdraft-only wf_new: not deployed; ingest wf_1: version 4, draft has undeployed changes' + ) + + request.mockReset() + request.mockResolvedValue({ data: { ...wrote.data, dryRun: true } }) + await apply('--dry-run') + expect(request.mock.calls.map((call) => call[0])).not.toContain( + '/api/v2/workflows/wf_1/deployment' + ) + }) + }) + it('appends the plan and its errors to the GitHub Actions step summary', async () => { const summary = join(dir, 'step-summary.md') vi.stubEnv('GITHUB_ACTIONS', 'true') @@ -1972,6 +2117,7 @@ describe('workspaces source apply', () => { if (path.endsWith('/source/catalog') && options.query?.workflowId) { throw new SimApiError('Service unavailable', 503, 'UNAVAILABLE') } + if (path === '/api/v2/workflows/wf_1/deployment') return deploymentStatus(null) return answer({ plan: [{ kind: 'workflow', key: 'ingest', action: 'update' }], applied: [{ kind: 'workflow', key: 'ingest', action: 'update', id: 'wf_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 2c1916214ef..f1dd479ee48 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -1,5 +1,7 @@ import { lstat } from 'node:fs/promises' import { join } from 'node:path' +import { mapWithConcurrency } from '@sim/utils/concurrency' +import { getErrorMessage } from '@sim/utils/errors' import { isRecordLike } from '@sim/utils/object' import { SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { @@ -30,12 +32,15 @@ import { SOURCE_HELD_EXIT_CODE, SOURCE_PARTIAL_EXIT_CODE } from '../../exit-code import type { ApplyWorkspaceSourceBody, ApplyWorkspaceSourceResponse, + GetWorkflowDeploymentResponse, GetWorkspaceSourceResponse, } from '../../generated/v2-api' -import { SimApiError } from '../../http/client' +import { isRequestCancelled, SimApiError } from '../../http/client' +import { sanitize } from '../../output/render' import { apiCommand, type OperationClient } from '../../runtime/called-operations' +import { draftIsLive, liveDeploymentStatus } from '../../runtime/deployment-live' import { searchTasks } from '../search' -import { type DeployedUrl, deployedUrls, deployedUrlsText, lockBlockNames } from './deployed-urls' +import { type DeployedUrl, deployedUrlsText, lockBlockNames, namedUrls } from './deployed-urls' import { gitProvenance } from './git-provenance' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' @@ -839,7 +844,11 @@ export function attachWorkspaceSourceApply(source: Command): void { const notSent = notSentFindings(submission.ignored) findings.print(notSent) /** Prints `data` as the result, with the findings about files the CLI did not send. */ - const report = (data: ApplyData, next?: NextStep, urls: WorkflowUrl[] = []) => { + const report = ( + data: ApplyData, + next?: NextStep, + { workflows, urls }: WrittenWorkflows = { workflows: [], urls: [] } + ) => { const diagnostics = [...notSent, ...data.diagnostics] publishSummary( () => planMarkdown({ ...data, diagnostics }, options.to ?? workspaceId), @@ -847,6 +856,7 @@ export function attachWorkspaceSourceApply(source: Command): void { ) const result = { ...summarize({ ...data, diagnostics }), + ...(workflows.length > 0 ? { workflows } : {}), ...(urls.length > 0 ? { urls } : {}), ...(next ? { next } : {}), } @@ -855,6 +865,7 @@ export function attachWorkspaceSourceApply(source: Command): void { { ...result, ...findings.result(diagnostics) }, { created: createdText(result.created), + ...(workflows.length > 0 ? { workflows: writtenWorkflowsText(workflows) } : {}), ...(urls.length > 0 ? { urls: workflowUrlsText(urls) } : {}), ...(next ? { next: next.command } : {}), } @@ -922,7 +933,7 @@ export function attachWorkspaceSourceApply(source: Command): void { report( data, undefined, - await deploymentUrls( + await writtenWorkflows( client, data, promotion ? undefined : (path) => readSourceText(options.dir, path) @@ -973,6 +984,28 @@ interface WorkflowUrl extends DeployedUrl { workflow: string } +/** + * A workflow a written apply created, updated, deployed or undeployed, and what is live for it: + * the id an agent would otherwise read out of `.sim/base.json`, and whether the draft serves. + */ +interface WrittenWorkflow { + key: string + workflowId: string + /** The live version, or null when nothing is deployed. */ + deployedVersion: number | null + /** Whether that version is the draft: deployed, nothing activating, and no undeployed change. */ + liveMatchesDraft: boolean + live: string +} + +interface WrittenWorkflows { + workflows: WrittenWorkflow[] + urls: WorkflowUrl[] +} + +/** Deployment reads one apply runs at once. */ +const DEPLOYMENT_READ_CONCURRENCY = 8 + /** The URLs as one display line: `lead-intake: leadin (hook) https://…; …`. */ function workflowUrlsText(urls: readonly WorkflowUrl[]): string { const byWorkflow = new Map() @@ -984,34 +1017,75 @@ function workflowUrlsText(urls: readonly WorkflowUrl[]): string { .join('; ') } +/** The workflows as one display line: `lead-intake : version 3, matches the draft; …`. */ +function writtenWorkflowsText(workflows: readonly WrittenWorkflow[]): string { + return workflows.map(({ key, workflowId, live }) => `${key} ${workflowId}: ${live}`).join('; ') +} + /** - * The webhook URLs of each workflow a written apply deployed (a `deployments/.ts` it created - * or updated), in the workspace it wrote: a promotion's are the target's, which are new URLs. - * Each block is named as the workflow's reprinted lock names it, or, when the apply did not - * reprint the workflow (it wrote only the deployment), as `savedLock` reads it from the directory - * (none for a promotion, whose directory holds the source workspace's block ids). + * Each {@link WrittenWorkflow}, read from its deployment in the workspace the apply wrote (a + * promotion's are the target's), and the webhook URLs of each one it deployed (a + * `deployments/.ts` it created or updated), which are new URLs for a promotion. Each block is + * named as the workflow's reprinted lock names it, or, when the apply did not reprint the workflow + * (it wrote only the deployment), as `savedLock` reads it from the directory (none for a + * promotion, whose directory holds the source workspace's block ids). A failed read is reported + * and leaves that workflow out: the apply itself stands. */ -async function deploymentUrls( +async function writtenWorkflows( client: OperationClient<'getWorkflowDeployment'>, data: ApplyData, savedLock?: (path: string) => Promise -): Promise { - if (data.dryRun) return [] +): Promise { + if (data.dryRun) return { workflows: [], urls: [] } const base = parseWorkspaceBase(data.base).base - const deployed = data.applied.filter( - (change) => change.kind === 'deployment' && change.action !== 'delete' + // A deleted deployment leaves its workflow, which then reports `not deployed`. + const written = data.applied.filter( + (change) => + change.kind === 'deployment' || (change.kind === 'workflow' && change.action !== 'delete') ) - const perWorkflow = await Promise.all( - deployed.map(async ({ key }): Promise => { - const workflowId = base?.resources[resourceAddress('workflow', key)]?.id - if (!workflowId) return [] - const lockPath = `${workflowFolder(key)}/${SOURCE_LOCK_FILE}` - const lock = data.files[lockPath] ?? (await savedLock?.(lockPath)) ?? null - const named = await deployedUrls(client, workflowId, lockBlockNames(lock)) - return named.map((url) => ({ workflow: key, ...url })) - }) + const keys = [...new Set(written.map((change) => change.key))] + const deployedKeys = new Set( + written + .filter((change) => change.kind === 'deployment' && change.action !== 'delete') + .map((change) => change.key) ) - return perWorkflow.flat() + const read = await mapWithConcurrency(keys, DEPLOYMENT_READ_CONCURRENCY, async (key) => { + const workflowId = base?.resources[resourceAddress('workflow', key)]?.id + if (!workflowId) return null + const status = await client + .request('getWorkflowDeployment', { params: { workflowId } }) + .then( + (response) => response.data, + (error: unknown) => { + if (isRequestCancelled(error)) throw error + printError( + `The apply was written, but the deployment of ${sanitize(key)} could not be read (${sanitize(getErrorMessage(error))}): \`sim workflows deployment status ${sanitize(workflowId)}\` shows it.` + ) + return null + } + ) + if (!status) return null + const workflow: WrittenWorkflow = { + key, + workflowId, + deployedVersion: status.activeDeployment?.version ?? null, + liveMatchesDraft: draftIsLive(status), + live: liveDeploymentStatus(status, workflowId).live, + } + if (!deployedKeys.has(key)) return { workflow, urls: [] } + const lockPath = `${workflowFolder(key)}/${SOURCE_LOCK_FILE}` + const lock = data.files[lockPath] ?? (await savedLock?.(lockPath)) ?? null + const urls = namedUrls(status.webhooks, lockBlockNames(lock)).map((url) => ({ + workflow: key, + ...url, + })) + return { workflow, urls } + }) + const found = read.filter((entry) => entry !== null) + return { + workflows: found.map((entry) => entry.workflow), + urls: found.flatMap((entry) => entry.urls), + } } /** This apply as a command, without `--yes` or `--dry-run`: what a plan run names next. */ diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 5ad0bdb8b78..9c5905448cb 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -2396,9 +2396,9 @@ always prints as null. For a copy to share outside this workspace, pass "Maximum duration of the run in seconds, capped by the plan's execution timeout. Requires --async or --wait-timeout", }, input: { json: true, describe: 'Trigger input as JSON' }, - // Built from --manual, --trigger, --mock-payload, --from-block, --source-run, - // --stop-after, --dry, --allow and --mock by `workflow-run-follow.ts`, so a run is - // selected one way only. + // Built from --deployment-version, --manual, --trigger, --mock-payload, --from-block, + // --source-run, --stop-after, --dry, --allow and --mock by `workflow-run-follow.ts`, so a + // run is selected one way only. run: { omit: true }, // `workflows runs get` takes the same names (`workflow-run-get.ts` resolves // them against the draft graph), which is why both describes name theirs. diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 93765342ecd..4837a15594e 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -1041,6 +1041,7 @@ export type ApplyWorkflowSourceResponse = { } mintedIds: Record notes: Array + deployedVersion: number | null needsRedeployment: boolean } } @@ -5520,6 +5521,7 @@ export type CreateWorkflowFromSourceResponse = { } mintedIds: Record notes: Array + deployedVersion: number | null needsRedeployment: boolean } } @@ -14746,6 +14748,7 @@ export type PlanWorkflowSourceResponse = { } mintedIds: Record notes: Array + deployedVersion: number | null needsRedeployment: boolean } } diff --git a/packages/sim-cli/src/runtime/deployment-live.test.ts b/packages/sim-cli/src/runtime/deployment-live.test.ts new file mode 100644 index 00000000000..411dadf1bac --- /dev/null +++ b/packages/sim-cli/src/runtime/deployment-live.test.ts @@ -0,0 +1,212 @@ +import { describe, expect, it } from 'vitest' +import { liveAgainstDraft, withDeploymentLive } from './deployment-live' + +const ID = '00000000-0000-4000-8000-00000000000a' + +const active = (version: number) => ({ + deploymentVersionId: `dv-${version}`, + version, + deployedAt: '2026-11-20T00:00:00Z', +}) + +const attempt = (version: number, status: string, error?: string, isCurrent = true) => ({ + id: `op-${version}`, + deploymentVersionId: `dv-${version}`, + version, + action: 'deploy', + status, + isCurrent, + readiness: { webhooks: 'ready', schedules: 'ready', mcp: 'ready' }, + requestedAt: '2026-11-20T00:00:00Z', + ...(error ? { error: { code: 'E', message: error, retryable: false } } : {}), +}) + +const STATUS = `sim workflows deployment status ${ID} # shows when version 7 is live` + +describe('withDeploymentLive after a deploy', () => { + it.each([ + { + name: 'the deployed version serves', + response: { + version: 7, + activeDeployment: active(7), + latestDeploymentAttempt: attempt(7, 'active'), + }, + live: 'version 7, serving (this deploy)', + next: `sim workflows run ${ID} # runs version 7, the live deployment; add --input '' for its input, or --manual to run the draft`, + }, + { + name: 'the older version still serves while the new one activates', + response: { + version: 7, + activeDeployment: active(6), + latestDeploymentAttempt: attempt(7, 'activating'), + }, + live: 'version 6 still serving; version 7 activating', + next: STATUS, + }, + { + name: 'the first version is still preparing', + response: { + version: 1, + activeDeployment: null, + latestDeploymentAttempt: attempt(1, 'preparing'), + }, + live: 'not deployed; version 1 activating', + next: `sim workflows deployment status ${ID} # shows when version 1 is live`, + }, + { + name: 'the new version failed', + response: { + version: 7, + activeDeployment: active(6), + latestDeploymentAttempt: attempt(7, 'failed', 'webhook registration failed'), + }, + live: 'version 6 still serving; version 7 failed: webhook registration failed', + next: `sim workflows deploy ${ID} # deploys again once the cause is fixed`, + }, + { + name: 'a later deploy overtook this one and is activating', + response: { + version: 7, + activeDeployment: active(6), + latestDeploymentAttempt: attempt(8, 'activating'), + }, + live: 'version 6 serving; version 7 replaced by version 8 (activating)', + next: undefined, + }, + { + name: 'a later deploy overtook this one and is already live', + response: { + version: 7, + activeDeployment: active(8), + latestDeploymentAttempt: attempt(8, 'active'), + }, + live: 'version 8 serving; version 7 replaced by version 8 (active)', + next: undefined, + }, + { + name: 'this attempt is no longer the current one', + response: { + version: 7, + activeDeployment: active(6), + latestDeploymentAttempt: attempt(7, 'activating', undefined, false), + }, + live: 'version 6 serving; version 7 replaced by a later deployment', + next: undefined, + }, + { + name: 'this attempt was superseded', + response: { + version: 7, + activeDeployment: active(6), + latestDeploymentAttempt: attempt(7, 'superseded'), + }, + live: 'version 6 serving; version 7 replaced by a later deployment', + next: undefined, + }, + ])('$name', ({ response, live, next }) => { + const payload = { id: ID, isDeployed: true, warnings: [], ...response } + const shown = withDeploymentLive('deployWorkflow', payload) as Record + expect(Object.keys(shown)[0]).toBe('live') + expect(shown.live).toBe(live) + expect(shown.next).toBe(next) + }) + + it('names a rollback and an activation as what made the version live', () => { + const payload = { + id: ID, + isDeployed: true, + version: 5, + activeDeployment: active(5), + latestDeploymentAttempt: attempt(5, 'active'), + } + expect(withDeploymentLive('rollbackWorkflow', payload)).toMatchObject({ + live: 'version 5, serving (this rollback)', + }) + expect(withDeploymentLive('activateWorkflowVersion', payload)).toMatchObject({ + live: 'version 5, serving (this activation)', + }) + // Only a deploy names itself as the retry of a failure. + const failed = { + ...payload, + activeDeployment: active(6), + latestDeploymentAttempt: attempt(5, 'failed', 'x'), + } + expect(withDeploymentLive('rollbackWorkflow', failed)).not.toHaveProperty('next') + }) +}) + +describe('withDeploymentLive on a deployment status', () => { + it.each([ + { + name: 'nothing is deployed, though needsRedeployment is false', + response: { activeDeployment: null, latestDeploymentAttempt: null, needsRedeployment: false }, + live: 'not deployed', + next: undefined, + }, + { + name: 'the live version is the draft', + response: { + activeDeployment: active(7), + latestDeploymentAttempt: attempt(7, 'active'), + needsRedeployment: false, + }, + live: 'version 7, matches the draft', + next: undefined, + }, + { + name: 'the draft has changed since', + response: { + activeDeployment: active(7), + latestDeploymentAttempt: attempt(7, 'active'), + needsRedeployment: true, + }, + live: 'version 7, draft has undeployed changes', + next: `sim workflows deploy ${ID} # makes the draft live`, + }, + { + name: 'a newer version is activating, which needsRedeployment reports as false', + response: { + activeDeployment: active(6), + latestDeploymentAttempt: attempt(7, 'activating'), + needsRedeployment: false, + }, + live: 'version 6 still serving; version 7 activating', + next: STATUS, + }, + { + name: 'the latest attempt failed', + response: { + activeDeployment: active(6), + latestDeploymentAttempt: attempt(7, 'failed', 'schedule invalid'), + needsRedeployment: true, + }, + live: 'version 6, draft has undeployed changes; version 7 failed: schedule invalid', + next: `sim workflows deploy ${ID} # makes the draft live`, + }, + ])('$name', ({ response, live, next }) => { + const payload = { id: ID, isDeployed: response.activeDeployment !== null, ...response } + const shown = withDeploymentLive('getWorkflowDeployment', payload) as Record + expect(shown.live).toBe(live) + expect(shown.next).toBe(next) + }) + + it('leaves any other operation as it was', () => { + const payload = { id: ID, activeDeployment: null, latestDeploymentAttempt: null } + expect(withDeploymentLive('undeployWorkflow', payload)).toBe(payload) + }) +}) + +describe('liveAgainstDraft', () => { + it.each([ + [null, false, 'not deployed'], + [3, false, 'version 3, matches the draft'], + [3, true, 'version 3, draft has undeployed changes'], + // A server older than `deployedVersion` leaves the version unknown. + [undefined, true, 'draft has undeployed changes'], + [undefined, false, undefined], + ])('live at %s, draft differs %s: %s', (deployedVersion, needsRedeployment, live) => { + expect(liveAgainstDraft(deployedVersion, needsRedeployment)).toBe(live) + }) +}) diff --git a/packages/sim-cli/src/runtime/deployment-live.ts b/packages/sim-cli/src/runtime/deployment-live.ts new file mode 100644 index 00000000000..4be870c72dd --- /dev/null +++ b/packages/sim-cli/src/runtime/deployment-live.ts @@ -0,0 +1,218 @@ +import { isRecordLike, toRecordOrNull } from '@sim/utils/object' +import type { GetWorkflowDeploymentResponse, V2OperationName } from '../generated/v2-api' +import { shellArgument } from './run-next' + +type DeploymentState = Pick< + GetWorkflowDeploymentResponse['data'], + 'activeDeployment' | 'latestDeploymentAttempt' +> +type DeploymentAttempt = NonNullable + +/** What is live, in one line, and the command that follows from it, with why. */ +export interface LiveDeployment { + live: string + next?: { command: string; reason: string } +} + +/** Operations that switch which version is live, and how `live` names the switch. */ +const ACTIVATIONS: Readonly>> = { + deployWorkflow: 'this deploy', + rollbackWorkflow: 'this rollback', + activateWorkflowVersion: 'this activation', +} + +const PENDING: ReadonlySet = new Set(['preparing', 'activating']) + +/** The latest deployment attempt, unless a later one has replaced it. */ +function currentAttempt(state: DeploymentState): DeploymentAttempt | null { + const attempt = state.latestDeploymentAttempt + return attempt && attempt.isCurrent !== false ? attempt : null +} + +/** What serves now, as the clause before what became of another version. */ +function serving(state: DeploymentState, still: boolean): string { + const active = state.activeDeployment + if (!active) return 'not deployed' + return `version ${active.version} ${still ? 'still serving' : 'serving'}` +} + +/** Why `version` failed, as the deployment attempt reported it. */ +function failure(version: number, attempt: DeploymentAttempt): string { + return `version ${version} failed: ${attempt.error?.message ?? 'no reason was given'}` +} + +/** The status read that shows when `version` is live. */ +function whenLive(workflowId: string, version: number): NonNullable { + return { + command: `sim workflows deployment status ${shellArgument(workflowId)}`, + reason: `shows when version ${version} is live`, + } +} + +/** + * What is live after a deploy, rollback or activation of `version`, read only from the response: + * the version that call made live; the one still serving while it activates or after it failed + * (`retry`, when given, is the command that tries again); or, when a later attempt overtook it, + * that attempt. The top-level `version` names the version the call admitted, not the live one, and + * `isDeployed` is true while any version is live, so neither alone says the call took effect. + */ +export function liveAfterActivation( + state: DeploymentState, + workflowId: string, + version: number | undefined, + subject: string, + retry?: string +): LiveDeployment { + const attempt = state.latestDeploymentAttempt + const target = version ?? attempt?.version + if (target === undefined) return { live: serving(state, false) } + if (state.activeDeployment?.version === target) { + return { + live: `version ${target}, serving (${subject})`, + next: { + command: `sim workflows run ${shellArgument(workflowId)}`, + reason: `runs version ${target}, the live deployment; add --input '' for its input, or --manual to run the draft`, + }, + } + } + if (!attempt) { + // No attempt reported: whether the version is on its way is unknown, and the status read says. + return { + live: `${serving(state, true)}; version ${target} not live yet`, + next: whenLive(workflowId, target), + } + } + if (attempt.version !== target) { + return { + live: `${serving(state, false)}; version ${target} replaced by version ${attempt.version} (${attempt.status})`, + } + } + if (attempt.isCurrent === false || attempt.status === 'superseded') { + return { live: `${serving(state, false)}; version ${target} replaced by a later deployment` } + } + if (PENDING.has(attempt.status)) { + return { + live: `${serving(state, true)}; version ${target} activating`, + next: whenLive(workflowId, target), + } + } + if (attempt.status === 'failed') { + return { + live: `${serving(state, true)}; ${failure(target, attempt)}`, + ...(retry + ? { next: { command: retry, reason: 'deploys again once the cause is fixed' } } + : {}), + } + } + return { live: `${serving(state, false)}; version ${target} no longer live` } +} + +/** A live version against the draft. */ +function versionAgainstDraft(version: number, needsRedeployment: boolean): string { + return needsRedeployment + ? `version ${version}, draft has undeployed changes` + : `version ${version}, matches the draft` +} + +/** + * The live version against the draft: `not deployed`, or the version and whether the draft + * matches it. `needsRedeployment` is false when nothing is deployed, so it is read only beside a + * version. A server that reports no `deployedVersion` (one older than the field) leaves the version + * unknown: only a draft known to differ is said, and otherwise nothing. + */ +export function liveAgainstDraft( + deployedVersion: number | null | undefined, + needsRedeployment: boolean +): string | undefined { + if (deployedVersion === null) return 'not deployed' + if (typeof deployedVersion === 'number') { + return versionAgainstDraft(deployedVersion, needsRedeployment) + } + return needsRedeployment ? 'draft has undeployed changes' : undefined +} + +/** + * What a deployment status says is live: the active version and whether the draft matches it, or + * the version still serving while a newer one activates or after it failed. `needsRedeployment` + * is false both when nothing is deployed and while an attempt activates, so neither reads as a + * draft matching what is live. + */ +export function liveDeploymentStatus( + state: DeploymentState & { needsRedeployment: boolean }, + workflowId: string +): LiveDeployment { + const active = state.activeDeployment + const attempt = currentAttempt(state) + if (attempt && PENDING.has(attempt.status) && attempt.version !== active?.version) { + return { + live: `${serving(state, true)}; version ${attempt.version} activating`, + next: whenLive(workflowId, attempt.version), + } + } + const failed = + attempt?.status === 'failed' && attempt.version !== active?.version + ? `; ${failure(attempt.version, attempt)}` + : '' + const live = `${active ? versionAgainstDraft(active.version, state.needsRedeployment) : 'not deployed'}${failed}` + if (!active || !state.needsRedeployment) return { live } + return { + live, + next: { + command: `sim workflows deploy ${shellArgument(workflowId)}`, + reason: 'makes the draft live', + }, + } +} + +/** Whether the draft is what serves: a version is live, none is activating, and the draft matches it. */ +export function draftIsLive(state: DeploymentState & { needsRedeployment: boolean }): boolean { + const attempt = currentAttempt(state) + return ( + state.activeDeployment !== null && + !(attempt && PENDING.has(attempt.status)) && + !state.needsRedeployment + ) +} + +/** A payload's deployment state, when it has the fields a deployment response always carries. */ +function deploymentState(payload: Record): DeploymentState | null { + if (!('activeDeployment' in payload) || !('latestDeploymentAttempt' in payload)) return null + return { + activeDeployment: toRecordOrNull( + payload.activeDeployment + ) as DeploymentState['activeDeployment'], + latestDeploymentAttempt: toRecordOrNull( + payload.latestDeploymentAttempt + ) as DeploymentState['latestDeploymentAttempt'], + } +} + +/** + * A deployment response with `live` first (the first line a person reads) and, when one follows, + * `next` last: for a deploy, rollback or activation, {@link liveAfterActivation}; for the status + * read, {@link liveDeploymentStatus}. Any other payload comes back as it was. + */ +export function withDeploymentLive(operation: V2OperationName, payload: unknown): unknown { + if (!isRecordLike(payload) || typeof payload.id !== 'string') return payload + const subject = ACTIVATIONS[operation] + if (subject === undefined && operation !== 'getWorkflowDeployment') return payload + const state = deploymentState(payload) + if (!state) return payload + const { live, next } = + subject === undefined + ? liveDeploymentStatus( + { ...state, needsRedeployment: payload.needsRedeployment === true }, + payload.id + ) + : liveAfterActivation( + state, + payload.id, + typeof payload.version === 'number' ? payload.version : undefined, + subject, + operation === 'deployWorkflow' + ? `sim workflows deploy ${shellArgument(payload.id)}` + : undefined + ) + // The command, then why as a shell comment: pasted whole, the comment is ignored. + return { live, ...payload, ...(next ? { next: `${next.command} # ${next.reason}` } : {}) } +} diff --git a/packages/sim-cli/src/runtime/result.test.ts b/packages/sim-cli/src/runtime/result.test.ts index 691c6a75277..39b8ad4f7d0 100644 --- a/packages/sim-cli/src/runtime/result.test.ts +++ b/packages/sim-cli/src/runtime/result.test.ts @@ -247,3 +247,62 @@ describe('a truncation the response states inside its payload', () => { expect(JSON.parse(logged.join('\n'))).toEqual(payload) }) }) + +describe('a deploy result read by a person', () => { + const ref = (blockId: string, blockName: string, blockType: string) => ({ + blockId, + blockName, + blockType, + }) + /** A clean report as a real two-block workflow gets it: a source, a sink, no finding. */ + const clean = { + sources: [ref('b-1', 'Start', 'start_trigger')], + sinks: [ref('b-2', 'Agent', 'agent')], + orphanBlocks: [], + emptyOutgoingPorts: [], + invalidBranchPorts: [], + invalidConnectionTargets: [], + fieldIssues: [], + unresolvedReferences: [], + tableFieldIssues: [], + manualRunIssue: null, + notes: [], + } + const deployed = (lint: Record) => ({ + id: 'wf-1', + isDeployed: true, + version: 7, + activeDeployment: { + deploymentVersionId: 'dv-7', + version: 7, + deployedAt: '2026-11-20T00:00:00Z', + }, + latestDeploymentAttempt: null, + warnings: [], + lint, + }) + + it('opens with what is live, and keeps only the lint findings', () => { + const orphan = ref('b-3', 'Stray', 'function') + renderResult( + 'deployWorkflow', + 'text', + deployed({ ...clean, orphanBlocks: [orphan] }), + CLI_CONTRACT.deployWorkflow ?? {} + ) + expect(logged[0]).toBe('live\tversion 7, serving (this deploy)') + expect(logged).toContain(`lint\t${JSON.stringify({ orphanBlocks: [orphan] })}`) + }) + + it('drops a report whose only entries are the graph sources and sinks, and keeps it whole for a machine', () => { + renderResult('deployWorkflow', 'text', deployed(clean), CLI_CONTRACT.deployWorkflow ?? {}) + expect(logged.some((line) => line.startsWith('lint\t'))).toBe(false) + + logged = [] + renderResult('deployWorkflow', 'json', deployed(clean), CLI_CONTRACT.deployWorkflow ?? {}) + expect(JSON.parse(logged.join('\n'))).toMatchObject({ + live: 'version 7, serving (this deploy)', + lint: clean, + }) + }) +}) diff --git a/packages/sim-cli/src/runtime/result.ts b/packages/sim-cli/src/runtime/result.ts index 55dcb39eba4..35bb86e1921 100644 --- a/packages/sim-cli/src/runtime/result.ts +++ b/packages/sim-cli/src/runtime/result.ts @@ -1,3 +1,4 @@ +import { isRecordLike, omit } from '@sim/utils/object' import { writeStderr } from '#sim-cli/output/io' import { styles } from '#sim-cli/output/presentation' import { truncationMetadata } from '#sim-cli/output/truncation' @@ -17,6 +18,7 @@ import { timestamp, } from '../output/render' import { printTraceSpans } from '../output/trace' +import { withDeploymentLive } from './deployment-live' import { withRunNext } from './run-next' /** Result fields holding a command to run, printed whole (a clipped flag would make it wrong). */ @@ -298,6 +300,27 @@ function inferColumns(rows: unknown[], expand?: string): Column[] { })) } +/** Lint report fields that describe the graph's shape rather than report a finding. */ +const LINT_GRAPH_FACTS: ReadonlySet = new Set(['sources', 'sinks']) + +/** + * A record whose `lint` (the workflow lint report a deploy or a graph write returns) keeps only + * its findings, for the human formats: the report lists every category, almost all empty, plus + * every workflow's source and sink blocks, and the one JSON line that made pushed the rest of the + * result off a short terminal or a `| tail`. Without a finding the field is dropped. Machine + * formats keep the report whole, as the API sent it. + */ +function withLintFindingsOnly(data: unknown): unknown { + if (!isRecordLike(data) || !isRecordLike(data.lint)) return data + const findings = Object.entries(data.lint).filter( + ([key, value]) => + !LINT_GRAPH_FACTS.has(key) && value !== null && !(Array.isArray(value) && value.length === 0) + ) + return findings.length > 0 + ? { ...data, lint: Object.fromEntries(findings) } + : omit(data, ['lint']) +} + function unwrapResource(data: unknown): unknown { if (!data || typeof data !== 'object' || Array.isArray(data)) return data const entries = Object.entries(data) @@ -443,7 +466,10 @@ export function renderResult( // matches the OpenAPI shape the docs and the agent reference card are generated from. const data = withRunNext( operation, - format === 'json' || format === 'yaml' ? raw : unwrapResource(raw) + withDeploymentLive( + operation, + format === 'json' || format === 'yaml' ? raw : withLintFindingsOnly(unwrapResource(raw)) + ) ) if (spec.itemsPath) { const items = at(data, spec.itemsPath) diff --git a/packages/sim-cli/src/runtime/run-next.ts b/packages/sim-cli/src/runtime/run-next.ts index 2461d706b76..47e220f81e0 100644 --- a/packages/sim-cli/src/runtime/run-next.ts +++ b/packages/sim-cli/src/runtime/run-next.ts @@ -13,7 +13,8 @@ function issuedId(value: unknown): value is string { const SAFE_ARGUMENT = /^[A-Za-z0-9_.:-]+$/ -function shellArgument(value: string): string { +/** `value` as one shell word: as it is when it needs no quoting, else single-quoted. */ +export function shellArgument(value: string): string { return SAFE_ARGUMENT.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'` }