suppa-mcp-2 1.44.3 → 1.44.5

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
@@ -746,7 +746,7 @@ node $S/render-graph.mjs placed.json preview.svg --png preview.png # look befo
746
746
 
747
747
  `references/node-reference.md` holds the parameter shapes verified on running
748
748
  automations: triggers, conditions, switch outputs, approvals, links, the request
749
- 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
750
750
  order.
751
751
 
752
752
  ---
@@ -818,6 +818,17 @@ npm publish
818
818
 
819
819
  The `prepublishOnly` script automatically runs `tsc` + the full test suite before publishing.
820
820
 
821
+ Before a release, check the projections this server sends against a stand people use (read-only, the platform's own
822
+ `select/validate`; needs a build and a session for that tenant):
823
+
824
+ ```bash
825
+ npm run build && npm run check:projections -- --tenant modern-expo.test.suppa.me
826
+ ```
827
+
828
+ It names every field the code asks for that the tenant does not have — the way `Tasks.author` sat in the task
829
+ projection after every tenant had renamed it `createdBy`, and cost one 400 in the platform's log per process start.
830
+ At run time a read is checked the same way before it is sent, so no tool learns a tenant's fields from a 400.
831
+
821
832
  ---
822
833
 
823
834
  ## Project structure
@@ -4,7 +4,11 @@
4
4
  * Faithful 1:1 port of the Python `suppa_mcp/http_client.py`. Uses the native
5
5
  * global `fetch` in place of `urllib`, with an AbortController for timeouts.
6
6
  */
7
+ import { createHash } from "node:crypto";
8
+ import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
9
+ import { join } from "node:path";
7
10
  import { config } from "./config.js";
11
+ import { homeDir } from "./registry.js";
8
12
  import { assertMergeLists, elideEchoedResponse, stripAccessMetadata } from "./utils.js";
9
13
  import * as tenants from "./tenants.js";
10
14
  import { lastRefreshError } from "./sessionDiag.js";
@@ -644,21 +648,138 @@ function invalidProjectionPaths(e) {
644
648
  f.location === "fields")
645
649
  .map((f) => f.path);
646
650
  }
