Workflow Branching Developer Guide 1 Engine - edmozley/freeitsm GitHub Wiki
Workflow branching - Developer Guide, part 1: the engine
Part 1 of 3 · Part 2: the canvas editor · Part 3: safety, saving and tests · Design and decisions: Workflow branching · GH #364 · 5.8.0
This page follows a workflow with branches from the database row to the run history: how a branch is stored, how the engine picks a path, what it writes to the step log, and how results flow on. Every snippet is quoted from the code as it ships.
In plain words
Before 5.8.0 a workflow was a straight line: trigger → conditions → action, action, action. A branch is a fork in that line. It is one more entry in the same list of actions, so:
- a workflow without a branch is stored, loaded and run exactly as before - nothing in the old path changed shape;
- a branch holds its own lists of actions, one per path, and the engine runs the chosen list with the same loop it runs the top level with - so every rule that applies to an action (switched-off modules, dry run, failure stops the run,
{{merge codes}}) applies inside a branch for free.
There are two kinds, and both always have a path for "none of the above":
| Type | Editor name | Picks a path by | Fallback |
|---|---|---|---|
branch_if |
If / Otherwise | each branch's own conditions, matched all or any | otherwise |
branch_switch |
Choose by value | one field's value, matched equals or contains against each case's values | default |
The files
| File | What it holds |
|---|---|
🟣 workflow/includes/engine.php |
BRANCH_TYPES, MAX_BRANCH_DEPTH, executeBranch(), switchCaseMatches(), evaluateOneCondition(), validateActionTree(), normaliseActionTree(), mapActionTree(), the depth-aware executeActionList() |
🟣 includes/webhook_delivery.php |
webhookMapWebhooks() - credentials encrypted at every depth (part 3) |
🟣 api/workflow/save.php, api/workflow/get.php, api/v1/resources/workflows.php |
The save and load routes (part 3) |
🟡 assets/js/workflow-editor.js, assets/js/workflow-executions.js |
The canvas and the run history (part 2) |
🧪 tests/workflow-branching.php |
38 checks (part 3) |
No new table and no new column: the branch lives in the JSON the workflows.actions column already held.
1. How a branch is stored
-- database/freeitsm.sql (unchanged by branching)
CREATE TABLE IF NOT EXISTS `workflows` (
...
`conditions` TEXT NULL, -- JSON array of {field, op, value}
`actions` TEXT NOT NULL, -- JSON array of {type, args}
...
An ordinary action is {type, args}. A branch is the same shape, with its paths inside args. This is the demo workflow from the test install - route new tickets by the requester's company, with a nested If inside one case:
[
{ "type": "log_message", "args": { "message": "New ticket {{ticket.id}}" }, "x": 220, "y": 200 },
{ "type": "branch_switch", "x": 220, "y": 340, "args": {
"field": "ticket.requester_email",
"compare": "contains",
"cases": [
{ "label": "ABC Ltd", "values": ["abc.com"],
"actions": [ { "type": "log_message", "args": { "message": "Route to Team A" } } ] },
{ "label": "XYZ Group", "values": ["xyz.com", "xyz.co.uk"],
"actions": [
{ "type": "log_message", "args": { "message": "Route to Team B" } },
{ "type": "branch_if", "args": {
"branches": [ { "label": "Urgent", "match": "any",
"conditions": [ { "field": "ticket.subject", "op": "contains", "value": "urgent" } ],
"actions": [ { "type": "log_message", "args": { "message": "Page XYZ on-call" } } ] } ],
"otherwise": { "actions": [] } } } ] } ],
"default": { "actions": [ { "type": "log_message", "args": { "message": "Route to the default team" } } ] } } },
{ "type": "log_message", "args": { "message": "Routed: {{last.message}}" }, "x": 220, "y": 960 }
]
Things to notice:
x/yonly on the top level. They are canvas positions the editor stores; the engine ignores them. Entries inside a path have no position - the path's list order is its order.valuesis a list of strings. The editor saves lookup ids as text ("4"), and the engine compares as text, so4and"4"match.- The fallback is always present.
normaliseActionTree()addsotherwise/defaulton save if a caller left it out (section 6).
Finding branched workflows in SQL is a text search, because the column is TEXT:
SELECT id, name
FROM workflows
WHERE actions LIKE '%"type":"branch\_%';
2. The constants
// workflow/includes/engine.php
public const BRANCH_TYPES = ['branch_if', 'branch_switch'];
/** A branch inside a branch inside a branch, and no deeper - past that it is two workflows. */
public const MAX_BRANCH_DEPTH = 3;
BRANCH_TYPES is deliberately not part of availableActions(), the action catalogue. The catalogue feeds the editor's action-type dropdown, the REST API's GET /workflow-actions, the AI co-author's list of tools and the save routes' "is this a real action?" check. Keeping branches out of it means none of those offer "branch" as an action - each place that must accept a branch asks for it by name.
3. Where a branch enters the run
Every run - a real event, Test fire, Dry run, a form's own action list - ends up in executeActionList(). It gained a $depth parameter and one early exit:
private static function executeActionList(array $actions, array &$payload, array &$stepLog, bool $dryRun = false, int $depth = 0): array
{
foreach ($actions as $i => $action) {
$type = $action['type'] ?? '';
$args = $action['args'] ?? [];
// GH #364: a branch picks one path and runs its actions through this same loop.
if (in_array($type, self::BRANCH_TYPES, true)) {
$failed = self::executeBranch($type, is_array($args) ? $args : [], $i, $payload, $stepLog, $dryRun, $depth);
if ($failed !== null) return ['failed', $failed];
continue;
}
// ... the ordinary action, exactly as before
Nothing below that if changed for a plain action, with one exception - where its result is stored (section 7).
4. executeBranch(): picking the path
private static function executeBranch(string $type, array $args, int $index, array &$payload, array &$stepLog, bool $dryRun, int $depth): ?string
{
$entry = ['kind' => 'branch', 'index' => $index, 'type' => $type, 'depth' => $depth];
if ($depth >= self::MAX_BRANCH_DEPTH) {
$entry['status'] = 'failed';
$entry['error'] = 'Branches can only go ' . self::MAX_BRANCH_DEPTH . ' deep.';
$stepLog[] = $entry;
return "Action {$index} ({$type}): " . $entry['error'];
}
The depth check is a second line of defence: the save routes already refuse a tree deeper than three (section 6), so this only fires for a row written some other way. It fails the run loudly rather than recursing without limit.
If / Otherwise
$path = null; // ['key' => 'branch:0' | 'case:1' | 'otherwise' | 'default', 'label' => .., 'actions' => [..]]
if ($type === 'branch_if') {
$entry['checked'] = [];
foreach (array_values(is_array($args['branches'] ?? null) ? $args['branches'] : []) as $bi => $br) {
if (!is_array($br)) continue;
$match = ($br['match'] ?? 'all') === 'any' ? 'any' : 'all';
$conds = array_values(array_filter(is_array($br['conditions'] ?? null) ? $br['conditions'] : [], 'is_array'));
$results = [];
$ok = $match === 'all'; // all: true until one fails; any: false until one passes
foreach ($conds as $c) {
$r = self::evaluateOneCondition($c, $payload);
$results[] = $r;
if ($match === 'all' && !$r['passed']) { $ok = false; break; }
if ($match === 'any' && $r['passed']) { $ok = true; break; }
}
if (!$conds) $ok = false; // a branch with no conditions never matches - it would hide Otherwise
$entry['checked'][] = ['branch' => $bi, 'label' => (string)($br['label'] ?? ''), 'match' => $match, 'conditions' => $results, 'passed' => $ok];
if ($ok) { $path = ['key' => 'branch:' . $bi, 'label' => (string)($br['label'] ?? ''), 'actions' => $br['actions'] ?? []]; break; }
}
if ($path === null) $path = ['key' => 'otherwise', 'label' => '', 'actions' => $args['otherwise']['actions'] ?? []];
- Short-circuit both ways. all stops at the first failing condition, any at the first passing one - the same cost as the workflow's own conditions.
- A branch with no conditions never matches. An empty
allwould otherwise be vacuously true and swallow every run, hiding Otherwise forever. The save routes refuse such a branch anyway; this is belt and braces. - Every branch tried is logged (
checked[]), not just the winner - so the run history can show why branch 1 was skipped before branch 2 ran.
evaluateOneCondition() is the body of the old evaluateConditions() loop, lifted out unchanged so the workflow's own conditions and a branch's conditions are tested by one implementation - including the category rule (a category condition also matches its subcategories, GH #298):
private static function evaluateOneCondition(array $cond, array $payload): array
{
$field = (string)($cond['field'] ?? '');
$op = (string)($cond['op'] ?? 'equals');
$value = $cond['value'] ?? null;
$actual = self::dotGet($payload, $field);
$tested = $value;
$withSubs = false;
if (in_array($field, self::CATEGORY_FIELDS, true) && in_array($op, ['in', 'not_in'], true) && self::categoryMatchIncludesSubcategories()) {
$tested = self::categoryIdsWithDescendants($value);
$withSubs = true;
}
$out = ['field' => $field, 'op' => $op, 'value' => $value, 'actual' => $actual, 'passed' => self::evaluateOperator($op, $actual, $tested)];
if ($withSubs) $out['includes_subcategories'] = true;
return $out;
}
🔑 Proving the refactor changed nothing: every template and every workflow on Ed's install was dry-run through the old engine and the new one with the same payload, and the two step logs compared byte for byte (part 3).
Choose by value
} else {
$field = (string)($args['field'] ?? '');
$compare = ($args['compare'] ?? 'equals') === 'contains' ? 'contains' : 'equals';
$actual = self::dotGet($payload, $field);
$entry += ['field' => $field, 'compare' => $compare, 'actual' => $actual];
$missing = $actual === null || $actual === '' || $actual === [];
if (!$missing) {
foreach (array_values(is_array($args['cases'] ?? null) ? $args['cases'] : []) as $ci => $case) {
if (!is_array($case)) continue;
if (self::switchCaseMatches($field, $compare, $actual, $case['values'] ?? [])) {
$path = ['key' => 'case:' . $ci, 'label' => (string)($case['label'] ?? ''), 'actions' => $case['actions'] ?? []];
break;
}
}
}
if ($path === null) {
$path = ['key' => 'default', 'label' => '', 'actions' => $args['default']['actions'] ?? []];
$entry['reason'] = $missing ? 'missing' : 'no_match';
}
}
A missing field goes straight to Default, with reason: missing. That is the whole point of Ed's rule - "the logic should always have a default path so unexpected inputs don't break it". A payload with no requester email, a field renamed by a later version, an empty value: none of them can throw, and the log says which it was.
private static function switchCaseMatches(string $field, string $compare, $actual, $values): bool
{
if (is_string($values)) $values = array_map('trim', explode(',', $values));
if (!is_array($values)) $values = [$values];
$values = array_values(array_filter($values, fn($v) => $v !== null && trim((string)$v) !== ''));
if (!$values) return false;
if ($compare === 'contains') {
foreach ($values as $v) if (self::textContains(is_scalar($actual) ? (string)$actual : null, (string)$v)) return true;
return false;
}
if (in_array($field, self::CATEGORY_FIELDS, true) && self::categoryMatchIncludesSubcategories()) {
$values = self::categoryIdsWithDescendants($values);
}
return self::value_in_list($actual, $values);
}
It reuses the engine's existing comparisons rather than writing new ones: textContains() (ignores capitals and the spaces round a typed value - GH #214) and value_in_list() (string-cast equality, so a numeric id matches the saved "4"). A case with no values never matches - an unfinished case cannot catch everything.
5. Running the path, and what the step log records
$entry['taken'] = $path['key'];
if ($path['label'] !== '') $entry['taken_label'] = $path['label'];
$actions = array_values(array_filter(is_array($path['actions']) ? $path['actions'] : [], 'is_array'));
$entry['nothing_to_do'] = $actions === [];
$inner = [];
$before = $payload['last'] ?? null;
unset($payload['last']);
[$status, $error] = self::executeActionList($actions, $payload, $inner, $dryRun, $depth + 1);
$entry['steps'] = $inner;
$entry['status'] = $status === 'failed' ? 'failed' : ($dryRun ? 'dry_run' : 'success');
$stepLog[] = $entry;
- The path runs through
executeActionList()itself, one level deeper - recursion, so a branch inside a path is handled by the same code with no special case. - The path's steps go into their own array (
$inner) and are nested under the branch's entry assteps. The top-level log keeps one entry per top-level item; the history draws the nesting (part 2). nothing_to_dorecords an empty Otherwise / Default being taken - it ran nothing, but it was the path, and the run history says so.
The log entry as stored in workflow_executions.step_log - this is the real run #488 on the test install ([email protected], subject "URGENT printer"):
{
"kind": "branch", "index": 1, "type": "branch_switch", "depth": 0,
"field": "ticket.requester_email", "compare": "contains", "actual": "[email protected]",
"taken": "case:1", "taken_label": "XYZ Group", "nothing_to_do": false,
"steps": [
{ "kind": "action", "index": 0, "type": "log_message", "status": "success", "result": { "message": "Route to Team B" } },
{ "kind": "branch", "index": 1, "type": "branch_if", "depth": 1,
"checked": [ { "branch": 0, "label": "Urgent", "match": "any",
"conditions": [ { "field": "ticket.subject", "op": "contains", "value": "urgent",
"actual": "URGENT printer", "passed": true } ],
"passed": true } ],
"taken": "branch:0", "taken_label": "Urgent", "nothing_to_do": false,
"steps": [ { "kind": "action", "index": 0, "type": "log_message", "status": "success", "result": { "message": "Page XYZ on-call" } } ],
"status": "success" }
],
"status": "success"
}
| Key | Meaning |
|---|---|
taken |
branch:N / case:N (zero-based) / otherwise / default |
taken_label |
the path's name, when it has one |
checked[] |
If only: every branch tried, its conditions with actual and passed |
field, compare, actual |
Choose only: what was compared |
reason |
Choose only, when Default was taken: missing or no_match |
nothing_to_do |
the path taken had no actions |
steps[] |
the path's own step log, same shapes, nested |
status |
success, failed or dry_run |
step_log is TEXT, but MySQL 8's JSON functions read it. Which path did each run of a workflow take?
SELECT e.id, e.started_datetime, jt.taken, jt.reason
FROM workflow_executions e,
JSON_TABLE(e.step_log, '$[*]' COLUMNS (
kind VARCHAR(20) PATH '$.kind',
taken VARCHAR(40) PATH '$.taken',
reason VARCHAR(20) PATH '$.reason')) jt
WHERE e.workflow_id = 143
AND jt.kind = 'branch'
ORDER BY e.id;
488 | case:1 | NULL
489 | default | no_match
490 | case:0 | NULL
491 | default | missing
(That reads top-level branches; a nested one is inside its parent's steps, at $[*].steps[*].)
6. Dry run and failure
- Dry run decides for real. Deciding only reads the payload, so a dry run takes the same path a real run would, and only the path's actions are previewed (
status: dry_run,would_run,would_args). That is the useful answer to "what would this do for this ticket?". - A failing action inside a path fails the run. The inner
executeActionList()returns['failed', ...],executeBranch()returns the message, and the outer loop returns['failed', $failed]- nothing after the branch runs, exactly as when a top-level action fails. The message names the branch:Action 1 (branch_if): Action 0 (set_ticket_priority): ticket_id is required.
7. Results after a branch - and the trap
Since #95 every action's result is merged into the payload so later actions can use it:
| Merge code | Means |
|---|---|
{{last.message}} |
the action just before this one |
{{steps.2.message}} |
the action numbered 2 on the canvas (one-based) |
mergeStepResult() writes steps[$i + 1]. Inside a path, $i counts within the path - so the first action in a path would write steps[1], overwriting the result of the workflow's first top-level action. Every {{steps.1...}} after it would silently read the wrong thing.
// executeActionList(), for a plain action
// TRAP (GH #364): inside a branch only {{last}} moves - $i counts within the
// branch, so writing steps[$i + 1] would overwrite a top-level action's result.
// The branch puts its last result in its own top-level slot when it ends.
if ($depth === 0) self::mergeStepResult($payload, $i, $result);
elseif (is_array($result) && $result !== []) $payload['last'] = $result;
And when the branch ends, what its path produced last becomes the branch's own result:
// What the path produced is the branch's result: in its own slot at the top level,
// so an action after the branch can use {{steps.N...}} whichever path ran.
if (array_key_exists('last', $payload)) {
if ($depth === 0) $payload['steps'][$index + 1] = $payload['last'];
} elseif ($before !== null) {
$payload['last'] = $before; // a path that produced nothing leaves {{last}} as it was
}
return $status === 'failed' ? "Action {$index} ({$type}): " . ($error ?? 'failed') : null;
So in the demo, the last action's Routed: {{last.message}} reads "Route to Team A", "Page XYZ on-call" or "Route to the default team" - whichever path ran - and {{steps.2.message}} (the branch is item 2) reads the same.
unset($payload['last']) before the path runs is what lets the code tell "the path produced something" from "it produced nothing": an empty path puts the old {{last}} back rather than pretending the branch produced it.
The test
a nested action never overwrites a top-level stepfails when the$depth === 0guard is removed - checked by removing it (part 3).
8. What a run looks like, end to end
dispatch('ticket.created', payload)
└─ run() → runInner()
├─ evaluateConditions() workflow's own conditions (unchanged)
└─ executeActionList(actions, depth 0)
├─ log_message steps[1], last
├─ branch_switch ─ executeBranch(depth 0)
│ ├─ requester_email "[email protected]" contains "xyz.co.uk" → case:1
│ └─ executeActionList(case 1 actions, depth 1)
│ ├─ log_message last only
│ └─ branch_if ─ executeBranch(depth 1)
│ ├─ subject contains "urgent" → branch:0
│ └─ executeActionList(branch 0 actions, depth 2)
│ └─ log_message last only
│ (branch_if ends: depth 1, so no steps slot)
│ (branch_switch ends: steps[2] = last)
└─ log_message "Routed: {{last.message}}" steps[3], last
Continue: Part 2 - the canvas editor.