suppa-mcp-2 1.39.0 → 1.40.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.
@@ -70,10 +70,20 @@ export const RELATION_LIKE_FIELD_TYPES = [
70
70
  "file",
71
71
  "multi-file",
72
72
  ];
73
- // Where `defaultValue` does NOT apply. builder.txt:43 — "defaultValue | string |
74
- // false | Default value. Not applicable to relations, enums, or unique fields."
75
- // So: every relation-like type above, plus ANY type when unique is set.
76
- export const NO_DEFAULT_VALUE_FIELD_TYPES = RELATION_LIKE_FIELD_TYPES;
73
+ // Types where `notNull` does NOT drag a `defaultValue` requirement with it. builder.txt:43
74
+ // reads "Not applicable to relations, enums, or unique fields", and that is true of the
75
+ // REQUIREMENT: measured, the builder answers 400 "`defaultValue` is required when creating a
76
+ // field with `notNull: true`" for the other types and accepts `notNull` alone for these.
77
+ //
78
+ // It is NOT true that these types cannot HOLD a default — we read that line too broadly and
79
+ // silently deleted a caller's default on update-field. Two live fields on the dev tenant say
80
+ // otherwise: `Tasks.priority` (enum) carries `defaultValue: 1557` (an Enums row id) and
81
+ // `Tasks.createdBy` (many-to-one) carries `"$current-user"`. The platform's Entity Builder doc
82
+ // gives the wire shape for the very endpoints these tools call: a REFERENCE — `{ id }`, or
83
+ // `[{ id }, …]` for a multi — "on add-fields, update-field and create-entity's columns".
84
+ export const NO_DEFAULT_REQUIRED_FIELD_TYPES = RELATION_LIKE_FIELD_TYPES;
85
+ /** @deprecated the old name, kept so nothing silently reads a list that changed meaning. */
86
+ export const NO_DEFAULT_VALUE_FIELD_TYPES = NO_DEFAULT_REQUIRED_FIELD_TYPES;
77
87
  // Where `notNull` does NOT apply — its own, narrower exclusion. builder.txt:41 —
78
88
  // "notNull | boolean | false | Field is required. Not applicable to many-to-many
79
89
  // / multi-enum." The comment above used to claim this exclusion was honoured
@@ -85,16 +95,28 @@ export function notNullApplies(fieldType) {
85
95
  return !NO_NOT_NULL_FIELD_TYPES.includes(fieldType);
86
96
  }
87
97
  /**
88
- * True when `defaultValue` is applicable to this field — and therefore when
89
- * `notNull` on it also demands one. Recorded evidence for that demand, on the
90
- * types where the default DOES apply: the builder answers HTTP 400
91
- * "`defaultValue` is required when creating a field with `notNull: true`" (an
92
- * empty string is rejected too). Where the default does not apply the builder
93
- * takes `notNull` alone, so no default is required — and none is sent.
98
+ * True when a `notNull` on this field also DEMANDS a `defaultValue`. Recorded evidence: the
99
+ * builder answers HTTP 400 "`defaultValue` is required when creating a field with `notNull: true`"
100
+ * (an empty string is rejected too). On a relation-like type it takes `notNull` alone.
101
+ *
102
+ * This is about the requirement, never about whether a default may be sent — see
103
+ * `defaultValueMayBeSent`.
94
104
  */
95
105
  export function defaultValueApplies(fieldType, unique = false) {
96
106
  return !unique && !RELATION_LIKE_FIELD_TYPES.includes(fieldType);
97
107
  }
108
+ /**
109
+ * True when a caller's `defaultValue` should be forwarded to the builder.
110
+ *
111
+ * Everything except a unique field, where the capture's exclusion is the only half still standing.
112
+ * A relation / enum / file default is a REFERENCE, not a literal: `{ id }` (or `[{ id }, …]` for a
113
+ * multi), never the option's value string or the enum name; a Users relation also takes the
114
+ * `$current-user` token. If the builder ever refuses one it answers 400 naming the field, which is
115
+ * a better outcome than this server deciding the request was inapplicable and dropping it.
116
+ */
117
+ export function defaultValueMayBeSent(unique = false) {
118
+ return !unique;
119
+ }
98
120
  // ---------------------------------------------------------------------------
99
121
  // Field options (the `options` object of a field body)
100
122
  // ---------------------------------------------------------------------------
@@ -1622,8 +1644,10 @@ export async function buildFieldDef(entityName, fieldName, fieldType, title, opt
1622
1644
  `field_type="${resolvedType}", required=true, default_value="now()") # SQL expression ` +
1623
1645
  "(quote text literals inside the string: \"'draft'\")",
1624
1646
  ],
1625
- no_default_needed_for: [...NO_DEFAULT_VALUE_FIELD_TYPES],
1647
+ no_default_needed_for: [...NO_DEFAULT_REQUIRED_FIELD_TYPES],
1626
1648
  no_default_needed_when: "unique=true (defaultValue does not apply to a unique field)",
1649
+ note_these_types_may_still_HOLD_a_default: "A relation / enum / file field does not REQUIRE a default, but it can carry one — as a " +
1650
+ "reference (`{ id }`, `[{ id }, …]`), or `$current-user` on a Users relation.",
1627
1651
  });
1628
1652
  }
1629
1653
  // Relation pre-flight: verify the target exists and the field is new, so we
