suppa-mcp-2 1.31.1 → 1.33.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.
@@ -2,17 +2,35 @@
2
2
  * Custom fields, declared in the repository instead of typed into a chat.
3
3
  *
4
4
  * THE PROBLEM THIS FIXES. Every other part of a Suppa application is code: an
5
- * entity class IS its migration, and a seed is a file. Custom fields are the
6
- * exception — the SDK has no decorator for them, they exist only as runtime
7
- * rows (CustomFieldSets + CustomFieldSetFields + values under the reserved
8
- * `customFields` key), and the only way to create one was to call a tool by
9
- * hand. So the one part of a schema that varies per context was also the one
10
- * part that lived nowhere in git: not reviewable, not diffable, and not
11
- * reproducible on a second tenant.
5
+ * entity class IS its migration, and a seed is a file. Custom fields used to be
6
+ * the exception — they exist only as runtime rows (CustomFieldSets +
7
+ * CustomFieldSetFields + values under the reserved `customFields` key), so the
8
+ * one part of a schema that varies per context was also the one part that lived
9
+ * nowhere in git: not reviewable, not diffable, not reproducible on a second
10
+ * tenant. Nothing forces the DECLARATION to be a chat message; a declaration
11
+ * file in the repo is the source of truth, and this converges a tenant to it.
12
12
  *
13
- * The platform will not grow a decorator for us, but nothing forces the
14
- * DECLARATION to be a chat message. A declaration file in the repo is the
15
- * source of truth; this converges a tenant to it.
13
+ * PREFER THE SDK WHEN YOU SHIP AN APPLICATION. @suppa/sdk 1.38.0 added a
14
+ * decorator that says all of this in the entity class itself — a nested class
15
+ * of columns reached through a `customFields` property, with the contexts on
16
+ * each column under `options.customFieldSets` (migrations.html#custom-fields,
17
+ * transcribed in docs/.../captures/migrations-custom-fields.txt):
18
+ *
19
+ * @CustomFields(() => TasksCustomFields)
20
+ * customFields?: TasksCustomFields;
21
+ *
22
+ * That route is strictly better where it applies: the platform converges every
23
+ * tenant on start, the property is TYPED, and `@CustomFields` implies the
24
+ * entity option rather than needing it switched on. Reach for THIS tool when it
25
+ * does not apply — an SDK below 1.38.0, a tenant nobody deploys an application
26
+ * to, or an entity another application owns (extension mode ignores the entity
27
+ * option, so the feature still has to be enabled once through
28
+ * suppa_update_entity_options).
29
+ *
30
+ * The two are not rivals: the declaration below is the same
31
+ * `{ entity, context_field, fields[] }` shape the platform's own
32
+ * `custom-fields-json-to-class.ts` turns into that class, so a file written for
33
+ * this tool ports to the decorator without being retyped.
16
34
  *
17
35
  * { "entity": "ServiceRequests",
18
36
  * "context_field": "country",
@@ -2460,6 +2460,147 @@ function _shapeProblemsFromDefs(defs, fields, customDefs = []) {
2460
2460
  }
2461
2461
  return problems;
2462
2462
  }
