Processes (*.bpmn, DMN)
Business work that spans several steps and waits — timers, events, people approving. Draw the process in BPMN (Camunda 8 / Zeebe flavour), decide by the numbers with a DMN table; manh.run keeps its state and resumes it on time.
app/orders/
├── checkout.bpmn # BPMN model (any BPMN modeler, Camunda 8 / Zeebe flavour)
├── reserve.task.ts # service task type="orders/reserve"
├── approval.dmn # DMN decision table (amount → who approves); a businessRuleTask calls it
├── post.ts # start("app/orders/checkout.bpmn", …)
└── [no]/pay/post.ts # send("order:" + no, "paid", …)Role
Use it when one piece of business takes time: an order that cancels itself if unpaid after 24 hours, a large order a manager must approve with escalation after 2 days, a follow-up email series. Nothing runs and nothing is used while a run waits. The state lives in the app’s own database. A single slow task after a request is a *.job.ts; a technical chain of steps written in code is a *.workflow.ts.
Exports
*.bpmn: one executable<process>. Service tasks point at their handler withzeebe:taskDefinition type; conditions are FEEL (=total >= 1000). A business rule task points at a DMN decision table withzeebe:calledDecision decisionId+resultVariable.*.task.ts:defaultis anasync (input, ctx)function returning an object, which becomes process variables. The type defaults to the path withoutapp/and.task.ts.*.dmn: one or more<decision id>as a decision table (DMN 1.3, any DMN editor). Each cell is FEEL (no leading=): an input column is an expression over the variables, a rule’s input entry is a unary test (< 20000000,[20..100),"VN",-for any), an output entry is an expression. Hit policy: UNIQUE (default), FIRST, COLLECT.
Example
import { BpmnError } from "manh/workflow";
import { reserveStock } from "./repository";
export default async function (input: { orderId: number }) {
const ok = await reserveStock(input.orderId);
if (!ok) throw new BpmnError("OUT_OF_STOCK", "Out of stock"); // takes the error boundary with this code
return { reserved: true };
}import { start } from "manh/workflow";
export default async (c, { body }) => {
const order = await createOrder(body);
start("app/orders/checkout.bpmn", { orderId: order.id, total: order.total }, { key: "order:" + order.id });
return order;
};import { tasks } from "manh/workflow";
export const access = ["manager"];
export default () => tasks({ group: "manager" }); // approval inbox; completeTask(id, data) approvesA “by the amount” rule (a purchase over 20M needs a department head, over 100M the director) belongs in a DMN decision table that a businessRuleTask calls, not a long chain of FEEL conditions on a gateway:
<decision id="approval" name="Who approves"><decisionTable hitPolicy="FIRST">
<input id="i1" label="Amount"><inputExpression typeRef="number"><text>amount</text></inputExpression></input>
<output id="o1" name="approver" typeRef="string"/>
<rule><inputEntry><text>< 20000000</text></inputEntry><outputEntry><text>"team_lead"</text></outputEntry></rule>
<rule><inputEntry><text>[20000000..100000000)</text></inputEntry><outputEntry><text>"head"</text></outputEntry></rule>
<rule><inputEntry><text>>= 100000000</text></inputEntry><outputEntry><text>"director"</text></outputEntry></rule>
</decisionTable></decision><bpmn:businessRuleTask id="who"><bpmn:extensionElements>
<zeebe:calledDecision decisionId="approval" resultVariable="approver" />
</bpmn:extensionElements></bpmn:businessRuleTask>
<!-- then a user task with assignee="=approver", or a gateway on =approver = "director" -->A full purchase-approval flow: multi-level approval (a DMN table picks the approvers by amount), parallel approval by several people (multi-instance), and an overdue reminder (a non-interrupting boundary timer that skips weekends + holidays):
<!-- 1) Multi-level approval: a DMN table picks who must sign, by amount -->
<bpmn:businessRuleTask id="pick"><bpmn:extensionElements>
<zeebe:calledDecision decisionId="approval" resultVariable="signers" />
</bpmn:extensionElements></bpmn:businessRuleTask>
<!-- 2) Parallel approval by several people: one task each, one token out when all finish (or two sign off) -->
<bpmn:userTask id="approve" name="Approve order"><bpmn:extensionElements>
<zeebe:assignmentDefinition assignee="=person" />
<zeebe:loopCharacteristics inputCollection="=signers" inputElement="person"
outputCollection="votes" outputElement="=ok" />
</bpmn:extensionElements>
<bpmn:multiInstanceLoopCharacteristics isSequential="false">
<bpmn:completionCondition>=count(votes) >= 2</bpmn:completionCondition>
</bpmn:multiInstanceLoopCharacteristics></bpmn:userTask>
<!-- 3) Overdue reminder: a NON-INTERRUPTING timer after 1 business day (skips weekends + VN holidays); the task stays open -->
<bpmn:boundaryEvent id="remind" cancelActivity="false" attachedToRef="approve">
<bpmn:extensionElements><zeebe:properties><zeebe:property name="calendar" value="vn" /></zeebe:properties></bpmn:extensionElements>
<bpmn:timerEventDefinition><bpmn:timeDuration>P1D</bpmn:timeDuration></bpmn:timerEventDefinition>
</bpmn:boundaryEvent>
<bpmn:sequenceFlow id="r1" sourceRef="remind" targetRef="sendReminder" /> <!-- side path: email a reminder -->Split a reusable flow into its own file and call it: “approve contract” calls “approve budget”.
<!-- call activity: run app/budget/approve-budget.bpmn as a child run, wait for it, then continue -->
<bpmn:callActivity id="approveBudget" name="Approve budget">
<bpmn:extensionElements><zeebe:calledElement processId="approve-budget" />
<zeebe:ioMapping>
<zeebe:input source="=contractValue" target="amount" /> <!-- into the child run -->
<zeebe:output source="=decision" target="budgetOk" /> <!-- back out -->
</zeebe:ioMapping></bpmn:extensionElements></bpmn:callActivity><bpmn:process id="approve-budget" isExecutable="true">
<bpmn:startEvent id="s" /> <!-- … budget-approval steps, set the variable decision … --> <bpmn:endEvent id="e" />
</bpmn:process>Good to know
- Supported: start, end, terminate, service / send, user, script (FEEL), business rule (DMN decision table), receive, exclusive, parallel, inclusive (diverge: every branch whose condition is true; join: wait for every token that can still arrive), event-based gateway, timer and message events, timer / error / message boundary events, embedded sub-process and call activity, plus standard loop, conditional events and the ad-hoc sub-process (below).
checkreports anything else (a Sequential ad-hoc sub-process, a timer-triggered event sub-process…) with the element id. - Embedded sub-process (
<bpmn:subProcess>): a block with its own start / flow / end (exactly one start, at least one end). A token enters the inner start, runs the inner flow, and one token leaves on the sub-process’s outgoing flow when the inner flow ends. Use it to attach one boundary event to a whole block: a boundary timer that cancels the block and takes a timeout path, or a boundary error that catches aBpmnErrorthrown by any task inside. An error inside the block (including aBpmnErrornothing inner catches) propagates to the sub-process’s error boundary; with no matching boundary anywhere the run stops in an incident. A sub-process shares the run’s variables (an inner write is visible to the rest of the run). Multi-instance on a sub-process is not open yet (put the multi-instance on a task inside it). - Call activity (
<bpmn:callActivity>+<zeebe:calledElement processId="..." />): runs another.bpmn(by its<process id>) as a separate child run — its own run row, tasks, timers and incidents, shown in the runs list. The parent waits at the call until the child finishes, then continues. By default all of the parent’s variables go in and all of the child’s come back; addzeebe:ioMappingto map only some. A child incident leaves the parent blocked at the call (fix and retry the child, and the parent resumes); a child that fails / is cancelled surfaces as an incident on the parent. Cancelling the parent cancels the child.checkreports acalledElementwhose process id no.bpmndefines, and a process cannot call itself. - A non-interrupting boundary (
cancelActivity="false", timer or message): opens a side path (a reminder, an escalation) without cancelling the host task — the host keeps running. An interrupting boundary (the default) cancels the host and takes the branch. SLA / deadline = a user task + a non-interrupting boundary timer. - Deadline (SLA): add
<zeebe:taskSchedule dueDate="P1D"/>to a user task (an ISO duration counted from creation, a date-time, or=FEEL). The inbox shows a “due soon” / “overdue” badge and sorts by the deadline; theoverdueflag is computed on read, with no extra write. Escalation when it passes is the non-interrupting boundary timer above. - Multi-instance (
multiInstanceLoopCharacteristicson a task): runs one instance per item ofinputCollection(a FEEL list), withinputElementbound to the item.isSequential="false"= parallel (“several people approve at once” — every task opens together);true= one after another. Exactly one token leaves when all instances finish orcompletionConditionis true;outputCollectiongathers the results in order (a service task gathers them here rather than merging into the shared variables, to avoid races). - Vietnam business calendar: add
zeebe:property name="calendar" value="vn"to a timer event → the duration counts business days, skipping Saturdays / Sundays and public holidays (Tết, Hùng Kings, 30 Apr, 1 May, 2 Sep); a due date landing on a weekend / holiday rolls to the next business day. Days / weeks only (not months / years). The lunar holiday list is updated yearly. - DMN tables: a cell is FEEL (no leading
=). Hit policy UNIQUE (default; more than one match stops the run as an incident), FIRST (the first matching row wins), COLLECT (a list of every match). No rule matches →null(UNIQUE/FIRST) or[](COLLECT). One output column → the value itself; several → an object. AbusinessRuleTaskpointing at a decision that does not exist is acheckerror. - With the same
keywhile a run is in progress,startreturns that run instead of starting a second one. - Deploying a new version of a model never redirects a running run: it finishes on the version it started with.
- Call
start,send,completeTaskfrom post / put / patch / delete, not fromget.ts. checkparses every FEEL expression (conditions, ioMapping, scripts, timers) and reports a syntax error with the element id.- A condition must give
trueorfalse. A missing variable (=amount > 1000with noamount), a service task out of retries or a missing handler stops the run as an incident (INCIDENT) instead of taking the default flow. Fix the data or deploy a fix, then press Retry: the run continues from that step. - Steps, retry from a failed step and cancel: Operations › Workflows in the workspace.
The “My Tasks” inbox
People do the user-task steps inside the app. tasks({ user }) is the signed-in person’s inbox (tasks assigned to them, taken by them, or their group); tasks({ requested: user }) is the tasks they started and are waiting on others for — they can see them but can’t complete them; tasks({ group }) is a group’s open tasks. Each task carries assignee, requestedBy (who triggered the run — pass start(path, input, { by: user.id })), dueAt and an overdue flag.
import { reassignTask, notifications, markRead } from "manh/process";
export default async (c, { user, body }) => {
// only someone who may work on it (assignee / claimer / group), or an app admin ({ admin: true }), may reassign
await reassignTask(body.taskId, { to: body.to, reason: body.reason }, user);
return { bell: await notifications({ user, unread: true }) }; // in-app notifications (no e-mail)
};reassignTask / delegateTask hand a task to someone else: the new assignee can act, the old one can’t; taskHistory(id) keeps the trail. Notifications are in-app (notifications, markRead) — one row per event (assigned / reassigned / overdue / completed). The tasklist block builds the whole /tasks page with these tabs, deadline badges, a reassign button and a notification bell.
Analytics
Operations › Analytics reads a process by time range, computed straight from run history (nothing to configure):
- Heatmap — painted on the diagram: how often each step runs, how long (avg / p50 / p90), how long people wait to pick a task up; paths glow by traffic.
- Variants — the paths runs actually took. A variant is the ordered sequence of steps a run ran, through to its end step (so two runs with different outcomes — approved, rejected, escalated on a deadline — are two variants). A ranked table shows which path is most common: case count, share, median duration; the rest fall into an “Others” row. Click a variant to highlight its path on the diagram and list the cases that took it.
- Compare — put two cohorts of cases side by side (by default the previous period and the current one, e.g. before and after a model change) and see what changed. Each cohort is a time range; the table shows, per metric, cohort A vs B and the delta: the variant mix (which variants rose, fell, appeared or disappeared), per-step durations (median / p90), each gateway’s branch split, and throughput (case count, completion rate, average run time). It always states each cohort’s case count; read a delta as “went together with”, not cause. The variant mix needs per-run detail (kept 30 days), so a cohort older than that has no mix.
- Journey — pick one case (click a row in the Variants or Outliers case list) to see that run end to end, in order: each executed step with its type, start / end time, duration and outcome; which branch each gateway took (and which it skipped); for user tasks who claimed and who did it, how long it waited and how long it was worked, the due date and any hand-offs; incidents with their error; what each step returned and the run’s variables (bounded). The path is painted on the diagram. One run of one process; run detail is kept 30 days. A gateway’s place on the timeline is inferred from the flows taken (a gateway writes no row of its own).
- Conformance — measures how far real runs deviate from a reference path. The reference defaults to the most common variant in the range; you can pin another variant (pick it from the list) as the “happy path”. A case conforms when its sequence of steps equals the reference exactly. The page shows the conforming rate, then for the deviating cases which steps were missing (in the reference but not run), which were unexpected (run but not in the reference), and the first divergence (after which reference step the case’s path first differs) — where runs most often go off-script — plus the most common deviating variants (click one to paint its off-reference steps on the diagram). It needs per-run detail, so it reads the last 30 days. This closes the variant-analysis set (Variants, Compare, Journey, Conformance).
- Outliers — the step that loses the most time above its p90, the slowest runs, and the variables slow runs tend to share.
- Branch — for a gateway and an end event: what share of runs on each outgoing path reach that end.
- People’s tasks — wait and work time by group, by person, by step.
Numbers come from per-run history for the last 30 days; longer ranges use daily rollups (kept 13 months). Variants, Outliers and Branch need per-run detail, so they always clamp to 30 days.
Signals, transactions and compensation
Two last pieces for real business processes: one event that reaches many runs at once, and a clean way to undo when a chain of steps fails part-way.
- A signal is a broadcast — one throw, many listeners. A message (
send) goes to one run; a signal is thrown once and reaches every catch of the same signal name across the app’s running instances at that moment (scope = this app; no cross-app signalling). Declare<bpmn:signal name="paid"/>and reference it bysignalRef. Throw it from an intermediate throw event or an end event (signalEventDefinition); catch it with an intermediate catch event or a boundary event on an activity (interrupting, orcancelActivity="false"for non-interrupting — a side path that leaves the task running); or put asignalEventDefinitionon a process’s start event so a broadcast starts a new instance of that process. A catch that is not waiting when the signal is thrown does not receive it (signals are transient) — when exactly one run must get it and it may arrive early, use a message. A throw with no waiting catch writes nothing. - Transactions and compensation — the saga / undo pattern. Wrap steps that must undo cleanly (reserve stock, charge a card, book a slot) in a
<bpmn:transaction>(it runs like an embedded sub-process). Give each reversible activity a compensation boundary (<bpmn:boundaryEvent><bpmn:compensateEventDefinition/>) linked by an<bpmn:association sourceRef="<boundary>" targetRef="<handler>"/>to a handler activity markedisForCompensation="true"(a service or script task —undoBook,refund); it sits off the normal flow and runs only on compensation. Each activity that completes is remembered. Trigger compensation with a cancel end event (<bpmn:endEvent><bpmn:cancelEventDefinition/>inside the transaction) or a compensation throw (<bpmn:intermediateThrowEvent><bpmn:compensateEventDefinition/>): the handlers of the activities that completed run in reverse completion order (the last thing done is undone first), and the ones that never ran are skipped. A cancel end also cancels the transaction and takes its cancel boundary’s path (<bpmn:boundaryEvent><bpmn:cancelEventDefinition/>on the transaction); a compensation throw compensates and then continues. A handler that throws stops the run in an incident; a retry resumes from the handler that failed (write handlers that are safe to run more than once). Known limits: compensation is triggered from inside the transaction (a completed transaction is not compensated from outside), a compensation handler is a single service or script task (not a user task or a sub-flow), and it sees the run’s current variables.
Event sub-processes and escalation
React to something that happens inside a scope (the whole process or one sub-process) without drawing a boundary on every step.
- An event sub-process (
<bpmn:subProcess triggeredByEvent="true">) sits inside the scope with no sequence flow in or out. Its own start event decides when it runs: aBpmnErrorin the scope, a signal, an escalation, or a message sent withsend. It listens only while the scope is running, and shares that scope’s variables. - Interrupting (the default, always for errors): the scope’s other tokens are cancelled (open user tasks closed), the handler runs, then the scope completes and the flow continues after it. Non-interrupting (
isInterrupting="false"): the handler runs as a side flow, the scope keeps going, and every signal / message / escalation that arrives is a new run. The scope does not complete while a handler is still running. - Escalation is a notice travelling up, not a failure. Declare
<bpmn:escalation id="late" escalationCode="LATE"/>, throw it from an intermediate throw or end event (escalationEventDefinition), catch it with an escalation boundary event on a sub-process (interrupting, orcancelActivity="false") or an event sub-process. It travels inside-out: at each scope the event sub-processes first, then the boundary on the sub-process, then the scope outside. Nobody catches it = ignored and the thrower carries on; a non-interrupting catch lets the thrower carry on too; an interrupting catch cancels the scope it sits on. - Limits: a timer-triggered event sub-process is refused by
check(it needs the external clock) — use a boundary timer on a sub-process; an escalation does not cross a call activity into the parent run; an escalation boundary attaches to a sub-process only; a signal / message is only caught while the run is waiting at that moment.
Loops, conditions and ad-hoc steps
Three more shapes for processes that repeat, wait for data, or leave the order to the people doing the work.
- Standard loop. Put
<bpmn:standardLoopCharacteristics testBefore="true" loopMaximum="5"><bpmn:loopCondition>=attempts < 3</bpmn:loopCondition></bpmn:standardLoopCharacteristics>on a service, user or script task, a business rule task or an embedded sub-process, and it repeats one iteration at a time while the condition is true.testBefore="true"(the default) checks first, so a false condition at once means the step never runs;testBefore="false"runs once and then checks.loopMaximum(1 to 1000) stops the loop quietly when reached. Without it there is a hard cap of 1000 iterations: a loop still true after that stops the run in an incident instead of spinning forever. The condition must give true or false, so an unset variable or a typo is an incident, just like on a gateway. For “once for each item of a list” use multi-instance instead; the two cannot share a task. - Conditional events.
<bpmn:conditionalEventDefinition><bpmn:condition>=stop = true</bpmn:condition></bpmn:conditionalEventDefinition>works as a boundary event (interrupting orcancelActivity="false"), as an intermediate catch that waits until the condition is true (already true on arrival means it carries on at once), or as the start of an event sub-process. The condition reads the process variables and is checked when the element becomes active and after every step that ran in the wake-up (a task finished, a script ran, a message came in). It is not a live watch: variables only change while the run is executing, so nothing polls and no timer is set. A condition about the clock or a table is never noticed; use a timer, or read the value in a script task first. An unset variable counts as false. A non-interrupting boundary or event sub-process fires once each time the condition goes from false to true, not on every check. - Ad-hoc sub-process.
<bpmn:adHocSubProcess>starts every activity inside it that has no incoming flow, all at once, and each runs on its own. No start or end event is needed. The optional<bpmn:completionCondition>=approved = true</bpmn:completionCondition>is checked each time an inner activity finishes; once it is true, whatever is still running is cancelled (open tasks close) and the process continues after the sub-process. With no completion condition it ends when every activity is done. Each activity runs once, so repeat one with a standard loop.ordering="Sequential"is refused because nothing chooses the next activity: chain the steps with sequence flows instead.
Link events: jump to another step in the same process
Long diagrams grow arrows that cross the whole page. Link events replace them with a pair of labels: where to jump from and where to land.
- Syntax. The jump is
<bpmn:intermediateThrowEvent><bpmn:linkEventDefinition name="review-again"/></bpmn:intermediateThrowEvent>. The landing is<bpmn:intermediateCatchEvent><bpmn:linkEventDefinition name="review-again"/></bpmn:intermediateCatchEvent>. When a run reaches the throw it moves at once to the catch of the same name and continues along that catch’s outgoing flow. Jumping backwards works too, so it can serve as a “do it again” loop. - Paired by name, inside one level. Each name has exactly one catch and one or more throws (all jump to that catch). Both sit at the same level: in the main process, or in the same embedded sub-process. Jumping across a sub-process border is refused, and links are not allowed inside an ad-hoc sub-process. A throw has no outgoing flow and a catch has no incoming flow.
- Nothing waits. This is not a message: the jump happens right inside the wake-up that is running, changes no variable and writes no event row.
checkrefuses a name with no catch, a catch nobody jumps to, two catches with the same name, or a pair on two different levels, naming the elements.
Starting a process by itself: timer and message
Two more ways to begin a process, besides calling start().
- Timer start. Give the process’s start event a cron:
<bpmn:startEvent id="daily"><bpmn:timerEventDefinition><bpmn:timeCycle>0 9 * * 1-5</bpmn:timeCycle></bpmn:timerEventDefinition></bpmn:startEvent>. It is a 5-field cron in UTC, the same as a.cron.tsfile, and nothing else is accepted on a start event: notimeDate, notimeDuration, noR/PT1Hrepeating intervals. Each time the schedule fires, one new instance starts with empty variables. A fire is not queued if it is missed, and an instance that is still running does not stop the next one from starting. The schedule counts toward your app’s cron limit like any other. - Message start. Put a
<bpmn:messageEventDefinition messageRef="M1"/>on the start event, with<bpmn:message id="M1" name="order.placed"/>declared in the file. Thensend("app/orders/checkout.bpmn", "order.placed", { orderId: 12 })— the process path where a run id would go — starts a new instance and returns its id; the object you send becomes the process variables. Every matchingsendstarts its own instance: there is no match-or-start by key. A name the start event does not listen for falls back to the normalsendto a run.
A process has exactly one start event, so it begins plain, with a signal, on a timer, or on a message. In the browser Playground a message start works through send, while a timer start only fires when you fast-forward the demo clock.
Next steps
- *.workflow.ts — a technical chain of steps written in code, on the same engine.
- *.job.ts — one slow task in the background after a request.
- *.cron.ts — runs on a schedule; it can call
startto open a process every morning.