diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx index 680fbaf6100..54bc539cf76 100644 --- a/apps/docs/content/docs/workflows/code/diagnostics.mdx +++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx @@ -350,6 +350,7 @@ Workspace source reports every workflow code above for the files of `workflows/< | `W_TABLE_COLUMN_RENAMED_IN_USE` | A table column this apply renames is still written, filtered or sorted by its old name in a stored workflow's Table block, which the run then drops. | | `E_WORKFLOW_FILES_MISSING` | A workflow folder sent without its files whose base names no workflow of this workspace. | | `E_WORKFLOW_FOLDER_COPIED` | A workflow folder holding the base of another declared folder's workflow: a copy. | +| `E_WORKFLOW_RENAMED_IN_USE` | A workflow folder this apply renames is still named by its old key in a deployment file or another declared workflow, which would then name no workflow. | | `W_UNDECLARED` | A resource the server holds that the directory does not declare (kept without `--allow-delete`). | | `W_BASE_OTHER_WORKSPACE` | The directory's base was read from another workspace: every resource is created anew. | | `W_PROMOTE_TARGET_DELETED` | A promotion (`apply --to`) keeps deleted a resource the directory declares that the target deleted since the last promotion: the target no longer holds it. | diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index baa318608ea..90c1ac5f049 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -27241,6 +27241,7 @@ "W_TABLE_COLUMN_RENAMED_IN_USE", "E_WORKFLOW_FILES_MISSING", "E_WORKFLOW_FOLDER_COPIED", + "E_WORKFLOW_RENAMED_IN_USE", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", "W_PROMOTE_TARGET_DELETED", @@ -27833,6 +27834,7 @@ "W_TABLE_COLUMN_RENAMED_IN_USE", "E_WORKFLOW_FILES_MISSING", "E_WORKFLOW_FOLDER_COPIED", + "E_WORKFLOW_RENAMED_IN_USE", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", "W_PROMOTE_TARGET_DELETED", @@ -28250,6 +28252,7 @@ "W_TABLE_COLUMN_RENAMED_IN_USE", "E_WORKFLOW_FILES_MISSING", "E_WORKFLOW_FOLDER_COPIED", + "E_WORKFLOW_RENAMED_IN_USE", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", "W_PROMOTE_TARGET_DELETED", @@ -29124,6 +29127,7 @@ "W_TABLE_COLUMN_RENAMED_IN_USE", "E_WORKFLOW_FILES_MISSING", "E_WORKFLOW_FOLDER_COPIED", + "E_WORKFLOW_RENAMED_IN_USE", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", "W_PROMOTE_TARGET_DELETED", @@ -29541,6 +29545,7 @@ "W_TABLE_COLUMN_RENAMED_IN_USE", "E_WORKFLOW_FILES_MISSING", "E_WORKFLOW_FOLDER_COPIED", + "E_WORKFLOW_RENAMED_IN_USE", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", "W_PROMOTE_TARGET_DELETED", diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts index e57fb190a9d..ff5b4337f17 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts @@ -48,7 +48,10 @@ export function withFallback( } } -/** `resources`, falling back to `pending` for a key, id or name it does not resolve. */ +/** + * `resources`, falling back to `pending` for a key, id or name it does not resolve; a resource the + * apply moves to a new key (`moved`) is named by that key first. + */ function withPendingResources( resources: ResourceKeyResolver, pending: readonly PendingResource[] @@ -56,12 +59,20 @@ function withPendingResources( if (pending.length === 0) return resources const byId = (kind: ResourceKind, id: string) => pending.find((entry) => entry.kind === kind && entry.id === id) - return withFallback(resources, { + const resolver = withFallback(resources, { toKey: (kind, id) => byId(kind, id)?.key ?? null, toId: (kind, key) => pending.find((entry) => entry.kind === kind && entry.key === key)?.id ?? null, nameOf: (kind, id) => byId(kind, id)?.name ?? null, }) + const moved = pending.filter((entry) => entry.moved) + if (moved.length === 0) return resolver + return { + ...resolver, + toKey: (kind, id) => + moved.find((entry) => entry.kind === kind && entry.id === id)?.key ?? + resolver.toKey(kind, id), + } } /** diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts index 025ef5ccef6..9eb88b8c038 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts @@ -88,6 +88,11 @@ export interface PendingResource { id: string /** `id` stands in for a resource the apply has yet to create, not one it stores already. */ placeholder?: boolean + /** + * The apply moves the stored resource `id` to `key` (a renamed workflow folder), so source + * names and prints it by `key`, not the key it is stored under. + */ + moved?: boolean /** The name the apply writes it under, which a workflow's stored reference repeats (a skill). */ name?: string /** diff --git a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts index 04134b3fb01..d77ac3192f5 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -344,9 +344,8 @@ export const applyWorkspaceSource = defineAuthorizedWorkspaceUseCase({ Object.assign(result.files, plan.reprint) const base: WorkspaceBaseV1 = { ...plan.base, resources: { ...plan.base.resources } } for (const change of plan.changes) { - if (change.action === 'noop' && change.base) { - base.resources[resourceAddress(change.kind, change.key)] = change.base - } + if (change.action !== 'noop' || change.renamedFrom !== undefined) continue + if (change.base) base.resources[resourceAddress(change.kind, change.key)] = change.base } const applyId = generateId() result.applyId = applyId @@ -354,6 +353,7 @@ export const applyWorkspaceSource = defineAuthorizedWorkspaceUseCase({ writeAll(plan.changes, ctx, plan.staged, lease, base, result) ) await consumeStagedBlobs(stagingScopeOf(principal, context.workspaceId), consumed) + moveUnwrittenWithRenames(base, plan.changes) result.base = base recordWorkspaceSourceApplied(facts, plan.changes, result) logger.info('Applied workspace source', { @@ -404,6 +404,29 @@ async function consumeStagedBlobs(target: StagingScope, consumed: StagedBlob[]): } } +/** + * Moves the base entry of each no-op that follows a workflow rename (an unchanged deployment) to + * the new key, once that rename was written: the base then records the workflow under the new key + * and no longer under the old one. A rename held back or stopped by a failed write moves nothing. + */ +function moveUnwrittenWithRenames(base: WorkspaceBaseV1, changes: readonly PlannedChange[]): void { + for (const change of changes) { + if (change.action !== 'noop' || change.renamedFrom === undefined) continue + const moved = + base.resources[resourceAddress('workflow', change.key)] !== undefined && + base.resources[resourceAddress('workflow', change.renamedFrom)] === undefined + if (!moved) continue + if (change.base) base.resources[resourceAddress(change.kind, change.key)] = change.base + dropRenamedEntry(base, change) + } +} + +/** Drops the base entry under the key `change` moves its resource from (a renamed folder). */ +function dropRenamedEntry(base: WorkspaceBaseV1, change: PlannedChange): void { + if (change.renamedFrom === undefined) return + delete base.resources[resourceAddress(change.kind, change.renamedFrom)] +} + /** * Writes the plan's changes in write order under `lease`, recording each into `base` and * `result`; the first failure stops it and is reported as `result.failed`. Each write reads its @@ -464,6 +487,7 @@ async function writeAll( const address = resourceAddress(change.kind, change.key) if (written.base) base.resources[address] = written.base else delete base.resources[address] + dropRenamedEntry(base, change) } catch (error) { const failure = failureOf(error, change, result.applyId) result.failed = failure.failed diff --git a/apps/sim/lib/workspace-source/application/deployments.integration.ts b/apps/sim/lib/workspace-source/application/deployments.integration.ts index 8312c5588c5..a453f052e23 100644 --- a/apps/sim/lib/workspace-source/application/deployments.integration.ts +++ b/apps/sim/lib/workspace-source/application/deployments.integration.ts @@ -1415,4 +1415,264 @@ describe('workspace source: deployments', () => { } } ) + + describe('a renamed workflow folder', () => { + const CALLER = 'workflows/caller/workflow.ts' + const RUNS_NIGHTLY = `// @sim-sdk 1 +import { childWorkflow, runWorkflow, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Caller', {}, () => { + const start = trigger.start('Start', { inputFormat: {} }) + const run = runWorkflow('Run', { workflowId: childWorkflow('nightly') }) + start.to(run) +}) +` + + /** `files` with `workflows//` moved to `workflows//`, every file kept as it is. */ + function moved(files: Files, from: string, to: string): Files { + return Object.fromEntries( + Object.entries(files).map(([path, text]) => [ + path.replace(`workflows/${from}/`, `workflows/${to}/`), + text, + ]) + ) + } + + /** `files` as the CLI sends them once nothing changed: each workflow folder as its base alone. */ + function asUnchanged(files: Files, workspaceId: string): Files { + const folders = new Map() + const rest: Files = {} + for (const [path, text] of Object.entries(files)) { + const key = /^workflows\/([^/]+)\//.exec(path)?.[1] + if (key === undefined) rest[path] = text + else folders.set(key, { ...folders.get(key), [path]: text }) + } + for (const [key, folder] of folders) + Object.assign(rest, unchangedFiles(key, folder, workspaceId)) + return rest + } + + /** The nightly workflow deployed from source beside a caller that runs it. */ + async function withCaller() { + const deployed = await deployedWorkspace() + const created = await apply( + deployed.workspaceId, + { ...asSent(deployed.files, deployed.workspaceId), [CALLER]: RUNS_NIGHTLY }, + { base: deployed.base } + ) + expect(created.failed).toBeUndefined() + const files: Files = { ...deployed.files, ...created.files } + return { ...deployed, files, base: created.base } + } + + /** The changes a dry run of `files` would write, and its errors: none once the apply converged. */ + async function status(workspaceId: string, files: Files, base: WorkspaceBaseV1) { + const plan = await apply(workspaceId, files, { base, dryRun: true }) + return { + writes: actions(plan.plan.filter((change) => change.action !== 'noop')), + errors: codes(plan.diagnostics), + } + } + + check('moves the key of a workflow whose folder alone is renamed', async () => { + const workspaceId = await workspaces.create({ name: 'Workspace source rename', ownerId }) + const created = await apply(workspaceId, { [WORKFLOW]: NIGHTLY }) + expect(created.failed).toBeUndefined() + const id = await workflowId(workspaceId) + const sent = asUnchanged(moved(created.files, 'nightly', 'evening'), workspaceId) + + const result = await apply(workspaceId, sent, { base: created.base }) + + expect(result.failed).toBeUndefined() + expect( + result.plan + .filter((change) => change.action !== 'noop') + .map(({ kind, key, action, fields }) => [`${action} ${kind}:${key}`, fields]) + ).toEqual([['update workflow:evening', ['key']]]) + expect(result.base.resources['workflow:evening']?.id).toBe(id) + expect(result.base.resources['workflow:evening']?.fingerprint).toBe( + created.base.resources['workflow:nightly']?.fingerprint + ) + expect(result.base.resources['workflow:nightly']).toBeUndefined() + expect(Object.keys((await getAll(workspaceId, ['workflow'])).files)).toContain( + 'workflows/evening/workflow.ts' + ) + expect(await status(workspaceId, sent, result.base)).toEqual({ writes: [], errors: [] }) + }) + + check('never moves the key of a folder copied unchanged beside its original', async () => { + const workspaceId = await workspaces.create({ name: 'Workspace source copy', ownerId }) + const created = await apply(workspaceId, { [WORKFLOW]: NIGHTLY }) + expect(created.failed).toBeUndefined() + const sent = asUnchanged( + { ...created.files, ...moved(created.files, 'nightly', 'evening') }, + workspaceId + ) + + const result = await apply(workspaceId, sent, { base: created.base }) + + expect(result.failed).toBeUndefined() + expect(actions(result.plan.filter((change) => change.action !== 'noop'))).toEqual([]) + expect(Object.keys((await getAll(workspaceId, ['workflow'])).files)).toContain(WORKFLOW) + }) + + check( + 'refuses a folder rename while a deployment file or a caller names the old key, writing nothing', + async () => { + const { workspaceId, id, files, base } = await withCaller() + const draft = await draftFingerprint(id) + const renamedFolder = Object.entries(moved(edited(files), 'nightly', 'evening')).filter( + ([path]) => path.startsWith('workflows/evening/') + ) + const sent: Files = { + ...asUnchanged(moved(files, 'nightly', 'evening'), workspaceId), + ...Object.fromEntries(renamedFolder), + } + + const refused = await refusal(apply(workspaceId, sent, { base })) + + const renamed = refused.diagnostics.filter( + (finding) => finding.code === 'E_WORKFLOW_RENAMED_IN_USE' + ) + expect(renamed.map((finding) => [finding.file, finding.hint])).toEqual([ + [CALLER, "Rename childWorkflow('nightly') to childWorkflow('evening') there."], + [DEPLOYMENT, 'Rename deployments/nightly.ts to deployments/evening.ts.'], + ]) + expect(codes(refused.diagnostics, 'warning')).not.toContain('W_DEPLOYED_DRAFT_CHANGED') + expect(Object.keys((await getAll(workspaceId, ['workflow'])).files)).toContain(WORKFLOW) + expect(await draftFingerprint(id)).toBe(draft) + expect((await deployState(id)).versions).toBe(1) + } + ) + + check( + 'renames a folder with its deployment file and callers, keeping the deployment', + async () => { + const { workspaceId, id, files, base } = await withCaller() + const before = await deployState(id) + const renamed = moved(files, 'nightly', 'evening') + delete renamed[DEPLOYMENT] + const sent: Files = { + ...asUnchanged(renamed, workspaceId), + 'deployments/evening.ts': files[DEPLOYMENT], + [CALLER]: files[CALLER].replace("childWorkflow('nightly')", "childWorkflow('evening')"), + } + + const result = await apply(workspaceId, sent, { base, allowDelete: true }) + + expect(result.failed).toBeUndefined() + expect(actions(result.plan.filter((change) => change.action !== 'noop')).sort()).toEqual([ + 'update workflow:caller', + 'update workflow:evening', + ]) + expect(result.files[CALLER]).toContain("childWorkflow('evening')") + const after = await deployState(id) + expect([after.isDeployed, after.versions, after.schedules]).toEqual([ + true, + before.versions, + before.schedules, + ]) + expect(result.base.resources['deployment:evening']?.id).toBe(id) + expect(result.base.resources['deployment:nightly']).toBeUndefined() + expect(await status(workspaceId, { ...sent, ...result.files }, result.base)).toEqual({ + writes: [], + errors: [], + }) + } + ) + + /** Declares a secret the workspace has no value for, so a workflow reading it is held back. */ + const MISSING_SECRET = { + 'secrets.ts': `// @sim-sdk 1 +import { defineSecrets } from '@sim/workflow-sdk/workspace' + +export default defineSecrets({ + OPENAI_API_KEY: { description: 'Model access' }, +}) +`, + } + const WITH_SECRETS: WorkspaceKind[] = ['secret', 'workflow', 'deployment'] + + /** `text` with its agent reading the missing secret. */ + function readingSecret(text: string): string { + return text + .replace('import { agent, ', 'import { agent, env, ') + .replace( + "model: 'claude-sonnet-4-6',", + "model: 'claude-sonnet-4-6',\n apiKey: env.OPENAI_API_KEY," + ) + } + + check('refuses a key-only move of a locked workflow, writing nothing', async () => { + const workspaceId = await workspaces.create({ name: 'Workspace source locked', ownerId }) + const created = await apply(workspaceId, { [WORKFLOW]: NIGHTLY }) + expect(created.failed).toBeUndefined() + const id = await workflowId(workspaceId) + await db.update(workflow).set({ locked: true }).where(eq(workflow.id, id)) + const sent = asUnchanged(moved(created.files, 'nightly', 'evening'), workspaceId) + + const refused = await refusal(apply(workspaceId, sent, { base: created.base })) + + expect(codes(refused.diagnostics)).toContain('E_APPLY_LOCKED') + expect(Object.keys((await getAll(workspaceId, ['workflow'])).files)).toContain(WORKFLOW) + }) + + check('refuses the rename while a held-back caller still names the old key', async () => { + const { workspaceId, files, base } = await withCaller() + const renamed = moved(files, 'nightly', 'evening') + delete renamed[DEPLOYMENT] + const caller = RUNS_NIGHTLY.replace( + 'import { childWorkflow, runWorkflow, trigger, workflow }', + 'import { agent, childWorkflow, env, runWorkflow, trigger, workflow }' + ).replace( + ' start.to(run)', + " const ask = agent('Ask', {\n model: 'claude-sonnet-4-6',\n apiKey: env.OPENAI_API_KEY,\n messages: [{ role: 'user', content: 'Hi' }],\n })\n start.to(run)\n run.to(ask)" + ) + const sent: Files = { + ...asUnchanged(renamed, workspaceId), + ...MISSING_SECRET, + 'deployments/evening.ts': files[DEPLOYMENT], + [CALLER]: caller, + } + + const refused = await refusal(apply(workspaceId, sent, { base, kinds: WITH_SECRETS })) + + expect( + refused.diagnostics + .filter((finding) => finding.code === 'E_WORKFLOW_RENAMED_IN_USE') + .map((finding) => finding.file) + ).toEqual([CALLER]) + expect(Object.keys((await getAll(workspaceId, ['workflow'])).files)).toContain(WORKFLOW) + }) + + check( + 'keeps the deployment under the old key when the renamed folder is held back', + async () => { + const deployed = await deployedWorkspace(PINNED) + const { workspaceId, base } = deployed + const files: Files = deployed.files + const renamed = moved( + { ...files, [WORKFLOW]: readingSecret(files[WORKFLOW]) }, + 'nightly', + 'evening' + ) + delete renamed[DEPLOYMENT] + const sent: Files = { + ...renamed, + ...MISSING_SECRET, + 'deployments/evening.ts': files[DEPLOYMENT], + } + + const result = await apply(workspaceId, sent, { base, kinds: WITH_SECRETS }) + + expect(result.failed).toBeUndefined() + expect(result.plan.filter((change) => change.held).map(({ key }) => key)).toEqual([ + 'evening', + ]) + expect(result.base.resources['workflow:nightly']).toBeDefined() + expect(result.base.resources['deployment:nightly']).toBeDefined() + expect(result.base.resources['deployment:evening']).toBeUndefined() + } + ) + }) }) diff --git a/apps/sim/lib/workspace-source/application/in-use.ts b/apps/sim/lib/workspace-source/application/in-use.ts index 98b99bb09bc..e1dbe498b31 100644 --- a/apps/sim/lib/workspace-source/application/in-use.ts +++ b/apps/sim/lib/workspace-source/application/in-use.ts @@ -1,17 +1,24 @@ /** - * Stored workflows that still use a resource a plan deletes. The check reads the workflows as the - * server stores them, by resource id, never the text the directory sent: a workflow folder sent - * unchanged carries no files (its codec's `isUnchanged`), so its text names nothing. A deployed - * workflow's live version runs apart from its draft, so the check reads it too. + * Stored workflows that still use a resource a plan deletes, or a workflow it renames. The check + * reads the workflows as the server stores them, by resource id, never the text the directory + * sent: a workflow folder sent unchanged carries no files (its codec's `isUnchanged`), so its text + * names nothing. A deployed workflow's live version runs apart from its draft, so the check reads + * it too. */ import { db } from '@sim/db' import { workflow, workflowBlocks, workflowDeploymentVersion } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { getPostgresErrorCode } from '@sim/utils/errors' +import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' import type { WorkspaceKind } from '@sim/workspace-code' +import { deploymentDeclarationPath } from '@sim/workspace-code/kinds/deployment' +import { workflowFolder } from '@sim/workspace-code/kinds/workflow' import { sql } from 'drizzle-orm' import { kindFinding, refDeletedFinding, where } from '@/lib/workspace-source/application/findings' -import type { PlannedChange } from '@/lib/workspace-source/application/types' +import type { + PlannedChange, + WorkspaceSourceDiagnostic, +} from '@/lib/workspace-source/application/types' const logger = createLogger('WorkspaceSourceInUse') @@ -119,16 +126,21 @@ export async function workflowsUsing( } /** - * `E_APPLY_REFUSED` for a delete of `change`'s resource whose users the scan could not confirm in + * `E_APPLY_REFUSED` for a delete (or a workflow folder rename) of `change`'s resource whose users the scan could not confirm in * time ({@link workflowsUsing} answered `null`): the delete is refused rather than made blind. */ -export function inUseUncheckedFinding(change: Pick) { +export function inUseUncheckedFinding( + change: Pick, + action: 'deleted' | 'renamed' = 'deleted' +) { return kindFinding( change.kind, change.key, 'E_APPLY_REFUSED', - `Could not confirm in time that no stored workflow uses ${where(change.kind, change.key)}, so it is not deleted.`, - { hint: 'Apply again; if it keeps timing out, delete it from the workspace instead.' } + `Could not confirm in time that no stored workflow uses ${where(change.kind, change.key)}, so it is not ${action}.`, + { + hint: `Apply again; if it keeps timing out, ${action === 'deleted' ? 'delete' : 'rename'} it from the workspace instead.`, + } ) } @@ -147,6 +159,18 @@ export function liveVersionsReplaced(changes: readonly PlannedChange[]): Set> +): boolean { + return !change.held && !unchanged.get('workflow')?.has(change.key) && change.refs !== undefined +} + /** * Checks every delete the plan makes against the stored workflows that use the resource. A * workflow the directory declares unchanged (`unchanged` lists the keys of each kind sent without @@ -192,12 +216,7 @@ export async function checkDeletesInUse( if (change.kind !== 'workflow' || change.storedId === undefined) continue if (change.action === 'delete') deletedWorkflows.add(change.storedId) else if (change.decl !== undefined) { - // A folder whose source was evaluated and is written is judged by the references it - // compiled to; one sent unchanged, found equal to its stored workflow without evaluating, - // or held back (not written), by the stored one. - const edited = - !change.held && !unchanged.get('workflow')?.has(change.key) && change.refs !== undefined - declared.set(change.storedId, { key: change.key, edited }) + declared.set(change.storedId, { key: change.key, edited: writesRefs(change, unchanged) }) } } const replacedLive = liveVersionsReplaced(changes) @@ -232,3 +251,88 @@ export async function checkDeletesInUse( ) } } + +/** + * `E_WORKFLOW_RENAMED_IN_USE` on `user` (a deployment file, or a workflow folder) for still naming + * workflow `renamed.renamedFrom`, whose folder this apply renames to `renamed.key`. + */ +function renamedInUseFinding( + user: Pick, + renamed: { key: string; renamedFrom: string } +): WorkspaceSourceDiagnostic { + const deployment = user.kind === 'deployment' + return kindFinding( + user.kind, + user.key, + 'E_WORKFLOW_RENAMED_IN_USE', + `${where(user.kind, user.key)} names workflow "${renamed.renamedFrom}", whose folder this apply renames to ${where('workflow', renamed.key)}.`, + deployment + ? { + hint: `Rename ${deploymentDeclarationPath(renamed.renamedFrom)} to ${deploymentDeclarationPath(renamed.key)}.`, + file: deploymentDeclarationPath(user.key), + } + : { + hint: `Rename childWorkflow('${renamed.renamedFrom}') to childWorkflow('${renamed.key}') there.`, + file: `${workflowFolder(user.key)}/${SOURCE_ENTRY_FILE}`, + } + ) +} + +/** A planned workflow change whose folder this apply renames from `renamedFrom`. */ +type RenamedWorkflow = PlannedChange & { renamedFrom: string; storedId: string } + +/** + * Refuses each workflow folder rename (`renamedFrom`) while the directory still names the workflow + * by its old key: a deployment file or an evaluated folder by the references it compiled to, a + * folder sent unchanged (or found as stored) by its stored workflow, whose text named the workflow + * by that key when it was read. The apply would leave them naming no workflow. A rename whose + * users could not be checked in time is refused too. + */ +export async function checkRenamesInUse( + changes: PlannedChange[], + unchanged: ReadonlyMap>, + workspaceId: string +): Promise { + const renames = changes.filter( + (change): change is RenamedWorkflow => + change.kind === 'workflow' && change.renamedFrom !== undefined && !!change.storedId + ) + if (renames.length === 0) return + const byOldKey = new Map(renames.map((renamed) => [renamed.renamedFrom, renamed])) + // A held user is not written and its errors refuse nothing, so its rename carries the refusal. + // A held folder names the old key both in its refs and as stored: it is reported once. + const reported = new Set() + const refuse = (user: PlannedChange, renamed: RenamedWorkflow) => { + const pair = `${user.kind}:${user.key}>${renamed.key}` + if (reported.has(pair)) return + reported.add(pair) + const carrier = user.held ? renamed : user + carrier.diagnostics.push(renamedInUseFinding(user, renamed)) + } + // Declared folders judged by their stored workflow, whose text names the old key. + const stored = new Map() + for (const change of changes) { + for (const ref of change.refs ?? []) { + const renamed = ref.kind === 'workflow' ? byOldKey.get(ref.key) : undefined + if (renamed) refuse(change, renamed) + } + if (change.kind === 'workflow' && change.storedId && change.decl) { + if (!writesRefs(change, unchanged)) stored.set(change.storedId, change) + } + } + if (stored.size === 0) return + const using = await workflowsUsing( + workspaceId, + renames.map((renamed) => renamed.storedId) + ) + if (using === null) { + for (const change of renames) change.diagnostics.push(inUseUncheckedFinding(change, 'renamed')) + return + } + for (const renamed of renames) { + for (const user of using.get(renamed.storedId) ?? []) { + const folder = stored.get(user.id) + if (user.draft && folder) refuse(folder, renamed) + } + } +} diff --git a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts index 986029a8ae1..ca3765d5d3f 100644 --- a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts @@ -503,6 +503,15 @@ async function planLiveDraft( } } +/** + * Whether this apply's write of a workflow changes its draft: a create, or an update that does + * more than move the workflow's key (a renamed folder). + */ +function editsDraft(change: PlannedChange<'workflow'> | undefined): boolean { + if (change?.action !== 'update') return change?.action === 'create' + return change.renamedFrom === undefined || (change.fields ?? []).some((field) => field !== 'key') +} + /** Plans one declared deployment against the workflow under the same key. */ async function planDeployment( key: string, @@ -540,7 +549,7 @@ async function planDeployment( ) return change } - const draftEdited = workflowChange?.action === 'update' || creating + const draftEdited = editsDraft(workflowChange) const base = ctx.base?.resources[resourceAddress('deployment', key)] const basePasswordEnv = passwordEnvOf(base) const resolved = resolveDeclared({ @@ -863,7 +872,9 @@ export const deploymentAdapter: KindAdapter<'deployment', ListedDeployment> = { return bindStored(ctx, 'workflow', records, { allocate }) }, - async plan(desired, listed, ctx) { + async plan(desired, listedAtLoad, planCtx) { + const renames = workflowRenames(planCtx.planned, desired) + const { listed, ctx } = underRenames(listedAtLoad, planCtx, renames) const stored = await readNeeded(listed, desired, ctx) const changes: DeploymentChange[] = [] for (const [key, decl] of desired) changes.push(await planDeployment(key, decl, stored, ctx)) @@ -889,7 +900,8 @@ export const deploymentAdapter: KindAdapter<'deployment', ListedDeployment> = { refused.message = `${deploymentDeclarationPath(change.key)} is removed; undeploying "${record.name}" stops ${describeStops(counts)}, and needs --allow-delete.` } } - return [...changes, ...undeclared] + const movedFrom = new Map([...renames].map(([from, to]) => [to, from])) + return [...changes, ...undeclared].map((change) => movedWith(change, movedFrom, ctx)) }, async authorize(change, ctx) { @@ -1035,6 +1047,78 @@ export const deploymentAdapter: KindAdapter<'deployment', ListedDeployment> = { }, } +/** + * The workflow keys this apply moves (renamed folders), old key to new. A rename whose old key a + * deployment file still declares is refused for that file (`checkRenamesInUse`), so the + * deployments stay planned under the keys they hold. + */ +function workflowRenames( + planned: readonly PlannedChange[], + desired: ReadonlyMap +): Map { + return new Map( + planned.flatMap((change) => + change.kind === 'workflow' && + change.renamedFrom !== undefined && + !desired.has(change.renamedFrom) + ? [[change.renamedFrom, change.key] as const] + : [] + ) + ) +} + +/** + * The listed deployments and the plan context as they stand once this apply's workflow renames + * move their keys: a renamed workflow's deployment, and its root base entry, are planned under + * the new key. So `deployments/.ts` keeps the deployment as it is, rather than deploying it + * anew while the deployment under the old key is undeployed. + */ +function underRenames( + listed: StoredSet, + ctx: PlanContext, + renames: ReadonlyMap +): { listed: StoredSet; ctx: PlanContext } { + if (renames.size === 0) return { listed, ctx } + const bound = new Map( + [...listed.bound].map(([key, record]) => { + const moved = renames.get(key) ?? key + return [moved, { ...record, key: moved }] as const + }) + ) + if (!ctx.base) return { listed: { bound, unbound: listed.unbound }, ctx } + const resources = { ...ctx.base.resources } + for (const [from, to] of renames) { + const entry = resources[resourceAddress('deployment', from)] + if (!entry) continue + delete resources[resourceAddress('deployment', from)] + resources[resourceAddress('deployment', to)] = entry + } + return { + listed: { bound, unbound: listed.unbound }, + ctx: { ...ctx, base: { ...ctx.base, resources } }, + } +} + +/** + * A deployment change under a renamed workflow's new key (`movedFrom`: new key to old), moved with + * it: the apply drops the base entry under the old key, and a no-op records the entry under the + * new one. + */ +function movedWith( + change: DeploymentChange, + movedFrom: ReadonlyMap, + ctx: PlanContext +): DeploymentChange { + const from = movedFrom.get(change.key) + if (from === undefined) return change + const entry = ctx.base?.resources[resourceAddress('deployment', change.key)] + return { + ...change, + renamedFrom: from, + ...(change.action === 'noop' && !change.base && entry ? { base: entry } : {}), + } +} + /** * The listed deployments a plan reads the settings of: those the directory declares and those the * base records, which a plan may update, adopt or undeploy. The rest stay unread (`null`): the plan @@ -1094,12 +1178,15 @@ export async function warnDeployedDraftChanges( .filter((change) => change.kind === 'deployment' && change.decl) .map((change) => change.key) ) + // A renamed folder whose deployment file still has the old key is refused for that file. const edited = changes.filter( (change) => change.kind === 'workflow' && change.action === 'update' && + editsDraft(change) && change.storedId !== undefined && - !declared.has(change.key) + !declared.has(change.key) && + !(change.renamedFrom !== undefined && declared.has(change.renamedFrom)) ) if (edited.length === 0) return const deployedIds = new Set((await listDeployedWorkflows(ctx)).map((workflow) => workflow.id)) diff --git a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts index d4511b3e614..09de1c64ae4 100644 --- a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts @@ -69,6 +69,7 @@ import { workflowSourceCreate, workflowSourceUpdate, } from '@/lib/workflows/application/source-pipeline' +import { updateWorkflow } from '@/lib/workflows/application/update-workflow' import { countLiveWorkflows, LAST_WORKFLOW_MESSAGE, @@ -88,6 +89,7 @@ import { import { bindStored, claimKey, listUpTo } from '@/lib/workspace-source/application/keys' import { liveTriggerCounts } from '@/lib/workspace-source/application/kinds/deployment/triggers' import type { + AppliedResource, KindAdapter, PlanContext, PlannedChange, @@ -308,6 +310,40 @@ function readLock( } } +/** The declared folders whose base names each workflow of this workspace, by workflow id. */ +function foldersByWorkflow( + desired: ReadonlyMap, + workspaceId: string +): Map { + const keysByWorkflow = new Map() + for (const [key, decl] of desired) { + const base = workflowSourceBase(decl) + if (base?.workspaceId !== workspaceId) continue + keysByWorkflow.set(base.workflowId, [...(keysByWorkflow.get(base.workflowId) ?? []), key]) + } + return keysByWorkflow +} + +/** + * Declared folders renamed since the read, each mapped to the key its workflow is bound under: + * the only folder whose base names a workflow bound under a key the directory no longer declares. + * A folder copied beside its still-declared original, or one of several naming the same workflow, + * moves no key. + */ +function renamedFolders( + desired: ReadonlyMap, + stored: StoredSet, + keysByWorkflow: ReadonlyMap +): Map { + const boundKeys = new Map([...stored.bound].map(([key, workflow]) => [workflow.id, key])) + const renamed = new Map() + for (const [workflowId, keys] of keysByWorkflow) { + const from = boundKeys.get(workflowId) + if (keys.length === 1 && from !== undefined && !desired.has(from)) renamed.set(keys[0], from) + } + return renamed +} + /** * Declared folders sent with their files whose base names the same workflow as another declared * folder's, other than the folder bound to that workflow: copies (`cp -r`), each mapped to the @@ -317,14 +353,8 @@ function readLock( function copiedFolders( desired: ReadonlyMap, stored: StoredSet, - workspaceId: string + keysByWorkflow: ReadonlyMap ): Map { - const keysByWorkflow = new Map() - for (const [key, decl] of desired) { - const base = workflowSourceBase(decl) - if (base?.workspaceId !== workspaceId) continue - keysByWorkflow.set(base.workflowId, [...(keysByWorkflow.get(base.workflowId) ?? []), key]) - } const copies = new Map() for (const [workflowId, keys] of keysByWorkflow) { if (keys.length < 2) continue @@ -366,7 +396,8 @@ function classifyFolder( decl: WorkflowDecl, stored: StoredSet, workspaceId: string, - copiedFrom: string | undefined + copiedFrom: string | undefined, + renamedFrom: string | undefined ): FolderStep { const change: WorkflowChange = { kind: 'workflow', key, action: 'noop', decl, diagnostics: [] } const base = workflowSourceBase(decl) @@ -396,8 +427,11 @@ function classifyFolder( ) return { change } } + if (existing) change.storedId = existing.id + // A folder renamed since the read moves its workflow's key (see `markRenames`). + if (existing && renamedFrom !== undefined) change.renamedFrom = renamedFrom const unchanged = Object.keys(decl.files).length === 0 - if (unchanged && existing) return { change: { ...change, storedId: existing.id } } + if (unchanged && existing) return { change } // The folder's base names a workflow of this workspace the server no longer holds. if (!existing && base?.workspaceId === workspaceId) { change.diagnostics.push(serverGoneFinding('workflow', key, !unchanged)) @@ -545,6 +579,19 @@ function orderCreates(changes: WorkflowChange[]): WorkflowChange[] { return changes.map((change) => (change.action === 'create' ? ordered[next++] : change)) } +/** + * `changes` with each renamed folder's change an update that moves its workflow's key: whatever + * else its folder changes (nothing, for a folder sent unchanged or found as stored), the write + * claims the new key and the apply moves the root base's entry to it. + */ +function markRenames(changes: WorkflowChange[]): WorkflowChange[] { + return changes.map((change) => + change.renamedFrom === undefined + ? change + : { ...change, action: 'update', fields: [...(change.fields ?? []), 'key'] } + ) +} + /** A folder sent with its files whose base names a stored workflow, planned as an update. */ type UpdateStep = Extract @@ -682,6 +729,22 @@ export async function refuseDeletingEveryWorkflow( } } +/** + * The write of a renamed folder that changes nothing else: the workflow stays as stored, and the + * claim after the write binds the new key. Its root base entry is the folder's own base. + */ +function moveKey(change: WorkflowChange): AppliedResource { + const base = change.decl ? workflowSourceBase(change.decl) : undefined + if (change.renamedFrom === undefined || !change.storedId || !base) { + throw new Error('A workflow write needs its plan') + } + return { + id: change.storedId, + base: { id: change.storedId, fingerprint: workflowFingerprint(base) }, + text: {}, + } +} + export const workflowAdapter: KindAdapter<'workflow', StoredWorkflowState> = { codec: workflowCodec, keys: 'every-write', @@ -714,9 +777,11 @@ export const workflowAdapter: KindAdapter<'workflow', StoredWorkflowState> = { async plan(desired, stored, ctx) { const { workspaceId } = ctx.workspace - const copies = copiedFolders(desired, stored, workspaceId) + const keysByWorkflow = foldersByWorkflow(desired, workspaceId) + const copies = copiedFolders(desired, stored, keysByWorkflow) + const renames = renamedFolders(desired, stored, keysByWorkflow) const steps = [...desired].map(([key, decl]) => - classifyFolder(key, decl, stored, workspaceId, copies.get(key)) + classifyFolder(key, decl, stored, workspaceId, copies.get(key), renames.get(key)) ) const planned = new Map() // Every create's id is minted first, so each folder resolves every workflow the apply creates. @@ -725,7 +790,13 @@ export const workflowAdapter: KindAdapter<'workflow', StoredWorkflowState> = { ? [{ step, created: { kind: 'workflow' as const, key: step.change.key, id: generateId() } }] : [] ) - const pending = [...ctx.pending, ...creates.map(({ created }) => created)] + // A renamed folder's workflow resolves under its new key, which the apply claims for it. + const moved = steps.flatMap(({ change }) => + change.renamedFrom !== undefined && change.storedId + ? [{ kind: 'workflow' as const, key: change.key, id: change.storedId, moved: true }] + : [] + ) + const pending = [...ctx.pending, ...creates.map(({ created }) => created), ...moved] ctx.loads.childSources = new Map( [...desired].flatMap(([key, decl]) => Object.keys(decl.files).length > 0 @@ -776,7 +847,9 @@ export const workflowAdapter: KindAdapter<'workflow', StoredWorkflowState> = { planned.set(change.key, change) }) refuseRenamesOntoOneName(updates, renamed, planned, stored, names) - const changes = orderCreates(steps.map((step) => planned.get(step.change.key) ?? step.change)) + const changes = orderCreates( + markRenames(steps.map((step) => planned.get(step.change.key) ?? step.change)) + ) // A delete is stale when the workflow changed on the server since the base recorded it; one // that cannot be read now never matches, so it is refused rather than deleted unseen. A locked // one (or one in a locked folder) is refused here, as the delete would refuse it mid-apply. @@ -842,6 +915,12 @@ export const workflowAdapter: KindAdapter<'workflow', StoredWorkflowState> = { principal, input: { workflowId: change.storedId, ...change.detail.update, files: change.decl.files }, }) + return + } + if (change.renamedFrom !== undefined) { + await updateWorkflow.authorize({ principal, input: { workflowId: change.storedId } }) + // A key-only move runs no update, so it takes the update's lock check (its own or its folder's). + await requireMutableWorkflow(change.storedId) } }, @@ -859,9 +938,8 @@ export const workflowAdapter: KindAdapter<'workflow', StoredWorkflowState> = { } const update = change.detail?.update const planned = change.detail?.planned - if (!planned || (change.action !== 'create' && !update)) { - throw new Error('A workflow write needs its plan') - } + if (!planned) return moveKey(change) + if (change.action !== 'create' && !update) throw new Error('A workflow write needs its plan') const provenance = ctx.provenance ? { provenance: ctx.provenance } : {} // A new folder has no base, so no later apply could adopt a workflow whose create committed // without its key: the create claims it in its own transaction, and a failed claim undoes it. diff --git a/apps/sim/lib/workspace-source/application/plan.ts b/apps/sim/lib/workspace-source/application/plan.ts index 9a65e58c071..33b59ecbad0 100644 --- a/apps/sim/lib/workspace-source/application/plan.ts +++ b/apps/sim/lib/workspace-source/application/plan.ts @@ -34,7 +34,7 @@ import { refHeldFinding, refUnavailableFinding, } from '@/lib/workspace-source/application/findings' -import { checkDeletesInUse } from '@/lib/workspace-source/application/in-use' +import { checkDeletesInUse, checkRenamesInUse } from '@/lib/workspace-source/application/in-use' import { warnDeployedDraftChanges } from '@/lib/workspace-source/application/kinds/deployment/adapter' import { refuseDeletingEveryWorkflow } from '@/lib/workspace-source/application/kinds/workflow/adapter' import { adapterOf } from '@/lib/workspace-source/application/registry' @@ -377,6 +377,7 @@ export async function buildWorkspacePlan( await refuseDeletingEveryWorkflow(changes, workspaceId) await warnDeployedDraftChanges(changes, ctx) await checkDeletesInUse(changes, unchanged, workspaceId) + await checkRenamesInUse(changes, unchanged, workspaceId) for (const kind of APPLY_ORDER) { try { await adapterOf(kind).checkRefs?.(changes, planCtx) diff --git a/apps/sim/lib/workspace-source/application/types.ts b/apps/sim/lib/workspace-source/application/types.ts index 84e189e1f88..3d2fc4a200d 100644 --- a/apps/sim/lib/workspace-source/application/types.ts +++ b/apps/sim/lib/workspace-source/application/types.ts @@ -131,6 +131,11 @@ interface ChangeFields { */ needsBlobs?: string[] storedId?: string + /** + * The key the stored resource is bound under before this apply moves it to `key` (a renamed + * workflow folder, and the deployment of that workflow): the apply drops that key's base entry. + */ + renamedFrom?: string /** * How a later kind's dry run (a workflow naming this resource by key) sees the change before it * is written: set by the kind on a create (a placeholder id), an adopt (the stored id), or a diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index 33f15336798..428ec4435aa 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -191,7 +191,7 @@ Keep \`${WORKSPACE_BASE_FILE}\` and each workflow's \`.sim/\` files as written. - A resource the server holds that this directory never managed is kept, and named in a warning. - Nothing deleted on the server comes back: an unchanged directory leaves it deleted, and an edit of it is refused as stale. - To fork a workflow, copy its folder to a new key and delete the copy's \`.sim/\`: without it the copy is created as a new workflow, while with it the copy still names the original. -- Renaming a workflow folder renames the key, not a delete. A resource a workflow still uses cannot be deleted. +- Renaming a workflow folder renames the key, not a delete; rename its \`deployments/.ts\` and every \`childWorkflow('')\` naming it in the same apply, which is refused while one still names the old key. A resource a workflow still uses cannot be deleted. - A delete cannot be undone by applying an older copy of this directory (a reverted commit): the resource stays deleted, and table rows, knowledge base documents, a workflow's run history and its webhook URLs and schedules are gone. The plan marks each such change and the summary counts them (\`destructive\`); deleting a deployed workflow lists the live webhooks and schedules that stop. ## Git and CI diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 3cbf028dd5a..0ac62af4294 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -1324,6 +1324,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_TABLE_COLUMN_RENAMED_IN_USE' | 'E_WORKFLOW_FILES_MISSING' | 'E_WORKFLOW_FOLDER_COPIED' + | 'E_WORKFLOW_RENAMED_IN_USE' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' | 'W_PROMOTE_TARGET_DELETED' @@ -1622,6 +1623,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_TABLE_COLUMN_RENAMED_IN_USE' | 'E_WORKFLOW_FILES_MISSING' | 'E_WORKFLOW_FOLDER_COPIED' + | 'E_WORKFLOW_RENAMED_IN_USE' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' | 'W_PROMOTE_TARGET_DELETED' @@ -11233,6 +11235,7 @@ export type GetWorkspaceSourceResponse = { | 'W_TABLE_COLUMN_RENAMED_IN_USE' | 'E_WORKFLOW_FILES_MISSING' | 'E_WORKFLOW_FOLDER_COPIED' + | 'E_WORKFLOW_RENAMED_IN_USE' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' | 'W_PROMOTE_TARGET_DELETED' @@ -15033,6 +15036,7 @@ export type PlanWorkspaceSourceResponse = { | 'W_TABLE_COLUMN_RENAMED_IN_USE' | 'E_WORKFLOW_FILES_MISSING' | 'E_WORKFLOW_FOLDER_COPIED' + | 'E_WORKFLOW_RENAMED_IN_USE' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' | 'W_PROMOTE_TARGET_DELETED' @@ -15331,6 +15335,7 @@ export type PlanWorkspaceSourceResponse = { | 'W_TABLE_COLUMN_RENAMED_IN_USE' | 'E_WORKFLOW_FILES_MISSING' | 'E_WORKFLOW_FOLDER_COPIED' + | 'E_WORKFLOW_RENAMED_IN_USE' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' | 'W_PROMOTE_TARGET_DELETED' diff --git a/packages/workspace-code/DESIGN.md b/packages/workspace-code/DESIGN.md index 39e963cfa7a..2e490ca2123 100644 --- a/packages/workspace-code/DESIGN.md +++ b/packages/workspace-code/DESIGN.md @@ -73,7 +73,11 @@ resource, finishing what the write left. A key never changes: a declaration whose file was renamed (the base read the same resource under the old key, which the directory no longer declares) is `E_KEY_RENAMED`, and the resource is not -deleted. A workflow still names a workspace file by its resource key (`file('report-pdf')`), not +deleted. A workflow folder is the exception: its `.sim/base.json` names the workflow, so a renamed +folder moves the workflow's key (`renamedFrom`, an update with `fields: ['key']` even when nothing +else changed), and its deployment's with it. The plan refuses the rename while a deployment file or +a declared workflow still names the old key (`E_WORKFLOW_RENAMED_IN_USE`), and the workflows it +writes print the new key. A workflow still names a workspace file by its resource key (`file('report-pdf')`), not its path: a file an apply creates claims the key a get would first allocate it, so a workflow of the same apply resolves it. diff --git a/packages/workspace-code/src/diagnostics/codes.ts b/packages/workspace-code/src/diagnostics/codes.ts index b0bc94ad38a..b2f89884f0e 100644 --- a/packages/workspace-code/src/diagnostics/codes.ts +++ b/packages/workspace-code/src/diagnostics/codes.ts @@ -273,6 +273,11 @@ const PLAN_CODES = [ 'E_WORKFLOW_FILES_MISSING', /** A workflow folder holding the base of another declared folder's workflow: a copy. */ 'E_WORKFLOW_FOLDER_COPIED', + /** + * A workflow folder this apply renames is still named by its old key in a deployment file or + * another declared workflow, which would then name no workflow. + */ + 'E_WORKFLOW_RENAMED_IN_USE', /** * A resource the server holds that the directory does not declare (kept without * `--allow-delete`).