suppa-mcp-2 1.43.4 → 1.44.0

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}]}}.'),
@@ -2713,9 +2713,9 @@ export function buildToolTable() {
2713
2713
  " FULL state (an omitted variable is deleted), so an empty one is never sent and one that\n" +
2714
2714
  " drops the form's default variable is refused. mobileSchema, code, localizations, entity,\n" +
2715
2715
  " alias and parent are never sent; a child form's `schema.overrides` is preserved.\n\n" +
2716
- " Refuses while someone else has the form open in the builder (lockedBy). Without\n" +
2717
- " confirm=true it returns the plan and a `revision`; pass it back as expected_revision and\n" +
2718
- " a form that moved since the preview is refused, not overwritten.",
2716
+ " Refuses: someone else's lock (lockedBy), another form's file, a child's layer over a root,\n" +
2717
+ " a merged tree over a child, an emptied form, a published read. The file's `revision` (or\n" +
2718
+ " expected_revision) guards it: a form that moved is refused, not overwritten.",
2719
2719
  inputSchema: {
2720
2720
  form_id: z.number().describe("The Forms row id — the `form=` in the builder URL."),
2721
2721
  path: z
@@ -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}]. */
@@ -885,13 +885,81 @@ function staleAnswer(message, id) {
885
885
  current_revision: current,
886
886
  };
887
887
  }
888
+ const isFileObj = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
889
+ /** The one record of a `records` answer (suppa_search_records), else the file itself. */
890
+ const fileBody = (v) => {
891
+ if (!isFileObj(v))
892
+ return null;
893
+ const recs = v.records;
894
+ return Array.isArray(recs) && recs.length === 1 && isFileObj(recs[0]) ? recs[0] : v;
895
+ };
896
+ // The marker alone, wherever the read sits: an agent that copied the answer without `generation`, or kept it inside
897
+ // `records`, still holds a published read (review of 1.43.4).
898
+ const isPublishedRead = (v) => fileBody(v)?.read === "published";
899
+ const isRefId = (v) => Number.isInteger(v) && v > 0 ? v : isFileObj(v) && Number.isInteger(v.id) && v.id > 0 ? v.id : null;
900
+ /** The form a file was read from, when it says: a suppa_get_form answer's `id`, a previous-draft file's `form_id`, a
901
+ * one-record Forms read's row id. A FormVersions row's `id` is a VERSION, so a snapshot says nothing here. */
902
+ function fileFormId(v) {
903
+ if (!isFileObj(v))
904
+ return null;
905
+ if (typeof v.generation === "string")
906
+ return isRefId(v.id);
907
+ if (Number.isInteger(v.form_id))
908
+ return v.form_id;
909
+ const body = fileBody(v);
910
+ return body && body !== v && !("snapshot" in body) ? isRefId(body.id) : null;
911
+ }
912
+ /** The parent a file declares — a real reference only (parent / parentForm / parentVersion). */
913
+ function fileParent(v) {
914
+ const body = fileBody(v);
915
+ return body ? isRefId(body.parentForm) ?? isRefId(body.parent) : null;
916
+ }
917
+ /** The revision a suppa_get_form answer was read at — the guard of the write it becomes. */
918
+ const fileRevision = (v) => (isFileObj(v) && typeof v.generation === "string" && typeof v.revision === "string" ? v.revision : null);
919
+ const elementIds = (list) => Array.isArray(list) ? list.map((e) => (isFileObj(e) && typeof e.id === "string" ? e.id : null)).filter((x) => Boolean(x)) : [];
888
920
  /**
889
- * A suppa_get_form version='published' answer is what this user sees, not the draft. For a child form it
890
- * is the MERGED tree with no `parent` (the published read carries none), so writing it as the draft would
891
- * turn the parent's elements and variables into the child's own layer; for any form it would revert the
892
- * draft's later edits. It is read-only — the published version comes back through rollback.
921
+ * What a draft must not do to the form it is written to, judged against the LIVE row — each a refusal:
922
+ * another form's file; a child's layer over a form that is no child; a child's draft that carries elements it
923
+ * INHERITS (a merged tree — the published read, a FormVersions snapshot, or one copied out of either: written as the
924
+ * child's own layer they detach those elements from the parent); every element of a populated form removed.
925
+ * The inherited ids are the parent's published elements; when that read fails the check is said to be skipped.
893
926
  */
