suppa-mcp-2 1.44.2 → 1.44.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -725,6 +725,9 @@ process when someone opens it:
725
725
  - request and form flows take what the submission already carries (`formData`,
726
726
  `number`, `createdBy`) instead of selecting it again;
727
727
  - business rules are visible on the canvas, technical logic goes into one `code` node.
728
+ - **Settings and the Set node.** `$workflow.settings` is read in any expression, trigger
729
+ conditions included, with no read node; a Set «Config» holds per-flow constants;
730
+ settings are never state and never hold secrets (those are credentials).
728
731
  - **Publishing that survives the builder.** It writes through the API with the builder
729
732
  tab closed, verifies the draft by hash, then publishes and tests a live run.
730
733
 
@@ -743,7 +746,7 @@ node $S/render-graph.mjs placed.json preview.svg --png preview.png # look befo
743
746
 
744
747
  `references/node-reference.md` holds the parameter shapes verified on running
745
748
  automations: triggers, conditions, switch outputs, approvals, links, the request
746
- trigger's output. `references/publishing.md` holds the write → hash → publish → live-test
749
+ trigger's output. `references/engine.md` holds how the engine runs a graph, read from the automation service: items per node, waits and resume snapshots, retries, the author's rights, auto-deactivation, before-* limits, comparators, lazy loading, expression globals, the code node, limits. `references/publishing.md` holds the write → hash → publish → live-test
747
750
  order.
748
751
 
749
752
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.44.2",
3
+ "version": "1.44.4",
4
4
  "description": "MCP server for the Suppa platform (modern.suppa.me) — Tasks, Docs/Pages, Entities & Schema, Forms, Automations, and file attachments, with multi-tenant Google auth. Node port of PyPI suppa-mcp.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -9,13 +9,13 @@ description: Use when creating, restructuring, renaming, laying out or optimizin
9
9
 
10
10
  Build an automation as a **source you regenerate** (a script that writes nodes, connections and settings), not by hand in the builder. Three goals: **English, numbered names** that read as the flow; a **layout where edges are straight**; and **no wasted runs or duplicate side effects**.
11
11
 
12
- Parameter shapes (triggers, conditions, switch outputs, approvals, links) are in `references/node-reference.md`. Never guess them: `events: ["update"]`, `watchFields: ["stageId"]`, `{ "and": [...] }` and switch outputs `"0"/"1"` are all wrong.
12
+ Parameter shapes (triggers, conditions, switch outputs, approvals, links) are in `references/node-reference.md`. How the engine runs them — items, waits, retries, comparators, limits, what publish refuses — is in `references/engine.md`. Never guess them: `events: ["update"]`, `watchFields: ["stageId"]`, `{ "and": [...] }` and switch outputs `"0"/"1"` are all wrong.
13
13
 
14
14
  ## Workflow
15
15
 
16
16
  `scripts/` sits next to this file: `suppa_health_check` → `skill_files.automations_skill` names the installed folder (an npm install: `node_modules/suppa-mcp-2/skills/building-suppa-automations/`). The scripts need only Node ≥ 18. `graph.json` is either shape:
17
17
  - the stored one, `{ nodes, connections, settings? }`: nodes carry `parameters`, connections are `{ source: { handle: [{ node, index }] } }`. That is what `suppa_update_automation` takes in `nodes_json` / `connections_json`, and what `auto-layout` / `layout` write;
18
- - a `suppa_get_automation` answer as is (`nodes[].config` + `edges`): the scripts read its draft side, `--previous` its `published` side.
18
+ - a `suppa_get_automation` answer as is (`nodes[].config` + `edges`): the scripts read its draft side.
19
19
 
20
20
  1. Design the flows with the checklist below. Write the build script (ids, names, parameters, settings), never the builder UI.
21
21
  2. `node scripts/lint-graph.mjs graph.json`
@@ -30,10 +30,13 @@ Parameter shapes (triggers, conditions, switch outputs, approvals, links) are in
30
30
  ## One process = one automation
31
31
 
32
32
  - **One automation per business process.** It may hold **several flows, each with its own trigger**, for example A for a form submission and B for a task stage change. The engine matches every trigger node separately and starts the run at the one that fired. Do not split a process into automations because "a workflow has one entry point" — it does not.
33
- - **Loop protection is keyed by workflow id.** A write from flow A never starts flow B of the same automation. A write from another automation does start it. So:
33
+ - **Loop protection is keyed by workflow id.** A write from flow A does not start flow B of the same automation. A write from another automation does start it. So:
34
34
  - inside one automation, the flow that writes does its own follow-up (mark the request rejected, notify);
35
35
  - across automations, the same write runs twice. That is the classic duplicate notification.
36
- - **Settings live in the automation.** Put everything tenant-specific in `settings.<key>`: people, project and stage ids, BP switches, testMode. Each flow reads it with `getById AutomationWorkflow id: "={{ $workflow.id }}"` → `activeSettings`. Do not keep a separate settings record or select.
36
+ - **Except after a wait.** A write made after an `approval` / `wait` resumed **does** start the automation's other flows (checked live on 2026-10-27).
37
+ - Give flow B a trigger filter that the post-approval write does not match: `watchFields` plus a `conditions` value that this write never sets.
38
+ - Or move the follow-up into the flow that writes.
39
+ - **Settings live in the automation.** Put everything tenant-specific in `settings.<key>`: people, project and stage ids, BP switches, testMode. Every expression reads it directly, trigger conditions included: `={{ $workflow.settings.<key>.<name> }}`. No settings read node is needed, and no separate settings record or select. Details and limits are in «Settings and the Set node».
37
40
 
38
41
  ## Requests and form submissions: the trigger already holds the data
39
42
 
@@ -111,23 +114,103 @@ Someone who opens the automation should read the flow from the canvas alone. Eve
111
114
 
112
115
  - **Do not leave dangling ends by accident.** A free `false` / `rejected` / switch output must be intended. Say so in the description, or connect it.
113
116
  - **Size budget.** More than ~25 nodes or ~20 columns in one flow means it no longer reads at a glance. Move logic into a `code` node or drop decoration before splitting.