651
+ // ---------------------------------------------------------------------------
652
+ // A read is checked BEFORE it is sent
653
+ //
654
+ // Every 400 lands in the platform's error log. Learning a tenant's fields from its
655
+ // 400s cost one per process start, per user, per tenant: on 2026-11-10/11 the
656
+ // suppa_get_task / suppa_search_tasks projection (`author` beside `createdBy`)
657
+ // put 79 of them in entity-builder's log from ~10 people, and 53 more came from
658
+ // projections agents wrote themselves (`author { fullName }`, a `name` that does
659
+ // not exist). POST /data/:entity/select/validate answers 200 with the same
660
+ // invalidFields the select would refuse with (entity-builder data.controller.ts,
661
+ // @HttpCode(OK), 1000 calls a minute; the select runs the same validator), so the
662
+ // read is checked there first:
663
+ // - a path of THIS SERVER's projection the tenant lacks is dropped before sending;
664
+ // - anything else invalid — a caller's projection, a filter, an order — is refused
665
+ // here with the platform's own words, and nothing reaches the platform.
666
+ // The verdict is kept per tenant, entity and query SHAPE (paths and comparators,
667
+ // never values): in memory for the process, and for this server's own reads also
668
+ // on disk for a day, so a new process does not ask again.
669
+ // ---------------------------------------------------------------------------
670
+ const READ_CHECK_TTL_MS = 24 * 60 * 60 * 1000;
671
+ /** `sha1(host|entity|shape)` -> the paths the platform's validator rejected (none = valid). */
672
+ const checkedReads = new Map();
673
+ /** The structure of a condition tree without its values: what the validator judges. */
674
+ function conditionShape(node) {
675
+ if (Array.isArray(node))
676
+ return node.map(conditionShape);
677
+ if (node === null || typeof node !== "object")
678
+ return typeof node;
679
+ const o = node;
680
+ if (Array.isArray(o.filters))
681
+ return { operator: o.operator ?? null, filters: o.filters.map(conditionShape) };
682
+ return { field: o.field ?? null, comparator: o.comparator ?? null };
683
+ }
684
+ function readCheckKey(ctx, entity, body) {
685
+ const shape = JSON.stringify({ fields: body.fields ?? null, orderBy: body.orderBy ?? null, conditions: conditionShape(body.conditions ?? null) });
686
+ return createHash("sha1").update(`${ctx.host}|${entity}|${shape}`).digest("hex");
687
+ }
688
+ function readCheckFile(key) {
689
+ return join(homeDir(), "cache", "select-validate", `${key}.json`);
690
+ }
691
+ function loadReadCheck(key) {
692
+ try {
693
+ const file = readCheckFile(key);
694
+ if (Date.now() - statSync(file).mtimeMs > READ_CHECK_TTL_MS)
695
+ return undefined;
696
+ const invalid = JSON.parse(readFileSync(file, "utf-8"));
697
+ return Array.isArray(invalid) ? invalid : undefined;
698
+ }
699
+ catch {
700
+ return undefined; // no verdict on disk, or an unreadable one: ask the validator
701
+ }
702
+ }
703
+ function saveReadCheck(key, invalid) {
704
+ try {
705
+ const file = readCheckFile(key);
706
+ mkdirSync(join(file, ".."), { recursive: true });
707
+ const tmp = `${file}.${process.pid}.tmp`;
708
+ writeFileSync(tmp, JSON.stringify(invalid));
709
+ renameSync(tmp, file);
710
+ }
711
+ catch {
712
+ // a verdict that cannot be kept costs one validator call next process, nothing else
713
+ }
714
+ }
715
+ /** The validator's verdict on a read, or null when it cannot answer (then the read goes as it was). */
716
+ async function validateRead(entity, body, ctx) {
717
+ const check = { fields: body.fields };
718
+ if (body.conditions !== undefined && body.conditions !== null)
719
+ check.conditions = body.conditions;
720
+ if (Array.isArray(body.orderBy) && body.orderBy.length > 0)
721
+ check.orderBy = body.orderBy;
722
+ let answer;
723
+ try {
724
+ // No retry: a validator that is busy or down is skipped, never paid for twice.
725
+ answer = await makeRequest("POST", dataUrl(entity, "select/validate"), check, { ctx, retryTransient: false });
726
+ }
727
+ catch (e) {
728
+ debug(`${entity}: select/validate did not answer (${e instanceof Error ? e.message : String(e)}) — the read goes unchecked`);
729
+ return null;
730
+ }
731
+ if (answer === null || typeof answer !== "object" || Array.isArray(answer))
732
+ return null;
733
+ const list = answer.invalidFields;
734
+ return Array.isArray(list) ? list.filter((f) => Boolean(f) && typeof f === "object") : [];
735
+ }
736
+ /** What the platform would have answered, said here — nothing was sent. */
737
+ function refusedBeforeSending(entity, invalid) {
738
+ const paths = invalid.map((f) => (f.location && f.location !== "fields" ? `${f.path} (${f.location})` : String(f.path))).join(", ");
739
+ return new ApiError(400, "Bad Request", JSON.stringify({
740
+ statusCode: 400,
741
+ code: "request.invalid",
742
+ message: `Select query on ${entity} references invalid fields: ${paths}. Checked with the platform's own ` +
743
+ "validator before sending — nothing was sent. suppa_describe_entity lists the entity's fields.",
744
+ invalidFields: invalid,
745
+ checkedBeforeSending: true,
746
+ }));
747
+ }
647
748
  /**
648
- * POST an entity read, trimming this server's own projection to fit the tenant.
749
+ * POST an entity read, checked first and trimmed to fit the tenant (see above).
649
750
  *
650
- * The platform names the offending paths in its own 400, so the fix is to
651
- * believe it: drop them, retry once, and remember for the rest of the process
652
- * so the wasted round trip is paid once per tenant and entity, not per call.
751
+ * The 400 path below is the safety net for what the check cannot see — a field
752
+ * removed since its verdict was kept, or a validator that did not answer: the
753
+ * platform names the offending paths in its 400, they are dropped, the read is
754
+ * retried once, and the verdict is corrected.
653
755
  */