@@ -1687,13 +1711,24 @@ export async function buildFieldDef(entityName, fieldName, fieldType, title, opt
1687
1711
  // sending it there is at best ignored, so it is never emitted. A default the
1688
1712
  // caller ASKED for and did not get is reported, like the other two — dropping
1689
1713
  // it silently was the same defect notNull and unique already had fixed.
1690
- if (defaultText.trim() !== "" && typeNeedsDefault) {
1691
- fieldDef.defaultValue = defaultText;
1714
+ if (defaultText.trim() !== "" && defaultValueMayBeSent(unique)) {
1715
+ // Objects and arrays go out AS THEY CAME: a reference default is `{ id }` / `[{ id }, …]`,
1716
+ // and `String()` would ship the literal text "[object Object]".
1717
+ fieldDef.defaultValue = typeof defaultValue === "object" && defaultValue !== null
1718
+ ? defaultValue
1719
+ : defaultText;
1720
+ if (RELATION_LIKE_FIELD_TYPES.includes(resolvedType) &&
1721
+ typeof defaultValue === "string" &&
1722
+ defaultValue !== "$current-user") {
1723
+ notApplicable.push(`defaultValue went out as the plain string ${JSON.stringify(defaultValue)} on a ` +
1724
+ `'${resolvedType}' field — a default on a relation/enum/file field is a REFERENCE: ` +
1725
+ "`{ id }`, or `[{ id }, …]` for a multi (a Users relation also takes `$current-user`). " +
1726
+ "Read the field back to check what was stored.");
1727
+ }
1692
1728
  }
1693
1729
  else if (defaultText.trim() !== "") {
1694
- notApplicable.push(`defaultValue was NOT set: builder.txt:43 — "Not applicable to relations, enums, or unique ` +
1695
- `fields" (this field is '${resolvedType}'${unique ? " and unique" : ""}). The field was ` +
1696
- "created WITHOUT a default.");
1730
+ notApplicable.push(`defaultValue was NOT set: it does not apply to a unique field. The field was created ` +
1731
+ "WITHOUT a default.");
1697
1732
  }
1698
1733
  // Sent exactly as validated: subTypeProblem() judged the TRIMMED value, and
1699
1734
  // ' date ' used to pass that check and then go out with the spaces.
@@ -1975,7 +2010,10 @@ export async function updateField(entityName, fieldName, opts = {}) {
1975
2010
  '"now()"), or omit default_value to leave the current default as it is.',
1976
2011
  });
1977
2012
  }
1978
- body.defaultValue = String(opts.defaultValue); // builder.txt:358
2013
+ // Same rule as the add path: a reference default is an object and must survive verbatim.
2014
+ body.defaultValue = typeof opts.defaultValue === "object" && opts.defaultValue !== null
2015
+ ? opts.defaultValue
2016
+ : String(opts.defaultValue); // builder.txt:358
1979
2017
  }
