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 — Phase 4: the engine — implementation plan
Spec / source: .ai/specs/2026-07-30-workflows-engine.md
Branch: feat/automation
Progress
- Task 1: Add the
itemvalue form to the definition contract - Task 2: Runtime value model (
runtime/types.ts,runtime/values.ts) - Task 3: Variable resolution and the
EntityLoaderseam - Task 4: Operator comparison and clause evaluation
- Task 5: The Condition executor
- Task 6: The Filter executor
- Task 7: Batch planning and item keys
- Task 8: Export the runtime from
@carbon/workflows - Task 9: The pure graph walker
- Task 10: Owner connection, claims and the permission check
- Task 11: The entity loader over the owner's connection
- Task 12: The step ledger
- Task 13: Run status transitions
- Task 14: Engine orchestration
- Task 15: Replace the Inngest stub
- Task 16: Full verification
- Task 17: Document the engine in
.claude/rules/and AGENTS files
Dependencies
- Task 2 needs Task 1 only for
ItemRefbeing exported; do Task 1 first. - Task 3 needs Task 2. Task 4 needs Task 2. Tasks 3 and 4 are independent of each other.
- Task 5 needs Tasks 3 + 4. Task 6 needs Tasks 1 + 3 + 4. Task 7 needs Task 2. Tasks 5, 6 and 7 are independent of each other.
- Task 8 needs Tasks 2–7.
- Task 9 needs nothing (pure graph maths) — can run in parallel with Tasks 2–8.
- Tasks 10, 12, 13 need nothing from the runtime — independent of each other and of Tasks 2–9.
- Task 11 needs Task 3 (the
EntityLoaderinterface) and Task 8. - Task 14 needs Tasks 8–13. Task 15 needs Task 14. Task 16 needs Task 15.
- Task 17 needs Task 15.
Conventions that apply to every task
- Package manager is pnpm, never npm.
packages/workflowsmust never import@carbon/databaseas a value, must never import@carbon/reactor app code, and must never importsrc/catalog/labels.generated.ts.- Keep zod unions flat and non-recursive —
apps/erpis near TypeScript's instantiation budget and a recursive union triggers TS2589 in unrelated files. - Comments: one-liners only (2 lines max), and only where the reason is not obvious from the code. No explainer blocks.
- Vitest runs with
globals: false— every test file mustimport { describe, expect, it } from "vitest";explicitly. - All customer-facing strings (anything written to
statusReasonorerror) are full sentences addressed to the customer, e.g."The owner of this workflow no longer has access to Purchasing."
Task 1: Add the item value form to the definition contract
Depends on: none
Files:
- Modify:
packages/workflows/src/definition/types.ts— additemRefSchemaand widenvalueOrRefSchema - Modify:
packages/workflows/src/definition/issues.ts— add theITEM_OUTSIDE_LOOPcode - Modify:
packages/workflows/src/definition/nodes.ts— item-scope typing, the single-list batch rule - Modify:
packages/workflows/src/definition/validate.ts— pass the item scope intoNodeContext - Modify:
packages/workflows/src/index.ts— exportItemRef/itemRefSchema - Modify:
packages/workflows/src/definition/validate.test.ts— new cases - Copy from (precedent): the existing
variableRefSchemablock inpackages/workflows/src/definition/types.ts(lines ~93-107)
Steps:
In
types.ts, aftervariableRefSchema, add:/** The item a looping node is currently on: a filter's list, or a batched action's. */ export const itemRefSchema = z.object({ kind: z.literal("item"), path: z.array(z.string()).default([]) }); export type ItemRef = z.infer<typeof itemRefSchema>;Widen the union, keeping the existing
superRefineon literals exactly as it is:export const valueOrRefSchema = z .discriminatedUnion("kind", [literalSchema, variableRefSchema, itemRefSchema]) .superRefine((value, ctx) => { if (value.kind !== "literal") return; if (!literalValueMatchesType(value.type, value.value)) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["value"], message: `This value is not ${describeType(value.type)}.` }); } });In
issues.ts, add"ITEM_OUTSIDE_LOOP"to theWorkflowIssueCodeunion.In
nodes.ts, add toNodeContext:/** The type of the item a looping node is on, or undefined when the node does not loop. */ itemTypeOf(nodeId: string): ValueType | undefined;typeOfmust now handlekind === "item": look upctx.itemTypeOf(atNodeId); if undefined, returnundefined(the config layer reportsITEM_OUTSIDE_LOOP); otherwise walkpathwith the same helperwalkPathalready uses invalidate.ts— exportwalkPathfromvalidate.tsis NOT allowed (it would invert the dependency); instead movewalkPathintonodes.tsas an exported helper and havevalidate.tsimport it from there.In
nodes.ts,getNodeRefsmust not returnitemvalues — they are not node references and the upstream-ancestor check does not apply to them.Add a
checkConfigrule shared by every node kind: for eachValueOrRefthe node holds, if it is{kind:"item"}andctx.itemTypeOf(node.id)isundefined, push{ code: "ITEM_OUTSIDE_LOOP", nodeId, field, message: "This test refers to the current item, but this step does not work through a list." }.In
nodes.ts, theactionkind'scheckConfiggains: whennode.data.batchis true, count the inputs whose resolved type is a list. Not exactly one →{ code: "INCOMPLETE_CONFIG", field: "batch", message: "A step that repeats needs exactly one list to repeat over." }.In
validate.ts, implementitemTypeOf(nodeId)increateContext:- filter node → resolve
data.source; if it is a list, returnsource.ofas aValueType; otherwiseundefined. - action node with
data.batch === true→ the item type of its single list-typed input, orundefined. - anything else →
undefined.
- filter node → resolve
Add tests to
validate.test.ts:- a filter whose clause is
{kind:"item", path:["dueDate"]}compared to a date literal validates clean; - the same clause on a condition node reports
ITEM_OUTSIDE_LOOP; - an
itempath naming a column that does not exist reportsTYPE_MISMATCHwith the message"This property does not exist on the items in that list."— add that case to the step-6 check, sincetypeOfreturningundefinedwould otherwise makecheckClausesreturn early and report nothing; - the existing test "rejects a filter whose source is its own output" still passes unchanged.
- a filter whose clause is
Verify:
pnpm --filter @carbon/workflows test
# Expected: all test files pass, including validate.test.ts with the new cases
pnpm --filter @carbon/workflows exec tsgo --noEmit
# Expected: no output (success)
Out of scope: the builder UI for the new value form (phase 8); changing
literalSchema or variableRefSchema; the action catalogue.
Task 2: Runtime value model
Depends on: Task 1
Files:
- Create:
packages/workflows/src/runtime/types.ts - Create:
packages/workflows/src/runtime/values.ts - Create:
packages/workflows/src/runtime/values.test.ts
Steps:
runtime/types.ts— declare, and nothing else (no logic in this file):import type { WorkflowCatalog } from "../definition/catalog"; import type { WorkflowNode } from "../definition/schema"; import type { PrimitiveKind, ScalarType, ValueType } from "../definition/types"; export type RuntimeValue = | { kind: "primitive"; of: PrimitiveKind; value: string | number | boolean | null } | { kind: "entity"; of: string; id: string } | { kind: "list"; of: ScalarType; items: RuntimeValue[] }; export type Resolution = | { ok: true; value: RuntimeValue } | { ok: false; reason: string }; /** Loads a record the run does not already hold. Implemented job-side; never here. */ export interface EntityLoader { load(entity: string, id: string): Promise<Record<string, unknown> | null>; } export interface RuntimeContext { catalog: WorkflowCatalog; loader: EntityLoader; /** nodeId → that node's outputs, filled in as the walk proceeds. */ outputs: Map<string, Record<string, RuntimeValue>>; /** The item a looping node is on; absent outside a loop. */ item?: RuntimeValue; } export type NodeResult = | { status: "Succeeded"; outputs: Record<string, RuntimeValue>; /** The handle to follow, or null to stop this path cleanly. */ handle: string | null; branchTaken?: string; /** A one-line note for the step row's statusReason, e.g. what a filter kept. */ summary?: string; } | { status: "Skipped"; reason: string } | { status: "Failed"; error: string; handle?: string | null }; export interface NodeExecutor<N extends WorkflowNode> { /** The permission module the owner must hold, or undefined when the node reads nothing. */ permission(node: N, catalog: WorkflowCatalog): string | undefined; execute(node: N, ctx: RuntimeContext): Promise<NodeResult>; }runtime/values.ts— pure constructors and conversions:export function primitiveValue(of: PrimitiveKind, value: string | number | boolean | null): RuntimeValue export function entityValue(of: string, id: string): RuntimeValue /** Slices to MAX_LIST_ITEMS and reports how many were dropped. */ export function listValue(of: ScalarType, items: RuntimeValue[]): { value: RuntimeValue; dropped: number } /** A raw database column value plus its catalog type → a RuntimeValue. */ export function fromColumn(type: ValueType, raw: unknown): RuntimeValue export function fromLiteral(literal: Literal): RuntimeValue export function typeOfValue(value: RuntimeValue): ValueType export function isNull(value: RuntimeValue): booleanRules
fromColumnmust follow:type.kind === "entity":rawnull/empty string → anullprimitive; otherwiseentityValue(type.of, String(raw)).type.kind === "primitive"andof === "date":rawbecomes an ISO string vianew Date(raw as string).toISOString(); an unparseable value becomes anullprimitive.type.kind === "primitive"andof === "number": non-finite →null.type.kind === "list":rawmust be an array; map each entry withfromColumn(type.of, entry); a non-array becomes an empty list.- Any
rawthat isnullorundefined→ anullprimitive (for a list type, an empty list).
Tests in
values.test.ts: date coercion including an unparseable string;listValueslicing 150 items to 100 withdropped === 50;fromColumnon an entity column holding"";typeOfValueround-tripping each shape.
Verify:
pnpm --filter @carbon/workflows test
# Expected: values.test.ts passes
Out of scope: any I/O; anything importing a Supabase or Kysely client.
Task 3: Variable resolution and the EntityLoader seam
Depends on: Task 2
Files:
- Create:
packages/workflows/src/runtime/resolve.ts - Create:
packages/workflows/src/runtime/resolve.test.ts
Steps:
Implement:
export async function resolveValue(value: ValueOrRef, ctx: RuntimeContext): Promise<Resolution> export async function resolveRef(ref: VariableRef, ctx: RuntimeContext): Promise<Resolution> export async function resolveItem(ref: ItemRef, ctx: RuntimeContext): Promise<Resolution>resolveRef:ctx.outputs.get(ref.nodeId)missing →{ ok: false, reason: "The step that produces this value did not run." }- that node's
ref.outputmissing →{ ok: false, reason: \This step did not produce "${ref.output}".` }` - then walk
ref.path(step 4).
resolveItem: start fromctx.item; absent →{ ok: false, reason: "There is no current item here." }; then walkref.path.Path walking, one segment at a time, starting from a
RuntimeValue:- current value is a
nullprimitive → stop,{ ok: true, value: null primitive }(reading a property of nothing is nothing, per the PRD). - current value is not an entity →
{ ok: false, reason: \"${segment}" is not something this value has.` }` ctx.catalog.getEntity(current.of)missing →{ ok: false, reason: ... }- the segment is not in that entity's
properties→{ ok: false, reason: ... } - otherwise
const row = await ctx.loader.load(current.of, current.id);nullrow →{ ok: false, reason: \The ${current.of} this refers to could not be read.` }` fromColumn(properties[segment], row[segment])becomes the new current value.
- current value is a
resolveValuedispatches onvalue.kind:"literal"→fromLiteral,"ref"→resolveRef,"item"→resolveItem.Tests using a hand-written fake
EntityLoader(aMapof rows) andcreateFixtureCatalog(): a one-segment path off a preloaded entity; a two-segment path crossing into a second record; a load returningnullproducingok: falsewith a readable reason; a path through anullcolumn short-circuiting to anullprimitive rather than failing; a ref to a node that never ran.
Verify:
pnpm --filter @carbon/workflows test
# Expected: resolve.test.ts passes
Out of scope: caching (that lives in the job-side loader, Task 11); loading by table name (the loader takes an entity name, not a table).
Task 4: Operator comparison and clause evaluation
Depends on: Task 2
Files:
- Create:
packages/workflows/src/runtime/compare.ts - Create:
packages/workflows/src/runtime/compare.test.ts
Steps:
Implement:
export function compare(left: RuntimeValue, operator: Operator, right: RuntimeValue): boolean export async function evaluateClauses( clauses: Clause[], combinator: Combinator, ctx: RuntimeContext ): Promise<{ ok: true; passed: boolean } | { ok: false; reason: string }>comparesemantics — exactly these, no coercion between kinds:number:eq neq gt gte lt ltenumerically.date: parse both to epoch milliseconds; compare numerically.string:eq/neqare case-sensitive;contains,startsWith,endsWithare case-insensitive (lowercase both sides first).booleanandnull:eq/neqonly.entity:eq/neqcompareofandid.list+contains: true when any item equals the right side under the sameeqrule for the item's kind.- Either side being a
nullprimitive:eqis true only when both are null;neqis its negation; every ordering and text operator is false. Never throw. - An operator that does not apply to the left value's kind returns
false(validation prevents this reaching the engine; the engine must not crash if it does).
evaluateClauses: resolve each clause'sleftandrightwithresolveValue. Any unresolved operand aborts immediately with{ ok: false, reason }carrying that operand's reason — it does not count as a failed clause. Otherwise combine withcombinator("and"→ every,"or"→ some), left to right. An empty clause list passes.Tests: one per row of the semantics list above, plus a two-clause
orwhere the first clause passes, plus an unresolvable operand producingok: false.
Verify:
pnpm --filter @carbon/workflows test
# Expected: compare.test.ts passes
Out of scope: short-circuit evaluation as an optimisation — resolve operands
in order and stop on the first unresolved one, but do not skip resolving the
right side of an or whose left already passed (a customer debugging a run
needs both resolved values recorded).
Task 5: The Condition executor
Depends on: Tasks 3, 4
Files:
- Create:
packages/workflows/src/runtime/condition.ts - Create:
packages/workflows/src/runtime/condition.test.ts
Steps:
Implement
export const conditionExecutor: NodeExecutor<ConditionNode>withpermission: () => undefined.execute:- Walk
node.data.pathsin stored order. - A path of
kind === "else"passes without evaluating clauses. - Otherwise
evaluateClauses(path.clauses, path.combinator, ctx).{ ok: false }→ return{ status: "Skipped", reason }immediately; do not fall through to later paths. - First passing path wins: return
{ status: "Succeeded", outputs: {}, handle: path.id, branchTaken: path.id }. - No path passed: return
{ status: "Succeeded", outputs: {}, handle: null, branchTaken: "none" }.
- Walk
Tests: the
ifbranch winning; anelse-ifwinning when theiffails; theelsewinning; no match and no else givinghandle: nullandbranchTaken: "none"; an unresolvable operand in the first path givingSkippedand not reaching theelse.
Verify:
pnpm --filter @carbon/workflows test
# Expected: condition.test.ts passes
Out of scope: writing the step row (Task 12) or following the handle (Task 9).
Task 6: The Filter executor
Depends on: Tasks 1, 3, 4
Files:
- Create:
packages/workflows/src/runtime/filter.ts - Create:
packages/workflows/src/runtime/filter.test.ts
Steps:
Implement
export const filterExecutor: NodeExecutor<FilterNode>withpermission: () => undefined.execute:node.data.sourceundefined →{ status: "Skipped", reason: "No list was chosen to filter." }.resolveRef(node.data.source, ctx);{ ok: false }→{ status: "Skipped", reason }.- The resolved value is not a list →
{ status: "Skipped", reason: "This step expected a list." }. - For each item, evaluate the clauses with a context whose
itemis that item ({ ...ctx, item }).ok: true && passed→ keep.ok: false→ drop the item and increment adroppedcounter; never abort the node. - Return
{ status: "Succeeded", outputs: { [DEFAULT_OUTPUT]: <the narrowed list> }, handle: DEFAULT_HANDLE }. The narrowed list keeps the source'sofand the source order.
Report the counts through the result's
summaryfield (added in Task 2), which the orchestrator writes to the step row'sstatusReason. Exportexport function filterSummary(kept: number, total: number, unresolved: number): stringreturning e.g."Kept 2 of 5; 1 could not be checked."and set it assummary. Do not add a column and do not overloadbranchTaken.Tests: 5 jobs narrowed to 2 by
item.dueDate < <date>, order preserved; an item whose clause operand cannot be resolved being dropped while the rest survive; a non-list source givingSkipped.
Verify:
pnpm --filter @carbon/workflows test
# Expected: filter.test.ts passes
Out of scope: batch mode (a filter is one step, not one per item).
Task 7: Batch planning and item keys
Depends on: Task 2
Files:
- Create:
packages/workflows/src/runtime/batch.ts - Create:
packages/workflows/src/runtime/batch.test.ts
Steps:
Implement:
/** Slices a list to MAX_LIST_ITEMS and reports what was left out. */ export function planBatch(list: RuntimeValue): { items: RuntimeValue[]; dropped: number } /** The stable key a step row is claimed under. Never the position in the list. */ export function itemKeyFor(value: RuntimeValue): stringitemKeyFor: an entity value → itsid. Anything else →"h:"plus a 64-bit FNV-1a hash, as 16 lowercase hex characters, ofJSON.stringify(value)with object keys written in sorted order. Implement the hash inline withBigInt— do not importnode:crypto; this package is also built for the browser by the phase-7 builder.Tests: a 150-item list planning to 100 items with
dropped === 50; two entity values with the same id producing the same key; two primitives with the same value producing the same key; different values producing different keys; the key being independent of position.
Verify:
pnpm --filter @carbon/workflows test
# Expected: batch.test.ts passes
Out of scope: running the batch (there is no batchable node until phase 5); parallelism across items.
Task 8: Export the runtime from @carbon/workflows
Depends on: Tasks 2–7
Files:
- Create:
packages/workflows/src/runtime/index.ts - Modify:
packages/workflows/src/index.ts— re-export the runtime barrel
Steps:
runtime/index.tsre-exports every public symbol fromtypes.ts,values.ts,resolve.ts,compare.ts,condition.ts,filter.ts,batch.ts.In
src/index.ts, follow the file's existing style: explicit named re-exports, types in theexport type { ... }block and values in theexport { ... }block. Do not add a bareexport *.Add a
runtimeentry to the package'sAGENTS.mdfile map if that file lists directories (check first; if it does not, skip).
Verify:
pnpm --filter @carbon/workflows exec tsgo --noEmit
# Expected: no output (success)
pnpm exec turbo run typecheck --filter=erp
# Expected: passes — this is the TS2589 canary for the widened value union
Out of scope: exporting anything from src/catalog/labels.generated.ts.
Task 9: The pure graph walker
Depends on: none
Files:
- Create:
packages/jobs/src/workflows/engine/walk.ts - Create:
packages/jobs/src/workflows/engine/walk.test.ts - Copy from (precedent):
packages/jobs/src/workflows/matcher.test.tsfor the test idiom (explicit vitest imports, small fixture builders)
Steps:
Implement, with no I/O and no imports beyond
@carbon/workflowstypes:export const MAX_NODE_EXECUTIONS = 500; export function findTriggerNode(definition: WorkflowDefinition): TriggerNode | undefined; /** Target node ids for one handle, in stored edge order. */ export function outgoing( definition: WorkflowDefinition, nodeId: string, handle: string | null ): string[]; export interface WalkState { frontier: string[]; executed: Set<string>; sequence: number; } export function createWalkState(definition: WorkflowDefinition): WalkState; /** Pops the next node id to execute, or undefined when the walk is done. */ export function nextNode(state: WalkState): string | undefined; /** Records an execution and appends the nodes its handle leads to. */ export function advance( state: WalkState, definition: WorkflowDefinition, nodeId: string, handle: string | null ): void;createWalkStateseeds the frontier from the trigger node'sDEFAULT_HANDLEtargets. No trigger node → an empty frontier.outgoingreturns[]whenhandleisnull.advanceaddsnodeIdtoexecutedand incrementssequence.The caller is responsible for the already-executed check; expose
export function alreadyExecuted(state: WalkState, nodeId: string): boolean.Tests: breadth-first order across a fan-out of three; edge order respected; a condition handle selecting only its own branch; a node reachable from two branches appearing once in the executed set and
alreadyExecutedreturning true on the second arrival;outgoingwithhandle: nullreturning[].
Verify:
pnpm --filter @carbon/jobs test
# Expected: walk.test.ts passes
Out of scope: executing anything; the 500 cap is enforced by the caller in Task 14, this file only exports the constant.
Task 10: Owner connection, claims and the permission check
Depends on: none
Files:
- Create:
packages/jobs/src/workflows/engine/owner.ts - Create:
packages/jobs/src/workflows/engine/owner.test.ts - Copy from (precedent): the permission decision in
packages/auth/src/services/auth.server.ts:326-355(the"0"wildcard handling is load-bearing)
Steps:
Implement:
import { getClaims, makePermissionsFromClaims, type Permission } from "@carbon/auth"; import { getUserScopedClient } from "@carbon/auth/client.server"; export type OwnerPermissions = Record<string, Permission>; /** A fresh five-minute connection as the owner. Call inside every step, never once per run. */ export async function getOwnerClient(ownerId: string, runId: string); export async function readOwnerPermissions( client: SupabaseClient<Database>, ownerId: string, companyId: string ): Promise<OwnerPermissions | null>; /** Pure. Exported for tests. */ export function hasPermission( permissions: OwnerPermissions, module: string, action: "view" | "create" | "update" | "delete", companyId: string ): boolean;getOwnerClientis exactlygetUserScopedClient(ownerId, { workflowRunId: runId }). TheworkflowRunIdis not optional — without it the write is untagged and the phase-3 loop guards go blind.readOwnerPermissionscallsgetClaims(client, ownerId, companyId)and passesdatathroughmakePermissionsFromClaims. A null or errored result returnsnull; the caller turns that into a failed run, never into "no permissions, continue".hasPermissionmirrors the precedent: the module must be present, and the action's array must include"0"(the all-companies wildcard) orcompanyId.Tests cover
hasPermissiononly (the other two need a live database): wildcard grant; exact-company grant; a different company denied; a missing module denied; a missing action array denied.
Verify:
pnpm --filter @carbon/jobs test
# Expected: owner.test.ts passes
pnpm --filter @carbon/jobs exec tsc --noEmit
# Expected: no output (success)
Out of scope: the permissions:${userId} Redis cache in
apps/erp/app/modules/users/users.server.ts — it is keyed by user only and its
role field is cross-company, so it must not be used for this check.
Task 11: The entity loader over the owner's connection
Depends on: Tasks 3, 8
Files:
- Create:
packages/jobs/src/workflows/engine/loader.ts
Steps:
Implement:
export function createEntityLoader(params: { client: SupabaseClient<Database>; companyId: string; cache: Map<string, Record<string, unknown> | null>; }): EntityLoader;load(entity, id):- cache hit (including a cached
null) → return it. REGISTRY_ENTRIES[entity]missing → cache and returnnull.- otherwise
client.from(table).select("*").eq("id", id).eq("companyId", companyId).maybeSingle(), wheretableisREGISTRY_ENTRIES[entity].table. - an error or no row → cache
nulland returnnull. Access denied by row-level security is indistinguishable from absent, and that is correct — the node stops with a reason either way.
- cache hit (including a cached
Export a helper that seeds the cache from a record trigger:
export function seedTriggerRows( cache: Map<string, Record<string, unknown> | null>, eventId: string, trigger: RunTrigger, catalog: WorkflowCatalog ): void;For a
kind: "record"trigger, the event'soutputsname which ofrecord/before/afterexist and what entity each is; put each whole row into the cache under${entityName}:${row.id}.beforeandafterare the same record id, so seedrecord/afterlast — the current row must win.The client passed in is always an owner-scoped client. If you find yourself passing
getJobDatabaseClient()here, STOP and report — that would read past row-level security.
Verify:
pnpm --filter @carbon/jobs exec tsc --noEmit
# Expected: no output (success)
Out of scope: caching across Inngest steps; batching loads.
Task 12: The step ledger
Depends on: none
Files:
- Create:
packages/jobs/src/workflows/engine/ledger.ts - Copy from (precedent): the Kysely insert with a named constraint in
packages/jobs/src/workflows/matcher.ts:191-213
Steps:
Implement, all taking a
JobDatabasefromgetJobDatabaseClient():export type StepClaim = | { claimed: true; stepRunId: string } | { claimed: false; existing: { status: string; output: unknown; branchTaken: string | null } | null }; export async function claimStep(db: JobDatabase, params: { runId: string; companyId: string; nodeId: string; nodeType: string; itemKey: string; sequence: number; }): Promise<StepClaim>; export async function settleStep(db: JobDatabase, params: { stepRunId: string; companyId: string; status: "Succeeded" | "Failed" | "Skipped"; statusReason?: string | null; error?: string | null; input?: unknown; output?: unknown; branchTaken?: string | null; startedAt: string; }): Promise<void>; /** Marks rows this run left mid-flight, so a lost action is visible rather than silent. */ export async function failInterruptedSteps( db: JobDatabase, runId: string, companyId: string ): Promise<number>;claimStepinserts withstatus: "Running"andstartedAt: new Date().toISOString(), then.onConflict((oc) => oc.constraint("workflowStepRun_idempotency_key").doNothing())and.returning(["id"]). Zero rows back → select the existing row by(runId, companyId, nodeId, itemKey)and return it asexisting.settleStepsetscompletedAtand computesdurationMsfromstartedAt. UsestatusReasonfor a skip reason anderrorfor a failure message — they are separate columns and must not be conflated.failInterruptedStepsupdates every row for this run whosestatusis'Running'to'Failed'witherror: "This step was interrupted and did not finish.", returning the count.
Verify:
pnpm --filter @carbon/jobs exec tsc --noEmit
# Expected: no output (success). Kysely must accept every column name — if it
# rejects one, the generated types are stale; STOP and report rather than casting.
Out of scope: compaction and purge (phase 9).
Task 13: Run status transitions
Depends on: none
Files:
- Create:
packages/jobs/src/workflows/engine/log.ts
Steps:
Implement:
export interface RunContext { run: { id: string; companyId: string; ownerId: string; workflowId: string; workflowVersionId: string; eventId: string; status: string }; workflowActive: boolean; version: { formatVersion: number | null; nodes: unknown; edges: unknown } | null; } export async function loadRunContext( db: JobDatabase, runId: string, companyId: string ): Promise<RunContext | null>; /** Flips Queued → Running. Returns false when the row was not Queued (a double delivery). */ export async function claimRun(db: JobDatabase, runId: string, companyId: string): Promise<boolean>; export async function finishRun(db: JobDatabase, params: { runId: string; companyId: string; status: "Succeeded" | "Failed" | "Skipped"; statusReason?: string | null; error?: string | null; startedAt: string; }): Promise<void>;loadRunContextis one query joiningworkflowRuntoworkflow(foractive) and toworkflowVersionon the run'sworkflowVersionId— never onworkflow.activeVersionId. Scope every join bycompanyId.claimRunisUPDATE ... SET status='Running', startedAt=now() WHERE id=? AND companyId=? AND status='Queued' RETURNING id, returning whether a row came back. This is the atomic double-delivery guard.finishRunsetscompletedAtanddurationMsfromstartedAt.
Verify:
pnpm --filter @carbon/jobs exec tsc --noEmit
# Expected: no output (success)
Out of scope: realtime broadcasting — it is already enabled on the table.
Task 14: Engine orchestration
Depends on: Tasks 8, 9, 10, 11, 12, 13
Files:
- Create:
packages/jobs/src/workflows/engine/execute.ts - Create:
packages/jobs/src/workflows/engine/index.ts(barrel) - Copy from (precedent):
packages/jobs/src/inngest/functions/events/queue.tsfor the shape of a bounded step loop with suffixed step ids
Steps:
Export one function taking the Inngest
stepandloggerplus the parsed payload:export async function executeWorkflowRun(params: { payload: { runId: string; companyId: string; workflowId: string; workflowVersionId: string; eventId: string; ownerId: string; sourceEventId: string; trigger: RunTrigger }; step: /* Inngest step tools */; logger: /* Inngest logger */; }): Promise<{ runId: string; status: string; steps: number }>;Step
"load"—getJobDatabaseClient()inside the step, then:loadRunContext; null → throwNonRetriableError("Workflow run not found").workflowActive === false→finishRunwithSkippedand"This workflow was switched off before the run started."; return a terminal marker so the handler stops.readWorkflowVersion(context.version)→ok: false→finishRunwithFailedand the read failure's message.claimRun; false → return a terminal marker (a double delivery; do not touch the run).- Return the definition plus
startedAt, as plain JSON.
Step
"permissions"— mintgetOwnerClient(ownerId, runId)inside the step,readOwnerPermissions; null → finish the runFailedwith"The permissions for the owner of this workflow could not be read.". Then check the trigger event's declared permission:catalog.getEvent(eventId)?.permission, action"view". Missing → finish the runFailedwith`The owner of this workflow no longer has access to ${title-cased module}.`. Return the permission map as the step result.The walk — build the catalog once with
createEventCatalog(), a freshMapfor the entity cache, seed it withseedTriggerRows, and populate the trigger node's outputs inctx.outputsfrompayload.trigger(a record trigger yieldsrecord/before/afterentity values built from the event's declaredoutputs; a moment trigger yields one entity value per declared output, taking each id fromtrigger.outputs[name].id).Then loop:
while ((nodeId = nextNode(state)) !== undefined) { if (executions >= MAX_NODE_EXECUTIONS) → finish Failed "This workflow ran too many steps." const result = await step.run(`node:${nodeId}`, () => runOneNode(...)); rebuild ctx.outputs from result.outputs advance(state, definition, nodeId, result.handle) }runOneNodedoes, in order: mint the owner client; build the loader;claimStep; if not claimed → settle nothing and return aSkippedmarker with"This step already ran in this run."(reusing the existing row's handle and output when that row is terminal, so the walk continues correctly); otherwise check the node's declared permission, execute via the executor registry,settleStep(aSkippedresult'sreasonand aSucceededresult'ssummaryboth go tostatusReason; aFailedresult's message goes toerror), and return a JSON-safe result.An already-executed node (
alreadyExecuted) is short-circuited before the step is created, and recorded throughclaimStep/settleStepin its own step so it appears in the run history.Executor registry:
condition→conditionExecutor,filter→filterExecutor;lookup,entityandactionreturn{ status: "Failed", error: "This kind of step is not available yet." }. They cannot be activated today, so this is a defence, not a feature.Step
"finish"—failInterruptedSteps, thenfinishRunwithFailedwhen any step failed, otherwiseSucceeded.Every
step.runid must be deterministic. Never include a timestamp, a random value, or a counter that depends on wall-clock ordering.
Verify:
pnpm --filter @carbon/jobs exec tsc --noEmit
# Expected: no output (success)
pnpm --filter @carbon/jobs test
# Expected: existing tests still pass
Out of scope: running batch items (no batchable node exists until phase 5) —
but the loop must call planBatch / itemKeyFor for a node whose data.batch
is true, so the machinery is exercised by the executor registry rather than
written later.
Task 15: Replace the Inngest stub
Depends on: Task 14
Files:
- Modify:
packages/jobs/src/inngest/functions/workflows/run.ts— replace the stub body, add concurrency and idempotency, addonFailure - Copy from (precedent):
packages/jobs/src/inngest/functions/tasks/assembly-plan.ts:32-53for theonFailureshape and its status guard
Steps:
Keep the export name
workflowRunFunction, the id"workflow-run"and the existingrunPayloadSchemaexactly as they are —packages/jobs/src/inngest/index.tsalready registers this function and must not be edited.Config becomes:
{ id: "workflow-run", retries: 3, idempotency: "event.data.runId", concurrency: [ { limit: 10, key: "event.data.companyId" }, { limit: 5, key: "event.data.workflowId" } ], onFailure: async ({ event, logger }) => { /* step 3 */ } }onFailureopensgetJobDatabaseClient()and updates the run toFailedwith the error message, guarded by.where("status", "in", ["Queued", "Running"])so a settled run is never clobbered. Read the ids fromevent.data.event.data(Inngest wraps the original event in the failure payload — confirm the shape againstassembly-plan.ts; if it differs, follow that file, not this plan).The handler body is
return executeWorkflowRun({ payload, step, logger }).
Verify:
pnpm --filter @carbon/jobs exec tsc --noEmit
# Expected: no output (success)
pnpm exec biome check packages/jobs packages/workflows
# Expected: no error-severity findings (pre-existing warnings elsewhere are fine)
Out of scope: editing packages/jobs/src/inngest/index.ts; changing the
event name or the payload schema.
Task 16: Full verification
Depends on: Task 15
Files: none
Steps:
Run every command in the Verify block below and paste the real output — do not summarise or assert success without it.
Confirm the privileged-access boundary by grep:
grep -rn "getCarbonServiceRole\|getJobDatabaseClient" packages/jobs/src/workflows/engineHits are allowed only in
ledger.ts,log.ts, and the"load"/"finish"steps ofexecute.ts. A hit anywhere else means a business read is bypassing the owner's permissions — STOP and report.End-to-end checking needs a running stack and a seeded database. Do not rebuild or reset the database. Instead, write the manual script into
.ai/runs/2026-07-30-workflows-engine.mdfor the user to run when they have the stack up: activate a workflow whose trigger ispurchaseOrder.orderTotal.changedwired to a conditionrecord.orderTotal > 10000, edit a purchase order's total, then read back theworkflowRunandworkflowStepRunrows and check the run reachedSucceededwithbranchTakenset. Report that this step is pending the user rather than claiming it passed.
Verify:
pnpm --filter @carbon/workflows test
# Expected: all suites pass
pnpm --filter @carbon/jobs test
# Expected: all suites pass
pnpm --filter @carbon/workflows exec tsgo --noEmit
# Expected: no output
pnpm --filter @carbon/jobs exec tsc --noEmit
# Expected: no output
pnpm exec turbo run typecheck --filter=erp
# Expected: passes (the TS2589 canary)
pnpm exec biome check packages/jobs packages/workflows
# Expected: no error-severity findings
pnpm run check:workflow-catalog
# Expected: exits 0 — the catalog is untouched but must still validate
Out of scope: running pnpm run build (slow, and nothing here changes the
build graph); a whole-repo typecheck (it OOMs — always scope with --filter).
Task 17: Document the engine
Depends on: Task 15
Files:
- Create:
.claude/rules/workflow-engine.md - Modify:
AGENTS.md— add the engine rule to the Workflows row of the Task Router - Modify:
packages/workflows/AGENTS.md— thesrc/runtime/directory and its rules - Modify:
packages/jobs/AGENTS.md— the engine's act-as-owner rule - Copy from (precedent):
.claude/rules/workflow-matcher.md(front-matterpaths:glob, structure, tone)
Steps:
.claude/rules/workflow-engine.mdfront-matter targetspackages/jobs/src/workflows/engine/**andpackages/workflows/src/runtime/**.Content it must state, because each is a rule someone will otherwise break: the owner-scoped client is minted per step and always carries
workflowRunId; the only privileged access is the two run-log tables; claim-before-acting is at-most-once on purpose;itemKeyis never a list position; a node runs once per run and a second arrival is aSkippedrow; comparison semantics live inruntime/compare.tsand must not be re-implemented in the builder.If anything in this phase contradicted a source document, add an entry to
.ai/lessons.mdin theContext → Problem → Rule → Applies toformat.
Verify:
pnpm exec biome check .claude/rules/workflow-engine.md 2>/dev/null || true
ls -la .claude/rules/workflow-engine.md
# Expected: the file exists
grep -n "workflow-engine" AGENTS.md
# Expected: one hit in the Workflows row of the Task Router
Out of scope: rewriting .claude/rules/workflow-matcher.md.