114
- - **Settings over literals.** Ids, people, stages and switches live in settings. The trigger filter is generated from them in the build.
117
+ - **Settings over literals.** Ids, people, stages and switches live in settings. The trigger filter reads them too (`"value": "={{ $workflow.settings.<key>.stages }}"`), so a change needs a republish, not a rebuild.
118
+ - **Three values must stay literal.** `formSubmission.formId` routes the trigger before any expression runs (E18), and every `credentialId` is checked at publish (E16): publish refuses an expression in either. `triggerWebhook.webhookPath` is matched as written: an expression there passes publish and the trigger never fires.
119
+
120
+ ## Settings and the Set node
121
+
122
+ Verified on modern-expo.test (2026-10-27, a throwaway probe automation):
123
+ - `$workflow.settings.*` resolves in any node's expressions and in trigger conditions;
124
+ - a production run sees the **published** settings: a draft change it ignored until the republish.
125
+
126
+ | Where a value lives | Use it for | How it is read |
127
+ |---|---|---|
128
+ | `settings.<key>` | Everything tenant-specific the whole automation shares: people, project / stage ids, switches, testMode. **The only place a trigger condition can read from** | `={{ $workflow.settings.<key>.<name> }}` in any expression. In a `code` node, inline it: `const cfg = ={{ JSON.stringify($workflow.settings.<key>) }};`, because the code text is resolved before it runs |
129
+ | A `set` node «Config» right after the trigger | Constants and derived values local to one flow, including ones computed from settings (`={{ $workflow.settings.<key>.limit * 2 }}`) | `={{ $('A1.1 Config').first().json.<name> }}` |
130
+ | A dedicated directory entity (real relation fields) | Many record references, or references that must survive moving the automation between dev / stage / prod | A `suppa` read |
131
+ | Credentials | **Secrets.** Never in settings or a `set`: every value an expression produces lands in the run data, which anyone who can read the automation's runs can see | — |
132
+
133
+ **Settings: shape and limits**
134
+ - **A relation from settings is written like any relation, `{ id }`, and the expression must be the whole field.** A Suppa node passes `fields` to entity-builder as they are.
135
+
136
+ | Field type | Value |
137
+ |---|---|
138
+ | many-to-one | `"responsible": "={{ { id: $workflow.settings.<key>.responsibleId } }}"` |
139
+ | many-to-many, replaced | `"watchers": "={{ $workflow.settings.<key>.watchers }}"`, with settings holding `[{ "id": 5 }, { "id": 7 }]` |
140
+ | many-to-many, added or removed | the same, plus `merge` / `unmerge: ["watchers"]` on an update |
141
+ | enum (a relation in 2.0) | `{ id: <enumValueId> }`, never the value text |
142
+
143
+ - `={{ … }}` in the middle of text turns an object into the string `[object Object]`. This was verified: `"owner ={{ { id: 1 } }}"` gave `"owner [object Object]"`.
144
+ - A bare number instead of `{ id }` returns success and stores `null`.
145
+ - **An id in settings is a number in JSON, not a relation.**
146
+ - Nothing checks that the record exists. A deleted record leaves a dangling id.
147
+ - Ids differ between tenants and environments. Moving an automation between dev, stage and prod does not remap the ids inside settings.
148
+ - Fields of that record are **not** reachable through settings. `$workflow.settings.<key>.responsible.name` does not exist, and lazy loading works only for `$json` items. For a name, read the record (`getById`).
149
+ - Settings suit one or two stable records, such as a default assignee. For many references, or ones that must survive environment moves, use a directory entity with real relation fields.
150
+ - **One top-level key per process (`settings.itRequest`).** The platform keeps keys of its own next to yours (seen on test: `alertUserIds`, `fullRefresh`, `definitionKey` / `definitionVersion`; the engine also reads `rateLimit*`, `errorBreaker*` and `alertChannels` there). An update merges top-level keys, so resend your whole `settings.<key>` and never replace the object as a whole.
151
+ - `settings.variables` / `$vars` is not available yet: `typeof $vars` is `undefined` in a run. Keep user-facing configuration under your own key.
152
+
153
+ **The Set node «Config»: what it does and does not do**
154
+ - **It is not visible to trigger conditions.** They are checked before any node has run, so filters read settings only.
155
+ - **It must be on the path the run took.** `$('Config').first()` is `null` when Config did not run in this run. `.json` on it throws an «Expression error» and fails the node. Use `$('X').first()?.json` only where skipping is intended.
156
+ - **It reshapes the item.**
157
+ - Without `keepOnlySet`, the config fields join `$json` and travel on with the record.
158
+ - With `keepOnlySet: true`, the item becomes the config, and the trigger data is reachable only through `$('A1. Start…')`.
159
+ - **Changing a value needs a republish, as with settings.** The value is part of the published nodes. A test run sees the draft at once.
160
+
161
+ **Settings are not state.** Nothing a run does reaches the automation's published settings:
162
+ - A `set` changes only the items moving through the flow.
163
+ - A Suppa write to `AutomationWorkflow.settings` changes only the **draft**. entity-builder's `AutomationDraftGuardExtension` strips every write to `activeSettings` except the publish, and raises `hasUnpublishedChanges`. Production runs do not see the value, and a run already going keeps its snapshot. An automation that edits itself is a bad idea in any case.
164
+ - A counter or a «last processed» marker belongs in a record of its own entity, read and written by `suppa` nodes.
115
165
 
116
166
  ## Safe runs
117
167
 
118
- - **Republishing does not restart the runs that are waiting.** A run parked at an `approval` resumes against the graph that is published when the approver answers. If that approval's node id is gone, or the nodes after it read names that no longer exist, the run cannot continue as designed.
119
- - Keep the ids of approval / wait nodes stable across rebuilds.
120
- - Before publishing a reshaped graph, list the waiting runs (`suppa_list_automation_runs status: "waiting"`) and say which ones the change strands.
121
- - `lint-graph graph.json --previous published.json` names approval ids the new graph drops.
168
+ - **A waiting run keeps the graph it started with.** A run parked at an `approval` / `wait` resumes with its own snapshot of the nodes, connections and settings. Republishing a reshaped graph is safe for it, and a fix does not reach it either.
169
+ - **Unpublishing cancels waiting runs.** Unpublishing, retiring or an auto-deactivation cancels each waiting run when it wakes. Before unpublishing, list them (`suppa_list_automation_runs status: "waiting"`) and say whose open approvals will be lost.
122
170
  - **Missing configuration is an error, not a quiet stop.** When settings lack a person, a stage or a project, the `code` node throws, for example `throw new Error('Not configured: chro, stage hrd')`. Then the run shows as failed, with the reason.
123
171
  - `return []` is for «this record is not ours», such as a filter or a test-mode guard.
124
172
  - A `return []` on a missing setting shows as a successful run that did nothing.
125
- - **A node can run twice; a write must not double.** Runs are retried (`retryCount`), and a stage can be moved back and forth.
173
+ - **Five failed runs in a row switch the automation off** (the error breaker, `references/engine.md`). The author and `alertUserIds` are alerted. So throw for a misconfiguration someone must fix, never for an expected case.
174
+ - **A node can run twice; a write must not double.** Whole runs are never retried (`retryCount` is always 0). What repeats a side effect:
175
+ - `retryOnError` on that node, which re-runs it whole, so a message goes again on every channel;
176
+ - a manual replay from a node;
177
+ - the trigger firing again: a stage moved back and forth, a write after a wait, or another automation's write.
126
178
  - Before a create that must happen once (a task, a link, a comment), check that it does not exist yet. Look it up by the link or by a field that marks it, such as `automationResults.taskId` on the request.
127
179
  - Alternatively, make the write an update of a known record.
128
180
  - Updates that set a value (stage, assignee) are safe to repeat.
129
181
  - Inserts and `merge` additions (watchers, auditors) are not.
130
182
 
183
+ ## How the engine runs a graph
184
+
185
+ The details, with the source lines, are in `references/engine.md`. The rules that change a design:
186
+
187
+ - **`suppa`, `approval`, `wait` and `responseEntity` run once, on item 0. `set`, `if`, `switch`, `filter` and messages run per item.**
188
+ - A `select` of N rows followed by `updateById` updates only the first row.
189
+ - The same select followed by a `notification` sends N messages.
190
+ - To write many records, use `update` with `conditions`, an `insert` with an array, or a `loop`.
191
+ - **The run acts as the automation's author.**
192
+ - Fields the author cannot read are `null`, and they never match a condition.
193
+ - A deactivated author fails every run.
194
+ - Give the automation an author whose rights cover what it reads and writes.
195
+ - **Before-* flows:**
196
+ - no `wait` or `approval` (E11);
197
+ - 5 s in total, after which the change is silently dropped, so avoid `suppa` and message nodes there;
198
+ - the record has no `id` yet;
199
+ - validate by answering `responseEntity { action: "abort", abortReason }`.
200
+ - **Conditions:**
201
+ - use only the engine's comparators (`references/engine.md`), because an unknown one silently acts as `=`;
202
+ - `like` is a substring test with no `%`;
203
+ - `watchFields` take top-level names only;
204
+ - `$meta.old` holds the record before an update.
205
+ - **Lazy loading is narrow.** Only a literal `$json.a.b` in the node right after a trigger, `suppa` or `set` loads an unselected field. `$json?.a` and `$('Start').first().json.a` load nothing, so select what the flow reads.
206
+ - **Per-node errors:**
207
+ - `onError: continueErrorOutput` needs an `error` edge, or the branch ends silently;
208
+ - `retryOnError` repeats the whole node, so keep it off inserts and messages.
209
+ - **Time:**
210
+ - `$now` and `$today` are UTC (`$today` is still yesterday before 02:00 / 03:00 Kyiv);
211
+ - a schedule cron runs in UTC, so a Kyiv hour shifts at DST;
212
+ - see `references/tenant-time.md`.
213
+
131
214
  ## Data in expressions
