suppa-mcp-2 1.43.5 → 1.44.1

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
@@ -528,6 +528,9 @@ extension table is created outside that check and is not subject to it.
528
528
  | `suppa_publish_automation` | Publish the draft snapshot (confirm-gated) |
529
529
  | `suppa_unpublish_automation` | Deactivate an automation (confirm-gated) |
530
530
 
531
+ Designing, laying out or optimizing an automation before writing it: the bundled
532
+ `skills/building-suppa-automations` skill (see below).
533
+
531
534
  ### Forms
532
535
 
533
536
  | Tool | Description |
@@ -701,6 +704,47 @@ covered; see `references/tabular-parts.md` and `references/registration.md`.
701
704
 
702
705
  ---
703
706
 
707
+ ## Bundled agent skill: building-suppa-automations
708
+
709
+ `skills/building-suppa-automations/` builds a Suppa 2.0 automation (AutomationWorkflow)
710
+ as a **source you regenerate**, not by hand in the builder, so the canvas reads as the
711
+ process when someone opens it:
712
+
713
+ - **One automation per process.** Several flows can share it, each with its own trigger.
714
+ Loop protection is keyed by workflow id, so splitting one process across
715
+ automations is what produces duplicate runs.
716
+ - **English, numbered node names** (`A5.1 Wait for head approval`). Expressions address
717
+ nodes by name.
718
+ - **Straight-edge layout**, computed from the builder's measured handle offsets.
719
+ - **Lean graphs:**
720
+ - filter in the trigger;
721
+ - one read per entity per flow;
722
+ - request and form flows take what the submission already carries (`formData`,
723
+ `number`, `createdBy`) instead of selecting it again;
724
+ - business rules are visible on the canvas, technical logic goes into one `code` node.
725
+ - **Publishing that survives the builder.** It writes through the API with the builder
726
+ tab closed, verifies the draft by hash, then publishes and tests a live run.
727
+
728
+ The scripts need only Node ≥ 18. They read `{ nodes, connections, settings? }` in the
729
+ stored shape — what `suppa_update_automation` takes — or a `suppa_get_automation` answer
730
+ as is, and write the stored shape. `suppa_health_check` → `skill_files.automations_skill`
731
+ names the installed folder:
732
+
733
+ ```bash
734
+ S=node_modules/suppa-mcp-2/skills/building-suppa-automations/scripts
735
+ node $S/lint-graph.mjs graph.json # ERROR / WARN / NOTE; exit 1 on an ERROR
736
+ node $S/auto-layout.mjs graph.json > placed.json # places every node, repairs crossings
737
+ node $S/layout-check.mjs placed.json # must list no problem (exit 0)
738
+ node $S/render-graph.mjs placed.json preview.svg --png preview.png # look before publishing
739
+ ```
740
+
741
+ `references/node-reference.md` holds the parameter shapes verified on running
742
+ automations: triggers, conditions, switch outputs, approvals, links, the request
743
+ trigger's output. `references/publishing.md` holds the write → hash → publish → live-test
744
+ order.
745
+
746
+ ---
747
+
704
748
  ## Development
705
749
 