654
756
  async function postEntityRead(entity, path, body, fields, opts = {}) {
655
757
  const ctx = opts.ctx ?? tenants.current();
656
758
  const own = fields !== null && isOwnProjection(fields);
759
+ const checkKey = readCheckKey(ctx, entity, body);
760
+ let invalid = checkedReads.get(checkKey) ?? (own ? loadReadCheck(checkKey) : undefined);
761
+ if (invalid === undefined) {
762
+ const verdict = await validateRead(entity, body, ctx);
763
+ if (verdict !== null) {
764
+ invalid = verdict;
765
+ if (own)
766
+ saveReadCheck(checkKey, verdict);
767
+ }
768
+ }
769
+ if (invalid !== undefined)
770
+ checkedReads.set(checkKey, invalid);
657
771
  let payload = body;
772
+ if (invalid !== undefined && invalid.length > 0) {
773
+ // Only this server's projection bends: a caller's, a filter or an order is the question asked.
774
+ const refused = own ? invalid.filter((f) => f.location !== "fields") : invalid;
775
+ if (refused.length > 0)
776
+ throw refusedBeforeSending(entity, refused);
777
+ payload = { ...body, fields: withoutPaths(fields, invalid.map((f) => String(f.path))) };
778
+ }
658
779
  if (own) {
659
780
  const known = rejectedFields.get(rejectKey(ctx, entity));
660
781
  if (known && known.size > 0) {
661
- payload = { ...body, fields: withoutPaths(fields, known) };
782
+ payload = { ...payload, fields: withoutPaths(payload.fields, known) };
662
783
  }
663
784
  }
664
785
  // A projection this server wrote also comes back without the platform's
@@ -685,8 +806,12 @@ async function postEntityRead(entity, path, body, fields, opts = {}) {
685
806
  if (known.size === before) {
686
807
  throw e; // the retry named the same fields — the problem is elsewhere
687
808
  }
809
+ // The kept verdict was wrong (or there was none): correct it, so the next read is checked right.
810
+ const corrected = [...(invalid ?? []), ...bad.map((p) => ({ path: p, location: "fields" }))];
811
+ checkedReads.set(checkKey, corrected);
812
+ saveReadCheck(checkKey, corrected);
688
813
  debug(`${entity}: this tenant has no ${bad.join(", ")} — retrying without them`);
689
- return shaped(await makeRequest("POST", path, { ...body, fields: withoutPaths(fields, known) }, opts));
814
+ return shaped(await makeRequest("POST", path, { ...payload, fields: withoutPaths(payload.fields, known) }, opts));
690
815
  }
691
816
  }