2463
+ /**
2464
+ * The Enums group each enum field is bound to, keyed by field name.
2465
+ *
2466
+ * A field whose subType and relationTarget are both empty is bound to NOTHING
2467
+ * (verified live: such a field reads back with no group and owns no values), so
2468
+ * it is left out — there is no group against which to judge a value.
2469
+ */
2470
+ function _enumGroups(defs) {
2471
+ const groups = Object.create(null); // see `types` above
2472
+ for (const f of defs) {
2473
+ if (!f.name) {
2474
+ continue;
2475
+ }
2476
+ const type = String(f.type ?? "").trim().toLowerCase().replace(/_/g, "-");
2477
+ if (type !== "enum" && type !== "multi-enum") {
2478
+ continue;
2479
+ }
2480
+ const raw = f.subType ?? f.relationTarget;
2481
+ const group = typeof raw === "string" ? raw.trim() : "";
2482
+ if (group) {
2483
+ groups[f.name] = group;
2484
+ }
2485
+ }
2486
+ return groups;
2487
+ }
2488
+ /**
2489
+ * Every enum id a batch writes, paired with the group its field is bound to.
2490
+ *
2491
+ * Pure: the caller does the reading, so every branch is testable without a
2492
+ * network. Only well-shaped references are collected — a value of the wrong
2493
+ * SHAPE is already refused before this runs, and reporting it again here would
2494
+ * say the same thing twice in one refusal.
2495
+ */
2496
+ export function _enumRefsInRecords(records, defs, customDefs = []) {
2497
+ const core = _enumGroups(defs);
2498
+ const custom = _enumGroups(customDefs);
2499
+ const refs = [];
2500
+ const take = (record, field, group, val) => {
2501
+ for (const one of Array.isArray(val) ? val : [val]) {
2502
+ if (!isPlainObject(one)) {
2503
+ continue;
2504
+ }
2505
+ const raw = one.id;
2506
+ // A numeric string is what a caller who built the id from text sends; the
2507
+ // platform resolves it the same way, so it is the same reference.
2508
+ const id = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() ? Number(raw) : NaN;
2509
+ if (Number.isFinite(id)) {
2510
+ refs.push({ record, field, group, id });
2511
+ }
2512
+ }
2513
+ };
2514
+ for (const [i, r] of records.entries()) {
2515
+ for (const [key, val] of Object.entries(r)) {
2516
+ if (val === null || val === undefined) {
2517
+ continue;
2518
+ }
2519
+ if (key === CUSTOM_FIELDS_KEY && isPlainObject(val)) {
2520
+ for (const [cname, cval] of Object.entries(val)) {
2521
+ // `id` addresses the values ROW, not a custom field — same exemption
2522
+ // the shape check makes one screen up.
2523
+ if (cname === "id" || cval === null || cval === undefined) {
2524
+ continue;
2525
+ }
2526
+ const group = custom[cname];
2527
+ if (group) {
2528
+ take(i, `${CUSTOM_FIELDS_KEY}.${cname}`, group, cval);
2529
+ }
2530
+ }
2531
+ continue;
2532
+ }
2533
+ const group = core[key];
2534
+ if (group) {
2535
+ take(i, key, group, val);
2536
+ }
2537
+ }
2538
+ }
2539
+ return refs;
2540
+ }
2541
+ /**
2542
+ * Refs whose Enums row belongs to a different group — pure, and deliberately
2543
+ * conservative in the same way the shape check is.
2544
+ *
2545
+ * An id the read did not answer with is NOT judged. It may be a row this
2546
+ * account cannot see, or one the read simply missed; refusing a write over a
2547
+ * row we could not read would turn a platform bug into an outage. Only a row
2548
+ * we positively read, carrying a group that is positively different, is a
2549
+ * problem.
2550
+ */
2551
+ export function _membershipProblems(refs, rows, many) {
2552
+ const problems = [];
2553
+ const seen = new Set();
2554
+ for (const ref of refs) {
2555
+ const row = rows.get(ref.id);
2556
+ if (!row || !row.name || row.name === ref.group) {
2557
+ continue;
2558
+ }
2559
+ const at = many ? `record[${ref.record}]: ` : "";
2560
+ // The same wrong id written to the same field twice is one problem.
2561
+ const key = `${at}${ref.field}:${ref.id}`;
2562
+ if (seen.has(key)) {
2563
+ continue;
2564
+ }
2565
+ seen.add(key);
2566
+ problems.push(`${at}'${ref.field}' is bound to the enum group '${ref.group}', but {"id": ${ref.id}} is a ` +
2567
+ `value of '${row.name}'${row.value ? ` (${row.value})` : ""}. The platform accepts this ` +
2568
+ "and stores it — the record then holds a value its own picker cannot show.");
2569
+ }
2570
+ return problems;
2571
+ }
2572
+ /**
2573
+ * The Enums rows behind a set of ids, or null if they cannot be read.
2574
+ *
2575
+ * deletedScope 'all': a soft-deleted row from the RIGHT group is still the
2576
+ * right group, and treating it as missing would leave a legitimate write
2577
+ * unjudged — while a soft-deleted row from the wrong group is still wrong.
2578
+ */
2579
+ async function _readEnumRows(ids) {
2580
+ try {
2581
+ const rows = await searchEntity("Enums",
2582
+ // One request for the whole batch: an AND of a single OR-group. Nested
2583
+ // conditions are the documented shape (data.txt:36).
2584
+ [{ operator: "or", filters: ids.map((id) => makeFilter("id", id)) }], { id: true, name: true, value: true }, Math.min(Math.max(ids.length, 1), 1000), 0, null, "", "and", "all");
2585
+ const byId = new Map();
2586
+ for (const row of rows) {
2587
+ if (!isPlainObject(row)) {
2588
+ continue;
2589
+ }
2590
+ const r = row;
2591
+ const id = Number(r.id);
2592
+ if (!Number.isFinite(id) || typeof r.name !== "string") {
2593
+ continue;
2594
+ }
2595
+ byId.set(id, { name: r.name, value: typeof r.value === "string" ? r.value : undefined });
2596
+ }
2597
+ return byId;
2598
+ }
2599
+ catch {
2600
+ // Unreadable → say nothing, exactly as an unreadable schema does above.
2601
+ return null;
2602
+ }
2603
+ }
2463
2604
  /**
2464
2605
  * A platform refusal this server can say something useful about — or null,
2465
2606
  * leaving the error to propagate exactly as before.
@@ -2562,6 +2703,9 @@ async function _validateRecordWrites(entityName, records) {
2562
2703
  }
2563
2704
  entityName = ent.name;
2564
2705
  let defs;
2706
+ // Filled in below when a written enum value turns out to belong to another
2707
+ // group. It rides back to the caller, which attaches it to the RESULT.
2708
+ let enumWarning;
2565
2709
  // The SAME schema read carries the entity's custom field definitions in its
2566
2710
  // own `customFields` array (name, type, options, setIds) — so validating the
2567
2711
  // inline custom values costs no extra request.
@@ -2619,10 +2763,45 @@ async function _validateRecordWrites(entityName, records) {
2619
2763
  }
2620
2764
  return { entityName, error: jsonResponse(body) };
2621
2765
  }
2766
+ // The shape is right; membership is the half the platform does not check.
2767
+ // Costs one read, and only on a write that actually carries an enum value
2768
+ // bound to a group.
2769
+ //
2770
+ // REPORTED, NEVER REFUSED — and that was decided by looking. A sweep of the
2771
+ // dev tenant on 2026-09-11 found 1,111 of 4,504 stored enum values already
2772
+ // sitting in a group other than their field's subType, across 30 entities:
2773
+ // ServiceInstallationChecklist.equipmentType is bound to a group holding one
2774
+ // row with an empty value, while every record stores rows of 'equipment_type'.
2775
+ // A refusal would therefore block a quarter of this tenant's enum writes —
2776
+ // read-modify-write re-sends the field, so ordinary edits to untouched
2777
+ // columns would start failing. The check is worth making and is not worth an
2778
+ // outage: say so on the way past.
2779
+ const refs = _enumRefsInRecords(records, defs, customDefs);
2780
+ if (refs.length > 0) {
2781
+ const rows = await _readEnumRows([...new Set(refs.map((r) => r.id))]);
2782
+ if (rows) {
2783
+ const wrongGroup = _membershipProblems(refs, rows, many);
2784
+ if (wrongGroup.length > 0) {
2785
+ enumWarning = {
2786
+ warning: "These enum values belong to a DIFFERENT group than the field they were written " +
2787
+ "to. The platform does not check this, so the write went through and the value is " +
2788
+ "stored.",
2789
+ problems: wrongGroup,
2790
+ note: "NOT blocked, on purpose: on the dev tenant 1,111 of 4,504 stored enum values were " +
2791
+ "already in this state, so refusing would break ordinary updates to existing " +
2792
+ "records. Treat it as something to check, not as a failure.",
2793
+ hint: "An enum field is bound to the group named by its subType (suppa_describe_entity " +
2794
+ "shows it). To see that group's real values, search Enums by that name: " +
2795
+ 'suppa_search_records(entity_name="Enums", filters_json=' +
2796
+ '[{"field": "name", "value": "<group>", "comparator": "="}]).',
2797
+ };
2798
+ }
2799
+ }
2800
+ }
2622
2801
  }
2623
2802
  // The defs travel back so the caller does not re-read the schema to decide
2624
2803
  // which written fields are actually list-valued (see `_replacedListNames`).
2625
- return { entityName, defs: defs && defs.length > 0 ? defs : null };
2804
+ return { entityName, defs: defs && defs.length > 0 ? defs : null, enumWarning };
2626
2805
  }
2627
2806
  // The only field types whose stored value IS a list, so the only ones an update
2628
2807
  // can replace wholesale and the only ones merge/unmerge applies to. Types from
@@ -2747,13 +2926,17 @@ export async function createRecord(entityName, fieldsJson) {
2747
2926
  reason: "Platform returned no row — nothing was inserted or the response was empty",
2748
2927
  });
2749
2928
  }
2750
- return jsonResponse(returned[0]);
2929
+ // Namespaced with a leading underscore so it cannot collide with a field:
2930
+ // the bare record IS the documented shape here, and this key only appears
2931
+ // when there is something to say.
2932
+ return jsonResponse(v.enumWarning ? { ...returned[0], _enum_group_warning: v.enumWarning } : returned[0]);
2751
2933
  }
2752
2934
  return jsonResponse({
2753
2935
  created: returned.length,
2754
2936
  requested: rows.length,
2755
2937
  entity: v.entityName,
2756
2938
  records: returned,
2939
+ ...(v.enumWarning ? { enum_group_warning: v.enumWarning } : {}),
2757
2940
  });
2758
2941
  }
2759
2942
  /** Parse a merge_json/unmerge_json parameter into a list of field names. */
