Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
Workflows Module
Customer-authored automation. A workflow is a graph of nodes (trigger, condition, compute, lookup, filter, action) stored as a versioned definition; the engine in packages/jobs walks it. This module is the ERP front end: the list page, the full-screen builder canvas, versioning and publishing.
The definition schema, validator, catalogs, matcher and engine all live outside this module in packages/workflows and packages/jobs. Read packages/workflows/AGENTS.md before touching anything that imports @carbon/workflows.
Key Domain Concepts
- Workflow — the
workflowrow. CarriesownerIdandpublishedVersionId. That pointer IS the on/off switch: set means the workflow runs that version,NULLmeans it is a draft and nothing fires. There is no separateactiveboolean — it was a second switch for the same idea and was removed (migration20260824163808_workflow-publish-unpublish.sql). Because the pointer names a version rather than carrying a flag, exactly one version can be published at a time by construction. - Version — a
workflowVersionrow holdingnodes,edgesandformatVersion. Numbered, never named. - Canvas state —
workflow.canvasStateJSONB:{ x, y, zoom, panOnScroll }. Per workflow (not per user, not per version), written by$id.canvas.tsxthroughupdateWorkflowCanvasState, restored asdefaultViewport. Node collapse is NOT here —expandedlives on each node in the definition and rides the autosave./save,/canvasand/positionsare all excluded fromshouldRevalidate; revalidating on a canvas write would snap the viewport back to where it was on load, and revalidating on a positions write would remount the builder store mid-drag. - Definition —
{ formatVersion, nodes, edges }, validated byworkflowDefinitionSchemafrom@carbon/workflows.CURRENT_DEFINITION_FORMAT_VERSIONis 3; the SQL column default is a stale 1, so the app always writes the constant explicitly. - Publish — validate → set
publishedVersionId→syncWorkflowTriggers→ wake the scheduler. One route does all four; splitting them leaves a workflow that looks published and never fires. - Unpublish — the inverse and the only off switch:
publishedVersionId = NULL→ the samesyncWorkflowTriggers, which is what deletes the trigger rows and clearsnextRunAt. It takes no boolean, because publishing needs a version id and has to validate first. - The published version is read-only. Editing a published workflow means creating a new version, the same rule released item revisions follow.
Safety
Always
- MUST read a version through
readWorkflowVersion(row)from@carbon/workflows— the only legal read path. On{ ok: false }render the failure and do not mount the canvas; a blank canvas would let an autosave overwrite a definition nobody could see. - MUST call
checkWorkflowVersionLockin every mutating route. The published-version lock is enforced server-side, not only in the UI. The ONE deliberate exception is$id.positions.tsx— node positions carry no behaviour, andupdateWorkflowNodePositionswrites onlyposition, only onto node ids that already exist, so that route cannot change what a workflow does even when called by hand. - MUST write
formatVersion: CURRENT_DEFINITION_FORMAT_VERSIONon every definition write. - MUST scope every query by
companyId. - MUST build version insert/update objects with every key explicitly present — PostgREST writes
NULLfor a present-but-undefinedkey, which would nullnodes/edgespast their'[]'defaults.
Ask First
- Changing who may own a workflow. A workflow runs with its owner's permissions.
- Adding undo. Its absence is a deliberate, recorded decision (recovery is via versions).
Never
- Never write
workflowTriggerEvent,workflow.nextRunAtoreventSystemSubscriptiondirectly.syncWorkflowTriggersis their sole writer, and it is what makes a workflow able to fire at all. - Never let
$id.owner.tsxaccept a submittedownerId. It writes the session user, always. An arbitrary id would let anyone withworkflows_updateborrow someone else's access. - Never derive node output handles from a hand-written list — use
getNodeHandles(node), the same function the validator uses, or the canvas can draw a handle the validator callsUNKNOWN_HANDLE. - Never add a per-kind component or a second per-kind lookup. All six node kinds render through one
WorkflowNodeCard; everything that differs between them is data inui/Builder/nodes/meta.ts, which the palette and the card both read. A new kind is a row inNODE_KIND_METAplus a row innodeTypes— both are exhaustiveRecord<WorkflowNodeType, …>, so missing either fails the build. - Never re-export
@carbon/workflows/labelsthrough the package barrel.msgis a build-time macro; only Vite-built app code may import it.
Validation Commands
pnpm exec turbo run typecheck --filter=erp # the app package is named `erp`, not @carbon/erp
pnpm --filter erp exec vitest run app/modules/workflows/ui/Builder/graph.test.ts
pnpm exec biome check apps/erp/app/modules/workflows apps/erp/app/routes/x+/workflow+ apps/erp/app/routes/x+/workflows+
pnpm --filter @carbon/checks workflow-events # trigger-row drift after a publish/unpublish
Layout
modules/workflows/
├── workflows.models.ts # zod validators
├── workflows.service.ts # building blocks: reads/writes, lock predicate, publish, unpublish
├── workflows.server.ts # service functions: createWorkflow, deleteWorkflow
├── workflows.utils.ts # browser-safe constants (MAX_RUN_STEPS)
├── types.ts # BuilderNode / BuilderEdge React Flow aliases
└── ui/
├── WorkflowsTable.tsx, WorkflowForm.tsx, WorkflowLockModal.tsx,
│ ConfirmUnpublishWorkflow.tsx, WorkflowsUpgradeOverlay.tsx
├── useWorkflowsSubmodules.tsx
└── Builder/ # canvas, store, node cards, palette, versions, issues
Routes split in two trees: x+/workflows+/ (list, create, rename, delete, with the module sidebar) and x+/workflow+/ (the full-screen builder and its POST-only actions, no sidebar).
Key Service Functions
getWorkflows/getWorkflow— list and detail readsgetWorkflowVersions/getWorkflowVersion/getWorkflowVersionNumbers— version reads (flat selects; nested embeds acrossworkflow+workflowVersiontrip TS2589 in this app)insertWorkflow/updateWorkflow— separate rather than oneupsert*insertWorkflowVersion/updateWorkflowDefinition/deleteWorkflowVersionupdateWorkflowOwner— takes the session user, never a submitted idcheckWorkflowVersionLock— the published-version lock; the rule is one equality againstpublishedVersionId, so there is no helper wrapping itupdateWorkflowNodePositions— the positions-only writer behind$id.positions.tsxpublishWorkflowVersion/unpublishWorkflow— both callsyncWorkflowTriggers, which uses Kysely and bypasses RLS; the route'srequirePermissionsis the only authorization gate
Operations (workflows.server.ts)
Each is a defineServiceFn const; the route calls it through carbon(request) (api.workflows.createWorkflow(input)). Neither is published (no @mcp). Every function under Key Service Functions is a building block in workflows.service.ts.
createWorkflow(x+/workflows+/new.tsx) — inserts the workflow (the creator is its owner) and version 1 with one trigger node; the New Workflow modal opens the builder on the returnedid.deleteWorkflow(x+/workflows+/delete.$id.tsx) — deletes the workflow, thensyncAfterWorkflowDeletereconciles the company's event subscriptions.
Both refuse with entitlement when the company's plan has no WORKFLOWS (companyHasFeature), the check the routes' requireFeature used to make.
Builder Notes
- One zustand store per builder instance, vanilla
createStorein a ref behind a context — theDocumentTemplateEditoridiom. React Flow keeps viewport and interaction state. - No undo. Deliberate; recovery is via versions.
- Autosave is a 1s debounce with two modes. An editable version posts the whole definition to
$id.save.tsx; a PUBLISHED version posts positions only, to$id.positions.tsx. The route exportsshouldRevalidatereturning false for both — without it every autosave re-seeds the canvas from server state mid-edit. - The builder store has TWO read-only reasons, not one:
canChangeDefinition(canEdit && !isVersionLocked) gates config, nodes, edges andexpanded;canMoveNodes(canEditalone) gates dragging and auto-arrange. Movement follows PERMISSION, not the lock, so a published workflow can still be tidied. Every store mutator is gated on one of them —updateNodeDatain particular, since every node config form funnels through it. - A draft saves half-filled; only publishing demands completeness.
clauseSchema.rightandlookupMatchSchema.valueare optional andlookupMatchSchema.fieldmay be"", so a node the user is still filling in round-trips throughworkflowDefinitionSchema(and thereforereadWorkflowVersion) instead of failing autosave.validateDefinition's config layer is what reports each gap asINCOMPLETE_CONFIGand blocks publish. Never re-tighten those three fields to make a runtime path simpler — the runtime skips with a reason (compare.ts,lookup.ts) precisely so it does not have to. When/savedoes returnok: false,Autosave.tsxraises the server'serrorstring as a toast and the route logs the zod issues. - Drawn loops are blocked at connection time by
isValidConnection+wouldCreateCycle. The validator'sCYCLEcheck stays as the backstop. - Converging edges are allowed: the engine is a first-arrival OR-join by design.
- The trigger node cannot be deleted —
onNodesChangefilters itsremovechange. - Nodes collapse to a one-line summary via a per-node
expandedflag (store.tssetNodeExpanded), toggled by the card's button and byBuilderControls' collapse/expand-all. There is no zoom threshold. Every kind collapses, includingcondition— a collapsed card drops its port labels and closes the gap between its source handles (NodeCard.tsx), so they stack on the midline and read as one dot. That is what makes a many-path card collapsible: without it, the labels smear and the handles look like separate targets that no longer line up with the paths they came from. - Every node kind has a form in
ui/Builder/config/forms/.NodeFormProps<K>narrowsnode.datato the kind's slice of the shared definition schema — never re-declare a node's data shape in a form. - Ports get their id, label, tone and anchor from
ui/Builder/ports.ts, which derives ids fromgetNodeHandles. Never hand-write a handle list, and never label a port anywhere else —ports.test.tsenforces the first rule. - Every source handle is
ui/Builder/OutputHandle.tsx— there is no bare<Handle type="source">left. It draws the dot, the right-sidePortLabel, and the 2s-hover panel listing what a step wired there could read. Handle appearance (handleClass,PortLabel,PortTone) lives inui/Builder/handles.tsxsoNodeCardandOutputHandledo not import each other. - Outputs are per node, not per handle.
packages/workflows/src/definition/nodes.tsgives each kind anoutputs(node, ctx)— dynamic (a trigger intersects every selected event; an action reads the catalog),undefinedwhen the node is not configured enough to know,{}forcondition, which only routes. The hover panel therefore asksvariablesFromHandle, which hangs a throwaway node off the handle and re-usesavailableVariables; branch reachability and theguaranteedflag stay in one implementation. - Node cards subscribe through
ui/Builder/selectors.ts(scalars) or read once viauseBuilderStoreApi(). Subscribing tostate.nodesre-renders every card on every drag frame.
Value fields
fields/control.tspickControlis the single ordered decision for which control a value renders in —inline(the{editor),chip(an already-picked reference) orliteral(everythingLiteralControldispatches). Order matters:choicesmust disqualify the free-text rule or every enum column loses its dropdown. Add a case there, never anifinValueField.fields/Field.tsxowns the label / required marker / issue shell. No control re-implements it.- Four controls, dispatched in
config/forms/ActionForm.tsxin this order:PairsFieldwhen the catalog input setspairs,MultiChoiceFieldwhenisMultiSelect(input)(choiceson at.listof text — derived, never a declared flag, so it cannot disagree with the type),TemplateFieldwhen it setstemplate,ValueFieldotherwise. Only the last consultspickControl.TemplateFieldis the prose editor — it takes line breaks (multiline,minRows={4}) so a JSON payload reads the way it is written;VariableTextencodes a break as a paragraph and a"\n"in the stored text, so newlines survive the round trip. fields/pairsRows.tsholdsPairsField's row maths and is macro-free by the same rule asvariableMenu.ts— the component pulls in the glossary, which vitest cannot compile. Rows are keyed by position, an emptied set is stored as absent, and per-row errors arrive asrowIssuesForField(issues, …)reading<field>.entries.<n>(partIssuesForFieldreads<field>.parts.<n>; a variable inside a row nests both).fields/multiChoice.tsholdsMultiChoiceField's value round-trip and is macro-free for the same reason aspairsRows.ts. Picks are stored in the order the choices are OFFERED, not clicked (two authors ticking the same channels must produce the same definition, or autosave churns), and an emptied set stores as absent.fields/choiceOptions.tsxis where a choice gets its title, its description and whether it is available — the notify job skips a channel the company has no plan or integration for in SILENCE, so build time is the only place the author can be told.choiceStateowns what renders ticked and what the author may not touch, and the two are NOT the same: a choice inLOCKED(inApp) is ticked and frozen because the platform sends it regardless, while an UNAVAILABLE choice can only never be ADDED — one already stored stays removable, or a node seeded with a channel the company has no plan for is a dead end.CatalogInput.defaultValueis seeded intoinputsbyActionFormwhen the action is picked — nothing reads it at run time, so a required input with a default still reportsMISSING_INPUTon a node saved before the default existed.showWhenis enforced in two places inActionForm: the visible-input list and an early return insiderenderInput, because arequireOneOfmember renders through a path the list never touches. Closing a gate clears the gated input's value in the sameupdateNodeDatacall.{…}is display only. A reference is stored as{ kind: "ref", nodeId, output, path }and binds to the node id; the braces and the label are a rendering of it, so a rename never touches storage.fields/tokenId.tsis the only encoder/decoder andfields/valueParts.tsthe only converter — a token label must come fromrefLabelso an inserted chip and a stored chip read identically (a mismatch trips the editor's remount check and steals focus mid-keystroke).- Serialization rule in
valueParts.ts: plain text stays aliteral, a lone variable stays a bareref, only mixed content becomes atemplate. Templates are legal only where a string is expected (packages/workflows/src/definition/nodes.ts). - Every field reaches variables through the same
{trigger.fields/VariableTreeMenu.tsxis the only menu; it is hosted byfields/InlineVariableMenu.tsx(inside the ProseMirror suggestion popup) andfields/VariableMenuPopover.tsx(a Radix popover, for controls you cannot type a brace into — those renderfields/VariablePickControl.tsxinside their own border).fields/menuNav.tsis the single keyboard implementation and is unit-tested apart from both hosts, so a key can never behave differently in one of them.VariableTreeMenubinds it to a document-level capture-phasekeydownrather than taking keys from its host: delegating through the ProseMirror suggestion plugin (or the popover's search input) is the thing that kept breaking. Focus deliberately stays in the field so search-as-you-type keeps working; the highlighted row isaria-selected, not focused. The listener no-ops when the menu's own root is detached or invisible — the editor popup is hidden, not unmounted, on dismissal, and a menu nobody can see must not eat arrow keys. Escape is never claimed; it belongs to whichever popup is wrapping the menu. - The tiptap popup mounts outside the React tree, so it can reach neither context nor a store hook.
fields/menuBridge.tsbridges it with one module-level slot. Do not replace this with context — context does not reach aReactRenderersubtree. The slot is published on focus (onFocusCaptureinInlineValueEditor), never on mount: every value field mounts an editor, so a mount-time publish hands the slot to whichever one rendered last, and its unmount then blanks the menu for all of them.retractVariableMenuDataonly clears the slot if the caller still holds it. VariableMenuPopoverusesPopoverAnchor, notPopoverTrigger— the control it wraps contains a Select and text inputs, and a trigger toggles the menu on every click that lands in any of them.openis therefore driven only by the field, so the menu's data must be built from an effect onopen, not fromonOpenChange(which never fires for a{}-button or typed-brace open).fields/variableMenu.tsexports both shapes:variableTree(browse, one level at a time) andvariableMenuItems(the flat search index). Search matches the fullStep › output › propertybreadcrumb, so it must keep coming from the flat list, not from the tree.variableMenu.ts,tokenId.tsandmenuNav.tsare macro-free by rule so the vitest runner can compile them — pass labels in as a parameter (labelFor), never importcatalog.tsor the Lingui macro.- Both variable menus read through
useVariablesGetter(computed on demand fromgetState()), neveruseAvailableVariables, which subscribes and re-renders on every drag frame. Reserve the subscribing hook for code that renders from the list. nodes/kinds.tsholds the per-kind facts layout and store code need (NODE_CARD_WIDTH). It exists becausenodes/meta.tsreaches the translation catalog, which the unit-test runner cannot compile — importingmeta.tsfromgraph.tsbreaksgraph.test.ts. Anything macro-free that non-React code needs belongs inkinds.ts; label-bearing presentation stays inmeta.ts, and pure label helpers live inlabelKeys.ts(re-exported bycatalog.tsfor React callers).- Per-field issue messages go through
ui/Builder/issues.tsissueForField, which also matches<field>.parts.<n>so a bad variable inside a template has somewhere to show. Validation still runs server-side on publish only. - Card-level issues (the red border plus the message list under the body) are gated on
selectIsConnected— a node with no edges in either direction shows none of them. An unwired node is a draft parked on the canvas that no run can reach, so flagging it is noise. The node's own form still renders its field errors regardless; only the card chrome is suppressed.
Related
packages/workflows— definition schema, validator, catalogs,syncWorkflowTriggers, pure runtimepackages/jobs/src/workflows/— the matcher, engine and scheduler.claude/rules/workflow-engine.md,.claude/rules/workflow-matcher.md,.claude/rules/workflow-event-catalog.md