suppa-mcp-2 1.34.0 → 1.35.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.
@@ -61,6 +61,25 @@ const ERROR_HINTS = [
61
61
  "reserved so the parked column can still be restored. Either bring the original back with " +
62
62
  "suppa_restore_custom_field (its values come with it), or choose a different name.",
63
63
  },
64
+ {
65
+ // Verified 2026-09-11 on modern-expo.dev.suppa.me, four shapes, all on the
66
+ // probe entity: a Localization object {en, uk} → 400 write.invalid_relation_value
67
+ // on path 'title'; {en} → 400 'Field "key" is required'; {key, en} → 400
68
+ // 'Field "category" is required' (the object is being written as a
69
+ // Localizations RECORD); a plain string → 201, echoed back, and stored as
70
+ // NULL; no title → 201. The last field whose title was stored dates from
71
+ // 2026-09-10 13:41. builder.txt:56 still says 'title | object | Localization
72
+ // object', so this is the platform, not the contract.
73
+ // The message arrives inside a stringified JSON body, so the quotes around
74
+ // the field name may carry a backslash: \"title\", \"key\".
75
+ match: /.?"title.?" must contain an integer id|invalid_relation_value[^]*"path":"title"|Field .?"(key|category).?" is required/i,
76
+ hint: "The builder is currently REJECTING field titles: the Localization object the doc prescribes " +
77
+ "(builder.txt:56) is being written as a Localizations record and fails, and a plain string is " +
78
+ "accepted but stored as null (verified on dev 2026-09-11; last title stored 2026-09-10 13:41). " +
79
+ "NOTHING was created. Re-send WITHOUT title — the field is created untitled and works; set the " +
80
+ "label in the UI or with suppa_update_field once the platform fix lands. This is a backend " +
81
+ "regression worth reporting with the traceId above.",
82
+ },
64
83
  {
65
84
  match: /HTTP 409|statusCode":409/,
66
85
  hint: "Concurrent write: two writers created the values row for the same record at once (the " +
package/dist/server.js CHANGED
@@ -1521,7 +1521,7 @@ export function buildServer() {
1521
1521
  })));
