suppa-mcp-2 1.34.0 → 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -600,11 +600,12 @@ string and is typed by shape — right there, W620 anywhere else.
600
600
  Those, plus
601
601
  `owner` first in a tabular part's `importKeyFields` (W607) and no `inverse` on
602
602
  `@ManyToOne`/`@ManyToMany` (W609), are the **rule violations** — W607, W609,
603
- W610, W611, W612, W613, W615, W616, W617, W618, W620 — and like errors they exit 1, because a
603
+ W610, W611, W612, W613, W615, W616, W617, W618, W619, W620, W621, W622, W623, W625 — and like errors they exit 1, because a
604
604
  rule that only warns is a rule that gets ignored. `--no-strict` demotes them for a legacy repo, and says so:
605
605
  they print as `[rule violation, demoted]` and the summary ends `NOT a clean
606
- run`. Advisory warnings — W601-W606, W608, W614 — never block; they report what
607
- the checker could not see.
606
+ run`. Advisory warnings — W601-W606, W608, W614, W624 — never block; they report what
607
+ the checker could not see. W624 is the one to read rather than skim: it names a
608
+ check that could NOT run, which is not the same as a check that passed.
608
609
 
609
610
  Tabular parts (owned child sub-tables like checklist items or order lines)
610
611
  and the remove-and-re-add-a-field semantics — a re-added field restores its
@@ -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.36.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,18 @@ 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
+ **An extension whose only member is `@CustomFields` is complete** — it declares the columns of the generated table and nothing else, and the gate treats that as declaring plenty. W617 ("adds nothing") fires only on a class that declares neither columns nor `@CustomFields`; on a stub, `@CustomFields` is E117 like any other field, because the columns it names land on a tenant you do not own.
135
+
136
+ 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 — owner mode only; in extension mode the owner's fields are declared elsewhere, so you get the advisory W624 instead of a block), 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`.
137
+
138
+ 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.
139
+
134
140
  ## Decorator decision table
135
141
 
136
142
  | You need | Decorator |
137
143
  |---|---|