894
- const isPublishedRead = (v) => Boolean(v && typeof v === "object" && !Array.isArray(v) && v.generation === "2.x" && v.read === "published");
927
+ async function writeRefusals(id, file, row, draftComponents) {
928
+ // (a published read is refused before this — in the preview even when the row cannot be read)
929
+ const refusals = [];
930
+ const notes = [];
931
+ const fromForm = fileFormId(file);
932
+ if (fromForm !== null && fromForm !== id) {
933
+ refusals.push(`this file was read from form ${fromForm}, not form ${id}: written here it would replace form ${id}'s draft with another form's. Read form ${id} (suppa_get_form) and edit that.`);
934
+ }
935
+ const rowParent = isRefId(row.parent);
936
+ const declared = fileParent(file);
937
+ if (declared !== null && rowParent === null) {
938
+ refusals.push(`this file is a child form's layer (its parent is form ${declared}), and form ${id} is not a child: a child's own layer over a root form would remove the elements it has.`);
939
+ }
940
+ const own = elementIds(isFileObj(row.schema) ? row.schema.components : null);
941
+ const draftIds = elementIds(draftComponents);
942
+ if (draftIds.length === 0 && own.length > 0) {
943
+ refusals.push(`the draft has no elements and form ${id} has ${own.length}: saving it would delete every one. Remove elements in the builder if that is really meant.`);
944
+ }
945
+ if (rowParent !== null && draftIds.length) {
946
+ try {
947
+ const parent = (await makeRequest("GET", `/api/core/forms/${rowParent}/schema`, null, { query: { mode: "published" } }));
948
+ const inherited = new Set(elementIds(isFileObj(parent?.schema) ? parent.schema.components : null));
949
+ const ownSet = new Set(own);
950
+ const carried = draftIds.filter((x) => inherited.has(x) && !ownSet.has(x));
951
+ if (carried.length) {
952
+ refusals.push(`the draft carries ${carried.length} element(s) form ${id} INHERITS from its parent, form ${rowParent} (${carried.slice(0, 5).join(", ")}${carried.length > 5 ? ", …" : ""}): ` +
953
+ "a merged tree — a published read, a FormVersions snapshot, or one copied out of either. A child's draft is its OWN layer: " +
954
+ "read it with suppa_get_form (the draft) and edit that.");
955
+ }
956
+ }
957
+ catch (e) {
958
+ notes.push(`the inherited-element check was skipped: form ${rowParent}'s published elements could not be read (${e instanceof Error ? e.message : String(e)}).`);
959
+ }
960
+ }
961
+ return { refusals, notes };
962
+ }
895
963
  const PUBLISHED_READ_REFUSAL = "this file is a suppa_get_form version='published' read — the version users see (a child form's MERGED tree, " +
896
964
  "without its own layer), not the draft. Saved as the draft it would revert the draft's later edits and turn a " +
897
965
  "child's inherited elements into its own. Read the draft (suppa_get_form without version) to edit it; to bring a " +
@@ -1040,11 +1108,30 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
1040
1108
  variables = `the form's variables could not be read (${e instanceof Error ? e.message : String(e)}); the confirmed call reads them again and refuses if that fails`;
1041
1109
  }
1042
1110
  }
