diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx index d9bc007f4fc..ef60b85f96a 100644 --- a/apps/docs/content/docs/workflows/code/diagnostics.mdx +++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx @@ -127,9 +127,9 @@ Reading the stored workflow in a get. | Code | Meaning | | --- | --- | | `E_CANON_LEGACY_NAME_COLLISION` | Two stored names normalize alike; the loser is keyed `key~n`. | -| `E_CANON_EDGE_SCOPE` | A stored edge crosses subflow scopes. | | `W_CANON_RESERVED_NAME` | A stored name normalizes to a reserved key. | | `W_CANON_DANGLING_EDGE` | A stored edge to a missing block; dropped. | +| `W_CANON_EDGE_DROPPED` | A stored edge every save drops (to or from a note, into a trigger, or across a loop or parallel boundary); left out of the source, and the next write removes it. | | `W_CANON_DANGLING_PARENT` | A parent that does not exist; the block is placed at the root and the raw parent kept. | | `W_CANON_RAW_HANDLE` | An unknown edge handle, kept as a raw port. | | `W_CANON_UNKNOWN_BLOCK_TYPE` | A type the catalog does not have; params kept. | diff --git a/apps/docs/content/docs/workflows/code/syntax.mdx b/apps/docs/content/docs/workflows/code/syntax.mdx index 132d37f5110..8dfcfa4b0ec 100644 --- a/apps/docs/content/docs/workflows/code/syntax.mdx +++ b/apps/docs/content/docs/workflows/code/syntax.mdx @@ -257,7 +257,7 @@ In a JavaScript file, `$ref.block.path` reads another block's output and `$env.N | `cond.key.to(x)` | one branch of a condition or router | | `container.to(x)` | what runs after the loop or parallel finishes | -Refused: `.to()` on a condition or router itself (`E_NO_DEFAULT_OUTPUT`; wire a branch), a branch that does not exist (`E_UNKNOWN_BRANCH`), an edge into a trigger (`E_TARGET_TRIGGER`), `onError` on a block with no error port (`E_ERROR_PORT_UNSUPPORTED`), an edge to or from a note (`E_EDGE_NOTE`), an edge across loop or parallel scopes (`E_EDGE_SCOPE`), a repeated edge (`E_DUPLICATE_EDGE`) and a cycle (`E_EDGE_CYCLE`). Repeat work with a `loop` instead. +Refused: `.to()` on a condition or router itself (`E_NO_DEFAULT_OUTPUT`; wire a branch), a branch that does not exist (`E_UNKNOWN_BRANCH`), an edge into a trigger (`E_TARGET_TRIGGER`), `onError` on a block with no error port (`E_ERROR_PORT_UNSUPPORTED`), an edge to or from a note (`E_EDGE_NOTE`), an edge across loop or parallel scopes (`E_EDGE_SCOPE`), a repeated edge (`E_DUPLICATE_EDGE`) and a cycle (`E_EDGE_CYCLE`). Repeat work with a `loop` instead. A saved edge into a trigger, to or from a note, or across loop or parallel scopes never appears in `source get`: every save drops it, so the read leaves it out with `W_CANON_EDGE_DROPPED` and the next write removes it. ## Comments diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 77aa3fc0b59..ea1a9ca53f7 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -19929,9 +19929,9 @@ "E_SOURCE_META_DUPLICATE_IDENT", "E_SOURCE_META_ANCHOR", "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", "W_CANON_RESERVED_NAME", "W_CANON_DANGLING_EDGE", + "W_CANON_EDGE_DROPPED", "W_CANON_DANGLING_PARENT", "W_CANON_RAW_HANDLE", "W_CANON_UNKNOWN_BLOCK_TYPE", @@ -20418,9 +20418,9 @@ "E_SOURCE_META_DUPLICATE_IDENT", "E_SOURCE_META_ANCHOR", "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", "W_CANON_RESERVED_NAME", "W_CANON_DANGLING_EDGE", + "W_CANON_EDGE_DROPPED", "W_CANON_DANGLING_PARENT", "W_CANON_RAW_HANDLE", "W_CANON_UNKNOWN_BLOCK_TYPE", @@ -21416,9 +21416,9 @@ "E_SOURCE_META_DUPLICATE_IDENT", "E_SOURCE_META_ANCHOR", "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", "W_CANON_RESERVED_NAME", "W_CANON_DANGLING_EDGE", + "W_CANON_EDGE_DROPPED", "W_CANON_DANGLING_PARENT", "W_CANON_RAW_HANDLE", "W_CANON_UNKNOWN_BLOCK_TYPE", @@ -22390,9 +22390,9 @@ "E_SOURCE_META_DUPLICATE_IDENT", "E_SOURCE_META_ANCHOR", "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", "W_CANON_RESERVED_NAME", "W_CANON_DANGLING_EDGE", + "W_CANON_EDGE_DROPPED", "W_CANON_DANGLING_PARENT", "W_CANON_RAW_HANDLE", "W_CANON_UNKNOWN_BLOCK_TYPE", @@ -23174,9 +23174,9 @@ "E_SOURCE_META_DUPLICATE_IDENT", "E_SOURCE_META_ANCHOR", "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", "W_CANON_RESERVED_NAME", "W_CANON_DANGLING_EDGE", + "W_CANON_EDGE_DROPPED", "W_CANON_DANGLING_PARENT", "W_CANON_RAW_HANDLE", "W_CANON_UNKNOWN_BLOCK_TYPE", @@ -28256,9 +28256,9 @@ "E_SOURCE_META_DUPLICATE_IDENT", "E_SOURCE_META_ANCHOR", "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", "W_CANON_RESERVED_NAME", "W_CANON_DANGLING_EDGE", + "W_CANON_EDGE_DROPPED", "W_CANON_DANGLING_PARENT", "W_CANON_RAW_HANDLE", "W_CANON_UNKNOWN_BLOCK_TYPE", @@ -28851,9 +28851,9 @@ "E_SOURCE_META_DUPLICATE_IDENT", "E_SOURCE_META_ANCHOR", "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", "W_CANON_RESERVED_NAME", "W_CANON_DANGLING_EDGE", + "W_CANON_EDGE_DROPPED", "W_CANON_DANGLING_PARENT", "W_CANON_RAW_HANDLE", "W_CANON_UNKNOWN_BLOCK_TYPE", @@ -29271,9 +29271,9 @@ "E_SOURCE_META_DUPLICATE_IDENT", "E_SOURCE_META_ANCHOR", "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", "W_CANON_RESERVED_NAME", "W_CANON_DANGLING_EDGE", + "W_CANON_EDGE_DROPPED", "W_CANON_DANGLING_PARENT", "W_CANON_RAW_HANDLE", "W_CANON_UNKNOWN_BLOCK_TYPE", @@ -30148,9 +30148,9 @@ "E_SOURCE_META_DUPLICATE_IDENT", "E_SOURCE_META_ANCHOR", "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", "W_CANON_RESERVED_NAME", "W_CANON_DANGLING_EDGE", + "W_CANON_EDGE_DROPPED", "W_CANON_DANGLING_PARENT", "W_CANON_RAW_HANDLE", "W_CANON_UNKNOWN_BLOCK_TYPE", @@ -30568,9 +30568,9 @@ "E_SOURCE_META_DUPLICATE_IDENT", "E_SOURCE_META_ANCHOR", "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", "W_CANON_RESERVED_NAME", "W_CANON_DANGLING_EDGE", + "W_CANON_EDGE_DROPPED", "W_CANON_DANGLING_PARENT", "W_CANON_RAW_HANDLE", "W_CANON_UNKNOWN_BLOCK_TYPE", 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 470220a4a1a..1eff9f545ef 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -3517,3 +3517,141 @@ describe('workflow variables in source', () => { expect(allowed.diff.variables.removed).toEqual(['threshold']) }) }) + +describe('stored edges every save drops', () => { + /** + * Seeds the fixture workflow plus a stored edge from Score into the Start trigger, which every + * save drops (`validateEdges`), with Start locked so a gate that judged the edge's absence as a + * removal would refuse. + */ + async function seedEdgeIntoLockedTrigger() { + const seeded = await seedWorkflow() + const droppedId = generateId() + await db.insert(workflowEdges).values({ + id: droppedId, + workflowId: seeded.workflowId, + sourceBlockId: seeded.scoreId, + targetBlockId: seeded.startId, + sourceHandle: 'source', + targetHandle: 'target', + }) + await db + .update(workflowBlocks) + .set({ updatedAt: new Date(), locked: true }) + .where(eq(workflowBlocks.id, seeded.startId)) + return { ...seeded, droppedId } + } + + async function storedEdgeIds(workflowId: string): Promise { + const rows = await db + .select({ id: workflowEdges.id }) + .from(workflowEdges) + .where(eq(workflowEdges.workflowId, workflowId)) + return rows.map((row) => row.id).sort(compareStrings) + } + + check( + 'get leaves an edge into a trigger out with a warning, and applying it unchanged is a no-op', + async () => { + const seeded = await seedEdgeIntoLockedTrigger() + const source = await getSource(seeded.workflowId) + expect(source.diagnostics.map((d) => d.code)).toContain('W_CANON_EDGE_DROPPED') + const before = await snapshot(seeded.workflowId) + + const result = await apply(source, source.files) + + expect(result.applied).toBe(false) + expect(result.diff.noop).toBe(true) + expect(await snapshot(seeded.workflowId)).toEqual(before) + expect(await storedEdgeIds(seeded.workflowId)).toContain(seeded.droppedId) + } + ) + + check( + 'moving a block out of a loop does not bring back its dropped edge into a locked block', + async () => { + const workflowId = generateId() + const ids = { + start: generateId(), + loop: generateId(), + child: generateId(), + target: generateId(), + dropped: generateId(), + } + const now = new Date() + await db.insert(workflow).values({ + id: workflowId, + userId: ownerId, + workspaceId, + name: `Source apply ${workflowId}`, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const block = (id: string, type: string, name: string, extra: Partial = {}) => + ({ + id, + type, + name, + position: { x: 0, y: 0 }, + subBlocks: {}, + outputs: {}, + enabled: true, + ...extra, + }) as BlockState + const saved = await saveWorkflowToNormalizedTables(workflowId, { + blocks: { + [ids.start]: block(ids.start, 'start_trigger', 'Start'), + [ids.loop]: block(ids.loop, 'loop', 'Repeat', { data: { loopType: 'for', count: 2 } }), + [ids.child]: block(ids.child, 'function', 'Child', { + subBlocks: { code: { id: 'code', type: 'code', value: 'return 1' } }, + data: { parentId: ids.loop, extent: 'parent' }, + }), + [ids.target]: block(ids.target, 'function', 'Target', { + subBlocks: { code: { id: 'code', type: 'code', value: 'return 2' } }, + locked: true, + }), + }, + edges: [ + { id: generateId(), source: ids.start, target: ids.loop }, + { + id: generateId(), + source: ids.loop, + target: ids.child, + sourceHandle: 'loop-start-source', + }, + { id: ids.dropped, source: ids.child, target: ids.target }, + ], + loops: {}, + parallels: {}, + }) + if (!saved.success) throw new Error(`Seeding the workflow failed: ${saved.error}`) + const source = await getSource(workflowId) + expect(source.diagnostics.map((d) => d.code)).toContain('W_CANON_EDGE_DROPPED') + const entry = source.files['workflow.ts'] + const child = entry.match(/^ +const (\w+) = fn\('Child'.*\n/m) + if (!child) throw new Error(`The source declares no Child block:\n${entry}`) + const moved = entry + .replace(child[0], '') + .replace(new RegExp(`^ +\\w+\\.to\\(${child[1]}\\)\\n`, 'm'), '') + .replace(/^}\)\s*$/m, `${child[0].trim()}\n})\n`) + + const result = await apply(source, { ...source.files, 'workflow.ts': moved }) + + expect(result.applied).toBe(true) + expect(await storedEdgeIds(workflowId)).not.toContain(ids.dropped) + } + ) + + check('an apply that writes removes such an edge and counts it as removed', async () => { + const seeded = await seedEdgeIntoLockedTrigger() + const source = await getSource(seeded.workflowId) + + const result = await apply(source, edit(source.files, SCORE_CODE, 'return 7')) + + expect(result.applied).toBe(true) + expect(result.diff.edges).toEqual({ added: 0, removed: 1 }) + expect(result.diagnostics.map((d) => d.code)).toContain('W_CANON_EDGE_DROPPED') + expect(await storedEdgeIds(seeded.workflowId)).toEqual([seeded.edgeId]) + }) +}) diff --git a/apps/sim/lib/workflows/application/source-commit.ts b/apps/sim/lib/workflows/application/source-commit.ts index 11089f3fd39..7ba44ad07a7 100644 --- a/apps/sim/lib/workflows/application/source-commit.ts +++ b/apps/sim/lib/workflows/application/source-commit.ts @@ -55,6 +55,7 @@ import { saveWorkflowToNormalizedTables, } from '@/lib/workflows/persistence/utils' import { parseWorkflowVariables } from '@/lib/workflows/variables/parse' +import { validateEdges } from '@/stores/workflows/workflow/edge-validation' /** What a commit (or a dry run's preview of one) stores, after persistence preparation. */ interface CommittedGraph { @@ -318,8 +319,12 @@ export async function commitSourceReplace(args: ExistingDraftCommit): Promise = new Set([ + 'W_CANON_DANGLING_EDGE', + 'W_CANON_EDGE_DROPPED', +]) + /** * Normalizes the changed values, snapshots MCP tool output schemas, lays out new blocks, lints the * graph, refuses ids of another workspace's resources, and gathers every finding pinned to the @@ -266,7 +272,16 @@ export async function finalizePlan( pending, keyOf: keyOfId, }) + const noop = !isNew && canonicalDiff.noop + // Stored edges a write removes though the source never held them: the ones every save drops. + const writtenEdgeIds = new Set(edges.map((edge) => edge.id)) + const removedBySave = noop + ? [] + : gated.droppedStoredEdges.filter((edge) => !writtenEdgeIds.has(edge.id)) const serverFindings = [ + ...(removedBySave.length > 0 + ? resolved.storedCanonical.diagnostics.filter((d) => DROPPED_EDGE_CODES.has(d.code)) + : []), ...resolved.keptDiagnostics, ...resolved.materializeDiagnostics, ...refusals.sourceRefusals, @@ -287,7 +302,6 @@ export async function finalizePlan( } } - const noop = !isNew && canonicalDiff.noop const mintedIds: Record = {} for (const entry of materialized.entries) { if (entry.status === 'created' && entry.idSource === 'minted') mintedIds[entry.key] = entry.id @@ -300,6 +314,18 @@ export async function finalizePlan( const compiledSource = { hints: compiled.hints, workflow: compiledWorkflow } const lockAfter = boundLock(materialized.identity, lock) + const summary = summarizeDiff( + canonicalDiff, + resolved.storedCanonical, + { workflow: materialized.workflow, identity: materialized.identity }, + noop, + metaChanged + ) + const diff = { + ...summary, + edges: { ...summary.edges, removed: summary.edges.removed + removedBySave.length }, + } + return { plan: { meta, @@ -310,13 +336,7 @@ export async function finalizePlan( storedVariables: variables === undefined ? state.variables : (parseWorkflowVariables(variables) ?? {}), diagnostics, - diff: summarizeDiff( - canonicalDiff, - resolved.storedCanonical, - { workflow: materialized.workflow, identity: materialized.identity }, - noop, - metaChanged - ), + diff, metaChanged, mintedIds, identity: materialized.identity, diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/gates.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/gates.ts index c366da5f9ea..156fdff81d5 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/gates.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/gates.ts @@ -7,11 +7,18 @@ import { diffGraphs, type SourceGraph } from '@/lib/workflows/code/apply/graph-d import { findLiveTriggerRemovals } from '@/lib/workflows/code/apply/live-triggers' import { findLockedBlockRefusals } from '@/lib/workflows/code/apply/locked' import { findInvalidSchedules } from '@/lib/workflows/code/apply/schedules' +import { validateEdges } from '@/stores/workflows/workflow/edge-validation' /** The gates phase's result: the graph diff and every gate's findings. */ export interface GatedGraph { - /** The stored graph. */ + /** + * The stored graph as every save keeps it: without the edges `validateEdges` drops, which the + * source never holds (`W_CANON_DANGLING_EDGE`, `W_CANON_EDGE_DROPPED`), so their absence from + * the materialized graph is no change for a gate to judge. + */ storedGraph: SourceGraph + /** The stored edges every save drops, which `storedGraph` leaves out. */ + droppedStoredEdges: WorkflowState['edges'] graphDiff: ReturnType /** The materialized blocks, with every hosted key a gate drops cleared. */ blocks: Record @@ -33,7 +40,9 @@ export async function gateSourceGraph( const { state } = input.stored const { materialized, keyOf, permissionConfig } = resolved - const storedGraph: SourceGraph = { blocks: state.blocks, edges: state.edges } + const validated = validateEdges(state.edges, state.blocks) + const storedGraph: SourceGraph = { blocks: state.blocks, edges: validated.valid } + const droppedStoredEdges = validated.dropped.map(({ edge }) => edge) let blocks = materialized.state.blocks const edges = materialized.state.edges const graphDiff = diffGraphs(storedGraph, { blocks, edges }) @@ -78,5 +87,5 @@ export async function gateSourceGraph( } } - return { storedGraph, graphDiff, blocks, edges, gateFindings } + return { storedGraph, droppedStoredEdges, graphDiff, blocks, edges, gateFindings } } diff --git a/apps/sim/lib/workflows/code/corpus/generate.ts b/apps/sim/lib/workflows/code/corpus/generate.ts index b9c58dd9601..771520c814b 100644 --- a/apps/sim/lib/workflows/code/corpus/generate.ts +++ b/apps/sim/lib/workflows/code/corpus/generate.ts @@ -17,13 +17,14 @@ * stored text, agent MCP and workflow-as-tool entries, and stored types the registry does not * know (retired and custom blocks), which must still print and compile. * - * {@link generateRejectedCorpus} holds the stored shapes source cannot express: each must fail to - * compile with its named diagnostic instead of round-tripping. + * {@link generateDroppedEdgeCorpus} holds the stored edges every save drops (`validateEdges`): source + * leaves each out, and writing one anew fails to compile with its named diagnostic. * * Deterministic: each case draws from a PRNG seeded by `(seed, case id)`, so the corpus is the * same on every machine and adding a block does not reshuffle the others. */ +import { isTriggerTarget } from '@sim/workflow-code/catalog/view' import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow' import { type BlockFixture, @@ -136,9 +137,11 @@ class CaseBuilder { return block.id } - connect(source: string, target: string, sourceHandle = 'source') { + /** Adds an edge and returns its id. */ + connect(source: string, target: string, sourceHandle = 'source'): string { + const id = this.newId() this.edges.push({ - id: this.newId(), + id, source, target, sourceHandle, @@ -146,6 +149,7 @@ class CaseBuilder { type: 'default', data: {}, }) + return id } build( @@ -245,11 +249,6 @@ function subject( return fixture } -/** Whether nothing may connect into blocks of this config in this mode. */ -function isTriggerOnly(config: BlockConfig, triggerMode: boolean): boolean { - return triggerMode || config.category === 'triggers' -} - function canConnect(config: BlockConfig): boolean { return config.type !== 'note' } @@ -283,7 +282,11 @@ function blockCases(config: BlockConfig, registry: Registry, seed: number): Corp // The Start block is single-instance: a start_trigger subject is the case's only Start. const start = type === 'start_trigger' ? null : startBlock(builder, registry) const { block } = subject(builder, registry, config, options) - if (start && !isTriggerOnly(config, options.triggerMode ?? false) && canConnect(config)) { + if ( + start && + !isTriggerTarget({ type: config.type, triggerMode: options.triggerMode }, config) && + canConnect(config) + ) { builder.connect(start, block.id) } after?.(builder, block.id) @@ -1021,12 +1024,18 @@ function storedShapeCases(registry: Registry, seed: number): CorpusCase[] { ] as const) { const config = at(type) if (!config) continue - const builder = new CaseBuilder(seed, `stored-shapes:${type}:empty-string-branches`) - const start = startBlock(builder, registry) - const { block } = subject(builder, registry, config, { name: 'Decide' }) - builder.connect(start, block.id) - setValue(block, param, '') - cases.push(builder.build('stored-shapes', quirk)) + for (const [detail, value] of [ + ['empty-string-branches', ''], + ['empty-list-branches', []], + ['empty-list-text-branches', '[]'], + ] as const) { + const builder = new CaseBuilder(seed, `stored-shapes:${type}:${detail}`) + const start = startBlock(builder, registry) + const { block } = subject(builder, registry, config, { name: 'Decide' }) + builder.connect(start, block.id) + setValue(block, param, value) + cases.push(builder.build('stored-shapes', quirk)) + } } const pastedSchema = { @@ -1265,32 +1274,80 @@ export function generateReapplyCorpus(options: CorpusOptions = {}): CorpusCase[] }) } -/** A stored shape source cannot express: print and compile must fail with `code`. */ -interface RejectedCase { +/** A stored edge every save drops (`validateEdges`), which source must leave out. */ +interface DroppedEdgeCase { id: string - /** The diagnostic compile must report. */ - code: string + /** The compile error the same edge gets when source writes it anew. */ + code: 'E_EDGE_SCOPE' | 'E_TARGET_TRIGGER' | 'E_EDGE_NOTE' + /** The id of the dropped edge in `state.edges`. */ + edgeId: string state: WorkflowState } /** - * Stored shapes the round trip must reject rather than reproduce. An error edge from a loop child - * to a block outside the loop crosses a subflow scope, which source has no way to write - * (`E_EDGE_SCOPE`). + * One stored edge of each kind a save drops besides a dangling one: an error edge from a loop + * child to a block outside the loop (`E_EDGE_SCOPE`), an edge into the Start trigger and one into + * the legacy starter block (`E_TARGET_TRIGGER`), and an edge out of a note (`E_EDGE_NOTE`). */ -export function generateRejectedCorpus(options: CorpusOptions = {}): RejectedCase[] { +export function generateDroppedEdgeCorpus(options: CorpusOptions = {}): DroppedEdgeCase[] { const seed = options.seed ?? DEFAULT_CORPUS_SEED const { registry } = buildRegistry(options) const fn = registry.byType.get('function') - if (!fn) return [] - const builder = new CaseBuilder(seed, 'reject:loop:child-error-edge-out') - const start = startBlock(builder, registry) - const loop = containerBlock(builder, { kind: 'loop', loopType: 'for' }, 'Loop') - builder.connect(start, loop) - const child = subject(builder, registry, fn, { name: 'Body', parentId: loop }) - builder.connect(loop, child.block.id, 'loop-start-source') - const outside = subject(builder, registry, fn, { name: 'Outside Handler' }) - builder.connect(child.block.id, outside.block.id, 'error') - const { state } = builder.build('subflow') - return [{ id: builder.id, code: 'E_EDGE_SCOPE', state }] + const note = registry.byType.get('note') + const starter = registry.byType.get('starter') + if (!fn || !note || !starter) return [] + const cases: DroppedEdgeCase[] = [] + + const scope = new CaseBuilder(seed, 'dropped:loop:child-error-edge-out') + const loop = containerBlock(scope, { kind: 'loop', loopType: 'for' }, 'Loop') + scope.connect(startBlock(scope, registry), loop) + const child = subject(scope, registry, fn, { name: 'Body', parentId: loop }) + scope.connect(loop, child.block.id, 'loop-start-source') + const outside = subject(scope, registry, fn, { name: 'Outside Handler' }) + const scopeEdge = scope.connect(child.block.id, outside.block.id, 'error') + cases.push({ + id: scope.id, + code: 'E_EDGE_SCOPE', + edgeId: scopeEdge, + state: scope.build('subflow').state, + }) + + const trigger = new CaseBuilder(seed, 'dropped:trigger:edge-into-start') + const start = startBlock(trigger, registry) + const step = subject(trigger, registry, fn, { name: 'Step' }) + trigger.connect(start, step.block.id) + const triggerEdge = trigger.connect(step.block.id, start) + cases.push({ + id: trigger.id, + code: 'E_TARGET_TRIGGER', + edgeId: triggerEdge, + state: trigger.build('shape').state, + }) + + const legacy = new CaseBuilder(seed, 'dropped:trigger:edge-into-legacy-starter') + const legacyStart = subject(legacy, registry, starter, { name: CORPUS_START_NAME }) + const legacyStep = subject(legacy, registry, fn, { name: 'Step' }) + legacy.connect(legacyStart.block.id, legacyStep.block.id) + const legacyEdge = legacy.connect(legacyStep.block.id, legacyStart.block.id) + cases.push({ + id: legacy.id, + code: 'E_TARGET_TRIGGER', + edgeId: legacyEdge, + state: legacy.build('shape').state, + }) + + const annotated = new CaseBuilder(seed, 'dropped:note:edge-out-of-note') + const noteStart = startBlock(annotated, registry) + const noted = subject(annotated, registry, fn, { name: 'Step' }) + annotated.connect(noteStart, noted.block.id) + const memo = subject(annotated, registry, note, { name: 'Memo' }) + const noteEdge = annotated.connect(memo.block.id, noted.block.id) + cases.push({ + id: annotated.id, + code: 'E_EDGE_NOTE', + edgeId: noteEdge, + state: annotated.build('shape').state, + }) + + return cases } diff --git a/apps/sim/lib/workflows/code/corpus/index.ts b/apps/sim/lib/workflows/code/corpus/index.ts index 8b80f4dcb2e..80642714fda 100644 --- a/apps/sim/lib/workflows/code/corpus/index.ts +++ b/apps/sim/lib/workflows/code/corpus/index.ts @@ -2,8 +2,8 @@ export { CORPUS_CRLF_TEXT, type CorpusCase, DEFAULT_CORPUS_SEED, + generateDroppedEdgeCorpus, generateReapplyCorpus, generateRegistryCorpus, - generateRejectedCorpus, } from './generate' export { CORPUS_TEXT, CORPUS_TEXT_MARKERS } from './values' diff --git a/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts b/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts index 214d3625c0f..5a3e9d95fac 100644 --- a/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts +++ b/apps/sim/lib/workflows/code/corpus/roundtrip.corpus.test.ts @@ -33,7 +33,7 @@ import { printWorkflow, } from '@sim/workflow-code' import { registryCatalog as catalog } from '@/lib/workflows/code/catalog/registry-catalog.test-helpers' -import { generateReapplyCorpus, generateRejectedCorpus } from '@/lib/workflows/code/corpus' +import { generateDroppedEdgeCorpus, generateReapplyCorpus } from '@/lib/workflows/code/corpus' import { CORPUS_RESOURCES, caseSubject, @@ -56,6 +56,7 @@ import { import { createMaterializeHooks } from '@/lib/workflows/code/materialize-hooks' import { hasWorkflowChanged } from '@/lib/workflows/comparison/compare' import { Serializer } from '@/serializer' +import { validateEdges } from '@/stores/workflows/workflow/edge-validation' import type { WorkflowState } from '@/stores/workflows/workflow/types' const SUITE = 'roundtrip-corpus' @@ -392,10 +393,62 @@ describe(`round-trip corpus (${subjects.length} workflows)`, () => { corpusBudgetMs(subjects.length, PROPERTY_BUDGET_MS) ) - it.each(generateRejectedCorpus())('rejects $id with $code instead of round-tripping', (c) => { + describe.each(generateDroppedEdgeCorpus())('a stored edge every save drops: $id', (c) => { const subject: ProofSubject = { id: c.id, blockTypes: [], state: c.state } - const codes = sourceRun(subject).compiled.diagnostics.map((d) => d.code) - expect(codes).toContain(c.code) + const kept = { ...c.state, edges: c.state.edges.filter((edge) => edge.id !== c.edgeId) } + + it('is left out of the source with a warning, so an unchanged apply is a no-op', () => { + const read = canonicalize(c.state, { + catalog, + meta: { name: c.id, description: null }, + resources: CORPUS_RESOURCES, + }) + expect(read.diagnostics.map((d) => d.code)).toContain('W_CANON_EDGE_DROPPED') + expect(validateEdges(c.state.edges, c.state.blocks).valid).toEqual(kept.edges) + const run = sourceRun(subject) + expect(assertNoErrors(run.compiled.diagnostics)).toEqual({ ok: true, oracle: 'P4' }) + const compiled = compiledOrThrow(run.compiled) + const written = materialize(compiled, null, { + catalog, + hooks, + prev: c.state, + resources: CORPUS_RESOURCES, + lockFreshness: 'none', + }) + expect( + diffCanonical(run.canonical, { ...written.workflow, meta: run.canonical.meta }, new Map()) + .noop + ).toBe(true) + expect(assertNoopIdentity({ original: kept, materialized: written.state }).ok).toBe(true) + }) + + it('is refused with $code when source writes it anew', () => { + const stored = sourceRun(subject).canonical + const { identity } = canonicalize(c.state, { + catalog, + meta: stored.meta, + resources: CORPUS_RESOURCES, + }) + const keyOf = (id: string) => + Object.entries(identity.blocks).find(([, block]) => block.id === id)?.[0] ?? id + const edge = c.state.edges.find((candidate) => candidate.id === c.edgeId) + if (!edge) throw new Error(`${c.id} has no edge ${c.edgeId}`) + const written: CanonicalWorkflow = { + ...stored, + edges: [ + ...stored.edges, + { + from: keyOf(edge.source), + port: edge.sourceHandle === 'error' ? { kind: 'error' } : { kind: 'out' }, + to: keyOf(edge.target), + }, + ], + } + const codes = compileFiles(printText(written, 'inline'), stored).diagnostics.map( + (d) => d.code + ) + expect(codes).toContain(c.code) + }) }) it('writes the report when a report path is set', () => { diff --git a/apps/sim/lib/workflows/persistence/replace-normalized-state.ts b/apps/sim/lib/workflows/persistence/replace-normalized-state.ts index 83ace1c35e9..e9063187b4e 100644 --- a/apps/sim/lib/workflows/persistence/replace-normalized-state.ts +++ b/apps/sim/lib/workflows/persistence/replace-normalized-state.ts @@ -17,6 +17,7 @@ import { prepareWorkflowStateForPersistence, } from '@/lib/workflows/persistence/prepare-state' import { saveWorkflowToNormalizedTables } from '@/lib/workflows/persistence/utils' +import { validateEdges } from '@/stores/workflows/workflow/edge-validation' import type { BlockState, WorkflowState } from '@/stores/workflows/workflow/types' const logger = createLogger('WorkflowStateReplacement') @@ -330,8 +331,13 @@ export async function replaceWorkflowNormalizedState( throw new Error('Failed to read the stored workflow graph') } const resolved = typeof state === 'function' ? await state(tx, stored) : state - // Block locks are admin-only and this write is not, so the stored lock state wins. - const { blocks, edges } = preserveProtectedWorkflowBlocks(stored, resolved) + // Block locks are admin-only and this write is not, so the stored lock state wins. The merge + // keeps only stored edges a save keeps: one every save drops must not come back because the + // write moved its blocks into one scope. + const { blocks, edges } = preserveProtectedWorkflowBlocks( + { blocks: stored.blocks, edges: validateEdges(stored.edges, stored.blocks).valid }, + resolved + ) const prepared = prepareWorkflowStateForPersistence({ blocks, edges }) preparedState = prepared.state warnings = prepared.warnings diff --git a/apps/sim/stores/workflows/workflow/edge-validation.ts b/apps/sim/stores/workflows/workflow/edge-validation.ts index 32c2450d4b6..b882ec7fa31 100644 --- a/apps/sim/stores/workflows/workflow/edge-validation.ts +++ b/apps/sim/stores/workflows/workflow/edge-validation.ts @@ -1,13 +1,14 @@ import { + getWorkflowEdgeDropKind, getWorkflowEdgeScopeDropReason, - isWorkflowAnnotationOnlyBlockType, + type WorkflowEdgeDropKind, } from '@sim/workflow-types/workflow' import type { Edge } from '@xyflow/react' import { TriggerUtils } from '@/lib/workflows/triggers/triggers' import type { BlockState } from '@/stores/workflows/workflow/types' /** Why an edge was dropped; `scope` is an edge crossing a loop's or parallel's boundary. */ -export type DroppedEdgeKind = 'missing_block' | 'annotation_only' | 'trigger_target' | 'scope' +export type DroppedEdgeKind = WorkflowEdgeDropKind interface DroppedEdge { edge: Edge @@ -20,6 +21,12 @@ export interface EdgeValidationResult { dropped: DroppedEdge[] } +const DROP_REASONS: Record, string> = { + missing_block: 'edge references a missing block', + annotation_only: 'edge references an annotation-only block', + trigger_target: 'trigger blocks cannot be edge targets', +} + export function validateEdges( edges: Edge[], blocks: Record @@ -28,42 +35,16 @@ export function validateEdges( const dropped: DroppedEdge[] = [] for (const edge of edges) { - const sourceBlock = blocks[edge.source] - const targetBlock = blocks[edge.target] - - if (!sourceBlock || !targetBlock) { - dropped.push({ edge, kind: 'missing_block', reason: 'edge references a missing block' }) + const kind = getWorkflowEdgeDropKind(edge, blocks, TriggerUtils.isTriggerBlock) + if (kind === null) { + valid.push(edge) continue } - - if ( - isWorkflowAnnotationOnlyBlockType(sourceBlock.type) || - isWorkflowAnnotationOnlyBlockType(targetBlock.type) - ) { - dropped.push({ - edge, - kind: 'annotation_only', - reason: 'edge references an annotation-only block', - }) - continue - } - - if (TriggerUtils.isTriggerBlock(targetBlock)) { - dropped.push({ - edge, - kind: 'trigger_target', - reason: 'trigger blocks cannot be edge targets', - }) - continue - } - - const scopeDropReason = getWorkflowEdgeScopeDropReason(edge, blocks) - if (scopeDropReason) { - dropped.push({ edge, kind: 'scope', reason: scopeDropReason }) - continue - } - - valid.push(edge) + const reason = + kind === 'scope' + ? (getWorkflowEdgeScopeDropReason(edge, blocks) ?? 'edge crosses a subflow scope') + : DROP_REASONS[kind] + dropped.push({ edge, kind, reason }) } return { valid, dropped } diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 44d4716e06b..f991dd21ad4 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -929,9 +929,9 @@ export type ApplyWorkflowSourceResponse = { | 'E_SOURCE_META_DUPLICATE_IDENT' | 'E_SOURCE_META_ANCHOR' | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' | 'W_CANON_RESERVED_NAME' | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_EDGE_DROPPED' | 'W_CANON_DANGLING_PARENT' | 'W_CANON_RAW_HANDLE' | 'W_CANON_UNKNOWN_BLOCK_TYPE' @@ -1441,9 +1441,9 @@ export type ApplyWorkspaceSourceResponse = { | 'E_SOURCE_META_DUPLICATE_IDENT' | 'E_SOURCE_META_ANCHOR' | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' | 'W_CANON_RESERVED_NAME' | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_EDGE_DROPPED' | 'W_CANON_DANGLING_PARENT' | 'W_CANON_RAW_HANDLE' | 'W_CANON_UNKNOWN_BLOCK_TYPE' @@ -1742,9 +1742,9 @@ export type ApplyWorkspaceSourceResponse = { | 'E_SOURCE_META_DUPLICATE_IDENT' | 'E_SOURCE_META_ANCHOR' | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' | 'W_CANON_RESERVED_NAME' | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_EDGE_DROPPED' | 'W_CANON_DANGLING_PARENT' | 'W_CANON_RAW_HANDLE' | 'W_CANON_UNKNOWN_BLOCK_TYPE' @@ -5424,9 +5424,9 @@ export type CreateWorkflowFromSourceResponse = { | 'E_SOURCE_META_DUPLICATE_IDENT' | 'E_SOURCE_META_ANCHOR' | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' | 'W_CANON_RESERVED_NAME' | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_EDGE_DROPPED' | 'W_CANON_DANGLING_PARENT' | 'W_CANON_RAW_HANDLE' | 'W_CANON_UNKNOWN_BLOCK_TYPE' @@ -10659,9 +10659,9 @@ export type GetWorkflowSourceResponse = { | 'E_SOURCE_META_DUPLICATE_IDENT' | 'E_SOURCE_META_ANCHOR' | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' | 'W_CANON_RESERVED_NAME' | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_EDGE_DROPPED' | 'W_CANON_DANGLING_PARENT' | 'W_CANON_RAW_HANDLE' | 'W_CANON_UNKNOWN_BLOCK_TYPE' @@ -11361,9 +11361,9 @@ export type GetWorkspaceSourceResponse = { | 'E_SOURCE_META_DUPLICATE_IDENT' | 'E_SOURCE_META_ANCHOR' | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' | 'W_CANON_RESERVED_NAME' | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_EDGE_DROPPED' | 'W_CANON_DANGLING_PARENT' | 'W_CANON_RAW_HANDLE' | 'W_CANON_UNKNOWN_BLOCK_TYPE' @@ -14701,9 +14701,9 @@ export type PlanWorkflowSourceResponse = { | 'E_SOURCE_META_DUPLICATE_IDENT' | 'E_SOURCE_META_ANCHOR' | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' | 'W_CANON_RESERVED_NAME' | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_EDGE_DROPPED' | 'W_CANON_DANGLING_PARENT' | 'W_CANON_RAW_HANDLE' | 'W_CANON_UNKNOWN_BLOCK_TYPE' @@ -15167,9 +15167,9 @@ export type PlanWorkspaceSourceResponse = { | 'E_SOURCE_META_DUPLICATE_IDENT' | 'E_SOURCE_META_ANCHOR' | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' | 'W_CANON_RESERVED_NAME' | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_EDGE_DROPPED' | 'W_CANON_DANGLING_PARENT' | 'W_CANON_RAW_HANDLE' | 'W_CANON_UNKNOWN_BLOCK_TYPE' @@ -15468,9 +15468,9 @@ export type PlanWorkspaceSourceResponse = { | 'E_SOURCE_META_DUPLICATE_IDENT' | 'E_SOURCE_META_ANCHOR' | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' | 'W_CANON_RESERVED_NAME' | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_EDGE_DROPPED' | 'W_CANON_DANGLING_PARENT' | 'W_CANON_RAW_HANDLE' | 'W_CANON_UNKNOWN_BLOCK_TYPE' diff --git a/packages/workflow-code/src/canonicalize/edges.ts b/packages/workflow-code/src/canonicalize/edges.ts index 02c9059f448..c9a376d775d 100644 --- a/packages/workflow-code/src/canonicalize/edges.ts +++ b/packages/workflow-code/src/canonicalize/edges.ts @@ -1,13 +1,14 @@ import { compareStrings } from '@sim/utils/string' import { type BlockState, - getWorkflowEdgeScopeDropReason, + getWorkflowEdgeDropKind, normalizeWorkflowEdgeSourceHandle, parseWorkflowSourceHandle, type WorkflowBranchKind, } from '@sim/workflow-types/workflow' import type { Edge } from '@xyflow/react' import { edgeTupleKey, portKey } from '../anchors' +import { catalogBlock, isTriggerTarget } from '../catalog/view' import { diagnostic } from '../diagnostics/factory' import type { BranchKey, CanonicalEdge, Port } from '../model' import type { CanonContext } from './context' @@ -40,13 +41,21 @@ function sourcePort( return key === undefined ? { kind: 'raw', handle: parsed.handle } : { kind: 'branch', key } } +/** How `W_CANON_EDGE_DROPPED` names each kind of edge a save drops between existing blocks. */ +const DROPPED_EDGE_DESCRIPTIONS = { + annotation_only: 'touches a note', + trigger_target: 'goes into a trigger', + scope: 'crosses a loop or parallel boundary', +} as const + /** * Edges by `(from, port, to)`. Handles heal on read * (side-anchored ids and `''` collapse, `normalizeWorkflowEdgeSourceHandle`); `condition-` / * `router-` become branch ports, `-start-source` / `-end-source` subflow ports, and - * anything else a `raw` port with `W_CANON_RAW_HANDLE`. An edge to or from a missing block is - * dropped (`W_CANON_DANGLING_EDGE`); a scope violation is kept and reported as an error - * (`E_CANON_EDGE_SCOPE`). Duplicate tuples collapse to one. + * anything else a `raw` port with `W_CANON_RAW_HANDLE`. The edges every save drops are left out, + * so the model holds what the workflow keeps: one to or from a missing block + * (`W_CANON_DANGLING_EDGE`), and one to or from a note, into a trigger or across a loop or + * parallel boundary (`W_CANON_EDGE_DROPPED`). Duplicate tuples collapse to one. * * Returns the edges sorted plus the ids of blocks an error edge leaves (`errorPort`). */ @@ -60,11 +69,13 @@ export function canonicalEdges( const errorSourceIds = new Set() for (const edge of edges) { - const source = inputs.blocks[edge.source] - const target = inputs.blocks[edge.target] const from = context.keyById.get(edge.source) const to = context.keyById.get(edge.target) - if (!source || !target || from === undefined || to === undefined) { + const dropKind = getWorkflowEdgeDropKind(edge, inputs.blocks, (block) => + isTriggerTarget(block, catalogBlock(context.catalog, block.type)) + ) + const source = inputs.blocks[edge.source] + if (dropKind === 'missing_block' || !source || from === undefined || to === undefined) { context.diagnostics.push( diagnostic( 'W_CANON_DANGLING_EDGE', @@ -76,6 +87,16 @@ export function canonicalEdges( ) continue } + if (dropKind) { + context.diagnostics.push( + diagnostic( + 'W_CANON_EDGE_DROPPED', + `Edge ${from} -> ${to} ${DROPPED_EDGE_DESCRIPTIONS[dropKind]}; every save drops such an edge, so the source leaves it out`, + { blockKey: from } + ) + ) + continue + } const handle = normalizeWorkflowEdgeSourceHandle(edge.sourceHandle) const port = sourcePort(handle, source, edge.source, inputs) @@ -94,15 +115,6 @@ export function canonicalEdges( ) ) } - const scopeProblem = getWorkflowEdgeScopeDropReason(edge, inputs.blocks) - if (scopeProblem) { - context.diagnostics.push( - diagnostic('E_CANON_EDGE_SCOPE', `Edge ${from} -> ${to}: ${scopeProblem}`, { - blockKey: from, - }) - ) - } - result.push({ from, port, to }) } diff --git a/packages/workflow-code/src/canonicalize/index.test.ts b/packages/workflow-code/src/canonicalize/index.test.ts index 95795ade1dd..9a8687399d8 100644 --- a/packages/workflow-code/src/canonicalize/index.test.ts +++ b/packages/workflow-code/src/canonicalize/index.test.ts @@ -1148,7 +1148,7 @@ describe('canonicalize: edges', () => { expect(onlyBlock(result, 'a').errorPort).toBe(false) }) - it('keeps unknown handles as raw ports, drops dangling edges and reports scope violations', () => { + it('keeps unknown handles as raw ports and drops dangling and scope-crossing edges', () => { const result = run( workflow( [ @@ -1189,30 +1189,59 @@ describe('canonicalize: edges', () => { to: 'c', }) expect(codes(result)).toEqual( - expect.arrayContaining(['W_CANON_RAW_HANDLE', 'W_CANON_DANGLING_EDGE', 'E_CANON_EDGE_SCOPE']) + expect.arrayContaining([ + 'W_CANON_RAW_HANDLE', + 'W_CANON_DANGLING_EDGE', + 'W_CANON_EDGE_DROPPED', + ]) ) expect(result.workflow.edges.some((edge) => edge.to === 'ghost')).toBe(false) + expect(result.workflow.edges.some((edge) => edge.from === 'a' && edge.to === 'inside')).toBe( + false + ) }) - it('reports a duplicated stored edge once', () => { + it('leaves out every edge a save drops, and the error port only such an edge wired', () => { const result = run( workflow( [ ...blocks, + blockState('s', 'start_trigger', 'Start'), + blockState('legacy', 'starter', 'Starter'), + blockState('t', 'function', 'Toggled', {}, { triggerMode: true }), + blockState('n', 'note', 'Note'), blockState('l1', 'loop', 'Loop 1', {}, { data: { loopType: 'for', count: 3 } }), blockState('in', 'function', 'In', {}, { data: { parentId: 'l1', extent: 'parent' } }), ], { edges: [ - { id: 'e1', source: 'f1', target: 'in', sourceHandle: 'legacy-handle' }, - { id: 'e2', source: 'f1', target: 'in', sourceHandle: 'legacy-handle' }, + { id: 'keep', source: 's', target: 'f1', sourceHandle: 'source' }, + { id: 'trigger', source: 'f1', target: 's', sourceHandle: 'source' }, + { id: 'starter', source: 'f1', target: 'legacy', sourceHandle: 'source' }, + { id: 'mode', source: 'f1', target: 't', sourceHandle: 'source' }, + { id: 'noteIn', source: 'f1', target: 'n', sourceHandle: 'source' }, + { id: 'noteOut', source: 'n', target: 'f2', sourceHandle: 'source' }, + { id: 'scope', source: 'in', target: 'f3', sourceHandle: 'error' }, ], } ) ) + expect(result.workflow.edges).toEqual([{ from: 'start', port: { kind: 'out' }, to: 'a' }]) + expect(codes(result).filter((code) => code === 'W_CANON_EDGE_DROPPED')).toHaveLength(6) + expect(onlyBlock(result, 'in').errorPort).toBe(false) + }) + + it('reports a duplicated stored edge once', () => { + const result = run( + workflow(blocks, { + edges: [ + { id: 'e1', source: 'f1', target: 'f2', sourceHandle: 'legacy-handle' }, + { id: 'e2', source: 'f1', target: 'f2', sourceHandle: 'legacy-handle' }, + ], + }) + ) expect(result.workflow.edges).toHaveLength(1) expect(codes(result).filter((code) => code === 'W_CANON_RAW_HANDLE')).toHaveLength(1) - expect(codes(result).filter((code) => code === 'E_CANON_EDGE_SCOPE')).toHaveLength(1) }) }) diff --git a/packages/workflow-code/src/catalog/view.ts b/packages/workflow-code/src/catalog/view.ts index fffd32908fc..1e5e52f7c4c 100644 --- a/packages/workflow-code/src/catalog/view.ts +++ b/packages/workflow-code/src/catalog/view.ts @@ -9,6 +9,7 @@ */ import { isRecordLike } from '@sim/utils/object' +import { isKnownWorkflowTriggerBlock } from '@sim/workflow-types/workflow' import { getOwn, setOwn } from '../records' import type { BlockCatalog, @@ -186,6 +187,18 @@ export function catalogBlock(catalog: BlockCatalog, type: string): CatalogBlock return Object.hasOwn(catalog.blocks, type) ? memoBlock(catalog, type) : undefined } +/** + * Whether a block is a trigger nothing may connect into, as persistence decides it + * (`validateEdges` through `TriggerUtils.isTriggerBlock`): trigger mode on, the legacy starter, or a + * `triggers`-category type. `declared` is the block's catalog entry. + */ +export function isTriggerTarget( + block: { type: string; triggerMode?: boolean }, + declared: Pick | undefined +): boolean { + return isKnownWorkflowTriggerBlock(block) || declared?.category === 'triggers' +} + /** The memoized expansion of a block type the catalog serves (an own key of `blocks`). */ function memoBlock(catalog: BlockCatalog, type: string): CatalogBlock { const memo = memoOf(catalog) diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index 3d1a7fb1a29..490e190c825 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -367,7 +367,9 @@ stored handle and compiles with `W_SUBFLOW_HANDLE_SCOPE`. Refused: `.to()` on a condition or router (`E_NO_DEFAULT_OUTPUT`), an unknown branch (`E_UNKNOWN_BRANCH`), an edge into a trigger (`E_TARGET_TRIGGER`), `onError` on a block with no error port (`E_ERROR_PORT_UNSUPPORTED`), an edge to or from a note (`E_EDGE_NOTE`), an edge across -subflow scopes (`E_EDGE_SCOPE`) and a repeated edge (`E_DUPLICATE_EDGE`). +subflow scopes (`E_EDGE_SCOPE`) and a repeated edge (`E_DUPLICATE_EDGE`). A stored edge into a +trigger, to or from a note, or across subflow scopes never prints: every save drops it, so +`source get` leaves it out with `W_CANON_EDGE_DROPPED` and the next write removes it. ## Comments @@ -504,9 +506,9 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | Code | Meaning | |---|---| | `E_CANON_LEGACY_NAME_COLLISION` | Two stored names normalize alike; the loser is keyed `key~n`. | -| `E_CANON_EDGE_SCOPE` | A stored edge crosses subflow scopes. | | `W_CANON_RESERVED_NAME` | A stored name normalizes to a reserved key. | | `W_CANON_DANGLING_EDGE` | A stored edge to a missing block; dropped. | +| `W_CANON_EDGE_DROPPED` | A stored edge every save drops (to or from a note, into a trigger, or across a loop or parallel boundary); left out of the source, and the next write removes it. | | `W_CANON_DANGLING_PARENT` | A parent that does not exist; the block is placed at the root and the raw parent kept. | | `W_CANON_RAW_HANDLE` | An unknown edge handle, kept as a raw port. | | `W_CANON_UNKNOWN_BLOCK_TYPE` | A type the catalog does not have; params kept. | diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index a210e0a2ced..f212ac669a4 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -1300,6 +1300,11 @@ function compileBlockBranches( ), } } + // Source writes a stored empty list and a never-persisted list alike (no entries), so an + // unchanged print keeps the stored empty list instead of overwriting it with `null`. + if (branches?.rows === null && storedBlockOf(ctx, state.decl)?.branches?.rows?.length === 0) { + branches = { kind: branches.kind, rows: [] } + } if (branches) { applyBranchMeta(ctx, branches.rows, state.meta.branches, state.site) } else if (state.meta.branches[0]) { diff --git a/packages/workflow-code/src/compile/edges.ts b/packages/workflow-code/src/compile/edges.ts index 9988523fb4f..e86b4cf3281 100644 --- a/packages/workflow-code/src/compile/edges.ts +++ b/packages/workflow-code/src/compile/edges.ts @@ -6,7 +6,7 @@ import { } from '@sim/workflow-types/workflow' import { edgeTupleKey, portKey } from '../anchors' import { literalText } from '../babel' -import { catalogBlock } from '../catalog/view' +import { catalogBlock, isTriggerTarget } from '../catalog/view' import type { AnchorKey, BlockKey, @@ -129,7 +129,7 @@ export class EdgeCollector { }) return false } - if (target.triggerMode || targetCatalog?.graph.canBeTarget === false) { + if (isTriggerTarget(target, targetCatalog) || targetCatalog?.graph.canBeTarget === false) { this.error( 'E_TARGET_TRIGGER', `${to.name} is a trigger; nothing can connect into it.`, diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index 4d7aefa0c6b..817c2bcc0ba 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -409,12 +409,15 @@ export type SourceMetaDiagnosticCode = (typeof SOURCE_META_DIAGNOSTIC_CODES)[num const CANONICALIZE_DIAGNOSTIC_CODES = [ /** Two stored names normalize to one key; the loser is keyed `key~n`. */ 'E_CANON_LEGACY_NAME_COLLISION', - /** A stored edge crosses subflow scopes (`getWorkflowEdgeScopeDropReason`). */ - 'E_CANON_EDGE_SCOPE', /** A stored block name normalizes to a reserved prefix (`loop`, `parallel`, `variable`). */ 'W_CANON_RESERVED_NAME', /** An edge whose source or target block does not exist; dropped. */ 'W_CANON_DANGLING_EDGE', + /** + * An edge every save drops (`validateEdges`): to or from a note, into a trigger, or across a + * loop or parallel boundary. Left out of the model; the next write removes it. + */ + 'W_CANON_EDGE_DROPPED', /** * A block whose `data.parentId` names no stored block. It is placed at the root and the raw * `parentId` is kept under `extra`, so nothing is lost. diff --git a/packages/workflow-types/src/workflow.ts b/packages/workflow-types/src/workflow.ts index 027c343a5df..9aeb43d83cc 100644 --- a/packages/workflow-types/src/workflow.ts +++ b/packages/workflow-types/src/workflow.ts @@ -678,6 +678,33 @@ export function getWorkflowEdgeScopeDropReason( return `blocks are in different scopes (${sourceParent ?? 'root'} -> ${targetParent ?? 'root'})` } +/** Why every save drops a stored edge; `scope` is an edge crossing a loop's or parallel's boundary. */ +export type WorkflowEdgeDropKind = 'missing_block' | 'annotation_only' | 'trigger_target' | 'scope' + +/** + * The rule every save applies to a stored edge, in order: an edge to or from a missing block, to + * or from a note, into a trigger, or across loop or parallel scopes is dropped. `isTriggerTarget` + * decides the trigger rule, since a block's `triggers` category lives in the block registry (see + * {@link isKnownWorkflowTriggerBlock}). Returns `null` for an edge a save keeps. + */ +export function getWorkflowEdgeDropKind( + edge: WorkflowEdgeEndpoints, + blocks: Record, + isTriggerTarget: (block: B) => boolean +): WorkflowEdgeDropKind | null { + const source = blocks[edge.source] + const target = blocks[edge.target] + if (!source || !target) return 'missing_block' + if ( + isWorkflowAnnotationOnlyBlockType(source.type) || + isWorkflowAnnotationOnlyBlockType(target.type) + ) { + return 'annotation_only' + } + if (isTriggerTarget(target)) return 'trigger_target' + return getWorkflowEdgeScopeDropReason(edge, blocks) === null ? null : 'scope' +} + /** True when a block's type is the annotation-only "note" block, which cannot participate in edges. */ export function isWorkflowAnnotationOnlyBlockType(blockType: string | undefined): boolean { return blockType === WORKFLOW_ANNOTATION_ONLY_BLOCK_TYPE