138
144
  | 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` |
145
+ | 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
146
  | Scalar column (text/numeric/integer/boolean/timestamp/json/uuid/multi-language/bytea/tsvector/multi-type/icon) | `@Column({ type: FieldTypeEnum.<Member> })` |
140
147
  | Date-only column (no time part) | `@Column({ type: FieldTypeEnum.Timestamp, subType: 'date' })` — there is **no** `FieldTypeEnum.Date` |
141
148
  | 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 — **owner mode only**, where the file declares the whole entity. Inherited `SystemBaseEntity` columns (`id`, `createdAt`, `updatedAt`, `deletedAt`, `createdBy`, `removedBy`) count as fields on the owner and never trip it |
242
+ | W623 | `options: { customFields: true }` written beside the decorator that implies it |
243
+ | W624 | advisory: the nested class is declared in another file, the SDK range cannot be read, or the class is an **extension** — there the owner's own fields are declared elsewhere, so `contextField` cannot be checked against them and W622 would be guesswork. Reported once per class, and never blocks |
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
@@ -768,6 +769,30 @@ function analyzeEntities(ts, sf, model, opts = {}) {
768
769
  });
769
770
  }
770
771
 
772
+ /**
773
+ * Every member the class DECLARES — which is NOT the same as `info.properties`.
774
+ *
775
+ * `info.properties` holds what became a COLUMN, and `@CustomFields` is
776
+ * deliberately kept out of it so no field rule treats it as one (see the
777
+ * CustomFields branch in collectEntities). Four rules then ask "does this class
778
+ * declare anything at all?" — W617 twice, E117 and W616 — and reading
779
+ * `properties.size` for that turned a class whose only member is `@CustomFields`
780
+ * into a class that declares nothing. That shipped: an extension holding one
781
+ * @CustomFields class, the exact form SKILL.md rule 22 prescribes for an entity
782
+ * you do not own, was told it "adds nothing" and the gate blocked it. The owner
783
+ * variant of the same class was told to rename itself to a stub, which would
784
+ * then have tripped E117.
785
+ *
786
+ * ANY future member kept off `properties` for the same reason must be added
787
+ * here, or those four rules go blind to it again. This is the one place that
788
+ * knows the difference between "declares no columns" and "declares nothing".
789
+ */
790
+ function declaredMembers(info) {
791
+ const names = [...info.properties.keys()];
792
+ if (info.customFieldsProp) names.push(info.customFieldsProp.propName);
793
+ return names;
794
+ }
795
+
771
796
  // ── rules: custom fields declared in code (@suppa/sdk 1.38.0) ──
772
797
  /**
773
798
  * `@CustomFields(() => Cls)` on an owner entity, with Cls a PLAIN class of
@@ -783,10 +808,42 @@ function analyzeEntities(ts, sf, model, opts = {}) {
783
808
  * break every custom-field read and write". Nothing else would catch that, and
784
809
  * the damage is silent, so it is an error rather than a warning.
785
810
  */
786
- function checkCustomFieldsClasses(ts, model, findings) {
811
+ function checkCustomFieldsClasses(ts, model, findings, rootDir = null) {
787
812
  const registered = new Set(model.modules.flatMap((m) => m.entities.names));
788
- for (const info of model.entities.values()) {
789
- if (info.outOfScope) continue;
813
+ const owners = [...model.entities.values()].filter((i) => !i.outOfScope && i.customFieldsProp);
814
+ if (!owners.length) return;
815
+
816
+ // "Requires @suppa/sdk 1.38.0 — @CustomFields and the declarative sets land in
817
+ // 1.38.0. Older SDKs have no way to describe custom fields from an
818
+ // application." Below the floor the decorator does not exist, so the file
819
+ // fails at import — a compile error this gate can name first. Once per run.
820
+ const floor = sdkFloorProblem(rootDir);
821
+ if (floor) {
822
+ const first = owners[0];
823
+ findings.push(finding(ts, first.sf, first.customFieldsProp.node, floor.code, floor.message));
824
+ }
825
+
826
+ // "one class serves one owner" — "the table is named after the OWNER, never
827
+ // after the class", so two owners sharing a class would both try to apply it
828
+ // to their own extension table, and "both rules fail the build loudly".
829
+ const byTarget = new Map();
830
+ for (const info of owners) {
831
+ const t = info.customFieldsProp.targetClass;
832
+ if (!t) continue;
833
+ if (!byTarget.has(t)) byTarget.set(t, []);
834
+ byTarget.get(t).push(info);
835
+ }
836
+ for (const [target, list] of byTarget) {
837
+ if (list.length < 2) continue;
838
+ for (const info of list.slice(1)) {
839
+ findings.push(finding(ts, info.sf, info.customFieldsProp.node, "E130",
840
+ `'${target}' is the @CustomFields class of BOTH '${list[0].className}' and '${info.className}', but ` +
841
+ `"one class serves one owner" — the table is named after the owner, so one class cannot be the ` +
842
+ `columns of two tables. Give '${info.className}' its own class (${info.className}CustomFields).`));
843
+ }
844
+ }
845
+
846
+ for (const info of owners) {
790
847
  const cf = info.customFieldsProp;
791
848
  if (!cf) continue;
792
849
 
@@ -863,14 +920,76 @@ function checkCustomFieldsClasses(ts, model, findings) {
863
920
  }
864
921
  }
865
922
 
923
+ /**
924
+ * Is the app's @suppa/sdk below the 1.38.0 floor @CustomFields needs?
925
+ *
926
+ * Reads the dependency RANGE from the app's package.json and takes its lowest
927
+ * version — the one a fresh install may resolve to. A range this cannot read
928
+ * (workspace:, latest, a git URL) is reported as unverified rather than as
929
+ * fine, and no package.json at all is silent: the tsconfig check already tells
930
+ * the caller what a rootDir without a project looks like.
931
+ */
932
+ export function sdkFloorProblem(rootDir, floorText = "1.38.0") {
933
+ if (!rootDir) return null;
934
+ let pkg;
935
+ try {
936
+ pkg = JSON.parse(readFileSync(join(resolve(rootDir), "package.json"), "utf-8"));
937
+ } catch {
938
+ return null;
939
+ }
940
+ const range =
941
+ pkg?.dependencies?.["@suppa/sdk"] ??
942
+ pkg?.peerDependencies?.["@suppa/sdk"] ??
943
+ pkg?.devDependencies?.["@suppa/sdk"];
944
+ if (range === undefined) {
945
+ return {
946
+ code: "W624",
947
+ message:
948
+ "@CustomFields needs @suppa/sdk 1.38.0, but package.json lists no @suppa/sdk dependency, so the " +
949
+ "floor could not be checked. Older SDKs have no way to describe custom fields from an application.",
950
+ };
951
+ }
952
+ const m = String(range).match(/(\d+)\.(\d+)\.(\d+)/);
953
+ if (!m) {
954
+ return {
955
+ code: "W624",
956
+ message:
957
+ `@CustomFields needs @suppa/sdk ${floorText}, and the declared range '${range}' names no version this ` +
958
+ "checker can compare — confirm the installed SDK is 1.38.0 or newer before relying on the decorator.",
959
+ };
960
+ }
961
+ const have = m.slice(1, 4).map(Number);
962
+ const want = floorText.split(".").map(Number);
963
+ const below = have[0] !== want[0] ? have[0] < want[0] : have[1] !== want[1] ? have[1] < want[1] : have[2] < want[2];
964
+ if (!below) return null;
965
+ return {
966
+ code: "E129",
967
+ message:
968
+ `@CustomFields is used, but package.json pins @suppa/sdk to '${range}' — below the ${floorText} floor. ` +
969
+ "\"Older SDKs have no way to describe custom fields from an application\": the decorator does not exist " +
970
+ "there, so this file fails at import. Upgrade the SDK (pnpm add @suppa/sdk@latest) or declare the " +
971
+ "fields on the tenant with suppa_add_custom_field / suppa_apply_custom_fields instead.",
972
+ };
973
+ }
974
+
866
975
  /** Every property of the nested class is one custom field. */
867
976
  function checkCustomFieldColumns(ts, info, cls, findings) {
868
- const ownerFields = new Set();
977
+ // Seeded with the inherited columns: every entity extends SystemBaseEntity,
978
+ // so id/createdAt/updatedAt/deletedAt/createdBy/removedBy are fields ON THE
979
+ // OWNER that are never written in the file. Keying a context on one of them
980
+ // is legal, and comparing against declared properties alone called it a
981
+ // field the owner does not declare.
982
+ const ownerFields = new Set(SYSTEM_COLUMNS);
869
983
  for (const [propName, prop] of info.properties) {
870
984
  ownerFields.add(propName);
871
985
  const colName = stringValue(ts, prop.nameNode);
872
986
  if (colName) ownerFields.add(colName);
873
987
  }
988
+ // In extension mode the owner's field list is not in this file, so
989
+ // contextField cannot be checked against it. Collected here and reported ONCE
990
+ // per class: one advisory per column per set would drown the real findings.
991
+ const extensionMode = isExtensionFileName(info.sf.fileName);
992
+ const unverifiedContexts = new Set();
874
993
 
875
994
  for (const member of cls.members ?? []) {
876
995
  if (!member.name) continue;
@@ -948,16 +1067,52 @@ function checkCustomFieldColumns(ts, info, cls, findings) {
948
1067
  continue;
949
1068
  }
950
1069
  const cfName = stringValue(ts, cfNode);
1070
+ // Resolution table: for an @Enum/@MultiEnum context field "what
1071
+ // contextValue may say" is "the stored enum value ('Refrigeration
1072
+ // equipment')", resolved to the id of that Enums row. A NUMBER there is
1073
+ // almost always that id written by hand — and ids differ per workspace,
1074
+ // which is the very thing the by-value declaration exists to avoid.
1075
+ const ownerProp = cfName ? info.properties.get(cfName) : null;
1076
+ const cvExpr = unwrapExpr(ts, cvNode);
1077
+ const cvIsNumber =
1078
+ ts.isNumericLiteral(cvExpr) ||
1079
+ (ts.isPrefixUnaryExpression(cvExpr) && ts.isNumericLiteral(cvExpr.operand));
1080
+ if (ownerProp && (ownerProp.kind === "enum" || ownerProp.kind === "multi-enum") && cvIsNumber) {
1081
+ findings.push(finding(ts, info.sf, cvNode, "W625",
1082
+ `'${propName}' keys its context on the enum '${cfName}' with a NUMBER (${cvExpr.getText(info.sf)}) — ` +
1083
+ `for an @Enum context field contextValue is the STORED VALUE ('design'), which the platform ` +
1084
+ `resolves to the Enums row id per workspace. An id written here is only right on the one ` +
1085
+ `tenant it was copied from.`));
1086
+ }
951
1087
  // "contextField — Name of the field ON THE OWNER whose value decides the
952
1088
  // context. It must exist on the owner."
953
- if (cfName && ownerFields.size > 0 && !ownerFields.has(cfName)) {
954
- findings.push(finding(ts, info.sf, cfNode, "W622",
955
- `'${propName}' keys its context on '${cfName}', which '${info.className}' does not declare — ` +
956
- `contextField must name a field ON THE OWNER. The migration resolves the context inside the ` +
957
- `write transaction, so an unresolvable one fails the whole start, not just this field.`));
1089
+ //
1090
+ // Only decidable when this file describes the whole owner. An EXTENSION
1091
+ // declares its own columns on a table another application owns, so the
1092
+ // owner's other fields are not here to be found and their absence proves
1093
+ // nothing — blocking on it would fail the very shape rule 22 prescribes
1094
+ // for an entity you do not own. Report it as a check that could not run.
1095
+ if (cfName && !ownerFields.has(cfName)) {
1096
+ if (extensionMode) {
1097
+ unverifiedContexts.add(cfName);
1098
+ } else {
1099
+ findings.push(finding(ts, info.sf, cfNode, "W622",
1100
+ `'${propName}' keys its context on '${cfName}', which '${info.className}' does not declare — ` +
1101
+ `contextField must name a field ON THE OWNER. The migration resolves the context inside the ` +
1102
+ `write transaction, so an unresolvable one fails the whole start, not just this field.`));
1103
+ }
958
1104
  }
959
1105
  }
960
1106
  }
1107
+
1108
+ if (unverifiedContexts.size > 0) {
1109
+ findings.push(finding(ts, info.sf, info.customFieldsProp.node, "W624",
1110
+ `'${info.className}' is an EXTENSION, so the owner's own fields are declared by whoever owns ` +
1111
+ `'${info.entityName}', not in this file — contextField ${[...unverifiedContexts].map((n) => `'${n}'`).join(", ")} ` +
1112
+ `could NOT be checked against them. Confirm each one exists on '${info.entityName}' ` +
1113
+ `(suppa_describe_entity("${info.entityName}")): the migration resolves the context inside the write ` +
1114
+ `transaction, so an unresolvable one fails the whole start, not just this field. Advisory — it does not block.`));
1115
+ }
961
1116
  }