132
215
 
133
216
  - **Compare enums and records by their stored `value` or `id`, never by `title`.** A title is a localized label. It can be `null` in the run (`type: { title: null, value: "Офісна" }`), and it changes when someone renames it.
@@ -144,12 +227,15 @@ Someone who opens the automation should read the flow from the canvas alone. Eve
144
227
  ## Optimize with measurements
145
228
 
146
229
  - `suppa_get_automation_run` gives per-node timings. Writes cost 150–500 ms each (create task, link, update); reads cost about 30 ms each, plus a node on the canvas. Reads of **the same entity** merge into one query (see «One read per entity per flow»). Reads of different entities stay separate nodes, because merging them through `code` hides what the flow reads.
147
- - **Idle runs** are the real waste. Filter in the trigger: `watchFields` plus `conditions` (for example `stage.id in [...]`), so moves that mean nothing start no run. Generate the id lists from settings in the build.
230
+ - **Idle runs** are the real waste. Filter in the trigger: `watchFields` plus `conditions` (for example `stage.id in [...]`), so moves that mean nothing start no run. Take the id lists from `$workflow.settings` in the condition value.
148
231
  - **A select that returns nothing ends the branch.** Guard optional lookups with an `if`, or fan out to the select and to a `merge` (append) so the flow continues.
149
- - A `code` node sees only `$json` / `$input`. Feed it from a `set` node that gathers `$('…')` values.
232
+ - A `code` node sees `$json` (item 0) and `$input.all()`, but no `$()`.
233
+ - Values from other nodes arrive through a `set` in front of it.
234
+ - Settings can be inlined into the code text, because `={{ }}` in it is resolved before it runs. Any `={{` in a code string or comment is resolved too.
150
235
  - testMode: route every role to the test user, and send approvals to a **second** account. An approval whose approver started the run is auto-approved.
151
236
  - Check that it really waits: a response comment «Automatically approved…» in the run's approval step means nobody was asked, and the `rejected` path was never run.
152
- - On modern-expo.test (2026-10-23 – 26) a second account on a plus-address of the tester's own mailbox was still auto-approved in 20 of 20 runs the tester started. The cause is not established; until one approval has waited for a click, the rejection path is untested.
237
+ - On modern-expo.test (2026-10-23 – 26) a second account on a plus-address of the tester's own mailbox was still auto-approved in 20 of 20 runs the tester started. The engine marks its approvals `skipAutoApprove`, so the cause lies outside the engine and is not established. Until one approval has waited for a click, the rejection path is untested.
238
+ - Approvals on some entities do wait, for example `HrVacancy`. There, a test answers by setting `isApproved` (with `respondedAt`) on the pending `<Entity>Approvers` row as the approver.
153
239
 
154
240
  ## Publish and verify
155
241
 
@@ -159,7 +245,7 @@ Follow `references/publishing.md`:
159
245
  - compare the draft with the build by hash;
160
246
  - publish;
161
247
  - test every flow with a real run (form submission, stage change) and read the per-node steps;
162
- - unpublish and soft-delete automations a merge made redundant.
248
+ - unpublish and soft-delete automations a merge made redundant, after checking their waiting runs, which the unpublish cancels.
163
249
 
164
250
  ## Common mistakes
165
251
 
@@ -169,11 +255,22 @@ Follow `references/publishing.md`:
169
255
  | Guard selects against duplicates from your own other automation | Merge the automations, or let only one side write |
170
256
  | `if` true/false or approved/rejected drawn into one row "because same size" | Place by handle offset, detour above |
171
257
  | Publishing a draft saved in the builder UI | The UI drops expression `approvers` to `[]`. Rebuild from source |
258
+ | A `getById AutomationWorkflow` node to read settings | `={{ $workflow.settings.<key> }}` in the expression: one node and one query fewer. `lint-graph` notes it |
259
+ | A secret (token, password) in settings or a `set` | Credentials. Expression values are stored in run data that everyone who reads runs can see |
260
+ | A counter or «last processed» written into settings | Its own entity. A settings write changes only the draft |
261
+ | `"text ={{ { id: x } }}"` for a relation | Make the expression the whole field. In text, an object becomes `[object Object]` |
172
262
  | Editing settings partially | Updates merge top-level keys. Resend the whole `settings.<key>`, then republish |
173
263
  | Option key `constructor` in settings | The platform strips it. Look options up with `hasOwnProperty` |
174
- | A node reads `$('X')` where X runs on another branch or later | `undefined` at runtime, with no error. `lint-graph` catches it |
175
- | Republishing a reshaped graph while runs wait at an approval | Keep approval ids stable; check `status: "waiting"` runs first. `lint-graph --previous` names dropped ids |
176
- | `return []` when a setting is missing | `throw new Error('Not configured: …')` — a failed run with the reason, not a silent success |
264
+ | A node reads `$('X')` where X runs on another branch or later | `$('X').first()` is `null`, so `.json` fails the node. `lint-graph` catches it |
265
+ | Unpublishing an automation with runs waiting at an approval | They are cancelled when they wake. Check `status: "waiting"` runs first. Republishing does not hurt them |
266
+ | Flow B written expecting loop protection after an approval | A write after a wait starts other flows. Filter B so that write does not match |
267
+ | `formId` / `webhookPath` / `credentialId` taken from settings | Literals. Publish refuses an expression in `formId` / `credentialId` (E18 / E16); one in `webhookPath` passes and never fires. `lint-graph` errors on all three |
268
+ | `select` (N rows) → `updateById` / `approval` | They use only the first row. Use `update` with `conditions`, or a `loop` |
269
+ | `select` (N rows) → `notification` | N messages. Aggregate first |
270
+ | An unknown comparator, or `like '%x%'` | An unknown one acts as `=`, and `%` is literal. `lint-graph` checks both |
271
+ | A `wait` / `approval` / `suppa` read after a `before-*` trigger | E11 for waits; 5 s budget otherwise. Use `responseEntity` |
272
+ | `onError: continueErrorOutput` with no `error` edge, or `retryOnError` on an insert or a message | Connect `error`; keep retries on idempotent nodes. `lint-graph` warns |
273
+ | `return []` when a setting is missing | `throw new Error('Not configured: …')` — a failed run with the reason, not a silent success. Never throw on an expected case: 5 failures in a row switch the automation off |
177
274
  | A create that a retry or a stage moved back and forth repeats | Look up the link / marker field first, or update a known record |
178
275
  | `type.title === 'Офісна'`, a stage compared by name | Compare `value` / `id` / `code`; titles are localized and may be `null` |
179
276
  | `deadline: date + 'T16:00:00+02:00'` | `atKyiv(day, '16:00')` from `references/tenant-time.md` |