692
817
  export async function searchEntity(entity, filters = null, fields = null, limit = 50, offset = 0, orderBy = null, searchValue = "", operator = "and", deletedScope = DEFAULT_DELETED_SCOPE, includeDeletedRelations = DEFAULT_INCLUDE_DELETED_RELATIONS) {
@@ -2,9 +2,10 @@
2
2
  * Which field projections belong to THIS SERVER, and how to trim one.
3
3
  *
4
4
  * A tenant's entities are editable, so a field this server names may simply not
5
- * be there — `Tasks.author` is absent on tenants that renamed it `createdBy`,
6
- * and that one field failed every task read with an opaque 400 about a
7
- * projection the user never chose and could not change.
5
+ * be there — `Tasks.author` (now gone everywhere, `createdBy` replaced it) once
6
+ * failed every task read with an opaque 400 about a projection the user never
7
+ * chose and could not change. httpClient checks such a read with the platform's
8
+ * validator first and drops the missing paths before sending.
8
9
  *
9
10
  * A projection tagged here may be trimmed to fit the tenant. One a caller
10
11
  * supplied never is: quietly returning everything except what someone asked for
@@ -20,6 +21,20 @@ export function ownProjection(fields) {
20
21
  OWN_PROJECTIONS.add(fields);
21
22
  return fields;
22
23
  }
24
+ /**
25
+ * Every projection this server owns, with the entity it reads — what scripts/check-own-projections.mjs checks against
26
+ * a tenant's schema before a release, so a field that does not exist (as `Tasks.author` did) is found by a check, not
27
+ * by a 400 in the platform's log.
28
+ */
29
+ export const OWN_PROJECTION_REGISTRY = [];
30
+ /** Register named own projections as reads of `entity` (call it right after their declarations). */
31
+ export function registerOwnProjections(entity, named) {
32
+ for (const [name, fields] of Object.entries(named)) {
33
+ if (!OWN_PROJECTIONS.has(fields))
34
+ throw new Error(`${name} is not an own projection — wrap it in ownProjection()`);
35
+ OWN_PROJECTION_REGISTRY.push({ entity, name, fields });
36
+ }
37
+ }
23
38
  /** True when `fields` is a projection this server owns. */
24
39
  export function isOwnProjection(fields) {
25
40
  return OWN_PROJECTIONS.has(fields);
@@ -12,7 +12,8 @@ import { makeRequest, searchEntity, selectEntity, insertEntity, updateEntity, re
12
12
  import { existsSync } from "node:fs";
13
13
  import { dirname, join } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
- import { ownProjection } from "../projection.js";
15
+ import { ownProjection, registerOwnProjections } from "../projection.js";
16
+ import { current as currentTenant } from "../tenants.js";
16
17
  import { makeFilter, jsonResponse, parseJsonParam, ACCESS_METADATA_KEYS, confirmRequired } from "../utils.js";
17
18
  /**
18
19
  * The bundled building-suppa-automations skill folder, from dist/tools/ or src/tools/ alike — what
@@ -74,6 +75,8 @@ const _RUN_FIELDS = ownProjection({
74
75
  triggerEntityName: true,
75
76
  error: true,
76
77
  });
78
+ registerOwnProjections(WORKFLOW_ENTITY, { _LIST_FIELDS, _GRAPH_FIELDS });
79
+ registerOwnProjections(EXECUTE_ENTITY, { _RUN_FIELDS });
77
80
  function isPlainObject(v) {
78
81
  return typeof v === "object" && v !== null && !Array.isArray(v);
79
82
  }
@@ -435,6 +438,11 @@ async function _scanWorkflows() {
435
438
  * fallback signal. Non-404 errors (e.g. 401) propagate.
436
439
  */
437
440
  export async function _fetchNodeCatalog() {
441
+ // A stand without the route answers 404 to every create / update / publish preview that asks; once is enough to
442
+ // know, for the rest of the process — a 404 the platform is certain to give is not asked for again.
443
+ const host = currentTenant().host;
444
+ if (_catalogAbsent.has(host))
445
+ return null;
438
446
  let cat;
439
447
  try {
440
448
  cat = await makeRequest("GET", NODE_CATALOG_PATH);
@@ -445,12 +453,19 @@ export async function _fetchNodeCatalog() {
445
453
  // must NOT be misread as "route absent" (and 401 must still surface).
446
454
  const msg = ex instanceof Error ? ex.message : String(ex);
447
455
  if (msg.startsWith("HTTP 404")) {
456
+ _catalogAbsent.add(host);
448
457
  return null;
449
458
  }
450
459
  throw ex;
451
460
  }
452
461
  return Array.isArray(cat) ? cat : null;
453
462
  }
463
+ /** Tenant hosts whose build has no /api/automation/nodes (answered 404), for this process. */
464
+ const _catalogAbsent = new Set();
465
+ /** Forget which stands lack the catalog — for tests that play several stands under one host. */
466
+ export function _forgetCatalogAbsence() {
467
+ _catalogAbsent.clear();
468
+ }
454
469
  /**
455
470
  * {node type: occurrences} across live graphs. Best-effort enrichment —
456
471
  * never raises (returns {} on any failure).
@@ -9,7 +9,7 @@
9
9
  * Python's server.py), so it is applied uniformly across all tools.
10
10
  */
11
11
  import { makeRequest, dataUrl, customOrderUrl, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
12
- import { ownProjection } from "../projection.js";
12
+ import { ownProjection, registerOwnProjections } from "../projection.js";
13
13
  import { makeFilter, writeOutcome, stripHtml, jsonResponse, wrapHtml, unescapeUnicode, parseJsonParam, parseProjectionParam, notFoundAnswer, } from "../utils.js";
14
14
  // ---------------------------------------------------------------------------
15
15
  // Constants
@@ -74,6 +74,9 @@ export const BLOCK_FIELDS = ownProjection({
74
74
  children: "#expand_tree(10)",
75
75
  createdAt: true,
76
76
  });
77
+ registerOwnProjections(ENTITY_DOCS, { DOC_FIELDS });
78
+ registerOwnProjections(ENTITY_PAGES, { PAGE_FIELDS });
79
+ registerOwnProjections(ENTITY_PAGE_BLOCKS, { BLOCK_FIELDS });
77
80
  // ---------------------------------------------------------------------------
78
81
  // Block content helpers
79
82
  // ---------------------------------------------------------------------------
@@ -296,6 +299,7 @@ const DOC_DETAIL_FIELDS = ownProjection({
296
299
  ...DOC_FIELDS,
297
300
  pages: { id: true, title: true, status: true, parent: { id: true } },
298
301
  });
302
+ registerOwnProjections(ENTITY_DOCS, { DOC_DETAIL_FIELDS });
299
303
  /** Get a document by ID, including its pages. */
300
304
  export async function getDoc(docId, fieldsJson = null) {
301
305
  const fields = _projection(fieldsJson, DOC_DETAIL_FIELDS);
@@ -901,11 +901,14 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
901
901
  return ent.error;
902
902
  }
903
903
  }
904
+ // A read refused before sending already carries the validator's answer (httpClient postEntityRead).
905
+ const body = e?.parsedBody;
906
+ const known = body?.checkedBeforeSending === true && Array.isArray(body.invalidFields) ? body.invalidFields : undefined;
904
907
  const diag = await _selectDiagnostic(entityName, {
905
908
  fields: fields,
906
909
  conditions,
907
910
  orderBy: order,
908
- });
911
+ }, known);
909
912
  if (!diag) {
910
913
  throw e;
911
914
  }
@@ -942,13 +945,20 @@ export async function searchRecords(entityName, filtersJson = "[]", fieldsJson =
942
945
  * check itself fails — a diagnostic must never turn a legitimate empty result
943
946
  * into an error.
944
947
  */
945
- async function _selectDiagnostic(entityName, payload) {
948
+ async function _selectDiagnostic(entityName, payload,
949
+ /** The validator's answer when it is already in hand — no second request for it. */
950
+ known) {
946
951
  let result;
947
- try {
948
- result = await validateSelect(entityName, payload);
952
+ if (known !== undefined) {
953
+ result = { valid: known.length === 0, invalidFields: known };
949
954
  }
950
- catch {
951
- return null;
955
+ else {
956
+ try {
957
+ result = await validateSelect(entityName, payload);
958
+ }
959
+ catch {
960
+ return null;
961
+ }
952
962
  }
953
963
  if (!result || result.valid !== false) {
954
964
  return null;
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { makeRequest, searchEntity, selectEntity, insertEntity, } from "../httpClient.js";
12
- import { ownProjection } from "../projection.js";
12
+ import { ownProjection, registerOwnProjections } from "../projection.js";
13
13
  import { makeFilter, jsonResponse, parseJsonParam, notFoundAnswer } from "../utils.js";
14
14
  // ---------------------------------------------------------------------------
15
15
  // Constants
@@ -30,6 +30,7 @@ export const FORM_DETAIL_FIELDS = ownProjection({
30
30
  ...FORM_LIST_FIELDS,
31
31
  data: true,
32
32
  });
33
+ registerOwnProjections(ENTITY_FORMS, { FORM_LIST_FIELDS, FORM_DETAIL_FIELDS });
33
34
  export const DEFAULT_FORM_SETTINGS = {
34
35
  id: 0,
35
36
  size: "md",
@@ -8,7 +8,7 @@
8
8
  * mutations lives one layer up (server.ts, mirroring server.py) — NOT here.
9
9
  */
10
10
  import { searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
11
- import { ownProjection } from "../projection.js";
11
+ import { ownProjection, registerOwnProjections } from "../projection.js";
12
12
  import { dropDerivablePlainDescription, statusValue } from "../readEconomy.js";
13
13
  import { makeFilter, parseDeadline, parseProjectionParam, wrapHtml, jsonResponse, localDayRange, writeOutcome, notFoundAnswer, } from "../utils.js";
14
14
  import * as tenants from "../tenants.js";
@@ -16,11 +16,11 @@ import { config } from "../config.js";
16
16
  // ---------------------------------------------------------------------------
17
17
  // Field projections
18
18
  // ---------------------------------------------------------------------------
19
- // `ownProjection` marks these as THIS SERVER's, not the caller's: a tenant
20
- // that does not have one of these fields gets it pruned on first use instead of
21
- // failing every task read. Both spellings of the person who filed the task are
22
- // listed on purpose — tenants renamed `author` to `createdBy`, and whichever is
23
- // absent here is dropped once, per tenant.
19
+ // `ownProjection` marks these as THIS SERVER's, not the caller's: a field a
20
+ // tenant lacks is dropped before the read is sent (httpClient postEntityRead,
21
+ // checked with select/validate). The person who filed the task is `createdBy`:
22
+ // `author` is gone on every tenant, and asking for both put one 400 per process
23
+ // start per user in entity-builder's log (79 in 36 h, 2026-11-10/11).
24
24
  export const TASK_LIST_FIELDS = ownProjection({
25
25
  id: true,
26
26
  title: true,
@@ -30,7 +30,6 @@ export const TASK_LIST_FIELDS = ownProjection({
30
30
  updatedAt: true,
31
31
  estimatedDuration: true,
32
32
  assignedTo: { id: true, firstName: true, lastName: true, fullName: true },
33
- author: { id: true, fullName: true },
34
33
  createdBy: { id: true, fullName: true },
35
34
  project: { id: true, title: true },
36
35
  parent: { id: true, title: true },
@@ -57,6 +56,7 @@ export const TASK_DETAIL_FIELDS = ownProjection({
57
56
  children: { id: true, title: true },
58
57
  attachments: { id: true, fileName: true, filePath: true },
59
58
  });
59
+ registerOwnProjections("Tasks", { TASK_LIST_FIELDS, TASK_DETAIL_FIELDS });
60
60
  const _ACTIVE_STATES = ["active", "inprogress"];
61
61
  /** Build the Tasks filter list shared by searchTasks and countTasks. */
62
62
  function _taskFilters(my = false, active = false, overdue = false, dueToday = false, projectId = null, workflowId = null, stageId = null, assignedToId = null) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.44.3",
3
+ "version": "1.44.5",
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": {
@@ -41,7 +41,8 @@
41
41
  "form:gate": "node skills/suppa-form-v2/scripts/validate-form-schema.mjs",
42
42
  "sync:formbuilder": "node scripts/sync-formbuilder.mjs",
43
43
  "sync:vue-compiler": "node scripts/sync-vue-compiler.mjs",
44
- "guards:install": "node skills/suppa-entity-code/scripts/install-entity-code-guards.mjs"
44
+ "guards:install": "node skills/suppa-entity-code/scripts/install-entity-code-guards.mjs",
45
+ "check:projections": "node scripts/check-own-projections.mjs"
45
46
  },
46
47
  "keywords": [
47
48
  "mcp",
@@ -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,9 +30,12 @@ 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
+ - **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.
36
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
@@ -112,6 +115,7 @@ Someone who opens the automation should read the flow from the canvas alone. Eve
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
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.
115
119
 
116
120
  ## Settings and the Set node
117
121
 
@@ -121,7 +125,7 @@ Verified on modern-expo.test (2026-10-27, a throwaway probe automation):
121
125
 
122
126
  | Where a value lives | Use it for | How it is read |
123
127
  |---|---|---|
124
- | `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. A `code` node has no `$workflow`, so pass it through the `set` before it |
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 |
125
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> }}` |
126
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 |
127
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 | — |
@@ -148,7 +152,7 @@ Verified on modern-expo.test (2026-10-27, a throwaway probe automation):
148
152
 
149
153
  **The Set node «Config»: what it does and does not do**
150
154
  - **It is not visible to trigger conditions.** They are checked before any node has run, so filters read settings only.
151
- - **It must be on the path the run took.** `$('Config')` sees only nodes that ran in this run. On a branch that did not run, it is `undefined`, and no error is raised.
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.
152
156
  - **It reshapes the item.**
153
157
  - Without `keepOnlySet`, the config fields join `$json` and travel on with the record.
154
158
  - With `keepOnlySet: true`, the item becomes the config, and the trigger data is reachable only through `$('A1. Start…')`.
@@ -161,19 +165,52 @@ Verified on modern-expo.test (2026-10-27, a throwaway probe automation):
161
165
 
162
166
  ## Safe runs
163
167
 
164
- - **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.
165
- - Keep the ids of approval / wait nodes stable across rebuilds.
166
- - Before publishing a reshaped graph, list the waiting runs (`suppa_list_automation_runs status: "waiting"`) and say which ones the change strands.
167
- - `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.
168
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.
169
171
  - `return []` is for «this record is not ours», such as a filter or a test-mode guard.
170
172
  - A `return []` on a missing setting shows as a successful run that did nothing.
171
- - **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.
172
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.
173
179
  - Alternatively, make the write an update of a known record.
174
180
  - Updates that set a value (stage, assignee) are safe to repeat.
175
181
  - Inserts and `merge` additions (watchers, auditors) are not.
176
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
+
177
214
  ## Data in expressions
178
215
 
179
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.
@@ -192,10 +229,13 @@ Verified on modern-expo.test (2026-10-27, a throwaway probe automation):
192
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.
193
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.
194
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.
195
- - 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.
196
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.
197
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.
198
- - 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.
199
239
 
200
240
  ## Publish and verify
201
241
 
@@ -205,7 +245,7 @@ Follow `references/publishing.md`:
205
245
  - compare the draft with the build by hash;
206
246
  - publish;
207
247
  - test every flow with a real run (form submission, stage change) and read the per-node steps;
208
- - 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.
209
249
 
210
250
  ## Common mistakes
211
251
 
@@ -221,9 +261,16 @@ Follow `references/publishing.md`:
221
261
  | `"text ={{ { id: x } }}"` for a relation | Make the expression the whole field. In text, an object becomes `[object Object]` |
222
262
  | Editing settings partially | Updates merge top-level keys. Resend the whole `settings.<key>`, then republish |
223
263
  | Option key `constructor` in settings | The platform strips it. Look options up with `hasOwnProperty` |
224
- | A node reads `$('X')` where X runs on another branch or later | `undefined` at runtime, with no error. `lint-graph` catches it |
225
- | 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 |
226
- | `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 |
227
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 |
228
275
  | `type.title === 'Офісна'`, a stage compared by name | Compare `value` / `id` / `code`; titles are localized and may be `null` |
229
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`.
@@ -37,12 +39,12 @@ Several triggers in one automation are allowed. The run starts at the trigger th
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,7 +70,8 @@ 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.
72
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`.
73
76
  - Settings are stored as jsonb:
74
77
  - object keys get re-sorted, so keep an explicit order array;
@@ -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
@@ -206,9 +224,77 @@ export const lint = (graph, { previous } = {}) => {
206
224
  };
207
225
  walk(graph.settings, '');
208
226
  if (secretKeys.length) add('WARN', `settings hold what looks like a secret (${secretKeys.join(', ')}) — expression values are kept in run data; use credentials`);
209
- if (previous) {
210
- const now = new Set(nodes.map((n) => n.id));
211
- 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`);
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
+ }
212
298
  }
213
299
 
214
300
  // --- size
@@ -223,9 +309,7 @@ export const lint = (graph, { previous } = {}) => {
223
309
 
224
310
  if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
225
311
  const args = process.argv.slice(2);
226
- const prevAt = args.indexOf('--previous');
227
- const previous = prevAt >= 0 ? readGraph(args[prevAt + 1], { side: 'published' }) : undefined;
228
- const res = lint(readGraph(args[0]), { previous });
312
+ const res = lint(readGraph(args[0]));
229
313
  const order = { ERROR: 0, WARN: 1, NOTE: 2 };
230
314
  res.sort((a, b) => order[a.level] - order[b.level]);
231
315
  for (const r of res) console.log(`${r.level.padEnd(5)} ${r.msg}`);
@@ -72,7 +72,7 @@ SELECT "id", "assignee", "tags" FROM TestTasks -- assignee:{i
72
72
 
73
73
  ```sql
74
74
  SELECT "id" FROM TestTasks WHERE "assignee.firstName" = $v -- :149
75
- SELECT id FROM Tasks WHERE "author.department.company.name" = 'Acme' -- 3-hop equality parser-round-trip.spec.ts:1907
75
+ SELECT id FROM Tasks WHERE "createdBy.department.company.name" = 'Acme' -- 3-hop equality (the spec says author; Tasks has createdBy) parser-round-trip.spec.ts:1907
76
76
  SELECT "id" FROM TestTasks WHERE "children.id" IS NOT NULL -- o2m existence planner-parity.spec.ts:172
77
77
  SELECT "id" FROM TestTasks WHERE "tags.label" = $v -- m2m subfield → EXISTS :185
78
78
  SELECT "id" FROM TestTasks WHERE "tags.taggedTasks.title" = 'x' -- deep m2m→backref chain :3478