1980
2018
  if (opts.relationEntity !== undefined && opts.relationEntity !== null && String(opts.relationEntity).trim() !== "") {
1981
2019
  body.relationTarget = String(opts.relationEntity).trim(); // builder.txt:359
@@ -2081,12 +2119,24 @@ export async function updateField(entityName, fieldName, opts = {}) {
2081
2119
  // the live metadata. The check used to read body.unique only, so a default
2082
2120
  // went out on a field that was already unique on the tenant.
2083
2121
  const willBeUnique = "unique" in body ? body.unique === true : meta?.unique === true;
2084
- if ("defaultValue" in body && !defaultValueApplies(liveType, willBeUnique)) {
2122
+ if ("defaultValue" in body && !defaultValueMayBeSent(willBeUnique)) {
2085
2123
  delete body.defaultValue;
2086
- notApplicable.push(`defaultValue was NOT sent: builder.txt:43 — "Not applicable to relations, enums, or ` +
2087
- `unique fields" ('${fieldName}' is '${liveType}'${willBeUnique ? " and unique" : ""}). ` +
2124
+ notApplicable.push(`defaultValue was NOT sent: it does not apply to a unique field ('${fieldName}'). ` +
2088
2125
  "The default is unchanged.");
2089
2126
  }
2127
+ else if ("defaultValue" in body &&
2128
+ RELATION_LIKE_FIELD_TYPES.includes(liveType) &&
2129
+ typeof body.defaultValue === "string" &&
2130
+ body.defaultValue !== "$current-user") {
2131
+ // Forwarded, not dropped — but a bare string on a reference field is almost always the
2132
+ // option's value or the target's name, which the builder stores as nothing recognisable.
2133
+ notApplicable.push(`defaultValue was sent as the plain string ${JSON.stringify(body.defaultValue)} on ` +
2134
+ `'${fieldName}', which is a '${liveType}' — a default on a relation/enum/file field is a ` +
2135
+ "REFERENCE: `{ id }`, or `[{ id }, …]` for a multi (a Users relation also takes the " +
2136
+ "`$current-user` token). Live examples on a tenant: `Tasks.priority` (enum) holds the " +
2137
+ "Enums row id, `Tasks.createdBy` (many-to-one) holds `$current-user`. Read the field " +
2138
+ "back to check what was stored.");
2139
+ }
2090
2140
  }
2091
2141
  if (Object.keys(body).length === 0) {
2092
2142
  return jsonResponse({
@@ -336,6 +336,7 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
336
336
  // costs no network call and cannot fail for a reason the user did not ask about.
337
337
  if (!confirm) {
338
338
  let preview = "the draft is gated on the confirmed call";
339
+ let draftSettings = {};
339
340
  try {
340
341
  const peek = readJson(target);
341
342
  if (peek.error)
@@ -345,6 +346,7 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
345
346
  if (s) {
346
347
  const mod = await import(pathToFileURL(s).href);
347
348
  const g = await mod.validateForm(peek.value, { normalize });
349
+ draftSettings = (g.draft && typeof g.draft.settings === "object" && g.draft.settings) || {};
348
350
  preview = {
349
351
  gate: g.refused ? "REFUSED" : g.ok ? "passes" : "has errors",
350
352
  elements: g.elements ?? 0,
@@ -357,11 +359,45 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
357
359
  catch (e) {
358
360
  preview = `the draft could not be checked yet: ${e instanceof Error ? e.message : String(e)}`;
359
361
  }
362
+ // WHAT IT WOULD REPLACE. A `/select` is a read, and the confirm-gate contract permits one here
363
+ // — a preview that describes only the draft is the half that does not matter for a call whose
364
+ // job is to overwrite two columns. A tenant that cannot be reached must still leave this as
365
+ // confirmation_required, so every failure degrades to a sentence.
366
+ let replaces = "the form could not be read from here; the confirmed call reads it again and aborts if that fails";
367
+ try {
368
+ const row = await selectEntity("Forms", [{ field: "id", comparator: "=", value: id }], { id: true, name: true, type: true, status: true, schema: true, settings: true, lockedBy: { id: true, fullName: true } });
369
+ if (!row)
370
+ replaces = `no form with id ${id} on this tenant`;
371
+ else {
372
+ const col = (row.schema && typeof row.schema === "object" && !Array.isArray(row.schema) ? row.schema : {});
373
+ const rowSettings = (row.settings && typeof row.settings === "object" ? row.settings : {});
374
+ // The merge keeps a row key the draft does not mention. That is deliberate — dropping keys
375
+ // this tool does not understand would be worse — but it is invisible, and invisible is how
376
+ // a setting an author thought they had removed stays switched on.
377
+ const kept = Object.keys(rowSettings).filter((k) => !(k in draftSettings));
378
+ replaces = {
379
+ form: { id: row.id, name: row.name, type: row.type, status: row.status },
380
+ elements_now: Array.isArray(col.components) ? col.components.length : 0,
381
+ connections_now: Array.isArray(col.connections) ? col.connections.length : 0,
382
+ overrides_now: Array.isArray(col.overrides) ? col.overrides.length : 0,
383
+ settings_overwritten: Object.keys(draftSettings),
384
+ settings_kept_because_the_draft_is_silent_about_them: kept,
385
+ ...(kept.length
386
+ ? { warning: "a settings key the draft does not mention is KEPT, not removed — say it explicitly (e.g. showSubmitButton: false) if you meant to turn it off" }
387
+ : {}),
388
+ ...(row.lockedBy ? { locked_by: row.lockedBy } : {}),
389
+ };
390
+ }
391
+ }
392
+ catch (e) {
393
+ replaces = `the form could not be read from here (${e instanceof Error ? e.message : String(e)}); the confirmed call reads it again and aborts if that fails`;
394
+ }
360
395
  return confirmRequired("save a form DRAFT (it never publishes)", { form_id: id, path: target }, {
361
396
  writes: ["schema", "settings"],
362
397
  never_written: ["status", "mobileSchema", "code", "variables", "localizations", "entity", "alias", "parent", "parentVersion"],
363
398
  publishes: false,
364
399
  draft: preview,
400
+ replaces,
365
401
  });
366
402
  }
367
403
  if (!Number.isInteger(id) || id <= 0) {
@@ -404,7 +440,7 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
404
440
  row = await selectEntity("Forms", [{ field: "id", comparator: "=", value: id }], {
405
441
  id: true, name: true, type: true, status: true, alias: true,
406
442
  schema: true, settings: true, data: true,
407
- lockedBy: { id: true, fullName: true },
443
+ lockedBy: { id: true, fullName: true }, lockedAt: true,
408
444
  entity: { id: true, name: true },
409
445
  parent: { id: true }, parentVersion: { id: true, versionNumber: true },
410
446
  });
@@ -433,10 +469,23 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
433
469
  mine = null;
434
470
  }
435
471
  if (mine === null || lockedBy.id !== mine) {
472
+ // The lock is sticky BY DESIGN: there is no heartbeat, so a killed tab leaves it held
473
+ // forever and there is nobody to ask. The platform's own takeover modal answers this by
474
+ // stating the lock's age; so does this refusal, for the same reason.
475
+ const heldSince = typeof row.lockedAt === "string" ? row.lockedAt : null;
476
+ const ageMs = heldSince ? Date.now() - Date.parse(heldSince) : NaN;
477
+ const age = Number.isFinite(ageMs)
478
+ ? (ageMs > 36e5 ? `${Math.round(ageMs / 36e5)}h` : `${Math.max(1, Math.round(ageMs / 6e4))}min`)
479
+ : null;
436
480
  return jsonResponse({
437
481
  written: false,
438
- error: `form ${id} is open in the builder by ${lockedBy.fullName ?? `user ${lockedBy.id}`}. ` +
439
- "Writing under them would silently lose one of the two edits — ask them to close it.",
482
+ locked_by: lockedBy,
483
+ locked_at: heldSince,
484
+ error: `form ${id} is open in the builder by ${lockedBy.fullName ?? `user ${lockedBy.id}`}` +
485
+ `${age ? `, held for ${age}` : ""}. Writing under them would silently lose one of the two ` +
486
+ "edits. A lock has no heartbeat, so a crashed tab holds one forever and there may be " +
487
+ "nobody to ask: if it looks dead, a human opens the form and presses Take over in the " +
488
+ "lock banner — always available, always asks, and it discards the holder's unsaved work.",
440
489
  });
441
490
  }
442
491
  }
@@ -468,6 +517,9 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
468
517
  elements: { before: Array.isArray(existingSchema.components) ? existingSchema.components.length : 0, after: schemaColumn.components ? schemaColumn.components.length : 0 },
469
518
  connections: Array.isArray(schemaColumn.connections) ? schemaColumn.connections.length : 0,
470
519
  overrides_preserved: Array.isArray(schemaColumn.overrides) ? schemaColumn.overrides.length : 0,
520
+ // Keys the row carries that the draft says nothing about survive the merge. Naming them is the
521
+ // difference between a setting you decided to keep and one you did not know was still there.
522
+ settings_kept_because_the_draft_is_silent_about_them: Object.keys(existingSettings).filter((k) => !(k in (draft.settings ?? {}))),
471
523
  warnings: gate.warnings,
472
524
  };
473
525
  let result;
@@ -502,7 +554,11 @@ export async function writeFormDraft(formId, path, confirm = false, normalize =
502
554
  : `READ-BACK MISMATCH: wrote ${plan.elements.after} elements, the row now holds ${savedCount ?? "unknown"} — check the form before trusting this`,
503
555
  note: "Saved as a DRAFT. No FormVersions row was created and `status` was not touched, so this is " +
504
556
  "not published: what other people see is still the last published version. Publishing is a " +
505
- "human action in the builder.",
557
+ "human action in the builder. This write goes through the generic data endpoint, not the " +
558
+ "builder's own `PUT /forms/:id/schema`, so it writes NO change-set: the edit will not appear " +
559
+ "in the History panel, and later change-set diffs are reconstructed from a log that does not " +
560
+ "contain it. Nothing is lost — but an edit somebody will need to read the history of belongs " +
561
+ "in the builder.",
506
562
  result,
507
563
  });
508
564
  }
@@ -1169,7 +1169,13 @@ async function _runWrite(action, fn) {
1169
1169
  // "Relation types" group, whose values live in a join/side table
1170
1170
  // (docs/superpowers/specs/captures/api-entity-builder-builder.txt:43 —
1171
1171
  // "defaultValue ... Not applicable to relations, enums, or unique fields";
1172
- // :63 lists the group). Mirrors NO_DEFAULT_VALUE_FIELD_TYPES in tools/entity.ts,
1172
+ // :63 lists the group). That line governs the REQUIREMENT only — these types can
1173
+ // still HOLD a default, as a reference (`{ id }` / `[{ id }, …]`, or
1174
+ // `$current-user` on a Users relation): measured on a live tenant, `Tasks.priority`
1175
+ // (enum) carries an Enums row id and `Tasks.createdBy` (many-to-one) carries the
1176
+ // token. This set is therefore "no default REQUIRED", not "no default allowed" —
1177
+ // the migrator writes none of its own either way.
1178
+ // Mirrors NO_DEFAULT_REQUIRED_FIELD_TYPES in tools/entity.ts,
1173
1179
  // kept local so the migrator decides before the write instead of learning from a
1174
1180
  // failed one — entity.js is module-mocked in the migrator's tests.
1175
1181
  const _NO_DEFAULT_VALUE_TYPES = new Set([
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.39.0",
3
+ "version": "1.40.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": {
@@ -52,15 +52,17 @@ rules — plus your own reading of the warnings — are what stands between that
52
52
  1. **Nesting is `layout[bp].parentId`**, set to the parent element's `id` (its uuid, never its
53
53
  `name`). The array is flat and its order is not structure. A child of a grid `container` writes
54
54
  `{x, y, width, height}` in **1-based cells**; a child of a `flexContainer` writes `{order}`.
55
- Give every element an `lg` entry — an undeclared breakpoint is dead schema at runtime.
55
+ **Every element needs an explicit `layout[bp]` for every key in `settings.breakpoints` — there
56
+ is no fallback**, and an element with no record for a declared breakpoint is invisible there.
56
57
  2. **`layout[bp].height` is a row span, and the only thing that makes an element taller.**
57
58
  `containerSettings.size.heightMode` (`auto` | `fixed` | `fill`) is scroll behaviour. `fill` on a
58
59
  table or a leaf field does not enlarge it; it makes it share leftover height with its siblings.
59
60
  Both keys are legal on the same element, so nothing can flag the mix-up.
60
61
  3. **A grid child spans its parent's columns, not the form's.** Inside a 12-column section, full
61
- width is `width: 12`; inside a 2-column container it is `width: 2`. A new form ships
62
- `settings.columnsNumber: 1` as an "unset" sentinel — treat the working grid as 12, and if you
63
- raise `columnsNumber`, re-span the elements already on the form in the same turn.
62
+ width is `width: 12`; inside a 2-column container it is `width: 2`. **Column count defaults to
63
+ 1, and 1 is a real count, not an "unset" flag** — the root grid reads `settings.columnsNumber`,
64
+ a grid container its own (1–12). Write the count you intend *before* you lay out spans; change
65
+ it and you re-span its children in the same turn.
64
66
  4. **There are 58 dedicated types.** Never assemble something out of `input` + `html` because no
65
67
  type came to mind. `html` is author-written static markup and is never a home for record data —
66
68
  bind an element instead. Six pairs where both choices validate are in
@@ -76,17 +78,21 @@ rules — plus your own reading of the warnings — are what stands between that
76
78
  with them and pushed to the platform **unexpanded** ships with no styling at all, and validates
77
79
  clean. Either gate it with `--normalize` and take the repaired draft, or write the real settings
78
80
  yourself.
79
- 7. **Style is one value across all breakpoints.** There is no per-breakpoint styling; only `layout`
80
- is per-breakpoint. A mobile presentation silently wears the desktop styling.
81
+ 7. **Style is one value across breakpoints — but not across presentations.** Only `layout` is
82
+ per-breakpoint. `mobileSchema` is an independent component set with its **own** component
83
+ config, so mobile styling is authored there; editing the desktop element changes nothing on the
84
+ phone. Its elements keep their `name` and take **fresh uuids** — ids must not overlap.
81
85
  8. **Schema writes come first, and they are not transactional.** When the form needs a field or an
82
86
  entity that does not exist: every `create-entity`, then every `add-field`, then `update-field`,
83
87
  then enum values last. A half-applied plan leaves real tables behind. Then write the form.
84
- 9. **A write replaces a whole column — and `FormVersions` is the undo.** Every publish snapshots
85
- the form, so a bad write on a versioned form is recoverable: restore the version. What history
86
- does not cover is a write that lands where nothing reads. Writing `data.formSchema` on a 2.1
87
- tenant returns 200, changes the row, and changes **nothing the builder renders**. Write `schema`;
88
- read the row first; and remember `variables` and `localizations` are separate rows, not part of
89
- the column.
88
+ 9. **A write replaces a whole column — and `FormVersions` is a PARTIAL undo.** A publish snapshots
89
+ `schema`, `mobileSchema`, `settings`, `variables`, `localizations`, `globalLocalizationKeys`,
90
+ `codeArtifact`, `sharedModuleRefs` — and nothing else. `type`, `isPublic`, `priority`,
91
+ `condition` and the access lists are unversioned *and* have no draft stage: written, they are
92
+ live for everyone at once, with no version to restore. Treat a metadata write as a production
93
+ change. History also cannot cover a write that lands where nothing reads: `data.formSchema` on
94
+ a 2.1 tenant returns 200 and changes **nothing the builder renders**. Write `schema`; read the
95
+ row first; `variables` and `localizations` are separate rows.
90
96
 
91
97
  ## Inherited forms
92
98
 
@@ -132,9 +138,10 @@ the key it read, and refuses the rest.
132
138
  `workspaceModule`. `custom` is the only kind allowed with no bound entity; `custom` and `workspace`
133
139
  are submitless. The v1 names (`elementForm`, `createForm`, `table`, …) still sit on old rows and are
134
140
  ignored by the 2.x builder. `formSettings.isFormBuilderV2: true` is the host's routing
135
- discriminator — a new form must carry it, and an edit must not drop it. `Forms.status`
136
- (`draft` | `editing` | `published`) is what the builder publishes through, and `lockedBy`/`lockedAt`
137
- mean someone has the form open.
141
+ discriminator — a new form must carry it, and an edit must not drop it. `lockedBy`/`lockedAt` mean
142
+ someone has the form open. `Forms.status` (`draft` | `editing` | `published`) is **not** the
143
+ publish switch — it is one more unversioned metadata column; publishing is a computed diff. See
144
+ `references/publishing.md`.
138
145
 
139
146
  The bound entity is set when the row is created and never changed. Its default variable's name **is
140
147
  the entity's system name verbatim**, and every `dataSource.fieldPath` is rooted at it:
@@ -0,0 +1,48 @@
1
+ # `embeddedForm` behaviour
2
+
3
+ *Open when a form is to render another form inside it — a record card with its own content form, a
4
+ side panel, a wizard step that reuses an existing form.*
5
+
6
+ `form` is `{ id, alias?, entity? }` — the whole reference the form picker emits, not a bare id. Two
7
+ modes: `source: 'record'` mounts a **full `FormHost`** for the active record (projection, hydration,
8
+ autosave, realtime, dirty guard — none of which the bare nested-runtime path has), and standalone
9
+ renders the form on its own. The builder always draws a dashed placeholder instead: there is no
10
+ design-time recursion.
11
+
12
+ ## The content form must be `update`, and non-transactional
13
+
14
+ **`type: 'update'` with `settings.isTransactionMode: false`.** `FormHost` arms autosave only for
15
+ `record && !submitless && !transaction`, and `custom` / `workspace` are submitless — so a `custom`
16
+ content form inside an embed **saves nothing**. Edits sit in the runtime and a record swap discards
17
+ them, with no error and no prompt. Measured by the platform on forms 219 and 218 of this dev
18
+ tenant. With `update` + non-transaction each field edit diff-PATCHes the active record.
19
+
20
+ Keep the content form `isPublic: false`. A second `update` form on the entity does not hijack the
21
+ card's own resolve (probed at priority 0, 1 and 100), but that is the tested configuration.
22
+
23
+ An edit that never left its input — typed, no blur, then a programmatic record swap — is still
24
+ dropped, exactly as in v1. A *committed* edit is safe: the host flushes a debounced autosave in
25
+ `onBeforeUnmount`, and the persist closure owns the old record id, so it can never land on the new
26
+ record.
27
+
28
+ ## Two traps for a form authored through the API instead of the builder
29
+
30
+ Both apply to this skill, because this skill writes rows rather than clicking the builder:
31
+
32
+ - **The default relation variable is not seeded for you.** `POST /core/forms/schema` creates the
33
+ form without it, and then every `{{Entity.*}}` path in the form dies silently. Write it in the
34
+ first update: `variables: [{ name: '<Entity>', type: 'relation', isDefault: true }]`.
35
+ - **`PUT /core/forms/:id/schema` must resend `code`** — omit it and the server **nulls
36
+ `codeArtifact`**. (This skill's `write_form_draft` avoids the hazard by using the generic data
37
+ endpoint and naming only `schema` and `settings`, so `code` and `codeArtifact` are untouched. The
38
+ trap is live the moment anything switches to the platform's own save-draft endpoint.)
39
+
40
+ ## Cross-form messaging
41
+
42
+ An embedded form talks to its host through the element's `formEvent`, scoped by **ownership**, not
43
+ by ids — two stacked cards on the same record stay independent. Never reach for `window` events:
44
+ they are global, they leak, and any form can spoof any other.
45
+
46
+ Failure states are explicit, never a blank: `embeddedFormRequired` (no form picked),
47
+ `embeddedFormEntityRequired` (record mode, no entity resolves), `embeddedFormRecordRequired`
48
+ (runtime only, no active record) and `formLoadFailed` (deleted, no access, or no published version).
@@ -2,7 +2,16 @@
2
2
 
3
3
  *Open when you are placing a record list / workspace over an entity, or a view tab on one is not showing what you configured.*
4
4
 
5
- One element draws the whole workspace: breadcrumb, toolbar (search, filters, Create), the view-tab strip, and the active data view over `dataSource.entity`'s records. Its children are toolbar slots the runtime injects, not layout you author; `slots` and `namedViews` are runtime-managed — never write them.
5
+ One element draws the whole workspace: breadcrumb, toolbar (search, filters, Create), the view-tab strip, and the active data view over `dataSource.entity`'s records. Its children are toolbar slots the runtime injects, not layout you author — `slots` is runtime-managed, never write it.
6
+
7
+ **`namedViews` is yours, though.** It is the tab strip's *builder-mode* source — an array of seeds on `EntityListElementSchema` that the builder mutates directly, with no backend call, and the form authoring guide lists it among `entityList`'s authorable props beside `views` / `defaultView` / `availableViewTypes`. A seed is `{ title, icon, type: 'system' }` plus its own filter; `title` is `LocalizedText` and `icon` takes the **IconValue object** (`{ name, color?, size?, bgColor?, … }`), never a bare glyph string. The platform's own defaults are *All* (no filter) and *Created by me* (`author.id = $currentUser.id`). At **runtime** the same strip is backed by per-user backend `Layout[]` records instead — those are the reader's and must not be authored, which is what makes the two halves easy to confuse.
8
+
9
+ **Its columns are not in the form.** `entityList` is the one element that refuses the builder's
10
+ column drill-in (`supportsColumnDrillIn()` is `true` on every other runtime): a list's visible
11
+ fields, widths, pinning, sort, grouping and filters live in an entity-scoped `Layout` record, saved
12
+ through *Save view*, and its per-column options are edited in **Entity Builder → Views → Table**.
13
+ Authoring `settings.columns` here configures nothing. (A standalone `table` element is the
14
+ opposite: it owns its columns in its own schema — see `references/tables.md`.)
6
15
 
7
16
  `availableViewTypes` is the only switch that makes a view type *reachable*. The runtime takes it when non-empty, else the enabled `views[]` presets' types, else `table` + `list`. A `cards` or `dashboard` block whose type is missing from it is dead config — authored, validated, never rendered.
8
17
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  *Open when a form has a sidebar navigation — a menuPanel, its items, or the pane it drives.*
4
4
 
5
- The panel's navigation **is** its `menuPanelItem` children, attached by `layout[bp].parentId`. Its value is the selected ITEM's `name`, not the entity. A `workspaceViewport` mirrors it by `menuComponent` (the menu's `name`) and opens that item's `entity` with that item's `filter`.
5
+ The panel's navigation **is** its `menuPanelItem` children, attached by `layout[bp].parentId`. **Its value is the selected item's `entity`** — an item is active when `owningPanel.value === entity`, and the URL sync is `?<urlParam>=<entity>`. A `workspaceViewport` mirrors it by `menuComponent` (the menu's `name`) and opens that entity with that item's `filter`.
6
6
 
7
7
  Nothing else consumes the selection. A panel no viewport names and no code-form reads is a list of rows that highlight and do nothing. Only a `menuComponent` naming the *wrong* element is caught here; an absent one is not.
8
8
 
@@ -10,4 +10,6 @@ Only items with `kind: 'entity'` **and** a non-empty `entity` are selectable. A
10
10
 
11
11
  Landing entry, in precedence order: the URL `?<urlParam>=` (a base prop; an empty string publishes nothing), then the user's remembered choice, then `defaultItem`. `rememberLastChoice` is true when absent, so `defaultItem` alone is a no-op for every returning user — to pin a landing row, set both.
12
12
 
13
+ **`defaultItem` takes either spelling.** `resolveMenuSelection` matches the item's own `name` first and falls back to an item's `entity` for back-compat; the platform's own module seeder writes the **entity** system name, which is the spelling its documentation describes. Either way it must land on a `kind: 'entity'` item with a non-empty `entity` — a `link` or `button` row can never be the landing entry, and a token matching nothing falls through to the first entity item with nothing reported. The gate catches both misses.
14
+
13
15
  `selectionScope` fuses several panels into one navigation: at most one highlighted row across all of them, one shared remembered choice, and only the first panel to mount seeds the default. The value is trimmed, so whitespace equals absent — and two menus that must stay independent must not share a tag.
@@ -10,9 +10,19 @@
10
10
 
11
11
  Segment 1 is a **variable name**. On an entity-bound form the auto-created default variable's name **is the entity's system name verbatim** — so `Users.email`, never `email`, never `record.email`. Every further segment is a field on the current entity.
12
12
 
13
- A form with no bound entity (always kind `custom`, not `workspace`) still has a default variable: a JSON container, conventionally `submitData`, whose **keys are the submit payload** — bind `submitData.email`, one identifier-only key per element. The platform auto-mints `<jsonRoot>.<elementName>` for the 14 input types, so write the path yourself only to choose a different key. When the form's variables are in hand, use the `isDefault` variable's exact name.
13
+ A form with no bound entity (always kind `custom`, not `workspace`) still has a default variable: a JSON container, conventionally `submitData`, whose **keys are the submit payload** — bind `submitData.email`, one identifier-only key per element. **Always write `dataSource.fieldPath` yourself.** The "key = element name" rule is a builder *interaction* — it fires when a human drops an element on the canvas, and never on a JSON write: *"Ключі завжди явні в схемі… контрактом є саме `fieldPath`"* ([datasource reference](https://docs.modern-expo.com/frontend-fb2/formBuilder/features/datasource-backend-reference.html)). A hand-authored element with no `fieldPath` carries no submit key at all, and the backend's own contract extraction (`components[].dataSource.fieldPath` with this root, where `isSubmitData !== false`) reads nothing for it. Keys are flat identifiers — `^[A-Za-z_][A-Za-z0-9_]*$`, no dots; nesting is not used. `isSubmitData: false` is the deliberate opt-out: the field stays on the form and its value is not sent. When the form's variables are in hand, use the `isDefault` variable's exact name.
14
14
 
15
- Variables live in the draft's `variables` array; the keys are closed — `{ id, name, type, multiple, isDefault, entity?, select?, hydrate?, enumValues?, defaultValue? }`. A relation variable's target is `entity: "Candidates"`, the system name as a plain string; `relationEntity` / `relationTarget` / `entityName` are entity-**field** metadata and inert here.
15
+ Variables live in the draft's `variables` array; the keys are closed — `{ id, name, type, multiple, isDefault, entity?, select?, hydrate?, enumValues?, defaultValue? }`. A relation variable's target is `entity: "Candidates"`, the system name as a plain string; `relationEntity` / `relationTarget` / `entityName` are entity-**field** metadata and inert here. A variable's identity is its `name` (the root of every `fieldPath`, and the merge key when a child form inherits); `id` is a client-minted uuid that nothing resolves.
16
+
17
+ **`entity` does not survive a save on a non-default variable.** The `FormVariables` table has no
18
+ such column — ask the platform for it and it answers `Field "entity" not found in entity
19
+ "FormVariables"` — and the rows cross the wire through a blind cast, so the key is simply dropped.
20
+ Only the **default** variable keeps its target, because `DefaultVariableFactory.ensure()` re-derives
21
+ it from the form's own `draft.entity` on every rebuild; for any other relation variable the target
22
+ is gone on the next load and the field palette falls back to *"Bind an entity to use its fields"*.
23
+ Until the backend column exists, a design that needs a second entity should reach for a second
24
+ **bound element** (a `table` / `entityList` with its own `dataSource.entity`) rather than a second
25
+ relation variable.
16
26
 
17
27
  ## The relation hop: loads, accepts the edit, saves nothing
18
28
 
@@ -20,7 +30,9 @@ A relation segment hops to its target entity, so `Tasks.customer.name` resolves
20
30
 
21
31
  ## What nothing checks
22
32
 
23
- The offline gate has no entity metadata. It validates only the **root** segment against the declared variables (`unknown_binding`); a misspelled or label-cased leaf passes everything. At runtime the record's load projection is `{ id, updatedAt }` plus the bound fieldPaths, so an unresolvable path resolves to `undefined`: the control renders **empty on a form that otherwise loads fine**.
33
+ The offline gate has no entity metadata. It validates only the **root** segment against the declared variables (`unknown_binding`); a misspelled or label-cased leaf passes everything. At runtime the record's load projection is `{ id, updatedAt }` plus the fields the form actually needs, so an unresolvable path resolves to `undefined`: the control renders **empty on a form that otherwise loads fine**.
34
+
35
+ The projection is collected from **four author-controlled** sources, not just the bindings — which is also where the remedies are: `dataSource` bindings on components; every field a `visible`/`readonly`/`required`/`disabled` condition references (so a field a *condition* needs is fetched automatically — never add a hidden element for it); every `{{path}}` interpolation inside a localized text, including the form title's; and the explicit `variable.select` array. On top of those, each element type declares its own decorative paths (a select's `labelField`/`colorField`, an avatar's initials fields, …) — automatic, nothing to author. If **nothing** contributes beyond the `{ id, updatedAt }` floor, the record is not fetched at all. **`select` is how you fetch a field nothing on the canvas shows** — the form-level counterpart of a table's `settings.requestFields` — e.g. `select: ['assignee.email']` on the `task` variable so form code can read it.
24
36
 
25
37
  ## Grounding: `suppa describe-entity --entity-name <E>`
26
38
 
@@ -38,6 +50,39 @@ It returns the raw platform shape. Translate it:
38
50
 
39
51
  Users name fields by label: match their wording against **both** `name` and every `title.<locale>`, then bind the matched `name` — a screenshot's "Followers" is the field `watchers`.
40
52
 
53
+ ## Do not retype a bound field's label
54
+
55
+ On an element bound to an entity field the label defaults to **linked**: `_labelLinked: true` (or
56
+ absent) plus `_labelGlobalKey` = the field's own key (`entity.<Entity>.field.<field>`). The text is
57
+ baked into `schema.label` from the field's title in every tenant locale so it renders at once, it
58
+ is read-only in the builder, and it **auto-follows** the field's translation — change the entity
59
+ field's title and every linked label moves with it. On save it stores as a bare reference,
60
+ `{ "key": _labelGlobalKey }`, with no duplicated strings.
61
+
62
+ Write a literal `{ en, uk }` label only when you mean a **custom** one — the author's own wording,
63
+ decoupled from the field (`_labelLinked: false`, `_labelGlobalKey` cleared, strings under
64
+ `<componentId>.label`) — or where the field has no key to link to. Retyping a field's own title as
65
+ a literal is the anti-pattern the form guide names: *"Duplicating a linked label's strings"*. And
66
+ the general rule behind it: **underscore-prefixed keys are UI meta** (`_labelLinked`,
67
+ `_labelGlobalKey`, …) — preserve them when you edit an element, and never invent new ones.
68
+
69
+ ## A localized field is a flat map, until it is a list
70
+
71
+ `LocalizedField = LocalizedText | LocalizationVariant[]`. The flat `{ "en": …, "uk": … }` map is
72
+ the shape to write and the shape the builder collapses back to on save. The array form exists for
73
+ **conditional text** — each entry is `{ localization, conditions, globalKey? }`, where `conditions`
74
+ is an ordinary `ConditionGroup` evaluated by the same engine as `visible`/`required`, and a variant
75
+ with `conditions: null` is the unconditional fallback. It is stored only when there are several
76
+ variants or a condition, **or** when the text is bound to a global translation: a global binding is
77
+ one unconditional variant carrying `globalKey`, and it is deliberately not collapsed, because
78
+ collapsing would lose the key. So when you edit an element whose `label` is already an array,
79
+ **echo the array** — flattening it silently drops a condition or a global binding.
80
+
81
+ Two reserved things: `key` is **not a locale** — it is the localization-registry reference, and an
82
+ unresolved `{ key }` renders as an empty string rather than showing the raw key (which is why a
83
+ missing registry looks like a blank label, not a broken one). And `globalTranslationId` and an
84
+ inline `localization` are mutually exclusive: where the first is set, the second is ignored.
85
+
41
86
  ## Enum options: the stored value, not the title
42
87
 
43
88
  ```json
@@ -45,7 +90,19 @@ Users name fields by label: match their wording against **both** `name` and ever
45
90
  "dataSource": { "kind": "enum", "enum": "Users.gender", "fieldPath": "Users.gender" } }
46
91
  ```
47
92
 
48
- `dataSource.enum` is the qualified name as a string and the stored value is the enum **value**; the title is display only, and conditions and filters compare the value. An enum column read back arrives as `{ value, title, id }`.
93
+ `dataSource.enum` is the qualified name as a string and the **field's** stored value is the enum
94
+ value; the title is display only. An enum column read back arrives as `{ value, title, id }`.
95
+
96
+ **In a CONDITION the shape is different, and getting it wrong is silent.** A backend enum — a
97
+ `custom_enum` entity field, or any element whose `dataSource.kind` is `'enum'` with a qualified
98
+ name — stores the whole option object in the condition's `value`: `{ id, value, title }` (an array
99
+ of them for `in` / `not in`). *"Бекенд матчить кастомні енумки по `id`… а строковий нейм не
100
+ матчиться ніколи — саме так фільтри графіків генерували робочу на вигляд, але порожню умову."* A
101
+ condition written with the bare code reads correctly in the editor, runs without error, and matches
102
+ nothing. Scalars are right in exactly two places: an element's **own static options** and an **enum
103
+ variable** — there the string *is* the stored value. Client-side (display) conditions compare the
104
+ intersection of every comparable scalar, so they tolerate both shapes; the backend does not. When
105
+ you have the option object, write the object.
49
106
 
50
107
  ## Narrowing an entity dropdown
51
108
 
@@ -15,11 +15,36 @@
15
15
  }
16
16
  ```
17
17
 
18
- Comparators are per field type: boolean `=` `!=`; string adds `like` `not like` `in` `not in` `empty` `not empty`; number adds `>` `>=` `<` `<=`; date is `=` `!=` `>` `<` `between` `not between` `empty` `not empty` (no `>=`/`<=`); enum and relation take `=` `!=` `in` `not in` `empty` `not empty`. `empty`/`not empty` take no `value`; `in` takes an array — "status is one of three" is one `in` leaf, not three `=` under an `or`. A leaf may carry `"disabled": true`; preserve it when editing.
19
-
20
- `field` prefixes: `$currentUser` (`.role`, …); `$components.<name>.<value|isVisible|isHidden|isReadonly|isRequired|isDisabled>`; anything else is a form variable dot-path. There is no `$components.<name>.isReadMode` — read mode is settable, never readable. The prefix is matched with its dot, so a bare `$form` is read as an ordinary variable name.
21
-
22
- `$form.<leaf>` reads the form's own state, five members: `type` = `create` | `update` | `custom` | `workspace`; `layout` = active breakpoint `sm` | `md` | `lg` (`$layout` alone is legacy — still evaluated, never authored); `isLoaded`, `isDirty`, `isValid` = booleans. "Disabled until the user changes something" is one `$form.isDirty = false` leaf, no code form.
18
+ **There is no `is null` / `is not null`** — emptiness is `empty` / `not empty`, and the platform's
19
+ own checklist says so outright (*"empty/not empty — never is null"*). This is the single most
20
+ common way a hand-written condition silently matches nothing.
21
+
22
+ Comparators per field type, as the [form authoring
23
+ guide](https://docs.modern-expo.com/frontend-fb2/formBuilder/ai-agents/form-authoring-guide.html)
24
+ documents them: boolean `=` `!=`; string `=` `!=` `like` `not like` `empty` `not empty`; number
25
+ adds `>` `>=` `<` `<=`; relation `=` `!=` `in` `not in` `empty` `not empty`; enum `=` `!=` `in`
26
+ `not in`; date `=` `!=` `>` `<` `between` `period` `empty` `not empty` — **no `>=`/`<=` on a
27
+ date**. `period` is a real comparator and easy to miss. Beyond that set we have observed `in` /
28
+ `not in` on strings and `empty` / `not empty` on enums working on the tenant; they are not in the
29
+ guide's per-type table, so prefer the documented comparator where one fits. `empty`/`not empty`
30
+ take no `value`; `in` takes an array — "status is one of three" is one `in` leaf, not three `=`
31
+ under an `or`. A leaf may carry `"disabled": true`; preserve it when editing.
32
+
33
+ `field` prefixes — the four the guide documents: `$currentUser` (drills relations: `.role`, …);
34
+ `$layout` (the active breakpoint key, used bare); `$components.<name>.<value|isVisible|isHidden|isReadonly|isRequired|isDisabled>`;
35
+ **anything else is a form variable dot-path**. There is no `$components.<name>.isReadMode` — read
36
+ mode is settable, never readable. The prefix is matched with its dot, so a bare `$form` is read as
37
+ an ordinary variable name.
38
+
39
+ `$form.<leaf>` is a **fifth prefix the official guide does not list**, and we have not found it in
40
+ any vendored dump — but the tenant uses it: on the 217 dev forms, `$form.isLoaded` (2),
41
+ `$form.layout` (2) and `$form.isDirty` (1) appear in live conditions, while bare `$layout` appears
42
+ **zero** times. Its members are `type` = `create` | `update` | `custom` | `workspace`; `layout` =
43
+ the active breakpoint `sm` | `md` | `lg`; `isLoaded`, `isDirty`, `isValid` = booleans. Treat it as
44
+ observed-and-working rather than contract: for the breakpoint, `$layout` is the documented spelling
45
+ and `$form.layout` the one in use; for `isDirty` / `isLoaded` / `type` there is no documented
46
+ alternative. "Disabled until the user changes something" is one `$form.isDirty = false` leaf, no
47
+ code form.
23
48
 
24
49
  While a record loads, a `visible` rule reading `$components` or a record variable is withheld and its element stays hidden; naming `$form.isLoaded` anywhere in the rule exempts the whole rule. The freeze is visibility-only.
25
50
 
@@ -40,7 +40,9 @@ Presets: `lg` 1024/1024 (`removable: false`), `md` 640/768, `sm` 0/480. Mobile l
40
40
 
41
41
  A bare string array (`['lg','md']`) is not a breakpoint list: `minWidth` is `undefined`, `BreakpointUtils.ordered()` sorts on NaN, and the form resolves to a breakpoint no element has an entry for — a blank form. The gate makes this an ERROR only when a settings baseline is given; from scratch it is a warning beside `ok: true`. Normalization does not repair it either: a string entry counts as "declared".
42
42
 
43
- There is no fallback between breakpoints. An element with an `lg` entry and no `md` entry is unplaced — invisible — at `md`. Repair only happens if you run the gate with `--normalize`, which copies each missing entry from the nearest wider one; that makes `md` a clone of the desktop layout, so a form that "declares md" is not a form that stacks on tablet until you author the `md` coordinates yourself.
43
+ There is no fallback between breakpoints — *"кожен елемент завжди має повний `layout[bp]` запис для кожного активного breakpoint форми; fallback chain не використовується"*. An element with an `lg` entry and no `md` entry is unplaced — invisible — at `md`. Repair only happens if you run the gate with `--normalize`, which copies each missing entry from the nearest wider one; that makes `md` a clone of the desktop layout, so a form that "declares md" is not a form that stacks on tablet until you author the `md` coordinates yourself.
44
+
45
+ **Where the narrow breakpoints actually apply, today.** The builder canvas and the Viewer preview resolve the active breakpoint from the container's width. The production runtime does **not** yet: *"Продакшн-рантайм (FormHost/FormCanvas) поки НЕ авто-резолвить breakpoint за реальною шириною контейнера — `currentLayout` там лишається на seed-значенні (найширший ключ)"* ([responsive layouts](https://docs.modern-expo.com/frontend-fb2/formBuilder/features/responsive-layouts.html)). So `md`/`sm` coordinates are real work with a real effect in the builder, and `lg` is the one that ships. Author the narrow entries when the form is meant to be edited responsively; do not promise a user that production stacks on a phone. (The phone story is `mobileSchema`, a separate presentation — see SKILL rule 7.)
44
46
 
45
47
  ## Array order is not structure
46
48