962
1117
 
963
1118
  // ── rules: tabular parts ──
@@ -1916,7 +2071,11 @@ function checkExtension(ts, info, findings) {
1916
2071
  : "")));
1917
2072
  }
1918
2073
 
1919
- if (info.properties.size === 0) {
2074
+ // declaredMembers, NOT properties.size: an extension whose only member is
2075
+ // @CustomFields contributes the columns of the nested class, and rule 22
2076
+ // prescribes exactly that shape for an entity you do not own — "the custom
2077
+ // field COLUMNS still come from your file, only the switch is an owner action".
2078
+ if (declaredMembers(info).length === 0) {
1920
2079
  findings.push(finding(ts, sf, anchor, "W617",
1921
2080
  `extension '${info.className}' declares no columns, so it adds nothing to ${target} — ` +
1922
2081
  `an extension exists to contribute fields. If you only need the entity as a RELATION TARGET, that is a ` +
@@ -2439,7 +2598,11 @@ function checkStubFiles(ts, model, findings) {
2439
2598
  const stubFile = isStubFileName(infos[0].sf.fileName);
2440
2599
  for (const info of infos) {
2441
2600
  const anchor = info.node.name ?? info.node;
2442
- const fields = info.properties.size;
2601
+ // declaredMembers, NOT properties.size — see its doc comment. A class
2602
+ // whose only member is @CustomFields declares plenty; counting columns
2603
+ // made it look empty to all three rules below at once.
2604
+ const members = declaredMembers(info);
2605
+ const fields = members.length;
2443
2606
 
2444
2607
  // The whole point of a stub is the EMPTY body: it names a table another
2445
2608
  // application owns, and any field it declares is a column the migration
@@ -2447,10 +2610,19 @@ function checkStubFiles(ts, model, findings) {
2447
2610
  // that KEPT its fields is the failure this catches — it used to pass.
2448
2611
  if (stubFile && fields > 0) {
2449
2612
  findings.push(finding(ts, info.sf, anchor, "E117",
2450
- `stub '${info.className}' declares ${fields} field(s) (${[...info.properties.keys()].slice(0, 4).join(", ")}` +
2613
+ `stub '${info.className}' declares ${fields} field(s) (${members.slice(0, 4).join(", ")}` +
2451
2614
  `${fields > 4 ? ", …" : ""}) — a stub stands in for a table this application does NOT own, and every ` +
2452
2615
  `field it declares is a column the migration will create or alter on that real table. The body must ` +
2453
- `be EMPTY. If this entity IS yours to describe, it is not a stub: move it to ` +
2616
+ `be EMPTY.` +
2617
+ // @CustomFields declares columns just as surely as @Column does, only
2618
+ // on the generated {Owner}CustomFields table — and it is the member a
2619
+ // stub is most likely to be given by mistake, because the columns sit
2620
+ // in a class one level down and do not look like the stub's own body.
2621
+ (info.customFieldsProp
2622
+ ? ` @CustomFields counts: the nested class it names becomes the columns of ` +
2623
+ `'${info.entityName}CustomFields', a table on that same tenant.`
2624
+ : "") +
2625
+ ` If this entity IS yours to describe, it is not a stub: move it to ` +
2454
2626
  `${kebabOf(info.className)}.entity.ts and describe it there. If you mean to ADD columns to an entity ` +
2455
2627
  `another application owns, that is an extension, not a stub — declare only your own columns in ` +
2456
2628
  `${kebabOf(info.entityName)}.extension.entity.ts (see SKILL.md rule 20)`));
@@ -2981,7 +3153,7 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
2981
3153
  if (info.outOfScope) continue;
2982
3154
  checkEntity(ts, info, sdk, model, findings);
2983
3155
  }
2984
- checkCustomFieldsClasses(ts, model, findings);
3156
+ checkCustomFieldsClasses(ts, model, findings, rootDir);
2985
3157
  for (const seed of model.seeds) checkSeed(ts, seed, model, findings);
2986
3158
  checkRegistration(ts, model, findings, rootDir, parsedByCanonical);
2987
3159
  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: [] })