@@ -0,0 +1,162 @@
1
+ # How the engine runs a graph
2
+
3
+ Source: the automation service (`suppa/automation`, `src/modules/engine/`; WES = `services/workflow-execution.service.ts`). Lines marked **live** were checked on modern-expo.test on 2026-10-27; the rest is read from the code.
4
+
5
+ ## Runs, waits, retries
6
+
7
+ - **A run that waits keeps the graph it started with.** At an `approval` / `wait`, the engine stores a snapshot of the nodes, connections and settings (WES:2100) and resumes from that snapshot (WES:2466). Republishing never reaches a waiting run, so renaming or re-id-ing nodes is safe for it.
8
+ - **Unpublishing cancels waiting runs.** A run whose automation was unpublished or auto-deactivated is cancelled when it wakes: «Resume refused: workflow is deactivated» (WES:2489). Before retiring an automation, list `status: "waiting"` runs and say who loses an open approval.
9
+ - **A write after a resume is not loop-protected (live).** A write made before an approval did not start the automation's other flow. The same write after the approval did start it (runs 526451 → 526452). The resumed run carries the wake-up event's context, not the original chain.
10
+ - **There is no whole-run retry.**
11
+ - `$execution.retryCount` is always 0 (WES:3599).
12
+ - The API's run retry answers 409.
13
+ - A redelivered job stops at the first side-effect node that already fired (`services/redelivery-side-effect-ledger.service.ts`).
14
+ - What repeats side effects:
15
+ - a node's `retryOnError` re-runs the whole node, so a notification goes again on every channel, including the ones that succeeded;
16
+ - a manual replay from a node;
17
+ - the trigger firing again: a stage moved back and forth, or another automation's write.
18
+
19
+ ## Items: per item or once
20
+
21
+ | Runs once, using item 0 only | Runs per item |
22
+ |---|---|
23
+ | `suppa` (every action), `approval`, `responseEntity`, `wait`, `code` (sees all items as `$input`), `merge`, `aggregate` | `set`, `if`, `switch`, `filter`, `notification`, `httpRequest`, `telegramSendMessage`, `emailSend` |
24
+
25
+ - A `select` returning N rows feeds N items to the next node.
26
+ - An `updateById` after it updates only the first row.
27
+ - A `notification` after it sends N messages.
28
+ - To write many records:
29
+ - `update` / `remove` with `conditions`;
30
+ - `insert` with an array of field objects (`nodes/suppa/suppa.node.ts:183`);
31
+ - or a `loop` (up to 1000 items).
32
+
33
+ ## Who the run is
34
+
35
+ - **Reads, writes, lazy loading and approvals run as the automation's author**, with the author's permissions (`authorQueryOptions`).
36
+ - A field the author cannot read never matches a condition and reads as `null` in an `if`.
37
+ - If the author is deactivated, every run fails with `AUTHOR_INACTIVE_RUNTIME` (WES:1454).
38
+ - **`$user`** is the user whose action triggered the run.
39
+
40
+ ## Automatic deactivation and guards
41
+
42
+ | Guard | Default | Override in `settings` |
43
+ |---|---|---|
44
+ | Error breaker: off after N failed runs in a row | 5 | `errorBreakerConsecutive` |
45
+ | Error breaker: off after 3 consecutive 60 s windows of ≥ 10 runs with ≥ 80 % errors | ratio 0.8, sample 10 | `errorBreakerRatio`, `errorBreakerMinSample`, `errorBreakerDisabled` |
46
+ | Rate backstop: sustained runs per 10 s | 500 | `rateLimitPerWindow`, `rateLimitDisabled` |
47
+ | One record triggering one automation | 25 per 10 s, then skipped | — |
48
+ | Automation chain length | 50 | — |
49
+
50
+ - Alerts go to the author plus `alertUserIds`, on `alertChannels: { critical | warning | info: ["inApp", "email"] }`. They are read from the **draft** settings (`alert-routing.service.ts`).
51
+ - So a `throw` on every run turns the automation off after 5 runs. Throw only for a real misconfiguration that someone must fix.
52
+
53
+ ## Before-* triggers
54
+
55
+ - **No `wait` / `approval` anywhere after a `before-*` trigger.** Publish refuses it with E11.
56
+ - **The whole flow has 5 s** (`beforeHookTimeoutMs`). On timeout the change is silently not applied. Avoid `suppa`, `httpRequest` and `notification` nodes there (warning W7).
57
+ - **The record is not saved yet.** It has no `id`, and its fields are not lazily loaded.
58
+ - **`responseEntity`:**
59
+ - `action: "apply"` with `values` sets fields;
60
+ - `action: "abort"` with `abortReason` refuses the save, which is how to validate.
61
+
62
+ ## Conditions (trigger, `filter`, `suppa` conditions, `switch` rule trees, `wait` resumeOn)
63
+
64
+ | Comparator | Aliases |
65
+ |---|---|
66
+ | `=` | `==`, `equals` |
67
+ | `===` | `strictEquals` |
68
+ | `!=` | `<>`, `notEquals` |
69
+ | `>` / `<` / `>=` / `<=` | `greaterThan` / `lessThan` / `greaterThanOrEqual` / `lessThanOrEqual` |
70
+ | `like` | `contains` |
71
+ | `not like` | `notContains` |
72
+ | `startsWith` / `endsWith` | — |
73
+ | `in` / `not in` | — |
74
+ | `between` / `not between` | — |
75
+ | `is null` | `empty` |
76
+ | `is not null` | `notEmpty` |
77
+ | `regex` | — |
78
+ | `type is` / `type is not` | multi-type fields |
79
+
80
+ - **An unknown comparator silently behaves as `=`** (`utils/enrichment.util.ts:428`).
81
+ - **`like` is a case-insensitive substring test.** `%` is a literal character, not a wildcard.
82
+ - A condition value may be an expression, including `$workflow.settings` (**live**). An expression that throws counts as no match.
83
+ - **`watchFields`:**
84
+ - top-level field names only;
85
+ - a watched field absent from the update counts as unchanged;
86
+ - relations compare by id, and lists ignore order.
87
+ - **On an update event, `$meta.old` holds the record before the change.**
88
+
89
+ ## Lazy loading
90
+
91
+ Only a literal `$json.a.b` in the current node's expressions loads a field that was not selected. It works only on an item that carries `meta.entity`: trigger, `suppa` and `set` outputs do; `code`, `merge` and `notification` outputs do not.
92
+
93
+ Nothing is fetched for:
94
+ - `$json?.a`;
95
+ - `$json['a']`;
96
+ - `$('A1. Start…').first().json.a`.
97
+
98
+ Select such a field, or read it as `$json.a` in a node right after the trigger.
99
+
100
+ ## Expressions
101
+
102
+ - **Globals:**
103
+ - `$json`, `$meta`, `$itemIndex`;
104
+ - `$('X')` with `.item` (the same position), `.first()`, `.last()`, `.all()` — each `{ json, meta }`, all output ports merged;
105
+ - `$workflow` (`.id`, `.settings`), `$execution`, `$trigger`, `$user`, `$tenant`;
106
+ - `$uuid()`, `$resumeUrls`, `$webhook`.
107
+ - **There is no `$input`, `$env`, `$vars` or luxon in expressions.**
108
+ - **`$('X').first()` is `null` when X has not run in this run.** `.json` on it throws an «Expression error» that fails the node (`nodes/expressions/expression.service.ts:138`). Write `$('X').first()?.json` only where skipping is intended.
109
+ - **`$now` is a UTC ISO string, not a date object. `$today` is the UTC date**, so until 02:00 / 03:00 Kyiv it is still yesterday.
110
+ - **Each expression is limited to 100 ms and 8 MB.**
111
+ - **A whole-field expression keeps its type.** An expression inside text becomes a string, and an object there becomes `[object Object]` (**live**).
112
+
113
+ ## The `code` node
114
+
115
+ - **Its code text is resolved like any parameter before it runs (live).**
116
+ - `const name = '={{ $workflow.settings.it.name }}';` arrives as the text.
117
+ - `const cfg = ={{ JSON.stringify($workflow.settings.it) }};` arrives as an object literal.
118
+ - So settings reach a `code` node without a `set` in front.
119
+ - Any other `={{` in the code — in a string or a comment — is resolved too.
120
+ - Inside the code, `$json` is item 0 and `$input.all()` holds every item. `$()` is not available, except through `={{ }}`.
121
+ - **Limits:**
122
+ - 1 s, 128 MB, 64 KB of code, 1 MB of output;
123
+ - synchronous only;
124
+ - `console.*` throws.
125
+
126
+ ## Errors per node
127
+
128
+ | Node field | Values | Effect |
129
+ |---|---|---|
130
+ | `onError` | `stopWorkflow` (default) | The run fails |
131
+ | | `continueRegularOutput` | Goes on along `main`, with `$json._error` |
132
+ | | `continueErrorOutput` | Routes to the `error` handle. Without an `error` edge, the branch silently ends |
133
+ | `retryOnError` | `{ maxRetries ≤ 5, delayMs ≤ 30000 }` | Re-runs the whole node. Keep it off inserts and messages |
134
+
135
+ - `getById` / `updateById` on an id that does not exist fails the run.
136
+
137
+ ## Nodes and parameters
138
+
139
+ | Node | What to know |
140
+ |---|---|
141
+ | `wait` | By time, by webhook (`$resumeUrls`), or by event: `resumeOn: { event, entityName, entityInstanceId, conditions, timeoutMs }`. Waiting for an event inside flow A can replace a separate trigger flow B. Waits live at most 30 days, webhook resume URLs 7 days |
142
+ | `loop` | Outputs `main` (each item) and `done`. At most 1000 items |
143
+ | `filter` | One output, `main`. Items that do not match are dropped |
144
+ | `aggregate` | Collapses items into one |
145
+ | `merge` | Modes `append`, `combineByIndex`, `combineByField` + `joinField`, `chooseBranch`. One edge per input |
146
+ | `switch` | `mode: "first" \| "all"`. Every rule needs a `condition` (E14). Output names must be unique. `fallbackOutput` names the fallback port (default `fallback`) |
147
+ | `suppa` select | `orderBy: [{ field, order }]`, `limit`, `fields`, `conditions` |
148
+ | `approval` | `flow` defaults to `parallel`. `timeout: { amount, unit }`. The `rejected` output also carries `status: "timeout" \| "cancelled"`. Without a timeout it goes `rejected` after 30 days. Its output is the decision (`responses`, `resolvedBy`), not the record |
149
+ | `notification` | Channels `inApp`, `inAppFlyout`, `email`, `mobilePush`. Its output replaces `$json` |
150
+ | `httpRequest`, `emailSend`, `telegramSendMessage` | Take a literal `credentialId` (E16) |
151
+ | `triggerSchedule` | One per automation (E13). Cron in **UTC only**, so a Kyiv time moves by an hour at DST. Missed slots are skipped. Runs as the author |
152
+ | `triggerWebhook` | `webhookPath` must be a non-empty string (E20) that no other active automation owns (E21). A request is matched on the path as written, so an expression there passes publish and never fires. `requiresAuth` defaults to `true` |
153
+ | `formSubmission` | A literal `formId` (E18) and no `events` (E19). A `triggerEntity` on `FormSubmissions` is refused (E17) |
154
+
155
+ ## Limits
156
+
157
+ | Limit | Value |
158
+ |---|---|
159
+ | Node executions per run | 1000 |
160
+ | Run data held in memory | 5 MB |
161
+ | Run history kept | 14 days (test runs: 1 day) |
162
+ | A graph | At most 500 nodes, 2000 edges, parameter depth 10, strings of 65 536 characters, and no cycles (E3) |
@@ -15,7 +15,9 @@ Connections: `{ "<from id>": { "<output handle>": [{ "node": "<to id>", "index":
15
15
  |---|---|
16
16
  | ordinary nodes, triggers | `main` |
17
17
  | `if` | `true` / `false` |
18
- | `approval` | `approved` / `rejected` |
18
+ | `approval` | `approved` / `rejected` (the latter also on timeout or cancel) |
19
+ | `loop` | `main` (each item) / `done` |
20
+ | `filter` | `main` (matching items only) |
19
21
  | `switch` | the rule's `output` **name** (not an index) |
20
22
 
21
23
  `index` is the target input. Only `merge` uses `1`.
@@ -33,16 +35,16 @@ Several triggers in one automation are allowed. The run starts at the trigger th
33
35
 
34
36
  | Node | Parameters |
35
37
  |---|---|
36
- | `suppa` getById | `{ "action": "getById", "entityName": "AutomationWorkflow", "id": "={{ $workflow.id }}", "fields": {"id": true, "activeSettings": true} }` — the automation's own settings. |
38
+ | `suppa` getById | `{ "action": "getById", "entityName": "Users", "id": "={{ $('A1. Start…').first().json.createdBy.id }}", "fields": {"id": true, "fullName": true, "employees": {"department": {"title": true}}} }` — one record, related records nested in `fields`. Settings need no read node: `={{ $workflow.settings.<key> }}`. |
37
39
  | `suppa` select | `{ "action": "select", "entityName": "OrgEmployees", "limit": 50, "fields": {"id": true, "user": {"id": true}}, "conditions": {"operator": "and", "filters": [{"field": "id", "comparator": "in", "value": "={{ … }}"}]} }` — **0 rows ends the branch.** |
38
40
  | `suppa` insert / updateById | `{ "action": "updateById", "entityName": "Tasks", "id": "={{ … }}", "fields": {"stage": "={{ x != null ? { id: x } : null }}"}, "merge": ["watchers"] }` — relations are `{id}`. List fields are replaced unless named in `merge`. |
39
41
  | `set` | `{ "keepOnlySet": true, "assignments": [{"name": "request", "value": "={{ $('A1. Start: …').first().json }}"}] }` |
40
- | `code` | `{ "code": "…return [{ … }];" }` — sees only `$json` / `$input`, with no `$()` / `$workflow` / `$now`. Feed it through a `set`. One run covers all input items. |
42
+ | `code` | `{ "code": "…return [{ … }];" }` — sees `$json` (item 0) and `$input.all()`, no `$()`. The code text is resolved like any parameter first: `const cfg = ={{ JSON.stringify($workflow.settings.it) }};` works, and any `={{` in a string or comment is resolved too. One run covers all input items; 1 s, synchronous, no `console`. |
41
43
  | `if` | `{ "expression": "={{ … === true }}" }` |
42
44
  | `switch` | `{ "mode": "first", "fallbackEnabled": false, "rules": [{"output": "approvalIt", "condition": "={{ $json.action === 'approvalIt' }}"}] }` |
43
45
  | `responseEntity` | Only after a `before-insert` / `before-update` trigger: `{ "action": "apply", "values": [{"name": "status", "value": "={{ … }}"}] }` — the values are applied to the record before it is saved (defaults, normalisation) at the cost of no write. Every listed field takes the value returned, so when a field needs no change, return what came in (`… ?? $('A1. Start…').first().json.<field>`). |
44
46
  | `merge` | `{ "mode": "append" }`, node field `"inputCount": 2`. Waits for both inputs and still runs when one select produced nothing (fan out: source → select → input 0, source → merge input 1). |
45
- | `approval` | `{ "flow": "sequential", "entityName": "Tasks", "instanceId": "={{ … }}", "approvers": "={{ … }}", "description": "Text ={{ expr }}: ={{ expr }}" }` — `approvers` = `[{ "user": { "id": 75 } }]`. |
47
+ | `approval` | `flow` defaults to `parallel`; `timeout: { amount, unit }` (none → `rejected` after 30 days). `{ "flow": "sequential", "entityName": "Tasks", "instanceId": "={{ … }}", "approvers": "={{ … }}", "description": "Text ={{ expr }}: ={{ expr }}" }` — `approvers` = `[{ "user": { "id": 75 } }]`. |
46
48
  | `notification` | `{ "type": "insert", "channels": [{"channel": "inApp"}], "entityName": "Tasks", "recordId": "={{ … }}", "userIds": "={{ [ … ] }}", "subjectTemplate": {"uk": "…", "en": "…"}, "bodyTemplate": {"uk": "… ={{ expr }} …"}, "navigateTo": {"entityId": 45, "instanceId": "={{ … }}"} }` |
47
49
 
48
50
  ## Linking a request to its task
@@ -68,9 +70,12 @@ then read `instanceA.value.id ?? instanceA.id`.
68
70
 
69
71
  - `={{ js }}` evaluates. Text and several `={{ }}` mix inside one string.
70
72
  - Reference a node as `$('Node name').first().json`. `$json` is the incoming item.
71
- - A trigger or `suppa` item lazily loads `$json.<field>` that was not selected (the item carries `meta.entity`).
73
+ - A trigger, `suppa` or `set` item lazily loads a literal `$json.<field>` that was not selected (the item carries `meta.entity`). `$json?.x`, `$json['x']` and `$('X').first().json.x` load nothing; `code` / `merge` / `notification` output carries no `meta.entity`.
74
+ - `$('X').first()` is `null` when X did not run — `.json` on it fails the node. `$now` / `$today` are UTC; `$meta.old` is the record before an update.
75
+ - `$workflow.settings.<key>` is the published settings in any expression, trigger conditions included; a test run sees the draft. A `code` node has no `$workflow` — pass values through a `set`.
72
76
  - Settings are stored as jsonb:
73
77
  - object keys get re-sorted, so keep an explicit order array;
74
78
  - a key named `constructor` is stripped;
75
79
  - an update merges top-level keys only, so resend the whole `settings.<key>`;
76
- - flows read `activeSettings`, so republish after any change.
80
+ - production runs read the published settings, so republish after any change.
81
+ - Never put a secret in settings or a `set`: expression values are kept in run data. Use credentials.
@@ -36,6 +36,31 @@ const key = (nodes) => nodes.map(n => ({ id: n.id, name: n.name, parameters: n.p
36
36
  - Read the run with `suppa_get_automation_run`. The output is large and lands in a file, so summarize it with `node -e` (`steps[].nodeId / status / error / output`).
37
37
  - Also confirm that a move which should start nothing starts no run (`suppa_list_automation_runs`).
38
38
  - Approvals auto-approve when the approver started the run, so route test approvals to a second account. A real rejection needs a click from that account.
39
- - Read the approval step of the run: `responses[0].comment` «Automatically approved…» means it did not wait. On modern-expo.test (2026-10-23 – 26) that happened in 20 of 20 runs the tester started, even with a second account (a plus-address of the tester's mailbox), cause not established — so the rejection path counts as tested only after an approval has waited and been rejected by a click.
40
- 7. **Retire what a merge replaced.** Run `suppa_unpublish_automation`, then `suppa_delete_automation`. The delete is soft; `suppa_restore_record('AutomationWorkflow', id)` undoes it.
39
+ - Where approvals do wait (e.g. `HrVacancy`), answer as the approver by setting `isApproved` + `respondedAt` on the pending `<Entity>Approvers` row; the run resumes within a second.
40
+ - Read the approval step of the run: `responses[0].comment` «Automatically approved…» means it did not wait. The engine marks its approvals `skipAutoApprove`, so the cause lies outside it. On modern-expo.test (2026-10-23 – 26) that happened in 20 of 20 runs the tester started, even with a second account (a plus-address of the tester's mailbox), cause not established — so the rejection path counts as tested only after an approval has waited and been rejected by a click.
41
+ 7. **Retire what a merge replaced.** First list its waiting runs (`suppa_list_automation_runs status: "waiting"`): an unpublish cancels each one when it wakes, so say whose open approvals end. Then run `suppa_unpublish_automation` and `suppa_delete_automation`. The delete is soft; `suppa_restore_record('AutomationWorkflow', id)` undoes it.
41
42
  8. **Update the description.** Start it with the step guide by flow letter and number, then list the real people per BP or role (test ids stay in settings).
43
+
44
+ ## What publish refuses
45
+
46
+ `suppa_publish_automation` runs the engine's pre-flight (`services/workflow-publish-validation.ts`); `lint-graph` mirrors the ones marked ✓.
47
+
48
+ | Code | Refused | lint |
49
+ |---|---|---|
50
+ | E1 | no trigger | ✓ |
51
+ | E2 | unknown node type, or an edge to a missing node | missing node |
52
+ | E3 | > 500 nodes / 2000 edges, parameter depth > 10, a string > 65 536 chars, a cycle, two edges into one merge input | cycles |
53
+ | E4 / E5 | `responseEntity` not reachable from an entity trigger / reachable only from after-* triggers | |
54
+ | E6 / E7 / E8 / E9 | webhook response node and trigger mode do not match, or a response node no trigger reaches | |
55
+ | E10 | webhook timeout outside (0, 300] s | |
56
+ | E11 | a `wait` / `approval` after a before-* trigger | ✓ |
57
+ | E12 / E15 | `responseEntity` names an unknown field / one the author may not write | |
58
+ | E13 | a bad schedule, or more than one schedule trigger | more than one |
59
+ | E14 | a switch rule without a condition | ✓ |
60
+ | E16 | a `credentialId` that is an expression, invalid, or not yours | expression |
61
+ | E17 | `triggerEntity` on `FormSubmissions` | ✓ |
62
+ | E18 | a `formSubmission` whose `formId` is not a literal | ✓ |
63
+ | E19 | `events` on a `formSubmission` | ✓ |
64
+ | E20 / E21 | a webhook trigger whose path is not a non-empty string / is owned by another active automation | E20, and an expression path (publish accepts it; it never fires) |
65
+
66
+ Warnings W1–W8 do not block. `lint-graph` mirrors W7: a `suppa` / message / HTTP node in a before-* flow, which has 5 s.
@@ -40,4 +40,7 @@ Usage:
40
40
  - «due at 16:00 on the picked day»: `atKyiv(toKyivDay(fd.desired_date), '16:00')`;
41
41
  - «+2 working days from now»: `atKyiv(addBusinessDays(kyivDay(new Date($json.now)), 2, holidays), '16:00')`. The `code` node has no `$now`, so feed `now: "={{ $now }}"` through the `set` before it, and read holidays from their entity.
42
42
 
43
+ - `$now` is a UTC ISO string and `$today` the UTC date: before 02:00 / 03:00 Kyiv, `$today` is still yesterday. Take the Kyiv day with `kyivDay(new Date($now))`.
44
+ - A `triggerSchedule` cron runs in **UTC only**. «Every weekday at 09:00 Kyiv» is `0 6 * * 1-5` in summer and `0 7 * * 1-5` in winter. Either accept the hour's drift, or schedule both hours and drop the wrong one in the flow: `if` on `kyivOffsetMin` against the expected Kyiv hour.
45
+
43
46
  For a tenant in another zone, replace `'Europe/Kyiv'` and the fallback rule. The trigger payload's `options.timezone` names the tenant's zone.
@@ -1,8 +1,7 @@
1
1
  // Finds what makes an automation wrong at runtime, hard to read, or heavier than it needs to be.
2
- // usage: node lint-graph.mjs <graph.json> [--previous published.json]
2
+ // usage: node lint-graph.mjs <graph.json>
3
3
  // graph.json: the stored { nodes, connections, settings? } or a suppa_get_automation answer as is (its draft side).
4
- // --previous: the graph that is published now (a suppa_get_automation answer: its `published` side) — names approval
5
- // nodes the new graph drops, which strands waiting runs.
4
+ // Engine facts behind the checks: references/engine.md (the automation service, src/modules/engine).
6
5
  // Prints ERROR / WARN / NOTE lines; exits 1 when there is an ERROR.
7
6
  import fs from 'node:fs';
8
7
  import { fileURLToPath } from 'node:url';
@@ -12,8 +11,17 @@ const TRIGGERS = new Set(['formSubmission', 'triggerEntity', 'triggerWebhook', '
12
11
  const STEP_NAME = /^(?:([A-Z])(?=\d))?(\d+)((?:\.\d+)*)(\.?)\s+\S/;
13
12
  const REF = /\$\('([^']*)'\)/g;
14
13
  const QUOTED_STEP = /«((?:[A-Z])?\d+(?:\.\d+)*\.?\s[^»]+)»/g;
14
+ // The engine's comparators (utils/enrichment.util.ts); anything else silently behaves as '='.
15
+ const COMPARATORS = new Set(['=', '==', 'equals', '===', 'strictEquals', '!=', '<>', 'notEquals', '>', 'greaterThan', '<', 'lessThan', '>=', 'greaterThanOrEqual', '<=', 'lessThanOrEqual', 'like', 'contains', 'not like', 'notContains', 'startsWith', 'endsWith', 'in', 'not in', 'between', 'not between', 'is null', 'empty', 'is not null', 'notEmpty', 'regex', 'type is', 'type is not']);
16
+ // Nodes that use item 0 only, and nodes that run once per item (references/engine.md «Items»).
17
+ const ONCE_PER_RUN = new Set(['approval', 'responseEntity', 'wait']);
18
+ const PER_ITEM_SIDE_EFFECT = new Set(['notification', 'httpRequest', 'emailSend', 'telegramSendMessage']);
19
+ const SIDE_EFFECT = new Set([...PER_ITEM_SIDE_EFFECT]);
20
+ const WRITE_ACTIONS = new Set(['insert', 'update', 'updateById', 'remove', 'removeById']);
21
+ // The code text is expression-resolved before it runs, so $() is available inside ={{ }} there.
22
+ const outsideExpressions = (code) => String(code ?? '').replace(/=\{\{[\s\S]*?\}\}/g, '');
15
23
 
16
- export const lint = (graph, { previous } = {}) => {
24
+ export const lint = (graph) => {
17
25
  const { nodes, connections = {} } = graph;
18
26
  const out = [];
19
27
  const seen = new Set();
@@ -28,7 +36,8 @@ export const lint = (graph, { previous } = {}) => {
28
36
  const err = n.onError === 'continueErrorOutput' ? ['error'] : [];
29
37
  if (n.type === 'if') return ['true', 'false', ...err];
30
38
  if (n.type === 'approval') return ['approved', 'rejected', ...err];
31
- if (n.type === 'switch') return [...(n.parameters?.rules || []).map((r) => r.output), ...(n.parameters?.fallbackEnabled ? ['fallback'] : []), ...err];
39
+ if (n.type === 'loop') return ['main', 'done', ...err];
40
+ if (n.type === 'switch') return [...(n.parameters?.rules || []).map((r) => r.output), ...(n.parameters?.fallbackEnabled ? [n.parameters?.fallbackOutput ?? 'fallback'] : []), ...err];
32
41
  return ['main', ...err];
33
42
  };
34
43
  for (const [from, handles] of Object.entries(connections)) {
@@ -57,6 +66,15 @@ export const lint = (graph, { previous } = {}) => {
57
66
  }
58
67
  for (const n of nodes) if (!flowOf[n.id]) add('ERROR', `${n.id} is not reachable from any trigger`);
59
68
  for (const n of nodes) if (TRIGGERS.has(n.type) && pred[n.id].length) add('ERROR', `trigger ${n.id} has incoming edges`);
69
+ {
70
+ // E3: the graph must be a DAG
71
+ const indeg = Object.fromEntries(nodes.map((n) => [n.id, pred[n.id].length]));
72
+ const q = nodes.filter((n) => !indeg[n.id]).map((n) => n.id);
73
+ let seenCount = 0;
74
+ while (q.length) { const id = q.shift(); seenCount++; for (const e of succ[id]) if (!--indeg[e.to]) q.push(e.to); }
75
+ // What Kahn's walk leaves behind is the cycle AND everything after it, so the list is not "the cycle".
76
+ if (seenCount < nodes.length) add('ERROR', `the graph has a cycle (nodes on it or after it: ${nodes.filter((n) => indeg[n.id] > 0).map((n) => n.id).join(', ')}) — publish refuses it (E3); repeat work with a loop node`);
77
+ }
60
78
 
61
79
  const ancestors = (id) => {
62
80
  const seen = new Set();
@@ -94,7 +112,7 @@ export const lint = (graph, { previous } = {}) => {
94
112
  else if (!anc.has(target.id)) add('ERROR', `${n.id}: $('${ref}') is not upstream of this node — it is undefined at runtime`);
95
113
  }
96
114
  for (const [, ref] of text.matchAll(QUOTED_STEP)) if (!byName[ref]) add('WARN', `${n.id}: comment or text mentions «${ref}», which is no node name (stale after a rename?)`);
97
- if (n.type === 'code' && /\$\('/.test(n.parameters?.code ?? '')) add('ERROR', `${n.id}: a code node has no $() — feed it through a set node`);
115
+ if (n.type === 'code' && /\$\('/.test(outsideExpressions(n.parameters?.code))) add('ERROR', `${n.id}: a code node has no $() — feed it through a set node, or inline it as ={{ … }} (the code text is resolved before it runs)`);
98
116
  }
99
117
 
100
118
  // --- node-specific checks
@@ -125,6 +143,16 @@ export const lint = (graph, { previous } = {}) => {
125
143
  else if (/formData/.test(text) && fieldKeys.length && fieldKeys.every((k) => k === 'id')) add('WARN', `${n.id}: reads only id of a record picked in the form — formData already has { id }`);
126
144
  }
127
145
  if (n.type === 'suppa' && p.entityName === 'AutomationWorkflow' && p.action === 'getById' && !/\$workflow\.id/.test(String(p.id))) add('WARN', `${n.id}: reads another automation's settings by literal id — keep settings in this automation ($workflow.id)`);
146
+ else if (n.type === 'suppa' && p.entityName === 'AutomationWorkflow' && p.action === 'getById') add('NOTE', `${n.id}: reads this automation's settings — every expression has them as $workflow.settings.<key>, trigger conditions included; drop the node`);
147
+ // An object literal inside a string that is not ONE whole expression arrives as "[object Object]".
148
+ // Only an object: an array of plain values in text joins as "a,b" (`[a, b].join('-')` is fine), and a
149
+ // string holding two expressions is text even when it starts with ={{ and ends with }}.
150
+ const objectInText = (v) => {
151
+ if (typeof v !== 'string' || !/=\{\{\s*\(?\s*\{/.test(v)) return false;
152
+ return !(v.split('={{').length === 2 && /^=\{\{[\s\S]*\}\}$/.test(v.trim()));
153
+ };
154
+ const values = n.type === 'set' ? (p.assignments || []).map((a) => [a.name, a.value]) : n.type === 'suppa' ? Object.entries(p.fields ?? {}) : [];
155
+ for (const [k, v] of values) if (objectInText(v)) add('WARN', `${n.id}: ${k} builds an object inside text — it arrives as "[object Object]"; make ={{ … }} the whole value`);
128
156
  if (n.type === 'triggerEntity') {
129
157
  const upd = (p.events || []).some((e) => /update/.test(e));
130
158
  if (upd && !(p.watchFields || []).length) add('WARN', `${n.id}: update trigger without watchFields starts a run on every edit`);
@@ -178,9 +206,95 @@ export const lint = (graph, { previous } = {}) => {
178
206
  if (t && typeof t === 'object' && !('uk' in t)) add('WARN', `${n.id}: ${key} has no uk — notifications carry the users' language next to en`);
179
207
  }
180
208
  }
181
- if (previous) {
182
- const now = new Set(nodes.map((n) => n.id));
183
- for (const n of previous.nodes ?? []) if (n.type === 'approval' && !now.has(n.id)) add('WARN', `approval ${n.id} («${n.name}») is published now and missing from the new graph — runs waiting there cannot continue; keep its id, or check status:"waiting" runs before publishing`);
209
+ // Settings values land in run data that anyone reading runs can see: secrets go to credentials.
210
+ // Matched on whole words of the key, so apiToken / webhookSecret / API_KEY are caught and
211
+ // secretaryId / tokenizerMode are not; only a filled string can be a secret.
212
+ const secretLike = (key) => {
213
+ const words = key.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
214
+ return words.some((w, i) => /^(password|passwd|secret|token|apikey|privatekey)s?$/.test(w) || (/^(api|private)$/.test(w) && words[i + 1] === 'key'));
215
+ };
216
+ const secretKeys = [];
217
+ const walk = (v, path) => {
218
+ if (!v || typeof v !== 'object') return;
219
+ for (const [k, x] of Object.entries(v)) {
220
+ const at = path ? `${path}.${k}` : k;
221
+ if (secretLike(k) && typeof x === 'string' && x !== '') secretKeys.push(at);
222
+ walk(x, at);
223
+ }
224
+ };
225
+ walk(graph.settings, '');
226
+ if (secretKeys.length) add('WARN', `settings hold what looks like a secret (${secretKeys.join(', ')}) — expression values are kept in run data; use credentials`);
227
+
228
+ // --- what publish refuses (E-codes of services/workflow-publish-validation.ts) and engine semantics
229
+ const hasExpr = (v) => typeof v === 'string' && v.includes('{{');
230
+ const schedules = nodes.filter((n) => n.type === 'triggerSchedule');
231
+ if (schedules.length > 1) add('ERROR', `${schedules.length} schedule triggers (${schedules.map((n) => n.id).join(', ')}) — one per automation (E13)`);
232
+ const beforeTriggers = triggers.filter((t) => t.type === 'triggerEntity' && (t.parameters?.events || []).some((e) => /^before-/.test(e)));
233
+ const reachFrom = (id) => { const s = new Set(); const st = [id]; while (st.length) for (const e of succ[st.pop()]) if (!s.has(e.to)) { s.add(e.to); st.push(e.to); } return s; };
234
+ const underBefore = new Set(beforeTriggers.flatMap((t) => [...reachFrom(t.id)]));
235
+ // W7, as publish words it: once per before-* trigger, naming the nodes, not once per node.
236
+ for (const t of beforeTriggers) {
237
+ const slow = [...reachFrom(t.id)].filter((id) => by[id] && (by[id].type === 'suppa' || SIDE_EFFECT.has(by[id].type)));
238
+ if (slow.length) add('WARN', `${t.id}: a before-* flow runs ${slow.join(', ')} — the whole flow has 5 s, after which the change is silently dropped (W7)`);
239
+ }
240
+ // E18 as publish judges it (constants/form-submission.constants.ts isLiteralFormId): an object, a blank
241
+ // string and anything holding ={{ are not literals.
242
+ const literalFormId = (v) => v != null && typeof v !== 'object' && String(v).trim() !== '' && !String(v).includes('={{');
243
+ for (const n of nodes) {
244
+ const p = n.parameters ?? {};
245
+ if (n.type === 'formSubmission') {
246
+ if (!literalFormId(p.formId)) add('ERROR', `${n.id}: formId must be a literal — the trigger is routed on it before any expression runs (E18)`);
247
+ if (p.events !== undefined) add('ERROR', `${n.id}: a formSubmission trigger takes no events (E19)`);
248
+ }
249
+ // triggerEntityNameOf: a 'trigger' node is an entity trigger too, and the name is matched case-insensitively.
250
+ if ((n.type === 'triggerEntity' || n.type === 'trigger') && String(p.entityName ?? '').trim().toLowerCase() === 'formsubmissions') add('ERROR', `${n.id}: an entity trigger on FormSubmissions is refused — use formSubmission { formId } (E17)`);
251
+ if (n.type === 'triggerWebhook') {
252
+ if (typeof p.webhookPath !== 'string' || !p.webhookPath) add('ERROR', `${n.id}: webhookPath must be a non-empty string (E20)`);
253
+ // Publish accepts this one, but a request is matched on the path as written: it never fires.
254
+ else if (hasExpr(p.webhookPath)) add('ERROR', `${n.id}: webhookPath is an expression — it is never resolved, a request is matched on the literal path, so this trigger never fires`);
255
+ }
256
+ if (hasExpr(p.credentialId)) add('ERROR', `${n.id}: credentialId must be a literal — pick the credential (E16)`);
257
+ if (n.type === 'switch') {
258
+ // E14: a non-blank `condition`, or a `conditions` tree with at least one filter.
259
+ for (const r of p.rules || []) {
260
+ const hasExpression = typeof r?.condition === 'string' && r.condition.trim() !== '';
261
+ const hasTree = Array.isArray(r?.conditions?.filters) && r.conditions.filters.length > 0;
262
+ if (!hasExpression && !hasTree) add('ERROR', `${n.id}: switch rule "${r?.output ?? '?'}" has no condition and no condition filters (E14)`);
263
+ }
264
+ // switch.node.ts throws on a repeated port name, an enabled fallback included.
265
+ const names = [...(p.rules || []).map((r) => r.output), ...(p.fallbackEnabled ? [p.fallbackOutput ?? 'fallback'] : [])];
266
+ const dup = names.filter((x, i) => names.indexOf(x) !== i);
267
+ if (dup.length) add('ERROR', `${n.id}: switch outputs repeat (${[...new Set(dup)].join(', ')}) — a duplicate name fails the node at runtime`);
268
+ }
269
+ if (underBefore.has(n.id) && (n.type === 'approval' || n.type === 'wait')) add('ERROR', `${n.id}: a ${n.type} after a before-* trigger is refused (E11) — the record is not saved yet`);
270
+ if (n.type === 'triggerEntity') for (const f of p.watchFields || []) if (String(f).includes('.')) add('WARN', `${n.id}: watchFields "${f}" — only top-level field names are compared; watch "${String(f).split('.')[0]}"`);
271
+ // every condition tree: unknown comparators act as '=', like has no wildcards
272
+ const walkConditions = (v) => {
273
+ if (!v || typeof v !== 'object') return;
274
+ if (Array.isArray(v)) { v.forEach(walkConditions); return; }
275
+ if (typeof v.comparator === 'string') {
276
+ if (!COMPARATORS.has(v.comparator)) add('ERROR', `${n.id}: unknown comparator "${v.comparator}" on ${v.field ?? 'a condition'} — the engine treats it as "="`);
277
+ if (/^(not )?like$|^(not)?[cC]ontains$/.test(v.comparator) && typeof v.value === 'string' && v.value.includes('%')) add('WARN', `${n.id}: "${v.comparator}" value "${v.value}" has % — like is a case-insensitive substring test; % is matched literally`);
278
+ }
279
+ for (const x of Object.values(v)) walkConditions(x);
280
+ };
281
+ walkConditions(p.conditions);
282
+ walkConditions(p.resumeOn);
283
+ for (const r of p.rules || []) walkConditions(r.conditions);
284
+ // per-node error handling
285
+ if (n.onError === 'continueErrorOutput' && !(succ[n.id] || []).some((e) => e.handle === 'error')) add('WARN', `${n.id}: onError continueErrorOutput with no error edge — a failure ends the branch silently`);
286
+ if (n.retryOnError && ((n.type === 'suppa' && (p.action === 'insert')) || SIDE_EFFECT.has(n.type))) add('WARN', `${n.id}: retryOnError re-runs the whole node — a ${n.type === 'suppa' ? 'second insert' : 'message on every channel again'}; keep retries on idempotent nodes`);
287
+ // lazy loading: only a literal $json.a.b loads an unselected field
288
+ if (/\$json\?\./.test(JSON.stringify(p))) add('NOTE', `${n.id}: $json?.x never lazily loads a field — select it, or write $json.x where loading is wanted`);
289
+ // items: a multi-row select feeding a node that uses item 0, or sends once per row
290
+ if (n.type === 'suppa' && p.action === 'select' && (p.limit == null || Number(p.limit) > 1)) {
291
+ for (const e of succ[n.id]) {
292
+ const t = by[e.to];
293
+ const q = t.parameters ?? {};
294
+ if (ONCE_PER_RUN.has(t.type) || (t.type === 'suppa' && WRITE_ACTIONS.has(q.action))) add('NOTE', `${n.id} → ${t.id}: a ${t.type}${q.action ? ' ' + q.action : ''} uses only the first of the selected rows — use update with conditions, an insert array or a loop`);
295
+ else if (PER_ITEM_SIDE_EFFECT.has(t.type)) add('NOTE', `${n.id} → ${t.id}: ${t.type} runs once per selected row — aggregate first if one message is meant`);
296
+ }
297
+ }
184
298
  }
185
299
 
186
300
  // --- size
@@ -195,9 +309,7 @@ export const lint = (graph, { previous } = {}) => {
195
309
 
196
310
  if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
197
311
  const args = process.argv.slice(2);
198
- const prevAt = args.indexOf('--previous');
199
- const previous = prevAt >= 0 ? readGraph(args[prevAt + 1], { side: 'published' }) : undefined;
200
- const res = lint(readGraph(args[0]), { previous });
312
+ const res = lint(readGraph(args[0]));
201
313
  const order = { ERROR: 0, WARN: 1, NOTE: 2 };
202
314
  res.sort((a, b) => order[a.level] - order[b.level]);
203
315
  for (const r of res) console.log(`${r.level.padEnd(5)} ${r.msg}`);