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 foundation (phase 1) — implementation plan
Spec / source: .ai/specs/2026-07-30-workflows-foundation.md (approved 2026-07-30)
Branch: feat/automation
Phase doc: /Users/aashu/work/carbon/plans/automations-engine/phases/phase-1-foundation.md
The spec contains the full SQL and the full TypeScript contract. Where a task says "copy from spec §X", copy the fenced code block in that section of the spec verbatim — the spec is the single source of truth; this plan only sequences and verifies it.
Verified against this repo before planning: pnpm db:migrate / pnpm run generate:types exist as
root scripts; package test script convention is "test": "vitest run", typecheck is "tsgo --noEmit", vitest config is a one-line re-export of @carbon/config/vitest (which sets
include: ["src/**/*.test.ts"]); pnpm-workspace.yaml already globs packages/* so no workspace
file edit is needed; catalog pins zod: 3.25.76; newest migration on this branch is
20260727183030_model-original-path.sql; local Postgres is postgresql://postgres:postgres@localhost:54322/postgres.
Progress
- Task 1: Write the migration file
- Task 2: Apply the migration and regenerate DB types
- Task 3: Verify schema behavior with psql
- Task 4: Scaffold
packages/workflows - Task 5: Value/schedule types and node/edge/definition schemas + tests
- Task 6: Normaliser and catalog interface + tests
- Task 7: Validator — structural checks + tests
- Task 8: Validator — reference, type and catalog checks + tests
- Task 9: Barrel, AGENTS.md, and consumer dependency wiring
- Task 10: Full verification sweep
Execution notes (2026-07-30)
Deviations and findings, recorded because later phases inherit them:
- This worktree had never been provisioned. No
node_modules, and@carbon/confighad nodist/, sosupabasecould not spawn (exit undefined, no SQL error) and vitest could not resolve its config. Fixed withpnpm installpluspnpm --filter @carbon/config build. Nothing to do with the migration. - Real bug found by Task 3's verification. The spec's
FOREIGN KEY ("activeVersionId", "companyId") ... ON DELETE SET NULLnulls both referencing columns, so deleting the active version failed withnull value in column "companyId" ... violates not-null constraintinstead of clearing the pointer. Fixed in the migration with the Postgres 15 column-list form,ON DELETE SET NULL ("activeVersionId"), verified against the live database. The migration file was edited in place (it is new, uncommitted, and had only ever reached this local database) and the constraint was replaced on the local database so file and schema agree. The spec's SQL in §3 should be corrected to match. - Layers 5 and 6 of the validator skip a node whose catalog entry is missing. Required to
satisfy the acceptance criterion "returns exactly one
UNKNOWN_ACTION" — otherwise an unknown action also producesMISSING_INPUTfor each of its inputs. Documented inpackages/workflows/AGENTS.md. - Time zones are validated with
new Intl.DateTimeFormat(...)in a try/catch, notIntl.supportedValuesOf("timeZone")— same check, no dependency on that newer API. - Issue messages are plain English, not wrapped in the Lingui macro.
@carbon/workflowsdeliberately depends only onzod; phase 8 translates at the render site. EMPTY_DEFINITIONis accompanied by anemptyDefinition()factory, andtoWorkflowDefinitionreturns a fresh object, so no caller can mutate shared state.- Two extras beyond the spec, both small and used by later phases: a duplicate-node-id check
(reported as
MALFORMED_DEFINITION) and an exportedOPERATORS_BY_TYPE/operatorsForTypetable so phase 8's clause editor offers only operators that fit the left-hand type. - Not verified: authenticated-role RLS behaviour (no JWT-scoped psql harness in this repo). Evidence at this layer is the policy matrix — 13 policies, exactly as intended — plus RLS enabled on all five tables.
Dependencies
- Tasks 1 → 2 → 3 strictly sequential (DB track).
- Tasks 4 → 5 → 6 → 7 → 8 → 9 sequential (package track).
- The two tracks are fully independent of each other — the package never imports generated DB types
(rows enter as
unknown). They may run as parallel subagents. - Task 10 needs everything.
Task 1: Write the migration file
Depends on: none Files:
- Create:
packages/database/supabase/migrations/20260730142317_workflows-foundation.sql - Copy from (precedent):
packages/database/supabase/migrations/20260326000000_print-manager.sql(lines 1–31, the module/permission block; also the run-log CHECK-constraint style)
Steps:
- Create the file with Write (do not use
pnpm db:migrate:new— the spec fixes the exact filename). If any migration newer than20260730142317exists inpackages/database/supabase/migrations/at execution time, STOP and report — the timestamp must stay newest. - Assemble the file from the spec's fenced SQL blocks, in this exact order:
- §Data Model Changes 1 —
Workflowsmodule enum +COMMIT+modulesview rebuild +employeeTypePermission/userPermissionseeding. - §2 —
CREATE TABLE "workflow". - §3 —
CREATE TABLE "workflowVersion"+ theALTER TABLE "workflow" ... "workflow_activeVersionId_fkey"block. - §4 —
CREATE TABLE "workflowTriggerEvent"+ its dispatch index. - §5 —
CREATE TABLE "workflowRun". - §6 —
CREATE TABLE "workflowStepRun". - §7 — all indexes.
- §8 — RLS: enable + four policies (
SELECT/INSERT/UPDATE/DELETE) onworkflowand the same four onworkflowVersion; onworkflowTriggerEventonly SELECT (workflows_view), INSERT and DELETE (bothworkflows_update); onworkflowRunandworkflowStepRunonly SELECT (workflows_view). Use the exact policy form from the spec's §8 block —get_companies_with_employee_permission('<key>')cast::text[]. Never usehas_role/has_company_permission. - §9 — the idempotent
DO $$realtime-publication block forworkflowRun, and the same block again withworkflowStepRun.
- §Data Model Changes 1 —
- Mid-file
COMMITafter the enumALTER TYPEis required and intentional (new enum values are unusable in the transaction that adds them) — do not "fix" it.
Verify:
ls packages/database/supabase/migrations/ | tail -1
# Expected: 20260730142317_workflows-foundation.sql
grep -c "CREATE TABLE" packages/database/supabase/migrations/20260730142317_workflows-foundation.sql
# Expected: 5
grep -c "CREATE POLICY" packages/database/supabase/migrations/20260730142317_workflows-foundation.sql
# Expected: 13
Out of scope: no writes to eventSystemSubscription, no seed data, no service layer, no edge
functions, no changes to any existing migration.
Task 2: Apply the migration and regenerate DB types
Depends on: Task 1 Files:
- Modify (generated):
packages/database/src/types.ts,packages/database/src/swagger-docs-schema.ts,packages/database/supabase/functions/lib/types.ts— regenerated, never hand-edited
Steps:
- Run
pnpm db:migrate. If the local Supabase stack is not running or the command errors for environment reasons, STOP and ask the user — never rebuild the database. - Run
pnpm run generate:types(required before any typecheck; the generator, notturbo, owns these files).
Verify:
grep -c '"workflowVersion"\|"workflowTriggerEvent"\|"workflowStepRun"' packages/database/src/types.ts
# Expected: a number ≥ 3 (all three table names present; workflow/workflowRun also appear)
grep -n "Workflows" packages/database/src/types.ts | head -2
# Expected: 'Workflows' listed in the module enum union
Out of scope: do not edit the generated files by hand; do not run whole-repo typecheck here.
Task 3: Verify schema behavior with psql
Depends on: Task 2
Steps:
export PSQL='psql postgresql://postgres:postgres@localhost:54322/postgres -v ON_ERROR_STOP=0 -c'- Run each check below and read the output. Use an existing
companyIdanduserid from the dev seed (SELECT id FROM company LIMIT 1;/SELECT id FROM "user" LIMIT 1;). Wrap all inserts in a transaction youROLLBACKat the end so no test rows persist.- Enum + seeding:
SELECT name FROM modules WHERE name = 'Workflows';→ one row.SELECT count(*) FROM "employeeTypePermission" WHERE module = 'Workflows';→ > 0. - Version uniqueness: insert two
workflowVersionrows with the same(workflowId, companyId, versionNumber)→ second fails23505. - Run dedupe: two
workflowRunrows with identical(workflowId, companyId, workflowVersionId, sourceEventId)(usesourceEventId = 'schedule:wf_test:2026-07-30T09:00:00Z'to prove the scheduled-key case) → second fails23505. - Step idempotency: two
workflowStepRunrows with same(runId, companyId, nodeId)anditemKeyomitted (defaults to'') → second fails23505. - Defaults: insert a
workflowVersionwithoutnodes/edges, select them back → both[]. - Cascade: delete the test
workflow→ its versions/trigger events/runs/step runs are gone. - SET NULL: point
workflow.activeVersionIdat a version, delete that version row →activeVersionId IS NULL, workflow row still present. - RLS presence:
SELECT tablename, policyname, cmd FROM pg_policies WHERE tablename LIKE 'workflow%' ORDER BY 1,3;→ 13 rows matching Task 1's policy matrix; plusSELECT relrowsecurity FROM pg_class WHERE relname IN ('workflow','workflowVersion','workflowTriggerEvent','workflowRun','workflowStepRun');→ allt. - Realtime:
SELECT tablename FROM pg_publication_tables WHERE pubname = 'supabase_realtime' AND tablename IN ('workflowRun','workflowStepRun');→ both rows.
- Enum + seeding:
Verify: the psql outputs above, pasted into the run log. Expected results are inline per check.
Out of scope: authenticated-role RLS simulation (no test harness for JWT-scoped psql exists in this repo; policy presence + the shared helper pattern is the accepted evidence at this layer).
Task 4: Scaffold packages/workflows
Depends on: none (parallel with Tasks 1–3) Files:
- Create:
packages/workflows/package.json,packages/workflows/tsconfig.json,packages/workflows/vitest.config.ts,packages/workflows/src/index.ts - Copy from (precedent):
packages/utils/package.json(minimal no-build package),packages/documents/vitest.config.ts(one-line vitest re-export)
Steps:
packages/workflows/package.json:{ "name": "@carbon/workflows", "private": true, "version": "0.0.0", "sideEffects": false, "exports": { ".": "./src/index.ts" }, "scripts": { "clean": "rimraf .turbo node_modules", "lint": "biome lint --write ", "test": "vitest run", "typecheck": "tsgo --noEmit" }, "dependencies": { "zod": "catalog:" }, "devDependencies": { "@carbon/config": "workspace:*", "typescript": "catalog:", "vitest": "catalog:" } }packages/workflows/tsconfig.json:{ "extends": "@carbon/config/tsconfig/base.json", "include": ["src"], "exclude": ["dist", "build", "node_modules"] }packages/workflows/vitest.config.ts: exactlyexport { default } from "@carbon/config/vitest";packages/workflows/src/index.ts: temporaryexport {};(replaced in Task 9).- Run
pnpm installat the repo root to link the workspace package.
Verify:
pnpm --filter @carbon/workflows exec tsgo --noEmit
# Expected: exit 0, no output
pnpm --filter @carbon/workflows test
# Expected: "No test files found" is acceptable at this task only (passWithNoTests is set)
Out of scope: no tsup/build step, no apps/erp/vite.config.ts alias, no react/db deps.
Task 5: Value/schedule types and node/edge/definition schemas + tests
Depends on: Task 4 Files:
- Create:
packages/workflows/src/definition/types.ts,packages/workflows/src/definition/schema.ts,packages/workflows/src/definition/schema.test.ts - Copy from (precedent):
packages/documents/src/template/schema.ts(versioned-JSON zod schema +Extract<>narrowers per kind)
Steps:
types.ts— copy the spec's §src/definition/types.tsblock:primitiveKindSchema,valueTypeSchema(discriminated union whoselistarm nests only primitive/entity, solist<list<T>>is unrepresentable),variableRefSchema,literalSchema,valueOrRefSchema,scheduleSchema. Export inferred types (ValueType,VariableRef,ValueOrRef,Schedule,Clause={ left: ValueOrRef; operator: string; right: ValueOrRef }with aclauseSchema).schema.ts— copy the spec's §src/definition/schema.tsblock: constantsCURRENT_DEFINITION_FORMAT_VERSION = 1,MAX_LIST_ITEMS = 100,MAX_CHAIN_DEPTH = 10;originSchema; the six node schemas withdatashapes exactly per the spec's node-kind table (triggerevents/origin/schedule?;conditionpaths with id/kind/combinator/clauses;entityoperation+inputs;lookupentity/returns/match;filtersource/combinator/clauses;actionaction/inputs/batch boolean defaulting false);nodeSchemaas a flat discriminated union;edgeSchema;workflowDefinitionSchema; type exportsWorkflowNode,WorkflowNodeType,TriggerNode… oneExtract<>per kind. Keep unions flat and annotate any self-referential schemaz.ZodType<T>explicitly (TS2589 guard, spec §Risks).schema.test.ts— assert: a minimal valid definition parses; an unknown nodetypefails; alistoflistis rejected byvalueTypeSchema;schedulebounds enforced (hour 24 fails,day: "last"passes); an edge missingsourceHandlefails; defaults land (origin→"Both",formatVersion→ 1,path→[]).
Verify:
pnpm --filter @carbon/workflows test
# Expected: schema.test.ts green, > 0 tests
pnpm --filter @carbon/workflows exec tsgo --noEmit
# Expected: exit 0
Out of scope: no validator logic here; no i18n on schema messages.
Task 6: Normaliser and catalog interface + tests
Depends on: Task 5 Files:
- Create:
packages/workflows/src/definition/normalize.ts,packages/workflows/src/definition/catalog.ts,packages/workflows/src/definition/normalize.test.ts - Copy from (precedent):
packages/documents/src/template/defaults.ts(migrateBlocks/resolveTemplateread-time seam)
Steps:
normalize.ts— per spec §src/definition/normalize.ts:StoredWorkflowVersionRow(formatVersion?: number | null; nodes?: unknown; edges?: unknown), privatemigrateDefinition(d, from)pass-through at v1 (the only place upgrades will ever happen),EMPTY_DEFINITION(formatVersion 1, empty arrays),parseWorkflowDefinition(value)returning zod safe-parse, andtoWorkflowDefinition(row)which: treatsnull/undefined/non-object rows asEMPTY_DEFINITION, assembles{ formatVersion: row.formatVersion ?? 1, nodes, edges }, safe-parses, returnsEMPTY_DEFINITIONon parse failure, then runsmigrateDefinition.catalog.ts— copy the spec's §src/definition/catalog.tsinterfaces verbatim (CatalogEvent,CatalogInput,CatalogAction,CatalogOperation,CatalogEntity,WorkflowCatalog) pluscreateFixtureCatalog(): WorkflowCatalog— a small in-memory fixture with at least: eventpurchaseOrder.status.changed(outputspurchaseOrderentity +before), entitypurchaseOrder(properties incl.amountnumber,assigneeentityuser), entityuser(propertymanagerentityuser), actionnotify(requiredrecipiententity user,messagestring; batchable true), actioncreateRecord, one operation, and alist<part>-producing lookup entitypart— enough to express every Task 7/8 test.normalize.test.ts— assert:toWorkflowDefinition(null)and({})→EMPTY_DEFINITIONwithout throwing; a row withnodes: []/edges: []/formatVersion: 1→ empty canvas; a row with garbagenodes: "oops"→EMPTY_DEFINITION; aformatVersion: 1row carrying only known fields round-trips unchanged (migrate is pass-through).
Verify:
pnpm --filter @carbon/workflows test
# Expected: normalize.test.ts green alongside schema tests
Out of scope: no real event/action catalogs (phases 2/5); fixture stays inside the package.
Task 7: Validator — structural checks + tests
Depends on: Task 6 Files:
- Create:
packages/workflows/src/definition/validate.ts,packages/workflows/src/definition/validate.test.ts
Steps:
validate.ts— per spec §src/definition/validate.ts: the fullWorkflowIssueCodeunion (all 19 codes, even those raised only in Task 8),WorkflowIssue, andvalidateDefinition(definition, catalog): WorkflowIssue[]. Implement check layers 1–4 (each layer runs only if the previous produced no issues):- Shape:
workflowDefinitionSchema.safeParse→MALFORMED_DEFINITIONwith zod path infield. - Trigger: exactly one trigger node (
NO_TRIGGER/MULTIPLE_TRIGGERS); it has events XOR a schedule (EMPTY_TRIGGERif neither or both); schedule shape rules —weekdaysonly whenweeklyand required then,dayonly whenmonthlyand required then,tzresolvable viaIntl.supportedValuesOf("timeZone")(elseINVALID_SCHEDULE). - Edges: endpoints exist (
DANGLING_EDGE); source handle exists on the source node (UNKNOWN_HANDLE) — condition handles are its path ids; action and lookup exposesuccess/failure; trigger, entity and filter expose one default handle. - Graph: DFS from trigger —
CYCLEon a back edge;UNREACHABLE_NODEfor any non-trigger node not reached.
- Shape:
validate.test.ts— one focused test per acceptance criterion:NO_TRIGGER,MULTIPLE_TRIGGERS,EMPTY_TRIGGER(neither),INVALID_SCHEDULE(weekly w/o weekdays; daily carryingday),DANGLING_EDGE,UNKNOWN_HANDLE(edge off a condition path id the node lacks),CYCLE(three-node loop),UNREACHABLE_NODE(island action node). Build definitions with small local helpers (makeTrigger(),makeAction(),edge(a, handle, b)).
Verify:
pnpm --filter @carbon/workflows test
# Expected: all structural-check tests green
Out of scope: layers 5–7 (Task 8). Do not export helper internals from the barrel.
Task 8: Validator — reference, type and catalog checks + tests
Depends on: Task 7 Files:
- Modify:
packages/workflows/src/definition/validate.ts— add layers 5–7 - Modify:
packages/workflows/src/definition/validate.test.ts— add the corresponding tests
Steps:
- Layer 5 (references): walk every
VariableRefin node configs.UNKNOWN_VARIABLEifnodeIddoesn't exist or the namedoutputisn't declared by that node's kind/catalog entry;REF_NOT_UPSTREAMif the referenced node is not an ancestor along the edges leading into the referencing node (a node on theifbranch is not upstream of one on theelsebranch); propertypathmust resolve step-by-step through the catalog's entity properties (UNKNOWN_VARIABLEon a missing property). - Layer 6 (types): compute each node's output types (trigger from
catalog.getEvent, entity from operation output, lookup fromentity+returns, filter passes its source list type through, action fromcatalog.getAction(...).outputs). Then for every input:MISSING_INPUTwhen a required catalog input is absent;TYPE_MISMATCHwhen the supplied literal/ref type differs from the declared type;LIST_INTO_SINGLEwhen alist<T>feeds a single-Tinput — except an action node withbatch: trueand a batchable catalog action, where each item's typeTis what's checked. Clauseoperatorlegality is per left-side type ("compare like with like"); unknown operator for that type →TYPE_MISMATCHwith the operator infield. - Layer 7 (config completeness):
UNKNOWN_EVENT/UNKNOWN_ACTION/UNKNOWN_OPERATION/UNKNOWN_ENTITYfor ids the injected catalog can't resolve;INCOMPLETE_CONFIGfor an unset required setting (emptyactionid, condition path with zero clauses other thanelse, filter without asource). - Tests — per acceptance criteria:
REF_NOT_UPSTREAM(else-branch node referencing if-branch output),LIST_INTO_SINGLE(list
Verify:
pnpm --filter @carbon/workflows test
# Expected: all tests green; the two end-to-end fixture tests present and passing
Out of scope: no cross-node value evaluation at runtime; no operator execution — legality tables only.
Task 9: Barrel, AGENTS.md, and consumer dependency wiring
Depends on: Task 8 (barrel), Task 2 (consumers must typecheck against regenerated types) Files:
- Modify:
packages/workflows/src/index.ts— real barrel - Create:
packages/workflows/AGENTS.md - Modify:
apps/erp/package.json,packages/jobs/package.json— add"@carbon/workflows": "workspace:*"todependencies - Copy from (precedent):
packages/documents/AGENTS.md(structure), any sibling for tone
Steps:
src/index.ts: re-export the public surface — everything inschema.ts(schemas, constants, types),toWorkflowDefinition/parseWorkflowDefinition/EMPTY_DEFINITION/StoredWorkflowVersionRowfromnormalize.ts, all catalog interfaces +createFixtureCatalog, andvalidateDefinition/WorkflowIssue/WorkflowIssueCode.migrateDefinitionstays private.AGENTS.md: what the package is (the shared workflow-definition contract — schema, normaliser, validator), the vocabulary note ("workflow" here means the customer-built feature, not the.claude/rules/workflow-*.mddev-procedure files), theworkflowTriggerEventinvariant phase 7 must uphold (rows ⇔ active workflow's promoted version's trigger events, rewritten in the same transaction), the rule thatmigrateDefinitionis the only upgrade seam, and the validation commands (pnpm --filter @carbon/workflows test,... exec tsgo --noEmit,pnpm exec biome check packages/workflows).- Add the dependency line to both consumers'
dependencies(alphabetical position), thenpnpm install.
Verify:
pnpm install
# Expected: resolves clean, lockfile updates only for the new package links
grep '"@carbon/workflows"' apps/erp/package.json packages/jobs/package.json
# Expected: one workspace:* line in each
Out of scope: no imports of @carbon/workflows added to any erp/jobs source file yet (phases
3, 4, 7 do that); no useModules.tsx nav entry; no route.
Task 10: Full verification sweep
Depends on: all previous
Steps & Verify (this task is the verification):
pnpm --filter @carbon/workflows test
# Expected: all suites green, real assertions
pnpm --filter @carbon/workflows exec tsgo --noEmit
# Expected: exit 0
(cd apps/erp && pnpm exec tsgo --noEmit)
# Expected: exit 0 — direct tsgo, NOT turbo (stale-cache false positives; erp filter name is `erp`)
pnpm exec turbo run typecheck --filter=@carbon/jobs --force
# Expected: exit 0
pnpm exec biome check packages/workflows
# Expected: "Checked N files" with zero errors (repo-wide pre-existing warnings don't count)
git status --porcelain
# Expected: only intended files. If packages/database/src/types.ts, swagger-docs-schema.ts or
# supabase/functions/lib/types.ts changed beyond Task 2's deliberate regeneration, restore them.
If erp typecheck surfaces TS2589 in unrelated files, apply the spec's mitigation (@ts-ignore,
keep unions flat) — if that doesn't clear it, STOP and report rather than restructuring the schema.
Then check off every spec acceptance criterion in .ai/specs/2026-07-30-workflows-foundation.md
against evidence, update this file's Progress list, and report. Do not commit — the user
commits on explicit ask only.
Out of scope: no whole-repo pnpm run typecheck (OOMs); no pnpm run build; no db rebuild.
Post-review fixes (2026-07-30)
A thermo-nuclear review found four blockers; all twelve findings are resolved. See
.ai/reviews/2026-07-30-workflows-foundation-thermo-nuclear.md for the findings and
their resolutions. Structural changes worth knowing when reading the plan above:
src/definition/nodes.tsis new and holdsNODE_KINDS— everything one node type declares about itself.validate.tsno longer switches on node type (828 → 397 lines).src/definition/issues.tsis new (the issue types).toWorkflowDefinitionis nowreadWorkflowVersion, returning a discriminated result rather than falling back to an empty canvas.EMPTY_DEFINITIONis gone.- Operator names come from
Operatorin@carbon/utils, extended there. The package now depends on@carbon/utils. scheduleSchema.freqis PascalCase;CONFLICTING_TRIGGERis a new issue code.- Migration: five FK indexes added and
workflow_due_idxnow also requires"activeVersionId" IS NOT NULL. Applied to the local DB by hand so the file and the schema agree; no regeneration needed (indexes are not in generated types).
Tests: 64 → 73. Two confirmed bugs (self-referential filter validating clean; the format-migration seam silently discarding data) have regression tests.