@@ -2837,6 +3020,10 @@ export async function updateRecord(entityName, recordId, fieldsJson, mergeJson =
2837
3020
  entity: entityName,
2838
3021
  reason: "Platform returned no row — record id may not exist, be " +
2839
3022
  "deleted, or the values matched the stored ones (no-op).",
3023
+ // A write that matched nothing still CARRIED the value, and the caller
3024
+ // still chose it. Dropping the warning here hid it from every probe that
3025
+ // targets a missing row — which is how this omission was found.
3026
+ ...(v.enumWarning ? { enum_group_warning: v.enumWarning } : {}),
2840
3027
  result,
2841
3028
  });
2842
3029
  }
@@ -2860,6 +3047,9 @@ export async function updateRecord(entityName, recordId, fieldsJson, mergeJson =
2860
3047
  "To add items instead, re-send with merge_json; to remove only the listed " +
2861
3048
  "items, use unmerge_json.";
2862
3049
  }
3050
+ if (v.enumWarning) {
3051
+ out.enum_group_warning = v.enumWarning;
3052
+ }
2863
3053
  out.result = Array.isArray(result) && result.length ? result[0] : result;
2864
3054
  return jsonResponse(out);
2865
3055
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.31.1",
3
+ "version": "1.33.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": {
@@ -98,6 +98,39 @@ Confirm all 5 before writing anything:
98
98
  **Prefer an entity-scoped enum in an extension.** A global enum name has no owning entity, so two applications using the same name write to the same rows — which is rule 18's default anyway: pass no name.
99
99
  21. **`EntityModule.forFeature()` must be consumed by an `@Module`, and has exactly two shapes.** It RETURNS a module: put it in `@Module({ imports: [...] })` and export that class from `src/index.ts` as `AppModule` — a bare `EntityModule.forFeature(...);` statement discards the result and registers nothing (E307). The two shapes (`references/registration.md`) are `forFeature([A, B], { seeds: [...] })` — classes FIRST, options second — and `forFeature({ entitiesPath, seedsPath })` for autoloading. The options object accepts only `seeds`, `entitiesPath` and `seedsPath`. `forFeature({ entities: [...] })` looks reasonable and registers NOTHING: the classes are dropped with the unknown option and no table is created for any of them. E306.
100
100
 
101
+ 22. **Custom fields are declared in code too — and the nested class that holds them is NOT an entity.** A field every record of the entity shows is an ordinary column and belongs in the entity class; only a field whose presence depends on another field's VALUE is a custom field. Declare those as a plain class of columns, reached through a property on the owner (`references/custom-fields.md`). **Needs `@suppa/sdk` 1.38.0** — "older SDKs have no way to describe custom fields from an application", so below that floor there is no code route and the API tools (`suppa_add_custom_field`, `suppa_apply_custom_fields`) are the answer.
102
+
103
+ ```ts
104
+ export class TasksCustomFields {
105
+ @Column({
106
+ type: FieldTypeEnum.Numeric,
107
+ nullable: true,
108
+ title: { en: 'Budget', uk: 'Бюджет' },
109
+ options: { customFieldSets: [{ contextField: 'category', contextValue: 'design' }] },
110
+ })
111
+ cfBudget?: number;
112
+ }
113
+
114
+ @Entity({ name: 'Tasks' })
115
+ export class Tasks extends SystemBaseEntity {
116
+ @Column({ name: 'category', type: FieldTypeEnum.Text })
117
+ category?: string;
118
+
119
+ @CustomFields(() => TasksCustomFields)
120
+ customFields?: TasksCustomFields;
121
+ }
122
+ ```
123
+
124
+ Five things bind, and the first is the one this skill's own reflexes get wrong:
125
+
126
+ - **The nested class has no `@Entity()`, does not extend `SystemBaseEntity`, and is NEVER passed to `forFeature()`** — register only the owner. Rules 19 and 21 do not reach it: it names no table of its own, and registering it makes the platform build a plain table where the generated `{Entity}CustomFields` belongs, which "would break every custom-field read and write". The table is named after the OWNER, never after the class.
127
+ - **The property must be named `customFields`**, and one class serves one owner — "that is the name the platform gives the back reference; both rules fail the build loudly".
128
+ - **`@CustomFields` implies `options: { customFields: true }`.** Writing that option beside it repeats what the decorator already says (rule 16).
129
+ - **Every column needs `options.customFieldSets`** — `{ contextField, contextValue, required?, readOnly?, defaultValue? }`, one field and one value per set, no compound conditions. `contextValue` is a business key (an enum's stored value, a relation's import key), not an id, which is what makes the declaration portable between workspaces. A column with no set "exists in the metadata but no record shows it" — valid, and almost never what you meant.
130
+ - **Inside the nested class the extension-mode restrictions apply:** `nullable: false` needs a `default`; `primary`, `@OneToMany()` and `@ManyToManyBackRef()` are rejected. Every other house rule still binds there too — relation typing (14), no option at its default (16), local enums unnamed (17), stubs for existing targets (19).
131
+
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
+
101
134
  ## Decorator decision table
102
135
 
103
136
  | You need | Decorator |
@@ -0,0 +1,225 @@
1
+ # Custom fields in code — verbatim rules
2
+
3
+ Transcribed from docs.modern-expo.com/backend/application-developing/migrations.html, section "Custom Fields" (captured 2026-09-11). The full capture is `docs/superpowers/specs/captures/migrations-custom-fields.txt` in the suppa-mcp-2 repository. If a rule is not here, it does not exist — stop and ask.
4
+
5
+ **Requires `@suppa/sdk` 1.38.0.** The doc is explicit: "`@CustomFields` and the declarative sets land in 1.38.0. Older SDKs have no way to describe custom fields from an application." Below that floor there is no code route at all — use the API tools (`suppa_add_custom_field`, `suppa_apply_custom_fields`) against the tenant instead. Check the floor before you write the class; a decorator that does not exist in the installed SDK fails at import, not at migration time.
6
+
7
+ ## What they are
8
+
9
+ > Custom fields are the extra fields a workspace shows **per context** — the fields a task of category `design` has and a task of category `support` does not. The platform keeps them in a generated extension table `{Entity}CustomFields`: one row per owner record, one real typed column per field. **Field sets** describe where each field applies.
10
+
11
+ This is the distinction that decides whether a field belongs here at all: **a field every record of the entity shows is an ordinary column** and belongs in the entity class. Only a field whose presence depends on another field's value is a custom field.
12
+
13
+ ## The declaration
14
+
15
+ > An application declares them the way a Nest controller declares a nested body: a class holds the fields, and the owner entity carries that class on a `customFields` property.
16
+
17
+ ```ts
18
+ import {
19
+ Column,
20
+ CustomFields,
21
+ Entity,
22
+ FieldTypeEnum,
23
+ SystemBaseEntity,
24
+ } from '@suppa/sdk';
25
+
26
+ export class TasksCustomFields {
27
+ @Column({
28
+ type: FieldTypeEnum.Numeric,
29
+ nullable: true,
30
+ title: { en: 'Budget', uk: 'Бюджет' },
31
+ options: {
32
+ customFieldSets: [
33
+ { contextField: 'category', contextValue: 'design' },
34
+ ],
35
+ },
36
+ })
37
+ cfBudget?: number;
38
+ }
39
+
40
+ @Entity({ name: 'Tasks', importKeyFields: ['shortUID'] })
41
+ export class Tasks extends SystemBaseEntity {
42
+ @Column({ name: 'title', type: FieldTypeEnum.Text, nullable: false })
43
+ title: string;
44
+
45
+ @Column({ name: 'category', type: FieldTypeEnum.Text })
46
+ category?: string;
47
+
48
+ @CustomFields(() => TasksCustomFields)
49
+ customFields?: TasksCustomFields;
50
+ }
51
+ ```
52
+
53
+ Three things follow from that one declaration:
54
+
55
+ | What | How |
56
+ |---|---|
57
+ | The feature is switched on for `Tasks` | "The `@CustomFields` property implies `options: { customFields: true }`" |
58
+ | `TasksCustomFields` becomes the columns of the `TasksCustomFields` table | The nested class is applied to the platform-generated extension table |
59
+ | Where each field applies | `options.customFieldSets` on the column |
60
+
61
+ > And because the property is typed, `customFields.cfBudget` is a real type everywhere the record is read or written.
62
+
63
+ **Do not write `options: { customFields: true }` next to `@CustomFields`.** The decorator implies it, and an option written at a value something else already sets is the same mistake as writing one at its default (rule 16).
64
+
65
+ ## The nested class is NOT an entity
66
+
67
+ > Register **only the owner** in `EntityModule.forFeature()`. The nested class is not an entity, has no `@Entity()`, does not extend `SystemBaseEntity` and is never registered — it is reached through the owner's property.
68
+
69
+ ```ts
70
+ EntityModule.forFeature([Tasks], { seeds: [] });
71
+ ```
72
+
73
+ This is the one place where the skill's usual reflex is wrong. Rule 19 says a class that names a table gets `@Entity()` and registration; rule 21 says a class that never reaches `forFeature()` does not exist. **Neither applies to the nested class** — it names no table of its own, and registering it would make the platform build a plain table where the generated extension table belongs:
74
+
75
+ > Only the **columns** are applied — no entity row is ever written for `{Entity}CustomFields`. The generated table carries the `owner` relation and the back reference; writing an entity row of your own would replace it with a plain table and break every custom-field read and write.
76
+
77
+ What the platform creates for you on start: "a unique `owner` relation back to `Tasks`, the standard columns, and a `customFields` back reference on the owner. Re-running is a no-op, and disabling the option later never drops the table or the values in it."
78
+
79
+ ## Two names that are not yours to choose
80
+
81
+ | Rule | Why |
82
+ |---|---|
83
+ | "The table is named after the **owner**, never after the class." | `@CustomFields(() => Whatever)` on `Tasks` always applies to `TasksCustomFields`. |
84
+ | "The property must be named `customFields`, and one class serves one owner." | "That is the name the platform gives the back reference; both rules fail the build loudly." |
85
+
86
+ ## The fields
87
+
88
+ > Every property of the nested class is one custom field, declared with the same decorators as any other field — `@Column()`, `@ManyToOne()`, `@ManyToMany()`, `@Enum()`, `@MultiEnum()`, `@File()`, `@MultiFile()`
89
+
90
+ ```ts
91
+ export class ServiceProductsCustomFields {
92
+ @Column({
93
+ name: 'articleCode',
94
+ type: FieldTypeEnum.Text,
95
+ nullable: true,
96
+ title: { en: 'Article code' },
97
+ })
98
+ articleCode?: string;
99
+
100
+ @ManyToOne(() => Compressors, {
101
+ name: 'compressor',
102
+ nullable: true,
103
+ title: { en: 'Compressor', uk: 'Компресор' },
104
+ })
105
+ compressor?: Compressors;
106
+ }
107
+ ```
108
+
109
+ Restrictions, and they are the **extension-mode restrictions** — the generated table is not this application's to reshape:
110
+
111
+ > `nullable: false` needs a `default`; `primary`, `@OneToMany()` and `@ManyToManyBackRef()` are rejected.
112
+
113
+ Every other house rule still binds inside the nested class: relation properties carry their type (rule 14), no option at its default (rule 16), a local enum takes no global name (rule 17), a relation target that already exists gets a stub (rule 19).
114
+
115
+ One default worth knowing rather than writing: "Columns default to `initiator: 'client'` — the marker of a *custom* field. Only a client field is reported as `isCustom` by the schema API and offered as a custom field by forms. Pass `initiator` explicitly only to opt out."
116
+
117
+ ## Where each field applies
118
+
119
+ > A set binds the owner entity to **one context value** — one field, one value, no compound conditions.
120
+
121
+ ```ts
122
+ @Column({
123
+ name: 'cfBudget',
124
+ type: FieldTypeEnum.Numeric,
125
+ nullable: true,
126
+ options: {
127
+ customFieldSets: [
128
+ { contextField: 'category', contextValue: 'design', required: true },
129
+ { contextField: 'category', contextValue: 'support' },
130
+ ],
131
+ },
132
+ })
133
+ cfBudget?: number;
134
+ ```
135
+
136
+ | Key | Meaning |
137
+ |---|---|
138
+ | `contextField` | "Name of the field **on the owner** whose value decides the context. It must exist on the owner." |
139
+ | `contextValue` | "The value that turns the set on" — resolved, see below |
140
+ | `required` | "The field must be filled on a record of this context. Default `false`." |
141
+ | `readOnly` | "Per-set override of the field's own `readOnly`. `null` (default) defers to the field." |
142
+ | `defaultValue` | "Per-set default. `null` (default) defers to the field." |
143
+
144
+ `contextValue` is written as a business key, not an id:
145
+
146
+ | Context field type | What `contextValue` may say | Resolved to |
147
+ |---|---|---|
148
+ | text / numeric / boolean | the value itself (`'design'`) | the value itself |
149
+ | `@Enum` / `@MultiEnum` | the stored enum value (`'Refrigeration equipment'`) | the id of that `Enums` row |
150
+ | `@ManyToOne` / `@ManyToMany` | the target's import key, its representative value, or the row id | the id of that row |
151
+
152
+ > That resolution is what makes a declaration portable: ids differ from workspace to workspace, business keys do not. A relation target with neither `importKeyFields` nor a representative field cannot be matched by name — declare the row id there, or give the entity an import key.
153
+
154
+ Sets are shared: "two fields declaring the same `(contextField, contextValue)` land in the same set, and a set a workspace administrator already created by hand is reused, not duplicated."
155
+
156
+ **A field with no set never shows up.** A column declared without `customFieldSets` "exists in the metadata (and in `GET /core/schema/Tasks` with an empty `setIds`) but no record shows it. That is a valid intermediate state — an administrator can create the sets in the workspace — but it is rarely what a migration wants."
157
+
158
+ ## An entity you do not own
159
+
160
+ > [Extension mode](./extensions.md) ignores entity-level options, so an application cannot switch the feature on for an entity that belongs to the platform, to another application, or to the workspace itself — the `@CustomFields` property still applies its columns, but the extension table has to exist. Enable the feature once per workspace through the API (or ask an administrator to):
161
+
162
+ ```http
163
+ POST /core/builder/ServiceProducts/update-options
164
+ { "customFields": true }
165
+ ```
166
+
167
+ Read that carefully, because half of it is easy to miss: **the columns still come from your file.** Only the switch is out of reach. With the Suppa MCP server the same call is `suppa_update_entity_options(entity_name, options_json)`; it is a schema change (it creates the `{Entity}CustomFields` side table), so record it in the plan beside the code that depends on it. This is what W618 is telling you when it fires on `options` in an extension.
168
+
169
+ ## What happens on start
170
+
171
+ 1. "The owner entity converges — and the `customFields` option implied by the property creates `{Entity}CustomFields` with the `owner` relation if it does not exist yet."
172
+ 2. "The columns of the nested class are created on that table as client fields, with their titles."
173
+ 3. "`options.customFieldSets` is materialized: each set is found or created, each link is created or brought in line with the declaration."
174
+
175
+ > All three steps are idempotent, so restarts and redeploys converge instead of duplicating. Steps 2 and 3 run inside the write transaction: a context that cannot be resolved fails the migration instead of leaving half a declaration behind.
176
+
177
+ **First boot of a brand-new owner.** "When the owner entity, the option and the custom fields all arrive in the very same first import, the column of a custom field can lose a race against the DDL that creates the extension table (`deadlock detected`). The next start applies it — nothing is lost and nothing needs fixing by hand, but do not read that first-boot error as a broken declaration."
178
+
179
+ ## Reading and writing values
180
+
181
+ Values ride the owner record under the same `customFields` key:
182
+
183
+ ```ts
184
+ await manager.insertOne('Tasks', {
185
+ title: 'Landing page',
186
+ category: 'design',
187
+ customFields: { cfBudget: 500 },
188
+ });
189
+
190
+ const [task] = await manager.select('Tasks', {
191
+ fields: { id: true, customFields: { cfBudget: true } },
192
+ conditions: {
193
+ operator: 'and',
194
+ filters: [
195
+ { field: 'customFields.cfBudget', comparator: '>', value: 100 },
196
+ ],
197
+ },
198
+ });
199
+ ```
200
+
201
+ > Only the keys present in `customFields` are written; the write guard rejects a value whose field is not in a set active for that record, and enforces `required`.
202
+
203
+ ## Limits worth knowing
204
+
205
+ - **"A link is never removed automatically."** Dropping a `customFieldSets` entry stops the platform re-creating it, "but the existing link stays — a workspace may have curated it. Remove it in the workspace (or through `CustomFieldSetFields`) when you mean it."
206
+ - **"Removing a property follows the normal rules."** It soft-deletes the field and renames the column; re-declaring restores the row with its data. "A field a workspace administrator removed is not resurrected by the next start."
207
+ - **"A field a user created through the UI is not a collision."** The declaration takes it over, keeping the column and the data.
208
+ - **"The per-table custom field cap guards the API, not migrations."** A declaration can push a table past it; watch the column count.
209
+
210
+ ## Porting a list of existing custom fields
211
+
212
+ > Turn it into one nested class per owner entity, one property per field, with the contexts of that field in `options.customFieldSets` — and keep the source file in the repository next to it: the class is the migration, the dump is the provenance.
213
+
214
+ For a large port the platform ships a generator rather than asking you to type it: `scripts/custom-fields-json-to-class.ts` in the `modern-expo` application (git.modern-expo.com/suppa/applications/modern-expo) turns a `{ entity, context_field, fields[] }` dump into the class and "reports the fields that still need a decision (enum value lists, unresolved relation targets)".
215
+
216
+ That dump shape is exactly the declaration `suppa_apply_custom_fields` reads, so a file written for the MCP tool ports to the decorator without being retyped — and vice versa.
217
+
218
+ ## Which route to take
219
+
220
+ | Situation | Route |
221
+ |---|---|
222
+ | You ship an application and the SDK is ≥ 1.38.0 | The decorator. The platform converges every tenant on start and the property is typed. |
223
+ | SDK below 1.38.0 | `suppa_add_custom_field` / `suppa_apply_custom_fields` against the tenant. |
224
+ | No application is deployed to this tenant | The API tools. |
225
+ | The owner belongs to another application | Both: the columns come from your file, but the option is enabled once through `suppa_update_entity_options`. |
@@ -1704,10 +1704,12 @@ function checkExtension(ts, info, findings) {
1704
1704
  // gap in the tooling — say so here rather than leaving them to guess.
1705
1705
  (opt === "options"
1706
1706
  ? `. If you need an option ENABLED on an entity you do not own — customFields, comments, ` +
1707
- `trackChangeHistory — that is an owner action and cannot come from a file: call ` +
1707
+ `trackChangeHistory — SWITCHING IT ON is an owner action and cannot come from a file: call ` +
1708
1708
  `suppa_update_entity_options(entity_name, options_json) once. It is a schema change ` +
1709
1709
  `(enabling customFields creates the {Entity}CustomFields side table), so record it in the ` +
1710
- `plan beside the code that depends on it`
1710
+ `plan beside the code that depends on it. Note what does NOT move out of the file: with ` +
1711
+ `@suppa/sdk 1.38.0+ the custom-field COLUMNS still come from your @CustomFields class — ` +
1712
+ `extension mode applies them, it only ignores the option that switches the feature on`
1711
1713
  : "")));
1712
1714
  }
1713
1715