1043
- if (revision) {
1111
+ // What the confirmed call will refuse outright, said now — the same guards, against the same row.
1112
+ const fileValue = peeked.error ? null : peeked.value;
1113
+ const published = isPublishedRead(fileValue);
1114
+ let refused = published;
1115
+ if (row && fileValue && !published) {
1116
+ const guards = await writeRefusals(id, fileValue, row, draftComponents);
1117
+ for (const r of guards.refusals)
1118
+ warnings.push(`the confirmed call will REFUSE this file: ${r}`);
1119
+ warnings.push(...guards.notes);
1120
+ refused = guards.refusals.length > 0;
1121
+ }
1122
+ const fromFile = fileRevision(fileValue);
1123
+ if (fromFile && revision && fromFile !== revision) {
1124
+ warnings.push(`the form changed since this file was read (read at ${fromFile}, now ${revision}): the confirmed call sends the file's revision and the ` +
1125
+ "platform refuses it, so the change made since is not overwritten — read the form again (suppa_get_form) and redo the edit on it.");
1126
+ }
1127
+ else if (fromFile) {
1128
+ warnings.push(`the confirmed call is guarded by the revision this file was read at (${fromFile}): it is refused, not written, if the form changed since.`);
1129
+ }
1130
+ else if (revision) {
1044
1131
  warnings.push(`pass expected_revision: "${revision}" on the confirmed call — it is then refused, not written, if the form changed since this preview.`);
1045
1132
  }
1046
1133
  return confirmRequired("save a form DRAFT (it never publishes)", { form_id: id, path: target }, {
1047
- writes: ["schema", "settings", ...(draftVars ? ["variables"] : [])],
1134
+ writes: refused ? [] : ["schema", "settings", ...(draftVars ? ["variables"] : [])],
1048
1135
  never_sent: NEVER_SENT,
1049
1136
  publishes: false,
1050
1137
  draft: preview,
@@ -1146,6 +1233,12 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
1146
1233
  }
1147
1234
  if (gate.refused || !gate.ok)
1148
1235
  return refusal(gate);
1236
+ // 3b. WHAT THE DRAFT MUST NOT DO TO THIS FORM — another form's file, a child's layer over a root form, a merged tree
1237
+ // over a child, every element removed. Judged against the live row, because the file can say anything.
1238
+ const guards = await writeRefusals(id, read.value, row, gate.draft?.schema);
1239
+ if (guards.refusals.length) {
1240
+ return jsonResponse({ written: false, error: guards.refusals.join(" "), refusals: guards.refusals, note: "Nothing was written." });
1241
+ }
1149
1242
  // 4. SOMEONE ELSE HAS IT OPEN. The builder holds `lockedBy` while a form is being edited; writing
1150
1243
  // under them means one of the two of you loses work without being told.
1151
1244
  const lockedBy = row.lockedBy;
@@ -1215,7 +1308,11 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
1215
1308
  if (existingSettings.isFormBuilderV2 === true && settings.isFormBuilderV2 !== true) {
1216
1309
  settings.isFormBuilderV2 = true; // the host's routing flag — an edit must not drop it
1217
1310
  }
1218
- const revision = expectedRevision || (typeof row.updatedAt === "string" ? row.updatedAt : null);
1311
+ // The guard is the revision the edit was BASED on: the caller's, else the one the file was read at (a suppa_get_form
1312
+ // answer carries it), and only else the row as read just now — which guards nothing about a save made in between.
1313
+ const fromFile = fileRevision(read.value);
1314
+ const revision = expectedRevision || fromFile || (typeof row.updatedAt === "string" ? row.updatedAt : null);
1315
+ const revisionFrom = expectedRevision ? "expected_revision" : fromFile ? "the file (the revision suppa_get_form read)" : "the row as read for this write";
1219
1316
  const body = { schema: schemaColumn, settings };
1220
1317
  if (draftVars)
1221
1318
  body.variables = draftVars;
@@ -1233,8 +1330,9 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
1233
1330
  // difference between a setting you decided to keep and one you did not know was still there.
1234
1331
  settings_kept_because_the_draft_is_silent_about_them: Object.keys(existingSettings).filter((k) => !(k in (draft.settings ?? {}))),
1235
1332
  guarded_by_revision: revision,
1333
+ revision_from: revisionFrom,
1236
1334
  warnings: gate.warnings,
1237
- notes: gate.notes,
1335
+ notes: [...(gate.notes ?? []), ...guards.notes],
1238
1336
  ...(gate.already_live.length ? { already_on_the_live_form: alreadyLive(gate.already_live) } : {}),
1239
1337
  ...(() => {
1240
1338
  if (row.parent?.id)
@@ -396,7 +396,7 @@ const nonEmpty = (v) => Array.isArray(v) && v.length > 0;
396
396
  /**
397
397
  * What only a 2.x form has: elements in the schema column, a Code Form or its build, a mobile layout, the
398
398
  * builder's flag, a parent (a child's own layer can be empty — its settings, elements and code inherited),
399
- * or overrides of a parent's elements, settings, connections or texts.
399
+ * overrides of a parent's elements, settings, connections or texts, or FormVariables rows.
400
400
  */
401
401
  function hasV2Evidence(a) {
402
402
  const schema = isObj(a.schema) ? a.schema : {};
@@ -409,7 +409,9 @@ function hasV2Evidence(a) {
409
409
  a.parentForm != null ||
410
410
  nonEmpty(a.settingsOverrides) ||
411
411
  nonEmpty(a.connectionOverrides) ||
412
- nonEmpty(a.localizationOverrides));
412
+ nonEmpty(a.localizationOverrides) ||
413
+ // FormVariables rows are 2.x only: measured on dev 2026-10-22, none of the 77 Suppa 1.0 forms has one
414
+ nonEmpty(a.variables));
413
415
  }
414
416
  /** An FB2 kind alone is weaker evidence: `Forms.type` is free text, and a 1.0 form can carry one. */
415
417
  const hasV2Kind = (a) => typeof a.type === "string" && V2_FORM_TYPES.has(a.type);
@@ -426,7 +428,8 @@ function artifactSummary(art) {
426
428
  * Empty lists and nulls are dropped; the compiled bundle is summarized unless asked for.
427
429
  */
428
430
  function v2FormAnswer(a, version, includeArtifact) {
429
- const { schema, mobileSchema, settings, variables, localizations, code, codeArtifact, codeArtifacts, dataSources, updatedAt, ...meta } = a;
431
+ // dataSources stays in `meta`: always [] today («Increment 2»), dropped as empty — but kept the day it is not.
432
+ const { schema, mobileSchema, settings, variables, localizations, code, codeArtifact, codeArtifacts, updatedAt, ...meta } = a;
430
433
  const notes = [];
431
434
  const parent = isObj(meta.parentForm) ? meta.parentForm : null;
432
435
  if (parent && version === "draft") {
@@ -475,14 +478,25 @@ function v2FormAnswer(a, version, includeArtifact) {
475
478
  * (formShema / formSettings / formModul).
476
479
  */
477
480
  export async function getForm(formId, version = "draft", includeArtifact = false) {
481
+ const where = `GET /core/forms/${formId}/schema${version === "published" ? "?mode=published" : ""}`;
478
482
  let assembled = null;
479
483
  try {
480
484
  const got = await makeRequest("GET", `/api/core/forms/${formId}/schema`, null, version === "published" ? { query: { mode: "published" } } : undefined);
481
- assembled = isObj(got) ? got : null;
485
+ // A 200 that is not a form is not «no builder read»: answering the row read instead would call a 2.x form 1.0.
486
+ if (!isObj(got))
487
+ throw new Error(`${where} answered 200 with ${got === null ? "null" : Array.isArray(got) ? "a list" : typeof got}, not a form`);
488
+ assembled = got;
482
489
  }
483
490
  catch (e) {
484
491
  if (e?.status !== 404)
485
492
  throw e;
493
+ // Only the platform's own «Form N not found» (data.not_found) means there is no such form for the builder; a
494
+ // 404 from anything else (a route this stand does not have, a proxy) is said, never read as «a 1.0 form».
495
+ const message = e instanceof Error ? e.message : String(e);
496
+ // (every 404's text starts «HTTP 404 Not Found» — it is the platform's body that says which one this is)
497
+ if (!/data\.not_found|Form \d+ not found/.test(message)) {
498
+ throw new Error(`${where} answered a 404 that is not the platform's «form not found»: ${message}`);
499
+ }
486
500
  if (version === "published") {
487
501
  return jsonResponse({
488
502
  error: `Form ${formId} has no published version this user sees (or does not exist). version='draft' reads the draft.`,
@@ -500,8 +514,18 @@ export async function getForm(formId, version = "draft", includeArtifact = false
500
514
  if (assembled && hasV2Kind(assembled) && !nonEmpty(formShema)) {
501
515
  return jsonResponse(v2FormAnswer(assembled, version, includeArtifact));
502
516
  }
503
- if (result === null)
517
+ if (result === null) {
518
+ // The builder read found the form, the row read did not: it is no deleted form — the row (a 1.0 form's layout)
519
+ // is what this user cannot read.
520
+ if (assembled) {
521
+ return jsonResponse({
522
+ error: `Form ${formId} exists (the builder read answered) but its Forms row could not be read — no access to the ` +
523
+ "row, most likely. The builder read holds no 2.x layout, so this is a Suppa 1.0 form whose `data` is in that row.",
524
+ type: assembled.type ?? null,
525
+ });
526
+ }
504
527
  return notFoundAnswer(ENTITY_FORMS, formId, "form");
528
+ }
505
529
  return jsonResponse({ generation: "1.0", ...result });
506
530
  }
507
531
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.43.4",
3
+ "version": "1.44.0",
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 |