706
750
  ```bash
@@ -791,6 +835,7 @@ suppa-mcp-node/
791
835
  │ ├── migrate.ts nameMap.ts v1Fields.ts
792
836
  │ └── workspace.ts
793
837
  ├── skills/suppa-entity-code/ # bundled agent skill: write v2 schema code + validator
838
+ ├── skills/building-suppa-automations/ # bundled agent skill: design, lay out, lint and publish automations
794
839
  ├── test/ # vitest suite (ports the Python test suite)
795
840
  ├── scripts/ # live read-only / write verify scripts
796
841
  ├── package.json
package/dist/server.js CHANGED
@@ -2076,8 +2076,9 @@ export function buildToolTable() {
2076
2076
  }, async (a) => text(await automation.listAutomations(a.search, a.is_active, a.limit, a.offset)));
2077
2077
  reg("suppa_get_automation", {
2078
2078
  description: "Get one automation workflow as a normalized graph: nodes + edges, settings,\n" +
2079
- " and the published snapshot. nodes [{id,type,name,config,position}], edges\n" +
2080
- ' [{from,fromHandle,to,toIndex}], under "published". Distinct from Task workflows.',
2079
+ " and the published snapshot. nodes [{id,type,name,config,position,…other keys}], edges\n" +
2080
+ ' [{from,fromHandle,to,toIndex}], under "published". Distinct from Task workflows.\n' +
2081
+ " Design / reshape: skill building-suppa-automations (suppa_health_check names its folder).",
2081
2082
  inputSchema: { automation_id: AutomationId },
2082
2083
  annotations: _READ,
2083
2084
  }, async (a) => text(await automation.getAutomation(a.automation_id)));
@@ -2139,8 +2140,7 @@ export function buildToolTable() {
2139
2140
  name: z.string().describe("Automation name."),
2140
2141
  nodes_json: z
2141
2142
  .string()
2142
- .describe('JSON array of nodes: [{"id","type","parameters":{...}}]. First node must be a ' +
2143
- "trigger (triggerEntity/triggerManual/triggerWebhook)."),
2143
+ .describe('JSON array of nodes: [{"id","type","name","parameters":{...},"position"}].'),
2144
2144
  connections_json: z
2145
2145
  .string()
2146
2146
  .describe('JSON object of connections: {"srcNodeId": {"handle": [{"node": "targetId", "index": 0}]}}.'),
@@ -3107,6 +3107,8 @@ async function healthCheck(deep = true) {
3107
3107
  form_v2_cell_rules: await formV2.cellRulesStatus(),
3108
3108
  entity_code_validator: await entityCode.validatorStatus(),
3109
3109
  sql_skill: sqlKb.sqlSkillFile("SKILL.md") && sqlKb.sqlSkillFile("references") ? "present" : "MISSING",
3110
+ // A path, not "present": the skill is files an agent reads and scripts it runs by path.
3111
+ automations_skill: automation.automationsSkillDir() ?? "MISSING",
3110
3112
  },
3111
3113
  };
3112
3114
  if (!token) {
@@ -9,8 +9,25 @@
9
9
  * present, and is otherwise DERIVED from the `nodes` JSON of live workflows.
10
10
  */
11
11
  import { makeRequest, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
12
+ import { existsSync } from "node:fs";
13
+ import { dirname, join } from "node:path";
14
+ import { fileURLToPath } from "node:url";
12
15
  import { ownProjection } from "../projection.js";
13
16
  import { makeFilter, jsonResponse, parseJsonParam, ACCESS_METADATA_KEYS, confirmRequired } from "../utils.js";
17
+ /**
18
+ * The bundled building-suppa-automations skill folder, from dist/tools/ or src/tools/ alike — what
19
+ * suppa_health_check names, so an agent on an npx or plugin install (no node_modules of its own)
20
+ * can find the SKILL.md and run the scripts by path.
21
+ */
22
+ export function automationsSkillDir() {
23
+ const here = dirname(fileURLToPath(import.meta.url));
24
+ for (const root of [join(here, "..", ".."), join(here, "..", "..", "..")]) {
25
+ const p = join(root, "skills", "building-suppa-automations");
26
+ if (existsSync(join(p, "SKILL.md")) && existsSync(join(p, "scripts", "lint-graph.mjs")))
27
+ return p;
28
+ }
29
+ return null;
30
+ }
14
31
  export const WORKFLOW_ENTITY = "AutomationWorkflow";
15
32
  export const EXECUTE_ENTITY = "AutomationWorkflowExecute";
16
33
  export const EXECUTE_DATA_ENTITY = "AutomationWorkflowExecuteData";
@@ -174,7 +191,14 @@ function _normalizeNodes(nodes) {
174
191
  }
175
192
  return [];
176
193
  }
177
- /** Raw node -> {id, type, name?, config, position?}. config = parameters verbatim. */
194
+ // Keys _normalizeNode reads into id/type/name/config/position; every OTHER node key is kept verbatim.
195
+ const _NODE_KEYS_READ = new Set(["id", "type", "nodeType", "kind", "name", "position", "parameters", "config", "data"]);
196
+ /**
197
+ * Raw node -> {id, type, name?, config, position?, ...other node keys}. config = parameters verbatim.
198
+ * The other keys (a merge's inputCount, onError) live beside parameters on the stored node; dropping
199
+ * them made a read -> edit -> suppa_update_automation round trip lose them with no error (live on
200
+ * modern-expo.test, 2026-10-26: automation 160's merge node carries inputCount 2).
201
+ */
178
202
  function _normalizeNode(raw) {
179
203
  const node = { id: raw.id ?? null, type: _nodeType(raw), config: _nodeConfig(raw) };
180
204
  if (raw.name !== null && raw.name !== undefined) {
@@ -183,6 +207,10 @@ function _normalizeNode(raw) {
183
207
  if (raw.position !== null && raw.position !== undefined) {
184
208
  node.position = raw.position;
185
209
  }
210
+ for (const [k, v] of Object.entries(raw)) {
211
+ if (!_NODE_KEYS_READ.has(k) && v !== undefined)
212
+ node[k] = v;
213
+ }
186
214
  return node;
187
215
  }
188
216
  /** Flatten {src: {handle: [{node, index}]}} -> [{from, fromHandle, to, toIndex}]. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.43.5",
3
+ "version": "1.44.1",
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": {
@@ -0,0 +1,185 @@
1
+ ---
2
+ name: building-suppa-automations
3
+ description: Use when creating, restructuring, renaming, laying out or optimizing a Suppa 2.0 automation (AutomationWorkflow nodes / connections / settings, workflow-builder canvas) — a new business process to automate, a messy or unreadable canvas, crooked edges, unclear node names, idle or duplicate runs, several automations serving one process, or porting a 1.0 BP template.
4
+ ---
5
+
6
+ # Building Suppa Automations
7
+
8
+ ## Overview
9
+
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
+
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.
13
+
14
+ ## Workflow
15
+
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
+ - 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.
19
+
20
+ 1. Design the flows with the checklist below. Write the build script (ids, names, parameters, settings), never the builder UI.
21
+ 2. `node scripts/lint-graph.mjs graph.json`
22
+ - Fix every ERROR: a `$('…')` that names no node or a node that has not run yet, `$()` inside `code`, wiped approvers, unreachable nodes, wrong output handles.
23
+ - Fix every WARN.
24
+ - Answer each NOTE: either it is intended or you fix it.
25
+ 3. `node scripts/auto-layout.mjs graph.json > placed.json`. It places every node with no hand-written spec and repairs what the edge model flags. Hand-tune with `scripts/layout.mjs` only when you must.
26
+ 4. `node scripts/layout-check.mjs placed.json` has to list no problem (exit 0).
27
+ 5. `node scripts/render-graph.mjs placed.json preview.svg --png preview.png`. Look at the picture before publishing.
28
+ 6. Publish and test (`references/publishing.md`).
29
+
30
+ ## One process = one automation
31
+
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:
34
+ - inside one automation, the flow that writes does its own follow-up (mark the request rejected, notify);
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.
37
+
38
+ ## Requests and form submissions: the trigger already holds the data
39
+
40
+ A request (Requests module) **is** a `FormSubmissions` row. Its automation starts from `formSubmission { formId }`. The trigger emits the whole row, with `number` and `requestType` already stamped by the before-insert hook:
41
+
42
+ | Field | Value |
43
+ |---|---|
44
+ | `id`, `number` (`REQ-000035`), `state`, `createdAt` | the request itself |
45
+ | `requestType`, `form` | `{ id, title }`, `{ id, name }` |
46
+ | `createdBy` | `{ id, fullName }` — the submitter |
47
+ | `formData.<key>` | what the user entered: text, numbers, date strings, option values (`"Lutsk"`), arrays for multi-selects and files, **relations as `{ id }` only** (`customer: { id: 72 }`) |
48
+
49
+ **Before adding any read in a request or form flow, look for the value in the trigger first.** Read it as `$('A1. Start…').first().json.formData.<key>`, `….number`, `….createdBy.fullName`.
50
+ - **No read needed:**
51
+ - writing a picked relation (`customer: "={{ { id: F.customer.id } }}"`);
52
+ - an approver or notification recipient (user `id`);
53
+ - a filter by id;
54
+ - a text value in a title or description;
55
+ - an `if` / `switch` on an option the user picked;
56
+ - the submitter's name, the request number.
57
+ - **A read is needed only for what `formData` lacks:**
58
+ - other fields of a picked record: its name, department, head, or the user behind an employee;
59
+ - related records the form does not show.
60
+ The request's own `FormSubmissions` row is never re-read: the trigger is that row.
61
+ - `formData` keys are the form's element keys and are form-specific; typos stay (`descriptoin`). Take them from a real run's trigger output (`suppa_get_automation_run`, step 0) or from the form schema, never by guessing from labels.
62
+ - In a stage-change flow (B) the trigger is the task, not the request. Reach the request through the link the request flow wrote (`EntityLinks`, `request-fulfilment`), and read it once there. Or, cheaper, have flow A copy what B needs onto the task when it creates it.
63
+
64
+ ## Names
65
+
66
+ | Element | Rule | Example |
67
+ |---|---|---|
68
+ | node `id` | readable kebab-case; connections use ids | `create-task`, `approve-head` |
69
+ | node `name` | English. Flow letter + step number + an action that says what happens. Business label before the BP code | `A4. Create task`, `A5.1 Wait for head approval`, `A6.1 Equipment (BP 006): deadline = +2 working days`, `B3.6 Rejected: notify submitter` |
70
+ | step numbers | One major number per phase (start, lookups, decide, create, approve, after approval). Its nodes in a row take `.1`, `.2`, … | `A5. Head approval needed?` → `A5.1 Wait for head approval` → `A5.2 …` → `A5.3 Move task to Rejected` |
71
+ | branch nodes | Every node of one branch keeps that branch's number and label | `A6.1 Equipment (BP 006): load holidays` → `A6.1 Equipment (BP 006): hand over to supervisor` |
72
+ | descriptions, messages | the users' language | — |
73
+ | notification templates | `subjectTemplate` and `bodyTemplate` carry the users' language (`uk`) next to `en`: the recipient reads the one their profile is set to | `{ "uk": "Заявку прийнято", "en": "Request accepted" }` |
74
+
75
+ - Expressions address nodes by **name** (`$('A4. Create task')`). Renaming a node means rewriting every `$('old')` and every `«old»` in code comments, inside the same automation.
76
+ - No ASCII apostrophe (`'`) in names, because it breaks `$('…')`. Use `ʼ`.
77
+ - The node registry has no notes field. Put the step-by-step guide («як читати схему») at the top of the automation `description`, keyed by the same step numbers.
78
+
79
+ ## Layout
80
+
81
+ Edges are step lines from an **output handle** to an **input handle**. An edge is straight only when both handles have the same y. Same-sized boxes in one row are **not** enough: `if` and `approval` outputs sit 5 px and 29 px below their input, and `switch` outputs are 24 px apart. The measured offsets are in `scripts/geometry.mjs`.
82
+
83
+ `auto-layout.mjs` applies these rules. Know them, so you can judge the picture:
84
+
85
+ 1. Columns run left to right, pitch 340. Column = longest path from the trigger.
86
+ 2. Place every node by its feeding output, not by row: input y = source handle y + dy. Hand-tuning: `scripts/layout.mjs` with a spec `{ id: [column, sourceId, handle, dy] }`.
87
+ 3. **Detours go above the line they leave.** If a lookup can be skipped, its `false` edge to the rejoin node stays straight on the main line, and the lookup goes 150 higher. The same applies to an approval with a straight bypass and to a parallel fetch before a merge.
88
+ 4. When an approval's `rejected` line runs far right, raise the next node on the `approved` line (dy −24, or −48 for a following approval). Otherwise the rejected line runs along its border.
89
+ 5. Collect the far targets of many branches, such as a shared «reject» node, **below and right of all branch rows**, so their vertical segments fall in empty column gaps.
90
+ 6. Branches that end without rejoining stack below, each clear of what is already in their columns. Each flow gets its own band, about 300 px below the previous one.
91
+ 7. `layout-check.mjs` must report nothing: no backward edges, no overlaps, no line through or along a node. Report the straight-edge count.
92
+
93
+ ## Lean graph checklist
94
+
95
+ Someone who opens the automation should read the flow from the canvas alone. Every node has to earn its place.
96
+
97
+ - **Every node does one of four things:** reads, decides, writes or waits. A node that only reshapes data is allowed in two places: as a `set` right before a `code` node (the sandbox has no `$()`), or as a `set` where branches rejoin. Elsewhere, read `$('…')` directly. `lint-graph` flags the rest.
98
+ - **Business decisions are visible; technical logic is hidden.** A choice the business cares about (which BP step, approved or rejected) is an `if` / `switch` on the canvas. Its outputs are named by the case: `equipment`, `1c-rights`, `rejected`, not `toNew` or `0`, because they label the lines. Lookups, mappings and deadline arithmetic go into one `code` node.
99
+ - **One write per record per phase.** Merge consecutive updates of the same record into one `updateById`, and put related fields (stage, assignee, watchers) into the same write.
100
+ - **Defaults before the save, not after it.** To fill fields of the record being created (a default approver, a status), trigger on `before-insert` and answer with `responseEntity { action: "apply", values: [{ name, value }] }`. The record is saved with the values, which costs no write.
101
+ - An `after-insert` → `updateById` costs one more write.
102
+ - It also starts every `after-update` trigger on that entity a second time.
103
+ - **Read only what the flow uses.** A lookup that only decorates a description is a candidate to drop. Give every `select` a `limit` and `fields`.
104
+ - **One read per entity per flow.** Several reads of the same entity are one query that was split.
105
+ - **The same record, different fields** → one `getById` with all the fields. Related records go in nested `fields` (`employees: { department: { head: { user: { id } } } }`) rather than a second read.
106
+ - **Several records of one entity by known ids** → one `select` with `id in [...]` and `limit` = the count. A picker filter takes several records with `comparator: "in"`. Pick each row afterwards: `$('2. Read the approvers').all().find(i => i.json.id === ID)?.json`, or inside the `code` node.
107
+ - **One node per role** (CEO, CFO, CHRO…, one stage per node) costs a query per role. Keep the role → id map in `settings` and read them together in one `select … id in`. Read them only if you need more than the id, such as a name for a message. For an id alone, settings are enough and need no read.
108
+ - **What legitimately stays separate:**
109
+ - a read that needs the result of a read before it (a task, then its parent);
110
+ - reads on exclusive branches, of which one run takes only one.
111
+
112
+ - **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
+ - **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.
115
+
116
+ ## Safe runs
117
+
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.
122
+ - **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
+ - `return []` is for «this record is not ours», such as a filter or a test-mode guard.
124
+ - 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.
126
+ - 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
+ - Alternatively, make the write an update of a known record.
128
+ - Updates that set a value (stage, assignee) are safe to repeat.
129
+ - Inserts and `merge` additions (watchers, auditors) are not.
130
+
131
+ ## Data in expressions
132
+
133
+ - **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.
134
+ - The same applies to stages and projects: compare their `id`, or a `code` where the entity has one.
135
+ - **Dates and deadlines in the tenant's time zone, not a fixed offset.**
136
+ - A datetime without an offset is read as UTC.
137
+ - A hard-coded `+02:00` / `+03:00` is wrong for half the year (Kyiv switches on the last Sundays of March and October).
138
+ - Compute the instant in the `code` node with `references/tenant-time.md`. A form date `YYYY-MM-DD` is the picked day. «Due at 16:00 that day» becomes `atKyiv(day, '16:00')`.
139
+ - **Write a relation as `{ id }`.**
140
+ - A bare number or a bare `={{ x.id }}` in a relation field returns success and stores `null`.
141
+ - Many-to-one: `"assignee": "={{ { id: … } }}"`.
142
+ - Many-to-many: `[{ id }, …]`, plus `merge: ["field"]` to add rather than replace.
143
+
144
+ ## Optimize with measurements
145
+
146
+ - `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.
148
+ - **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.
150
+ - 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
+ - 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.
153
+
154
+ ## Publish and verify
155
+
156
+ Follow `references/publishing.md`:
157
+ - check the active tenant (the MCP can drift to prod);
158
+ - keep the workflow-builder tab **closed** while writing through the API, because it autosaves a stale graph over yours;
159
+ - compare the draft with the build by hash;
160
+ - publish;
161
+ - 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.
163
+
164
+ ## Common mistakes
165
+
166
+ | Mistake | Fix |
167
+ |---|---|
168
+ | Two automations for one process | One automation, two trigger flows |
169
+ | Guard selects against duplicates from your own other automation | Merge the automations, or let only one side write |
170
+ | `if` true/false or approved/rejected drawn into one row "because same size" | Place by handle offset, detour above |
171
+ | Publishing a draft saved in the builder UI | The UI drops expression `approvers` to `[]`. Rebuild from source |
172
+ | Editing settings partially | Updates merge top-level keys. Resend the whole `settings.<key>`, then republish |
173
+ | 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 |
177
+ | 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
+ | `type.title === 'Офісна'`, a stage compared by name | Compare `value` / `id` / `code`; titles are localized and may be `null` |
179
+ | `deadline: date + 'T16:00:00+02:00'` | `atKyiv(day, '16:00')` from `references/tenant-time.md` |
180
+ | `assignee: "={{ $json.userId }}"` (a bare id) | `"={{ { id: $json.userId } }}"` — a bare id stores `null` |
181
+ | `after-insert` → `updateById` of the same record to fill defaults | `before-insert` + `responseEntity` |
182
+ | A notification with only `en` | Add the users' language (`uk`) to `subjectTemplate` and `bodyTemplate` |
183
+ | Switch outputs `toNew`, `analyst`, `0` | Name them by the business case. They label the canvas lines |
184
+ | A read node per person / per stage of the same entity | One `select … id in [...]`, rows picked by id. `lint-graph` flags it |
185
+ | A select in a request flow for the submitter, the request row or a picked id | Take it from the trigger: `formData.<key>`, `createdBy`, `number`. `lint-graph` flags it |
@@ -0,0 +1,76 @@
1
+ # Node reference (verified on published, running automations)
2
+
3
+ Every shape below comes from a published, running automation; the ids in the examples are sample values.
4
+ For a type not listed, call `suppa_get_automation_node_schema`.
5
+
6
+ ## Graph
7
+
8
+ ```json
9
+ { "id": "create-task", "type": "suppa", "name": "A4. Create task", "parameters": { … }, "position": { "x": 7900, "y": 292 } }
10
+ ```
11
+
12
+ Connections: `{ "<from id>": { "<output handle>": [{ "node": "<to id>", "index": 0 }] } }`.
13
+
14
+ | Node type | Output handles |
15
+ |---|---|
16
+ | ordinary nodes, triggers | `main` |
17
+ | `if` | `true` / `false` |
18
+ | `approval` | `approved` / `rejected` |
19
+ | `switch` | the rule's `output` **name** (not an index) |
20
+
21
+ `index` is the target input. Only `merge` uses `1`.
22
+
23
+ ## Triggers
24
+
25
+ | Trigger | Parameters | Notes |
26
+ |---|---|---|
27
+ | Form submission / request | `formSubmission` `{ "formId": 1260 }` | Routes on `formId` alone, fires after insert. The output is the FormSubmissions row: `id`, `number`, `state`, `requestType {id,title}`, `form`, `createdBy {id,fullName}`, `formData` (relations as `{id}` only). Read values from it — see SKILL.md «Requests and form submissions». |
28
+ | Entity change | `triggerEntity` `{ "entityName": "Tasks", "events": ["after-update"], "watchFields": ["stage"], "conditions": { "operator": "and", "filters": [ {"operator": "or", "filters": [{"field": "project", "comparator": "=", "value": {"id": 3683}}]}, {"field": "stage.id", "comparator": "in", "value": [947, 968]} ] } }` | `events` take `after-insert` / `after-update` / `after-remove` (and `before-*`). Conditions nest `{operator, filters}`. Relation fields take `{id}` values or dotted paths (`stage.id`). Comparators include `=`, `!=`, `in`, `not in`, `contains`, `is null`, `is not null` (the null checks take no `value`). |
29
+
30
+ Several triggers in one automation are allowed. The run starts at the trigger that fired.
31
+
32
+ ## Core nodes
33
+
34
+ | Node | Parameters |
35
+ |---|---|
36
+ | `suppa` getById | `{ "action": "getById", "entityName": "AutomationWorkflow", "id": "={{ $workflow.id }}", "fields": {"id": true, "activeSettings": true} }` — the automation's own settings. |
37
+ | `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
+ | `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
+ | `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. |
41
+ | `if` | `{ "expression": "={{ … === true }}" }` |
42
+ | `switch` | `{ "mode": "first", "fallbackEnabled": false, "rules": [{"output": "approvalIt", "condition": "={{ $json.action === 'approvalIt' }}"}] }` |
43
+ | `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
+ | `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 } }]`. |
46
+ | `notification` | `{ "type": "insert", "channels": [{"channel": "inApp"}], "entityName": "Tasks", "recordId": "={{ … }}", "userIds": "={{ [ … ] }}", "subjectTemplate": {"uk": "…", "en": "…"}, "bodyTemplate": {"uk": "… ={{ expr }} …"}, "navigateTo": {"entityId": 45, "instanceId": "={{ … }}"} }` |
47
+
48
+ ## Linking a request to its task
49
+
50
+ Do not invent a field on the task. Use `EntityLinks`.
51
+
52
+ To create the link:
53
+ ```json
54
+ { "action": "insert", "entityName": "EntityLinks", "fields": {
55
+ "type": "={{ { id: <link type id from settings> } }}",
56
+ "instanceA": { "type": "many-to-one", "relationTarget": "FormSubmissions", "value": { "id": "={{ … }}" } },
57
+ "instanceB": { "type": "many-to-one", "relationTarget": "Tasks", "value": { "id": "={{ … }}" } } } }
58
+ ```
59
+
60
+ To find the request from the task: select `EntityLinks` with the filters
61
+ - `type.id = <type>`,
62
+ - `instanceB.$entityId = 45` (the Tasks entity id),
63
+ - `instanceB.$instanceId = <task id>`,
64
+
65
+ then read `instanceA.value.id ?? instanceA.id`.
66
+
67
+ ## Expressions and settings
68
+
69
+ - `={{ js }}` evaluates. Text and several `={{ }}` mix inside one string.
70
+ - 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`).
72
+ - Settings are stored as jsonb:
73
+ - object keys get re-sorted, so keep an explicit order array;
74
+ - a key named `constructor` is stripped;
75
+ - an update merges top-level keys only, so resend the whole `settings.<key>`;
76
+ - flows read `activeSettings`, so republish after any change.
@@ -0,0 +1,41 @@
1
+ # Publishing and verifying an automation
2
+
3
+ ## Draft and published
4
+
5
+ `AutomationWorkflow` has two sides:
6
+ - the **draft** — `nodes` / `connections` / `settings`;
7
+ - the **published** version — `activeNodes` / `activeConnections` / `activeSettings`.
8
+
9
+ Production runs only the published side. `hasUnpublishedChanges` tells you the draft differs.
10
+
11
+ ## Order of work
12
+
13
+ 1. **Tenant.** Run `suppa_use_tenant("<full https URL>")`, then confirm with `suppa_list_tenants`. Aliases collide, and the MCP may start on (or drift back to) prod. Check again before every write.
14
+ 2. **Close the builder.** Any `workflow-builder/<id>` tab must be navigated away before you write through the API. An open builder autosaves its stale graph over yours. It also turns expression `approvers` into `[]`, adds duplicate `condition` keys and re-lays-out the nodes. After writing, compare `nodes` with `activeNodes`. If the draft was overwritten, copy `activeNodes` / `activeConnections` back into it and republish.
15
+ 3. **Write.**
16
+ - Small graphs: `suppa_update_automation` (`nodes_json`, `connections_json`, `settings_json`; settings merge top-level).
17
+ - Big graphs (> ~40 KB): build the graph **inside the tenant page** from the stored `activeNodes` plus small inline maps (names, positions, new nodes). Then `POST /api/core/data/AutomationWorkflow/update/<id>` with `{ fields: { … } }` using the page's own session.
18
+ - A page **cannot** fetch `http://127.0.0.1` (Chrome Local Network Access): the call hangs and nothing arrives.
19
+ 4. **Verify by hash, not by reading.** `suppa_get_automation` returns 150 KB+. Run `node scripts/graph-hash.mjs graph.json` locally, and compute the same thing in the page:
20
+
21
+ ```js
22
+ const canon = (v) => Array.isArray(v) ? '[' + v.map(canon).join(',') + ']' : v && typeof v === 'object' ? '{' + Object.keys(v).sort().map(k => JSON.stringify(k) + ':' + canon(v[k])).join(',') + '}' : JSON.stringify(v);
23
+ const sha = async (s) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)))].map(b => b.toString(16).padStart(2, '0')).join('');
24
+ const key = (nodes) => nodes.map(n => ({ id: n.id, name: n.name, parameters: n.parameters, position: n.position })).sort((a, b) => a.id < b.id ? -1 : 1);
25
+ // compare (await sha(canon(key(row.nodes)))) with the local hash; return booleans, not hashes —
26
+ // the browser tool redacts long hex strings from results
27
+ ```
28
+
29
+ Settings hashes must drop `constructor` keys, because the platform strips them.
30
+ 5. **Publish** with `suppa_publish_automation`. This copies the draft to the published side and runs pre-flight checks.
31
+ - The builder may keep showing «Unpublished changes» for a graph written through the API. It compares its own normalized copy, not the server state.
32
+ - Trust `hasUnpublishedChanges` and `nodes == activeNodes` instead.
33
+ - Never press «Publish changes» in the UI to clear the badge: it publishes the builder's version, with expression approvers wiped.
34
+ 6. **Test every flow live.**
35
+ - Submit the form, or move a test task to the stage.
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
+ - Also confirm that a move which should start nothing starts no run (`suppa_list_automation_runs`).
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.
41
+ 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).
@@ -0,0 +1,43 @@
1
+ # Tenant time in a `code` node
2
+
3
+ A datetime written without an offset is read as **UTC**, and Kyiv is +02:00 in winter and +03:00 in summer. The switch happens on the last Sunday of March and of October, at 01:00 UTC. So never append a fixed offset. Paste these helpers at the top of the `code` node that computes dates. They use `Intl` time zones when the sandbox has them and fall back to the EU rule Ukraine follows.
4
+
5
+ ```js
6
+ const kyivOffsetMin = (d) => {
7
+ try {
8
+ const name = new Intl.DateTimeFormat('en-US', { timeZone: 'Europe/Kyiv', timeZoneName: 'longOffset' }).formatToParts(d).find((p) => p.type === 'timeZoneName').value;
9
+ const m = /GMT([+-])(\d{2}):(\d{2})/.exec(name);
10
+ if (m) return (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3]));
11
+ } catch (e) { /* no Intl time zones in the sandbox */ }
12
+ const y = d.getUTCFullYear();
13
+ const lastSunday = (month) => { const t = new Date(Date.UTC(y, month + 1, 0, 1)); t.setUTCDate(t.getUTCDate() - t.getUTCDay()); return t; };
14
+ return d >= lastSunday(2) && d < lastSunday(9) ? 180 : 120;
15
+ };
16
+ const pad2 = (n) => String(n).padStart(2, '0');
17
+ // The calendar day an instant falls on in Kyiv, as a UTC-midnight Date.
18
+ const kyivDay = (d) => { const k = new Date(d.getTime() + kyivOffsetMin(d) * 60000); return new Date(Date.UTC(k.getUTCFullYear(), k.getUTCMonth(), k.getUTCDate())); };
19
+ // A form date: 'YYYY-MM-DD' is already the picked day; an ISO instant is the Kyiv day it falls on
20
+ // (a picker may send local midnight, which is the previous day in UTC).
21
+ const toKyivDay = (v) => {
22
+ if (v == null || v === '') return null;
23
+ const s = String(v);
24
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return new Date(s + 'T00:00:00Z');
25
+ const d = new Date(s);
26
+ return Number.isNaN(d.getTime()) ? null : kyivDay(d);
27
+ };
28
+ // ISO-8601 with the right offset for HH:MM Kyiv on that day.
29
+ const atKyiv = (day, hhmm) => {
30
+ const [h, m] = String(hhmm || '16:00').split(':').map(Number);
31
+ const off = kyivOffsetMin(new Date(Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), h, m) - 120 * 60000));
32
+ const a = Math.abs(off);
33
+ return `${day.toISOString().slice(0, 10)}T${pad2(h)}:${pad2(m)}:00${off < 0 ? '-' : '+'}${pad2(Math.floor(a / 60))}:${pad2(a % 60)}`;
34
+ };
35
+ // N working days after a Kyiv day; weekends and the days in `off` ('YYYY-MM-DD') are skipped.
36
+ const addBusinessDays = (day, n, off = new Set()) => { const d = new Date(day); while (n > 0) { d.setUTCDate(d.getUTCDate() + 1); if (d.getUTCDay() % 6 !== 0 && !off.has(d.toISOString().slice(0, 10))) n--; } return d; };
37
+ ```
38
+
39
+ Usage:
40
+ - «due at 16:00 on the picked day»: `atKyiv(toKyivDay(fd.desired_date), '16:00')`;
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
+
43
+ For a tenant in another zone, replace `'Europe/Kyiv'` and the fallback rule. The trigger payload's `options.timezone` names the tenant's zone.