1522
1522
  reg("suppa_apply_custom_fields", {
1523
1523
  description: "Custom fields DECLARED IN A REPO FILE, applied to a tenant — the file is the source of truth.\n" +
1524
- " The SDK has no decorator for them, so they are the one part of a schema with no home in git.\n" +
1524
+ " On @suppa/sdk 1.38.0+ prefer @CustomFields in the entity class (SKILL.md rule 22).\n" +
1525
1525
  ' declaration: {"entity","context_field","fields":[{"name","type","title","contexts":["PL"]}]}.\n' +
1526
1526
  " Idempotent — a second run answers already_converged. Creates per context in ONE atomic\n" +
1527
1527
  " batch, then links existing fields into their other contexts.\n" +
@@ -29,7 +29,7 @@
29
29
  import { insertEntity, makeRequest, removeEntity, searchEntity, updateEntity, } from "../httpClient.js";
30
30
  import { confirmRequired, jsonResponse, parseJsonParam } from "../utils.js";
31
31
  import { buildFieldDef } from "./entity.js";
32
- import { customFieldsEntity, resolveBody } from "./customFields.js";
32
+ import { customFieldsEntity, customFieldsUsage, quotaNote, resolveBody, } from "./customFields.js";
33
33
  const SET_ENTITY = "CustomFieldSets";
34
34
  const LINK_ENTITY = "CustomFieldSetFields";
35
35
  const META_ENTITY = "FieldMetadata";
@@ -326,6 +326,14 @@ export async function addCustomFieldsBatch(entityName, fieldsJson, sel) {
326
326
  const envelope = { fields: defs };
327
327
  if (hasContext)
328
328
  envelope.context = { field: sel.contextField, value: sel.contextValue };
329
+ // Read before the write, so the number is what the batch adds TO.
330
+ let usage = null;
331
+ try {
332
+ usage = await customFieldsUsage(extension);
333
+ }
334
+ catch {
335
+ usage = null;
336
+ }
329
337
  let result;
330
338
  try {
331
339
  result = await makeRequest("POST", `/api/core/builder/${entityName}/add-fields`, {
@@ -341,6 +349,8 @@ export async function addCustomFieldsBatch(entityName, fieldsJson, sel) {
341
349
  });
342
350
  }
343
351
  const out = { created: defs.length, fields: defs.map((d) => d.name), result };
352
+ if (usage)
353
+ Object.assign(out, quotaNote(usage, defs.length));
344
354
  if (hasContext) {
345
355
  try {
346
356
  const { body } = resolveBody(null, sel.contextField ?? null, sel.contextValue ?? null);
@@ -42,7 +42,7 @@
42
42
  * field mandatory is `required` on the CustomFieldSetFields link row, which
43
43
  * the platform enforces when the values row is created.
44
44
  */
45
- import { makeRequest } from "../httpClient.js";
45
+ import { makeRequest, searchEntity } from "../httpClient.js";
46
46
  import { customFieldsHint } from "../customFieldHints.js";
47
47
  import { jsonResponse, confirmRequired } from "../utils.js";
48
48
  import { buildFieldDef, CUSTOM_FIELDS_EXTENSION_SUFFIX, CUSTOM_FIELDS_KEY, CUSTOM_FIELDS_OPTION, } from "./entity.js";
@@ -74,6 +74,58 @@ export function customFieldsEntity(ownerEntity) {
74
74
  : `${ownerEntity}${CUSTOM_FIELDS_EXTENSION_SUFFIX}`;
75
75
  }
76
76
  export { customFieldsHint };
77
+ // ---------------------------------------------------------------------------
78
+ // The per-table quota
79
+ // ---------------------------------------------------------------------------
80
+ /**
81
+ * api/entity-builder/custom-fields.html: "Active client fields per extension
82
+ * table capped at CUSTOM_FIELDS_LIMIT (default 200). Exceeding limit → 400 with
83
+ * usage numbers." And migrations.html: the cap "guards the API, not migrations"
84
+ * — a declaration can push a table past it, and the API then stops serving that
85
+ * table. The number is env-overridable and a product decision, so everything
86
+ * here REPORTS against the default and never refuses on it: the platform knows
87
+ * its own limit and says so in its 400.
88
+ */
89
+ export const CUSTOM_FIELDS_DEFAULT_LIMIT = 200;
90
+ /** How many active client fields the extension table already carries. */
91
+ export async function customFieldsUsage(extension) {
92
+ const rows = (await searchEntity("FieldMetadata", [{ field: "entity.name", value: extension, comparator: "=" }],
93
+ // Only CLIENT fields count: the platform's own service columns on the
94
+ // extension table (owner, id, createdAt…) are not custom fields.
95
+ { id: true, name: true, deletedAt: true, initiator: true }, 500));
96
+ let active = 0;
97
+ for (const r of Array.isArray(rows) ? rows : []) {
98
+ if (!r || r.deletedAt)
99
+ continue;
100
+ // A row that does not say who created it is counted: undercounting is the
101
+ // side that surprises.
102
+ if (r.initiator !== undefined && r.initiator !== null && r.initiator !== "client")
103
+ continue;
104
+ active++;
105
+ }
106
+ return { active_client_fields: active, default_limit: CUSTOM_FIELDS_DEFAULT_LIMIT };
107
+ }
108
+ /** The quota lines for a response that adds `adding` fields — a warning only when it earns one. */
109
+ export function quotaNote(usage, adding) {
110
+ const after = usage.active_client_fields + adding;
111
+ const out = {
112
+ custom_fields_on_table: after,
113
+ default_limit: usage.default_limit,
114
+ };
115
+ if (after > usage.default_limit) {
116
+ out.quota_warning =
117
+ `${after} active custom fields on this table is OVER the default CUSTOM_FIELDS_LIMIT of ` +
118
+ `${usage.default_limit}. The platform enforces its configured limit with a 400 carrying the usage ` +
119
+ "numbers; a tenant may run a higher one, so this is a flag, not a refusal. The cap guards the " +
120
+ "API, not migrations — a declaration can push a table past it and the API then stops serving it.";
121
+ }
122
+ else if (after >= Math.floor(usage.default_limit * 0.9)) {
123
+ out.quota_warning =
124
+ `${after} of the default CUSTOM_FIELDS_LIMIT (${usage.default_limit}) active custom fields on ` +
125
+ "this table — within 10% of the cap.";
126
+ }
127
+ return out;
128
+ }
77
129
  /** Turn a thrown transport error into the tool's JSON answer, with a hint when there is one. */
78
130
  function errorResponse(e, extra = {}) {
79
131
  const message = e instanceof Error ? e.message : String(e);
@@ -220,6 +272,14 @@ export async function addCustomField(entityName, fieldName, fieldType, title, op
220
272
  else {
221
273
  fieldDef.sets = ids;
222
274
  }
275
+ // Read BEFORE the write, so the number is what this field is added to.
276
+ let usage = null;
277
+ try {
278
+ usage = await customFieldsUsage(extension);
279
+ }
280
+ catch {
281
+ usage = null; // the quota line is a courtesy; a failed read is not a failed add
282
+ }
223
283
  let result;
224
284
  try {
225
285
  result = await makeRequest("POST", `/api/core/builder/${entityName}/add-fields`, {
@@ -230,6 +290,8 @@ export async function addCustomField(entityName, fieldName, fieldType, title, op
230
290
  return errorResponse(e, { sent: { customFields: envelope } });
231
291
  }
232
292
  const out = { result };
293
+ if (usage)
294
+ Object.assign(out, quotaNote(usage, 1));
233
295
  if (built.notApplicable && built.notApplicable.length > 0) {
234
296
  out.not_applicable = built.notApplicable;
235
297
  }
@@ -48,7 +48,7 @@
48
48
  * migration with data in it, and guessing at one from a diff is how data is
49
49
  * lost.
50
50
  */
51
- import { customFieldsEntity } from "./customFields.js";
51
+ import { customFieldsEntity, customFieldsUsage, quotaNote } from "./customFields.js";
52
52
  import { addCustomFieldsBatch, extensionFields, linkCustomFields } from "./customFieldSets.js";
53
53
  import { jsonResponse, parseJsonParam } from "../utils.js";
54
54
  import { makeRequest } from "../httpClient.js";
@@ -204,10 +204,21 @@ export async function applyCustomFieldsDeclaration(declaration, opts = {}) {
204
204
  const contexts = [...new Set(decl.fields.flatMap((f) => f.contexts.map(String)))];
205
205
  const offered = await readOffered(decl.entity, decl.context_field, contexts);
206
206
  const plan = diffDeclaration(decl, live, offered);
207
+ // Where the table stands after convergence — a port of a long list is exactly
208
+ // how a table is pushed past the cap (migrations.html: the cap "guards the API,
209
+ // not migrations").
210
+ let quota = {};
211
+ try {
212
+ quota = quotaNote(await customFieldsUsage(extension), plan.create.reduce((n, g) => n + g.fields.length, 0));
213
+ }
214
+ catch {
215
+ quota = {};
216
+ }
207
217
  if (!opts.confirm) {
208
218
  return jsonResponse({
209
219
  status: planIsEmpty(plan) ? "already_converged" : "dry_run",
210
220
  plan,
221
+ ...quota,
211
222
  next: planIsEmpty(plan)
212
223
  ? "Nothing to do — the tenant already matches the file."
213
224
  : "Re-call with confirm=true to apply. Nothing has been created yet.",
@@ -248,6 +259,7 @@ export async function applyCustomFieldsDeclaration(declaration, opts = {}) {
248
259
  entity: decl.entity,
249
260
  extension,
250
261
  applied,
262
+ ...quota,
251
263
  unchanged: plan.unchanged.length,
252
264
  type_drift: plan.type_drift,
253
265
  not_declared: plan.not_declared,
@@ -1648,8 +1648,18 @@ export async function buildFieldDef(entityName, fieldName, fieldType, title, opt
1648
1648
  const fieldDef = {
1649
1649
  name: fieldName,
1650
1650
  type: resolvedType,
1651
- title: await _expandTitle(title, fieldName),
1652
1651
  };
1652
+ // Sent ONLY when the caller gave one. builder.txt:56 marks title optional, and
1653
+ // the fallback that used to fill it from the field name did two things badly:
1654
+ // it stored a machine name as a human label, and since 2026-09-11 it makes
1655
+ // EVERY add fail on dev — the builder there answers 400 to any title object
1656
+ // (write.invalid_relation_value on path 'title'), accepts a plain string and
1657
+ // stores null for it, and last stored a title on 2026-09-10 13:41. A field
1658
+ // with no title is created; one with an invented title is not.
1659
+ const hasTitle = title !== null && title !== undefined && (isPlainObject(title) || String(title).trim() !== "");
1660
+ if (hasTitle) {
1661
+ fieldDef.title = await _expandTitle(title, fieldName);
1662
+ }
1653
1663
  // Applicability is per the builder's own table, and a constraint that does not
1654
1664
  // apply is DROPPED by the builder without complaint — so sending it would be
1655
1665
  // reported back to the agent as applied while nothing changed. Each of these
@@ -1778,9 +1788,23 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
1778
1788
  // Correct endpoint is /builder/{Entity}/add-fields and the body is the bare
1779
1789
  // array of field defs (the old /builder/add-fields with an {entityName,fields}
1780
1790
  // wrapper 404s).
1781
- const result = await makeRequest("POST", `/api/core/builder/${entityName}/add-fields`, [
1782
- built.fieldDef,
1783
- ]);
1791
+ let result;
1792
+ try {
1793
+ result = await makeRequest("POST", `/api/core/builder/${entityName}/add-fields`, [
1794
+ built.fieldDef,
1795
+ ]);
1796
+ }
1797
+ catch (e) {
1798
+ // A platform refusal this server can explain comes back as JSON with the
1799
+ // next step, the way suppa_add_custom_field already answers. Anything else
1800
+ // propagates exactly as before.
1801
+ const message = e instanceof Error ? e.message : String(e);
1802
+ const hint = customFieldsHint(message);
1803
+ if (hint) {
1804
+ return jsonResponse({ error: message, hint, sent: built.fieldDef });
1805
+ }
1806
+ throw e;
1807
+ }
1784
1808
  // Plain result when everything asked for was applied — the shape callers and
1785
1809
  // tests already read. The wrapper appears only when something was withheld,
1786
1810
  // because that is the case a bare success would misreport.
@@ -2660,6 +2684,23 @@ async function _resolveEntity(name) {
2660
2684
  if (ci) {
2661
2685
  return { name: ci, names };
2662
2686
  }
2687
+ // The platform hides its extension tables ('<Entity>CustomFields') from the
2688
+ // listing, so a name that is absent from it may still be readable by name —
2689
+ // describeEntityCompact learned this first. A write to one is legitimate
2690
+ // (api/entity-builder/custom-fields.html §6B), just not atomic with the owner,
2691
+ // and the write path says so; refusing it as "does not exist" was the listing
2692
+ // talking, not the tenant.
2693
+ if (name.endsWith(CUSTOM_FIELDS_EXTENSION_SUFFIX)) {
2694
+ try {
2695
+ const schema = await makeRequest("GET", `/api/core/schema/${name}`);
2696
+ if (_extractFields(schema).some((f) => f.name === "owner")) {
2697
+ return { name, names };
2698
+ }
2699
+ }
2700
+ catch {
2701
+ // fall through to the refusal below — a failed read is not an entity
2702
+ }
2703
+ }
2663
2704
  const nl = name.toLowerCase();
2664
2705
  const near = names
2665
2706
  .filter((n) => n.toLowerCase().includes(nl) || nl.includes(n.toLowerCase()))
@@ -2706,6 +2747,11 @@ async function _validateRecordWrites(entityName, records) {
2706
2747
  // Filled in below when a written enum value turns out to belong to another
2707
2748
  // group. It rides back to the caller, which attaches it to the RESULT.
2708
2749
  let enumWarning;
2750
+ // Set when the target IS an extension table. api/entity-builder/custom-fields.html:
2751
+ // both paths validate against the owner's active sets, but a direct write
2752
+ // "bridges into an owner update after the values row is written" and is NOT
2753
+ // atomic — the values commit first. Inline on the owner is the atomic path.
2754
+ let extensionWarning;
2709
2755
  // The SAME schema read carries the entity's custom field definitions in its
2710
2756
  // own `customFields` array (name, type, options, setIds) — so validating the
2711
2757
  // inline custom values costs no extra request.
@@ -2719,6 +2765,17 @@ async function _validateRecordWrites(entityName, records) {
2719
2765
  defs = null; // unreadable → can't validate fields; proceed
2720
2766
  }
2721
2767
  if (defs && defs.length > 0) {
2768
+ if (entityName.endsWith(CUSTOM_FIELDS_EXTENSION_SUFFIX) &&
2769
+ defs.some((f) => f.name === "owner" && /many.?to.?one/i.test(String(f.type ?? "")))) {
2770
+ const owner = entityName.slice(0, -CUSTOM_FIELDS_EXTENSION_SUFFIX.length);
2771
+ extensionWarning = {
2772
+ warning: `'${entityName}' is the custom-values table of '${owner}'. Writing it directly works, but it ` +
2773
+ "is NOT atomic with the owner: the values row commits first and the owner update is bridged " +
2774
+ "in afterwards, so a failing owner hook leaves the values changed.",
2775
+ prefer: `suppa_update_record("${owner}", <record id>, fields_json='{"customFields": {"<field>": <value>}}')` +
2776
+ " — one transaction, updatedAt bumped, triggers and automations see customFields among the changed fields.",
2777
+ };
2778
+ }
2722
2779
  const many = records.length > 1;
2723
2780
  const fieldNames = new Set(defs.map((f) => f.name).filter((n) => Boolean(n)));
2724
2781
  const unknown = [
@@ -2801,7 +2858,7 @@ async function _validateRecordWrites(entityName, records) {
2801
2858
  }
2802
2859
  // The defs travel back so the caller does not re-read the schema to decide
2803
2860
  // which written fields are actually list-valued (see `_replacedListNames`).
2804
- return { entityName, defs: defs && defs.length > 0 ? defs : null, enumWarning };
2861
+ return { entityName, defs: defs && defs.length > 0 ? defs : null, enumWarning, extensionWarning };
2805
2862
  }
2806
2863
  // The only field types whose stored value IS a list, so the only ones an update
2807
2864
  // can replace wholesale and the only ones merge/unmerge applies to. Types from
@@ -2929,7 +2986,13 @@ export async function createRecord(entityName, fieldsJson) {
2929
2986
  // Namespaced with a leading underscore so it cannot collide with a field:
2930
2987
  // the bare record IS the documented shape here, and this key only appears
2931
2988
  // when there is something to say.
2932
- return jsonResponse(v.enumWarning ? { ...returned[0], _enum_group_warning: v.enumWarning } : returned[0]);
2989
+ return jsonResponse(v.enumWarning || v.extensionWarning
2990
+ ? {
2991
+ ...returned[0],
2992
+ ...(v.enumWarning ? { _enum_group_warning: v.enumWarning } : {}),
2993
+ ...(v.extensionWarning ? { _direct_extension_write_warning: v.extensionWarning } : {}),
2994
+ }
2995
+ : returned[0]);
2933
2996
  }
2934
2997
  return jsonResponse({
2935
2998
  created: returned.length,
@@ -2937,6 +3000,7 @@ export async function createRecord(entityName, fieldsJson) {
2937
3000
  entity: v.entityName,
2938
3001
  records: returned,
2939
3002
  ...(v.enumWarning ? { enum_group_warning: v.enumWarning } : {}),
3003
+ ...(v.extensionWarning ? { direct_extension_write_warning: v.extensionWarning } : {}),
2940
3004
  });
2941
3005
  }
2942
3006
  /** Parse a merge_json/unmerge_json parameter into a list of field names. */
@@ -3024,6 +3088,7 @@ export async function updateRecord(entityName, recordId, fieldsJson, mergeJson =
3024
3088
  // still chose it. Dropping the warning here hid it from every probe that
3025
3089
  // targets a missing row — which is how this omission was found.
3026
3090
  ...(v.enumWarning ? { enum_group_warning: v.enumWarning } : {}),
3091
+ ...(v.extensionWarning ? { direct_extension_write_warning: v.extensionWarning } : {}),
3027
3092
  result,
3028
3093
  });
3029
3094
  }
@@ -3050,6 +3115,9 @@ export async function updateRecord(entityName, recordId, fieldsJson, mergeJson =
3050
3115
  if (v.enumWarning) {
3051
3116
  out.enum_group_warning = v.enumWarning;
3052
3117
  }
3118
+ if (v.extensionWarning) {
3119
+ out.direct_extension_write_warning = v.extensionWarning;
3120
+ }
3053
3121
  out.result = Array.isArray(result) && result.length ? result[0] : result;
3054
3122
  return jsonResponse(out);
3055
3123
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.34.0",
3
+ "version": "1.35.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": {
@@ -23,7 +23,7 @@ Code is authoritative: on every start, entity metadata is **overridden** to matc
23
23
  Confirm all 5 before writing anything:
24
24
 
25
25
  1. Target app repo exists, with `src/index.ts` exporting `AppModule`.
26
- 2. `@suppa/sdk@latest` is installed (`pnpm add @suppa/sdk@latest`).
26
+ 2. `@suppa/sdk@latest` is installed (`pnpm add @suppa/sdk@latest`) — and **1.38.0 or newer if the schema declares custom fields** (`@CustomFields` does not exist below it; E129).
27
27
  3. `tsconfig.json` has both `experimentalDecorators: true` and `emitDecoratorMetadata: true`.
28
28
  4. Recommended layout is in place (or will be created): `src/common/database/{entities,seeds}`, each with an `index.ts` barrel.
29
29
  5. A local module — conventionally `src/common/modules.ts` (imported as `'../../modules'` from `src/common/database/seeds/`) — exports `EntityNamesEnum` (one member per entity `name`).
@@ -131,11 +131,16 @@ Confirm all 5 before writing anything:
131
131
 
132
132
  On an entity you do **not** own, the columns still come from your file — only the switch is out of reach: extension mode ignores entity options, so enable the feature once with `suppa_update_entity_options(entity_name, '{"customFields": true}')` (`POST /core/builder/<Entity>/update-options`). That is what W618 means when it fires on `options`.
133
133
 
134
+ The gate enforces all of it — E124 (nested class registered, decorated or extending a base class), E125 (property name), E126 (primary / reverse relation), E127 (`nullable: false` without a default), E128 (half a context), E129 (SDK below 1.38.0), E130 (one class shared by two owners), W621 (column with no set), W622 (`contextField` not on the owner), W623 (the option written beside the decorator), W625 (a number as `contextValue` on an enum context field — that is an Enums row id copied off one tenant, not the stored value). Start from `templates/custom-fields.template.ts`.
135
+
136
+ Two limits from the API reference: the extension table is capped at `CUSTOM_FIELDS_LIMIT` active custom fields (**default 200** — the cap guards the API, not migrations, so a long port can push a table past it and the API then stops serving it; the MCP tools that add fields report where the table stands), and a set declared for a context value applies to that value's **descendants** when the context field points at a hierarchical entity, so one entry covers a subtree.
137
+
134
138
  ## Decorator decision table
135
139
 
136
140
  | You need | Decorator |
137
141
  |---|---|
138
142
  | Repeating rows owned by one parent record (checklist items, order lines, attendees) | **Tabular part** — `type: 'tabular-part'` + `relationEntityName` + a `@ManyToOne` field named `owner` on `@Entity()`; see `templates/tabular-part.template.ts` and `references/tabular-parts.md` |
143
+ | A field only SOME records show, decided by another field's value (custom fields) | `@CustomFields(() => OwnerCustomFields)` on a property named `customFields`; the columns in a plain nested class with `options.customFieldSets` — rule 22, `templates/custom-fields.template.ts`, `references/custom-fields.md` |
139
144
  | Scalar column (text/numeric/integer/boolean/timestamp/json/uuid/multi-language/bytea/tsvector/multi-type/icon) | `@Column({ type: FieldTypeEnum.<Member> })` |
140
145
  | Date-only column (no time part) | `@Column({ type: FieldTypeEnum.Timestamp, subType: 'date' })` — there is **no** `FieldTypeEnum.Date` |
141
146
  | Time-only column | `@Column({ type: FieldTypeEnum.Timestamp, subType: 'time' })` — there is **no** `FieldTypeEnum.Time` |
@@ -226,6 +226,23 @@ The migrations page links to a separate [custom fields API reference](https://do
226
226
  - **You can sort and filter through a relation custom field** — `customFields.reviewer.fullName` — because each step of the chain yields at most one row. A multi-row collection in the chain is `400 query.planner_unsupported`. Full-text search covers the extension table's own searchable TEXT fields only (not a relation's content), and the base entity must have at least one searchable field of its own.
227
227
  - **Write values inline on the owner, not on the extension table.** Both paths validate against the active sets, but a direct extension-table write "bridges into an owner update after the values row is written" and is **not atomic** — the values commit first. Inline writes run inside the owner's transaction, bump `updatedAt`, and fire triggers, socket events and automations with `customFields` among the changed fields.
228
228
 
229
+ ## What the gate checks
230
+
231
+ | Code | Rule it enforces |
232
+ |---|---|
233
+ | E124 | the nested class is passed to `forFeature()`, carries `@Entity()`, or extends a base class |
234
+ | E125 | the property is not named `customFields` |
235
+ | E126 | `primary`, `@OneToMany()` or `@ManyToManyBackRef()` on a custom-field column |
236
+ | E127 | `nullable: false` with no `default` |
237
+ | E128 | a `customFieldSets` entry without `contextField` or `contextValue` |
238
+ | E129 | `@suppa/sdk` pinned below 1.38.0 in `package.json` |
239
+ | E130 | one class named by `@CustomFields` on two owners |
240
+ | W621 | a column with no `customFieldSets` — no record shows it |
241
+ | W622 | `contextField` names no field on the owner |
242
+ | W623 | `options: { customFields: true }` written beside the decorator that implies it |
243
+ | W624 | advisory: the nested class is declared in another file, or the SDK range cannot be read, so a check was skipped |
244
+ | W625 | a number as `contextValue` on an `@Enum` context field — an id, where the stored value belongs |
245
+
229
246
  ## Which route to take
230
247
 
231
248
  | Situation | Route |
@@ -14,14 +14,15 @@
14
14
  */
15
15
 
16
16
  export const HOUSE_RULES_DIGEST = `WRITING ENTITY CODE (*.entity.ts in an application repo — NOT the API tools above)
17
- These six rules are house rules of this platform. They OVERRIDE the platform's own migrations doc (which contradicts two of them) and the style of the entities already in the repo you are editing — a file that breaks them is the habit these rules exist to stop, not a convention to match. Full skill: skills/suppa-entity-code/SKILL.md in the installed suppa-mcp-2 package; the six bind whether or not you open it.
17
+ These seven rules are house rules of this platform. They OVERRIDE the platform's own migrations doc (which contradicts two of them) and the style of the entities already in the repo you are editing — a file that breaks them is the habit these rules exist to stop, not a convention to match. Full skill: skills/suppa-entity-code/SKILL.md in the installed suppa-mcp-2 package; the seven bind whether or not you open it.
18
18
  1. TYPE EVERY RELATION PROPERTY to match its decorator: @ManyToOne -> \`owner: Target;\` (\`owner?: Target\` when the relation is nullable); @ManyToMany/@OneToMany/@ManyToManyBackRef -> \`peers: Target[];\`. Never \`any\`.
19
19
  2. ENUM MEMBER KEYS ARE PascalCase — \`NotFilled = 'Not filled'\` — the stored value is the string on the right and need not match the key.
20
20
  3. NEVER WRITE A FIELD OPTION AT ITS DEFAULT: canGroup, canSort, showInTable, editFromTable and canFilter are already true; readOnly and searchable are already false. Write one ONLY where the field departs from that (usually just \`searchable: true\`); all seven spelled out is wrong even though it works.
21
21
  4. @Enum/@MultiEnum TAKE THE GLOBAL NAME ONLY WHEN THE ENUM IS GLOBAL — shared by another entity, or referenced from a seed record. Otherwise omit the first argument: \`@Enum(StatusEnum, StatusTitles, { … })\` derives <ClassName>.<propertyName>. A field's own \`key: 'Entity.field'\` is the rename key, NOT a reference, and does not make the enum global.
22
22
  5. A RELATION TARGET THAT ALREADY EXISTS on the tenant (created earlier, or owned by another application) gets a STUB — three things at once: \`@Entity({ name: 'Accounts', key: 'Accounts' }) export class Accounts extends SystemBaseEntity {}\` with an EMPTY body, ALONE in a file named \`accounts.stub.entity.ts\`, and REGISTERED in forFeature() with the entities you create. Never a bare \`export class Accounts {}\` — it satisfies the thunk but registers nothing, so the platform cannot resolve the relation (E116). Never fields on a stub — it only lets a relation point at the table (E117); to ADD columns there, see rule 6. Platform system entities need no stub: import UsersEntity/FilesEntity/IconsEntity from @suppa/sdk.
23
23
  6. TO ADD COLUMNS TO AN ENTITY YOU DO NOT OWN, DECLARE AN EXTENSION — not a stub; there is no separate API. Declare the entity by its EXISTING name with only your own columns, in \`<owner-entity>.extension.entity.ts\` (class \`<OwnerEntity>Extension\`), registered like any other entity: \`@Entity({ name: 'Users' }) export class UsersExtension extends SystemBaseEntity { @Column({ type: FieldTypeEnum.Numeric, nullable: true }) accountId?: number; }\`. The platform picks the mode by OWNERSHIP at start. In extension mode: entity options are IGNORED (title/icon/type/options/representativeFieldName/importKeyFields — W618); no @OneToMany or @ManyToManyBackRef (E118); no \`primary: true\` (E119); no \`nullable: false\` without a default (E120); @Index/@Check only over your own columns, listed as a literal array (E121/E122). Write @Entity()/@Column() options as literal objects — one passed by reference or through a spread cannot be read, so none of this can be checked on it (E123). A relation to an entity you do not own takes NO string target - name it on a raw column (W620): \`@Column({ type: RelationTypeEnum.ManyToOne, relationEntityName: 'Invoices', relationFieldName: 'id' }) invoice?: { id: number };\`.
24
- Before reporting the file done, run the gate: suppa_validate_entity_code(path=<app-root>). It fails on every one of the six and names file:line; passed=false means fix and re-run, not "note and move on". (CLI: node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root>.)`;
24
+ 7. CUSTOM FIELDS IN CODE need @suppa/sdk 1.38.0 (E129) and a nested class of columns that is NOT an entity — no @Entity(), never in forFeature() (E124: registering it breaks every custom-field read and write) — reached by a property that MUST be named customFields (E125): \`@CustomFields(() => TasksCustomFields) customFields?: TasksCustomFields;\`. Every column needs options.customFieldSets [{contextField (on the owner), contextValue (a value, not an id)}] or no record shows it (W621). SKILL.md rule 22; template custom-fields.template.ts.
25
+ Before reporting the file done, run the gate: suppa_validate_entity_code(path=<app-root>). It fails on every one of the seven and names file:line; passed=false means fix and re-run, not "note and move on". (CLI: node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root>.)`;
25
26
 
26
27
  /** What the gate blocks on, for a message that must not understate it. */
27
28
  export const BLOCKING_SUMMARY =
@@ -33,5 +34,5 @@ export const BLOCKING_SUMMARY =
33
34
  "the other one is then analyzed by nothing (W619), no " +
34
35
  "`inverse` on @ManyToOne/@ManyToMany (W609) — and, on a @CustomFields class, never registering or " +
35
36
  "decorating it, the `customFields` property name, a set on every column, no primary, no reverse " +
36
- "relation, no NOT NULL without a default " +
37
- "(E124/E125/E126/E127/E128/W621/W622/W623)";
37
+ "relation, no NOT NULL without a default, the 1.38.0 SDK floor, one class per owner, a value not an id " +
38
+ "for an enum context (E124/E125/E126/E127/E128/E129/E130/W621/W622/W623/W625)";
@@ -74,6 +74,7 @@ export const RULE_WARNINGS = [
74
74
  "W621", // custom-field column with no customFieldSets: no record shows it
75
75
  "W622", // customFieldSets contextField names no field on the owner
76
76
  "W623", // options: { customFields: true } written beside @CustomFields
77
+ "W625", // customFieldSets contextValue is a NUMBER on an @Enum context field (an id, not the value)
77
78
  ];
78
79
  /**
79
80
  * W613 argues from ABSENCE — "nothing references this name". That only holds
@@ -783,10 +784,42 @@ function analyzeEntities(ts, sf, model, opts = {}) {
783
784
  * break every custom-field read and write". Nothing else would catch that, and
784
785
  * the damage is silent, so it is an error rather than a warning.
785
786
  */
786
- function checkCustomFieldsClasses(ts, model, findings) {
787
+ function checkCustomFieldsClasses(ts, model, findings, rootDir = null) {
787
788
  const registered = new Set(model.modules.flatMap((m) => m.entities.names));
788
- for (const info of model.entities.values()) {
789
- if (info.outOfScope) continue;
789
+ const owners = [...model.entities.values()].filter((i) => !i.outOfScope && i.customFieldsProp);
790
+ if (!owners.length) return;
791
+
792
+ // "Requires @suppa/sdk 1.38.0 — @CustomFields and the declarative sets land in
793
+ // 1.38.0. Older SDKs have no way to describe custom fields from an
794
+ // application." Below the floor the decorator does not exist, so the file
795
+ // fails at import — a compile error this gate can name first. Once per run.
796
+ const floor = sdkFloorProblem(rootDir);
797
+ if (floor) {
798
+ const first = owners[0];
799
+ findings.push(finding(ts, first.sf, first.customFieldsProp.node, floor.code, floor.message));
800
+ }
801
+
802
+ // "one class serves one owner" — "the table is named after the OWNER, never
803
+ // after the class", so two owners sharing a class would both try to apply it
804
+ // to their own extension table, and "both rules fail the build loudly".
805
+ const byTarget = new Map();
806
+ for (const info of owners) {
807
+ const t = info.customFieldsProp.targetClass;
808
+ if (!t) continue;
809
+ if (!byTarget.has(t)) byTarget.set(t, []);
810
+ byTarget.get(t).push(info);
811
+ }
812
+ for (const [target, list] of byTarget) {
813
+ if (list.length < 2) continue;
814
+ for (const info of list.slice(1)) {
815
+ findings.push(finding(ts, info.sf, info.customFieldsProp.node, "E130",
816
+ `'${target}' is the @CustomFields class of BOTH '${list[0].className}' and '${info.className}', but ` +
817
+ `"one class serves one owner" — the table is named after the owner, so one class cannot be the ` +
818
+ `columns of two tables. Give '${info.className}' its own class (${info.className}CustomFields).`));
819
+ }
820
+ }
821
+
822
+ for (const info of owners) {
790
823
  const cf = info.customFieldsProp;
791
824
  if (!cf) continue;
792
825
 
@@ -863,6 +896,58 @@ function checkCustomFieldsClasses(ts, model, findings) {
863
896
  }
864
897
  }
865
898
 
899
+ /**
900
+ * Is the app's @suppa/sdk below the 1.38.0 floor @CustomFields needs?
901
+ *
902
+ * Reads the dependency RANGE from the app's package.json and takes its lowest
903
+ * version — the one a fresh install may resolve to. A range this cannot read
904
+ * (workspace:, latest, a git URL) is reported as unverified rather than as
905
+ * fine, and no package.json at all is silent: the tsconfig check already tells
906
+ * the caller what a rootDir without a project looks like.
907
+ */
908
+ export function sdkFloorProblem(rootDir, floorText = "1.38.0") {
909
+ if (!rootDir) return null;
910
+ let pkg;
911
+ try {
912
+ pkg = JSON.parse(readFileSync(join(resolve(rootDir), "package.json"), "utf-8"));
913
+ } catch {
914
+ return null;
915
+ }
916
+ const range =
917
+ pkg?.dependencies?.["@suppa/sdk"] ??
918
+ pkg?.peerDependencies?.["@suppa/sdk"] ??
919
+ pkg?.devDependencies?.["@suppa/sdk"];
920
+ if (range === undefined) {
921
+ return {
922
+ code: "W624",
923
+ message:
924
+ "@CustomFields needs @suppa/sdk 1.38.0, but package.json lists no @suppa/sdk dependency, so the " +
925
+ "floor could not be checked. Older SDKs have no way to describe custom fields from an application.",
926
+ };
927
+ }
928
+ const m = String(range).match(/(\d+)\.(\d+)\.(\d+)/);
929
+ if (!m) {
930
+ return {
931
+ code: "W624",
932
+ message:
933
+ `@CustomFields needs @suppa/sdk ${floorText}, and the declared range '${range}' names no version this ` +
934
+ "checker can compare — confirm the installed SDK is 1.38.0 or newer before relying on the decorator.",
935
+ };
936
+ }
937
+ const have = m.slice(1, 4).map(Number);
938
+ const want = floorText.split(".").map(Number);
939
+ const below = have[0] !== want[0] ? have[0] < want[0] : have[1] !== want[1] ? have[1] < want[1] : have[2] < want[2];
940
+ if (!below) return null;
941
+ return {
942
+ code: "E129",
943
+ message:
944
+ `@CustomFields is used, but package.json pins @suppa/sdk to '${range}' — below the ${floorText} floor. ` +
945
+ "\"Older SDKs have no way to describe custom fields from an application\": the decorator does not exist " +
946
+ "there, so this file fails at import. Upgrade the SDK (pnpm add @suppa/sdk@latest) or declare the " +
947
+ "fields on the tenant with suppa_add_custom_field / suppa_apply_custom_fields instead.",
948
+ };
949
+ }
950
+
866
951
  /** Every property of the nested class is one custom field. */
867
952
  function checkCustomFieldColumns(ts, info, cls, findings) {
868
953
  const ownerFields = new Set();
@@ -948,6 +1033,23 @@ function checkCustomFieldColumns(ts, info, cls, findings) {
948
1033
  continue;
949
1034
  }
950
1035
  const cfName = stringValue(ts, cfNode);
1036
+ // Resolution table: for an @Enum/@MultiEnum context field "what
1037
+ // contextValue may say" is "the stored enum value ('Refrigeration
1038
+ // equipment')", resolved to the id of that Enums row. A NUMBER there is
1039
+ // almost always that id written by hand — and ids differ per workspace,
1040
+ // which is the very thing the by-value declaration exists to avoid.
1041
+ const ownerProp = cfName ? info.properties.get(cfName) : null;
1042
+ const cvExpr = unwrapExpr(ts, cvNode);
1043
+ const cvIsNumber =
1044
+ ts.isNumericLiteral(cvExpr) ||
1045
+ (ts.isPrefixUnaryExpression(cvExpr) && ts.isNumericLiteral(cvExpr.operand));
1046
+ if (ownerProp && (ownerProp.kind === "enum" || ownerProp.kind === "multi-enum") && cvIsNumber) {
1047
+ findings.push(finding(ts, info.sf, cvNode, "W625",
1048
+ `'${propName}' keys its context on the enum '${cfName}' with a NUMBER (${cvExpr.getText(info.sf)}) — ` +
1049
+ `for an @Enum context field contextValue is the STORED VALUE ('design'), which the platform ` +
1050
+ `resolves to the Enums row id per workspace. An id written here is only right on the one ` +
1051
+ `tenant it was copied from.`));
1052
+ }
951
1053
  // "contextField — Name of the field ON THE OWNER whose value decides the
952
1054
  // context. It must exist on the owner."
953
1055
  if (cfName && ownerFields.size > 0 && !ownerFields.has(cfName)) {
@@ -2981,7 +3083,7 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
2981
3083
  if (info.outOfScope) continue;
2982
3084
  checkEntity(ts, info, sdk, model, findings);
2983
3085
  }
2984
- checkCustomFieldsClasses(ts, model, findings);
3086
+ checkCustomFieldsClasses(ts, model, findings, rootDir);
2985
3087
  for (const seed of model.seeds) checkSeed(ts, seed, model, findings);
2986
3088
  checkRegistration(ts, model, findings, rootDir, parsedByCanonical);
2987
3089
  checkTsconfig(ts, rootDir, model, findings);
@@ -0,0 +1,95 @@
1
+ /**
2
+ * TEMPLATE — custom fields declared in code (@suppa/sdk 1.38.0 or newer).
3
+ *
4
+ * Copy into the OWNER's entity file, or beside it. Replace `Tasks`/`category`
5
+ * and the columns; keep the shape. Every line that departs from the shape is a
6
+ * rule the gate blocks on — the code is in the comment.
7
+ *
8
+ * Doc: migrations.html#custom-fields, transcribed in references/custom-fields.md.
9
+ */
10
+ import {
11
+ Column,
12
+ CustomFields,
13
+ Entity,
14
+ FieldTypeEnum,
15
+ SystemBaseEntity,
16
+ } from '@suppa/sdk';
17
+
18
+ /**
19
+ * The nested class: a PLAIN class of columns.
20
+ *
21
+ * - no @Entity(), does not extend SystemBaseEntity, NEVER passed to
22
+ * EntityModule.forFeature() (E124 — registering it makes the platform build
23
+ * a plain table where the generated extension table belongs, breaking every
24
+ * custom-field read and write)
25
+ * - named after the owner by convention only: the TABLE is always
26
+ * `{Owner}CustomFields`, whatever this class is called
27
+ * - one class serves one owner (E130)
28
+ *
29
+ * Inside it the extension-mode restrictions apply: no `primary`, no
30
+ * @OneToMany()/@ManyToManyBackRef() (E126); `nullable: false` needs a `default`
31
+ * (E127). Every other house rule still binds — relation typing, no option at
32
+ * its default, local enums unnamed, stubs for existing targets.
33
+ */
34
+ export class TasksCustomFields {
35
+ /**
36
+ * One property = one custom field. EVERY column needs options.customFieldSets,
37
+ * or it exists in the metadata and shows on no record (W621). A set binds the
38
+ * owner to ONE context value; several entries = several contexts.
39
+ *
40
+ * contextField — a field ON THE OWNER (W622)
41
+ * contextValue — a business key, never an id (W625): the value itself for a
42
+ * text/number/boolean field, the STORED enum value for an
43
+ * @Enum, an import key or representative value for a relation
44
+ * required — default false; readOnly / defaultValue — default null
45
+ * (defer to the field)
46
+ */
47
+ @Column({
48
+ type: FieldTypeEnum.Numeric,
49
+ nullable: true,
50
+ title: { en: 'Budget', uk: 'Бюджет' },
51
+ options: {
52
+ customFieldSets: [
53
+ { contextField: 'category', contextValue: 'design', required: true },
54
+ { contextField: 'category', contextValue: 'support' },
55
+ ],
56
+ },
57
+ })
58
+ cfBudget?: number;
59
+
60
+ @Column({
61
+ type: FieldTypeEnum.Text,
62
+ nullable: true,
63
+ title: { en: 'Client reference' },
64
+ options: {
65
+ customFieldSets: [{ contextField: 'category', contextValue: 'support' }],
66
+ },
67
+ })
68
+ cfClientRef?: string;
69
+ }
70
+
71
+ @Entity({ name: 'Tasks', key: 'Tasks', importKeyFields: ['shortUID'] })
72
+ export class Tasks extends SystemBaseEntity {
73
+ @Column({ name: 'shortUID', type: FieldTypeEnum.Text, nullable: false })
74
+ shortUID: string;
75
+
76
+ @Column({ name: 'title', type: FieldTypeEnum.Text, nullable: false })
77
+ title: string;
78
+
79
+ /** The context field the sets above key on. */
80
+ @Column({ name: 'category', type: FieldTypeEnum.Text })
81
+ category?: string;
82
+
83
+ /**
84
+ * The property MUST be named `customFields` (E125). The decorator implies
85
+ * `options: { customFields: true }` — do not write the option beside it (W623).
86
+ * On an entity you do NOT own, the columns still come from this file, but the
87
+ * option has to be switched on once: suppa_update_entity_options(entity_name,
88
+ * '{"customFields": true}').
89
+ */
90
+ @CustomFields(() => TasksCustomFields)
91
+ customFields?: TasksCustomFields;
92
+ }
93
+
94
+ // Register ONLY the owner:
95
+ // EntityModule.forFeature([Tasks], { seeds: [] })