suppa-mcp-2 1.6.0 → 1.7.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
@@ -339,8 +339,18 @@ when resolvable, falling back to the doc tables otherwise
339
339
  spread or by reference can't be statically checked and fire a W606 warning
340
340
  instead. An entity or seed left out of `EntityModule.forFeature()` fires
341
341
  E301/E302, naming the module file to edit so the fix is a find-and-add, not a
342
- search. Exit code 1 on any error. Use the `write_entity_code` MCP prompt to
343
- drive it from any client.
342
+ search. Use the `write_entity_code` MCP prompt to drive it from any client.
343
+
344
+ It also enforces the four **authoring rules** the platform doc does not: a
345
+ relation property must carry a TypeScript type that agrees with its decorator
346
+ (E114/E115/W610; a type naming no class, such as `any`, is the advisory W615),
347
+ enum member keys are PascalCase (W611), no field option
348
+ may be written at its platform default (W612), and `@Enum`/`@MultiEnum` take a
349
+ global name only when the enum is actually shared (W613). These are **rule
350
+ violations**: like errors, they exit 1, because a rule that only warns is a rule
351
+ that gets ignored. `--no-strict` demotes them to warnings for a legacy repo.
352
+ Advisory warnings — W601-W606, W608, W614, W615 — never block; they report what
353
+ the checker could not see.
344
354
 
345
355
  Tabular parts (owned child sub-tables like checklist items or order lines)
346
356
  and the remove-and-re-add-a-field semantics — a re-added field restores its
package/dist/server.js CHANGED
@@ -269,7 +269,7 @@ ATTACHMENTS (files on a record)
269
269
  - A record can carry files only if its entity has a 'file' or 'multi-file' field; check with suppa_describe_entity and add one with suppa_add_field if it has none.
270
270
  - WRITE: suppa_attach_file_to_record(entity, record_id, absolute_path) uploads from the local disk and returns file_ids — keep them, they are the only handle that gets the bytes back.
271
271
  - READ: suppa_list_record_files(entity, record_id) lists fileName/size/mimeType/paths for one record. It does NOT return ids; get those from the attach response, or with suppa_search_records on the 'Files' entity.
272
- - GET THE BYTES: suppa_download_file(file_id, absolute_dest_path) writes one file to disk — file_type='file' (original), 'preview' or 'pdf'. suppa_download_files_zip(file_ids, dest) fetches several as one archive. Nothing is overwritten unless overwrite=true.
272
+ - GET THE BYTES: suppa_download_file(file_id, absolute_dest_path) writes one file to disk — file_type='file' (original), 'preview' or 'pdf'. suppa_download_files_zip fetches several as one archive — by file_ids, or by entity_name + record_ids for everything attached to those records. Nothing is overwritten unless overwrite=true.
273
273
  - To duplicate a record's attachments onto a copy, use suppa_copy_record(copy_files=true) — there is no local path for a file that already lives on the platform.
274
274
 
275
275
  MIGRATION (Suppa 1.0 → 2.0)
@@ -305,7 +305,7 @@ export function buildServer() {
305
305
  // Reset so repeated buildServer() calls (e.g. in tests) do not double-count.
306
306
  TOOL_NAMES.length = 0;
307
307
  PROMPT_NAMES.length = 0;
308
- const server = new McpServer({ name: "suppa-2.0", version: "1.6.0" }, { instructions: INSTRUCTIONS });
308
+ const server = new McpServer({ name: "suppa-2.0", version: "1.6.1" }, { instructions: INSTRUCTIONS });
309
309
  const reg = (name, cfg, handler) => {
310
310
  server.registerTool(name, {
311
311
  description: cfg.description,
@@ -1108,13 +1108,17 @@ export function buildServer() {
1108
1108
  .string()
1109
1109
  .nullable()
1110
1110
  .default(null)
1111
- .describe('Field options as a JSON object, e.g. {"searchable": true, "searchPriority": 3, ' +
1112
- '"showInTable": true, "canSort": true}. Keys: searchable, searchPriority (1-4, ' +
1113
- "higher = stronger weight), readOnly, canGroup, canSort, showInTable, " +
1114
- "editFromTable, canFilter. WITHOUT these a new field does not appear in table " +
1115
- "views and free-text search (suppa_search_records search=...) cannot see it — " +
1116
- "only fields marked searchable participate. Unknown keys are refused here " +
1117
- "(the platform would silently drop them)."),
1111
+ .describe('Field options as a JSON object, e.g. {"searchable": true, "searchPriority": 3}. ' +
1112
+ "Keys: searchable, searchPriority (1-4, higher = stronger weight), readOnly, " +
1113
+ "canGroup, canSort, showInTable, editFromTable, canFilter. Pass ONLY the ones " +
1114
+ "that differ from the defaults the platform already applies — canGroup, canSort, " +
1115
+ "showInTable, editFromTable and canFilter are true; readOnly and searchable are " +
1116
+ "false (verified on a live tenant 2026-08-17; the Field Options table in " +
1117
+ "builder.txt:66-73 lists them as false, which the platform contradicts). So the " +
1118
+ "one usually worth passing is searchable (+searchPriority): free-text search " +
1119
+ "(suppa_search_records search=...) only covers fields marked searchable. " +
1120
+ "Restating a default changes nothing and buries the option that does. Unknown " +
1121
+ "keys are refused here (the platform would silently drop them)."),
1118
1122
  max_length: z
1119
1123
  .number()
1120
1124
  .int()
@@ -1167,11 +1171,12 @@ export function buildServer() {
1167
1171
  reg("suppa_update_field", {
1168
1172
  description: "Edit an EXISTING field of an entity (POST /core/builder/<entity>/<field>/update-field).\n" +
1169
1173
  " Send only what changes — everything is optional.\n\n" +
1170
- " Use it to fix a label, rename a field, flip required/unique, set a default, or —\n" +
1171
- " most often — turn on the field OPTIONS a field was created without:\n" +
1172
- " searchable / searchPriority (1-4) / readOnly / canGroup / canSort / showInTable /\n" +
1173
- " editFromTable / canFilter. A field with none of them is invisible in table views\n" +
1174
- " and cannot be found by free-text search.\n\n" +
1174
+ " Use it to fix a label, rename a field, flip required/unique, set a default, or\n" +
1175
+ " change the field OPTIONS: searchable / searchPriority (1-4) / readOnly / canGroup /\n" +
1176
+ " canSort / showInTable / editFromTable / canFilter. A field created without any of\n" +
1177
+ " them already has the platform defaults — visible, sortable, groupable, filterable,\n" +
1178
+ " editable, not read-only, NOT searchable — so the usual reason to come here is\n" +
1179
+ " searchable (+searchPriority), or turning one of the others OFF.\n\n" +
1175
1180
  " WHAT THE PLATFORM DOES NOT ALLOW (refused here BEFORE any request, so a rejected\n" +
1176
1181
  " call changes nothing):\n" +
1177
1182
  " - The TYPE of a field can never be changed ('Field type cannot be changed.') —\n" +
@@ -1240,10 +1245,13 @@ export function buildServer() {
1240
1245
  .string()
1241
1246
  .nullable()
1242
1247
  .default(null)
1243
- .describe('Field options as a JSON object, e.g. {"showInTable": true, "canFilter": true, ' +
1244
- '"searchable": true, "searchPriority": 3}. Keys: searchable, searchPriority ' +
1245
- "(1-4), readOnly, canGroup, canSort, showInTable, editFromTable, canFilter. " +
1246
- "Unknown keys are refused (the platform would drop them silently)."),
1248
+ .describe('Field options as a JSON object, e.g. {"searchable": true, "searchPriority": 3} ' +
1249
+ 'or {"showInTable": false}. Keys: searchable, searchPriority (1-4), readOnly, ' +
1250
+ "canGroup, canSort, showInTable, editFromTable, canFilter. Send only what " +
1251
+ "CHANGES — the platform already applies canGroup/canSort/showInTable/" +
1252
+ "editFromTable/canFilter true and readOnly/searchable false, so restating one " +
1253
+ "of those is a no-op. Unknown keys are refused (the platform would drop them " +
1254
+ "silently)."),
1247
1255
  confirm: Confirm,
1248
1256
  },
1249
1257
  annotations: _MUT,
@@ -1519,16 +1527,33 @@ export function buildServer() {
1519
1527
  annotations: _READ,
1520
1528
  }, async (a) => text(await files.downloadFile(a.file_id, a.dest_path, a.file_type, a.overwrite)));
1521
1529
  reg("suppa_download_files_zip", {
1522
- description: "Download several attached files at once as a ZIP archive.\n" +
1530
+ description: "Download several attachments at once as one ZIP archive.\n" +
1523
1531
  "\n" +
1524
- " file_ids are ids of rows in the 'Files' entity. dest_path must be ABSOLUTE;\n" +
1525
- " point it at a directory to keep the archive name the platform sends.\n" +
1532
+ " Two ways to choose what goes in, and exactly one of them at a time:\n" +
1533
+ " file_ids — those specific files\n" +
1534
+ " entity_name + record_ids — EVERY file attached to those records\n" +
1535
+ " file_ids are ids from the 'Files' entity, as returned by\n" +
1536
+ " suppa_list_record_files or suppa_attach_file_to_record.\n" +
1537
+ "\n" +
1538
+ " dest_path must be ABSOLUTE; point it at a directory and the archive is\n" +
1539
+ " named download.zip, since this endpoint sends no filename of its own.\n" +
1526
1540
  " Nothing is overwritten unless overwrite=true.\n",
1527
1541
  inputSchema: {
1528
1542
  file_ids: z
1529
1543
  .array(z.number().int())
1530
- .min(1)
1531
- .describe("Ids of the rows in the 'Files' entity to include."),
1544
+ .nullable()
1545
+ .default(null)
1546
+ .describe("Ids of rows in the 'Files' entity. Use this OR entity_name + record_ids."),
1547
+ entity_name: z
1548
+ .string()
1549
+ .nullable()
1550
+ .default(null)
1551
+ .describe("Entity whose records' attachments to fetch. Pair with record_ids."),
1552
+ record_ids: z
1553
+ .array(z.number().int())
1554
+ .nullable()
1555
+ .default(null)
1556
+ .describe("Record ids whose every attachment goes into the archive."),
1532
1557
  dest_path: z
1533
1558
  .string()
1534
1559
  .describe("Absolute path to write the .zip to — a file, or a directory."),
@@ -1538,7 +1563,7 @@ export function buildServer() {
1538
1563
  .describe("Allow replacing an existing archive at dest_path."),
1539
1564
  },
1540
1565
  annotations: _READ,
1541
- }, async (a) => text(await files.downloadFilesZip(a.file_ids, a.dest_path, a.overwrite)));
1566
+ }, async (a) => text(await files.downloadFilesZip(a.file_ids, a.dest_path, a.overwrite, a.entity_name, a.record_ids)));
1542
1567
  reg("suppa_attach_file_to_record", {
1543
1568
  description: "Attach a local file to a record (instance) of any entity.\n\n" +
1544
1569
  " Auto-detects the entity's file/attachment field from its schema; pass\n" +
@@ -2211,9 +2236,10 @@ export function buildServer() {
2211
2236
  "then suppa_add_field on the returned entity_name (the `owner` link is created for you).\n" +
2212
2237
  "4. Verify with suppa_describe_entity, and suppa_list_tabular_parts(parent) for any tabular parts.\n" +
2213
2238
  "5. Offer a form: suppa_create_form(generate_from_entity=true, entity_name=...). \n" +
2214
- "Pass options_json on each field the user should see or search — {\"showInTable\": true, \"canFilter\": true, " +
2215
- '"canSort": true} and {"searchable": true, "searchPriority": 3} on the ones worth finding by text; without ' +
2216
- "them the field is absent from table views and from free-text search.\n" +
2239
+ 'Pass options_json ONLY where a field departs from the defaults: {"searchable": true, "searchPriority": 3} ' +
2240
+ "on the ones worth finding by text (free-text search covers searchable fields only), or an option turned OFF. " +
2241
+ "A field created without options_json is already visible, sortable, groupable, filterable and editable — " +
2242
+ "restating those buries the one option that actually differs.\n" +
2217
2243
  "Fields cannot be REMOVED via this server (UI only) and a field's TYPE can never be changed — so get the types " +
2218
2244
  "right before creating; names, labels, flags and options can be corrected later with suppa_update_field.");
2219
2245
  regPrompt("migrate_from_v1", {
@@ -2252,7 +2278,14 @@ export function buildServer() {
2252
2278
  "representativeFieldName, and per-field nullable.\n" +
2253
2279
  "3. Write src/common/database/entities/*.entity.ts — @Entity class extending SystemBaseEntity; scalars via @Column({ type: FieldTypeEnum.X }); " +
2254
2280
  "relations via thunks (@ManyToOne(() => Target)) — pass the thunk and the options object only; do not add the optional inverse selector to @ManyToOne/@ManyToMany; " +
2255
- "fixed choices via @Enum('Entity.field', ...); attachments via @File/@MultiFile; " +
2281
+ "TYPE every relation property to match its decorator (@ManyToOne -> `owner: Target;`, or `owner?: Target` when the relation is nullable; " +
2282
+ "@ManyToMany/@OneToMany/@ManyToManyBackRef -> `peers: Target[];`) — an untyped relation is `any` to every caller. " +
2283
+ "Fixed choices via @Enum(StatusEnum, StatusTitles, { ... }) with PascalCase member keys (Active = 'active') and NO global name — " +
2284
+ "the decorator derives <ClassName>.<propertyName>; add the '<Entity>.<field>' first argument ONLY when the value set is shared across " +
2285
+ "entities or referenced from a seed record. Attachments via @File/@MultiFile; " +
2286
+ "NEVER write a field option that already holds its default — canGroup/canSort/showInTable/editFromTable/canFilter are true and " +
2287
+ "readOnly/searchable are false already, so declare one only where the field DEPARTS from that. If the repo's existing entities " +
2288
+ "restate those defaults on every field, do not copy that habit into the new file. " +
2256
2289
  "'default' is a SQL expression STRING ('false', \"'draft'\") — never a JS value. Repeating rows owned by one parent record " +
2257
2290
  "(checklist items, order lines) are a TABULAR PART, not a plain entity: type: 'tabular-part' + relationEntityName + a @ManyToOne " +
2258
2291
  "field named owner, with owner first in importKeyFields (see references/tabular-parts.md). " +
@@ -2263,6 +2296,7 @@ export function buildServer() {
2263
2296
  "5. Export the entity and seed from their barrels (entities/index.ts, seeds/index.ts), and add the seed to " +
2264
2297
  "EntityModule.forFeature()'s seeds array, positioned after the seeds of everything it references — dependencies first.\n" +
2265
2298
  "6. Gate before claiming done: node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root> " +
2299
+ "(strict by default — restated default options and unreferenced enum global names fail it, exit 1) " +
2266
2300
  "(or the skills/ dir of a checkout) reports 0 errors; npx tsc --noEmit passes; " +
2267
2301
  "push, reload (POST /core/applications/:appId/reload), verify with suppa_describe_entity — " +
2268
2302
  "the gate fails with E301 if anything is unregistered — run it, do not assume.\n" +
@@ -1226,8 +1226,10 @@ async function _relationPreflight(entityName, fieldName, relationType, relationE
1226
1226
  * ever invented.
1227
1227
  * options: the builder's Field Options object (builder.txt:60, keys :66-73) —
1228
1228
  * searchable / searchPriority / readOnly / canGroup / canSort / showInTable /
1229
- * editFromTable / canFilter. Omitting it leaves the field out of table views and
1230
- * out of free-text search (data.txt:218).
1229
+ * editFromTable / canFilter. Omitting it leaves the platform defaults in place —
1230
+ * visible, sortable, groupable, filterable, editable, not read-only, and NOT
1231
+ * searchable, so only free-text search is actually lost (data.txt:218). Pass a
1232
+ * key only where it departs from that; restating a default says nothing.
1231
1233
  * sub_type is checked against the documented matrix (migrations.txt:212-216)
1232
1234
  * before the request: timestamp takes 'date' | 'time' | 'timestamp', text takes
1233
1235
  * 'encrypted', enum/multi-enum have it set by the platform, and no other type
@@ -27,8 +27,8 @@ const MAX_LIMIT = 500;
27
27
  *
28
28
  * Body is {recordId, limit, offset} (files.txt:164-167; limit is REQUIRED).
29
29
  * The response rows carry fileName/filePath/pdfPath/previewPath/size/mimeType/
30
- * type (files.txt:176-183) — and, notably, NO id, while the download endpoint
31
- * is keyed on one. That gap is surfaced in the result rather than papered over.
30
+ * type (files.txt:176-183) plus an `id` the doc's table omits — see the note
31
+ * where the ids are collected.
32
32
  */
33
33
  export async function listRecordFiles(entityName, recordId, limit = 50, offset = 0) {
34
34
  const name = String(entityName ?? "").trim();
@@ -45,19 +45,29 @@ export async function listRecordFiles(entityName, recordId, limit = 50, offset =
45
45
  };
46
46
  const result = await makeRequest("POST", `/api/core/files/${name}`, body);
47
47
  const rows = Array.isArray(result) ? result : [];
48
+ // The doc's response table (files.txt:176-183) lists no id, but the platform
49
+ // does return one — verified on modern-expo.dev.suppa.me, 2026-08-17, where
50
+ // every row came back with `id` alongside fileName/filePath/size/mimeType.
51
+ // That id is what suppa_download_file takes, so surface it rather than
52
+ // sending the caller off to the Files entity as the doc's shape would imply.
53
+ const ids = rows
54
+ .filter((r) => r !== null && typeof r === "object")
55
+ .map((r) => r.id)
56
+ .filter((id) => typeof id === "number");
48
57
  return jsonResponse({
49
58
  entity: name,
50
59
  record_id: body.recordId,
51
60
  count: rows.length,
61
+ file_ids: ids,
52
62
  files: rows,
53
- // Honest about the shape rather than inventing an id: the caller needs one
54
- // to download, and this endpoint does not return it.
55
- note: rows.length > 0
56
- ? "This endpoint returns no file id (files.txt:176-183), and suppa_download_file needs " +
57
- "one. Get ids from suppa_search_records on the 'Files' entity, or from the response of " +
58
- "suppa_attach_file_to_record, which returns success[].id."
59
- : "No files attached to this record — or the entity has no file field at all " +
60
- "(check with suppa_describe_entity).",
63
+ note: rows.length === 0
64
+ ? "No files attached to this record — or the entity has no file field at all " +
65
+ "(check with suppa_describe_entity)."
66
+ : ids.length === rows.length
67
+ ? "Pass any file_ids entry to suppa_download_file, or all of them to " +
68
+ "suppa_download_files_zip."
69
+ : "Some rows carry no id; for those, look the file up on the 'Files' entity with " +
70
+ "suppa_search_records to get one.",
61
71
  });
62
72
  }
63
73
  /** Where a download may be written, and under what name. */
@@ -145,35 +155,72 @@ export async function downloadFile(fileId, destPath, fileType = "file", overwrit
145
155
  return jsonResponse({ ...dest, bytes_received: res.bytes.length, not_written: true });
146
156
  }
147
157
  writeFileSync(dest.path, res.bytes);
148
- return jsonResponse({
158
+ const out = {
149
159
  file_id: id,
150
160
  file_type: fileType,
151
161
  saved_to: dest.path,
152
162
  bytes: res.bytes.length,
153
163
  content_type: res.contentType,
154
164
  suggested_name: suggested,
155
- });
165
+ };
166
+ if (fileType !== "file") {
167
+ // Verified on modern-expo.dev.suppa.me, 2026-08-17: asking for 'preview' or
168
+ // 'pdf' on a file that has neither returns the ORIGINAL bytes, byte for
169
+ // byte, with no error — so a caller can end up with a .pdf that is not a
170
+ // PDF. The row's pdfPath / previewPath is what says whether the variant
171
+ // exists at all.
172
+ out.caveat =
173
+ `A '${fileType}' variant is not generated for every file. When it does not exist the ` +
174
+ "platform returns the ORIGINAL bytes with no error, so check the file's " +
175
+ `${fileType === "pdf" ? "pdfPath" : "previewPath"} in suppa_list_record_files before ` +
176
+ "trusting the format.";
177
+ }
178
+ return jsonResponse(out);
156
179
  }
157
180
  /**
158
181
  * Several files at once, as a ZIP — POST core/files/download-all (files.txt:83).
159
182
  *
160
- * Body is {instanceIds: number[]} (files.txt:91) and the response is a zip
161
- * stream (files.txt:100).
183
+ * THE DOC'S BODY IS WRONG. files.txt:91 gives one required field,
184
+ * `instanceIds: number[]`, described as "List of file IDs (Files)". Sending
185
+ * exactly that is rejected — verified on modern-expo.dev.suppa.me, 2026-08-17:
186
+ *
187
+ * {"instanceIds":[2859,2860]}
188
+ * -> HTTP 400 validation.invalid_payload
189
+ * "Provide either fileIds or entityName with instanceIds"
190
+ *
191
+ * The endpoint takes one of two selections, both of which return a real zip
192
+ * (magic 50 4b 03 04), and neither of which sends Content-Type or
193
+ * Content-Disposition:
194
+ * {fileIds: [...]} — those files
195
+ * {entityName: "X", instanceIds: [...]} — every file of those RECORDS
196
+ * So `instanceIds` means RECORD ids, not file ids, and only alongside an
197
+ * entityName. Both modes are exposed here rather than picking one, because the
198
+ * second answers "give me everything attached to these records" in one call.
162
199
  */
163
- export async function downloadFilesZip(fileIds, destPath, overwrite = false) {
200
+ export async function downloadFilesZip(fileIds, destPath, overwrite = false, entityName = null, recordIds = null) {
164
201
  const ids = (fileIds ?? []).map((n) => Math.trunc(Number(n))).filter((n) => Number.isFinite(n));
165
- if (ids.length === 0) {
202
+ const records = (recordIds ?? []).map((n) => Math.trunc(Number(n))).filter((n) => Number.isFinite(n));
203
+ const entity = String(entityName ?? "").trim();
204
+ const byFile = ids.length > 0;
205
+ const byRecord = entity !== "" && records.length > 0;
206
+ if (byFile === byRecord) {
166
207
  return jsonResponse({
167
- error: "file_ids must hold at least one Files record id (files.txt:91 — instanceIds).",
208
+ error: byFile
209
+ ? "Pass EITHER file_ids OR entity_name + record_ids, not both — the platform accepts " +
210
+ "one selection at a time."
211
+ : "Nothing selected. Pass file_ids (ids from the 'Files' entity), or entity_name " +
212
+ "together with record_ids to get every file attached to those records.",
168
213
  });
169
214
  }
215
+ const body = byFile ? { fileIds: ids } : { entityName: entity, instanceIds: records };
170
216
  let res;
171
217
  try {
172
- res = await makeRequestBinary("POST", "/api/core/files/download-all", { instanceIds: ids });
218
+ res = await makeRequestBinary("POST", "/api/core/files/download-all", body);
173
219
  }
174
220
  catch (e) {
175
221
  return jsonResponse({
176
- error: `Download of ${ids.length} file(s) failed: ${e instanceof Error ? e.message : String(e)}`,
222
+ error: `Download failed: ${e instanceof Error ? e.message : String(e)}`,
223
+ sent: body,
177
224
  });
178
225
  }
179
226
  const suggested = filenameFromDisposition(res.contentDisposition) ?? "download.zip";
@@ -183,7 +230,7 @@ export async function downloadFilesZip(fileIds, destPath, overwrite = false) {
183
230
  }
184
231
  writeFileSync(dest.path, res.bytes);
185
232
  return jsonResponse({
186
- file_ids: ids,
233
+ selection: byFile ? { file_ids: ids } : { entity: entity, record_ids: records },
187
234
  saved_to: dest.path,
188
235
  bytes: res.bytes.length,
189
236
  content_type: res.contentType,
@@ -549,7 +549,21 @@ export async function readV1Enum(enumInput) {
549
549
  // all primitives, localized text/json, custom fields, enums (single + multi),
550
550
  // relations (FK + many-to-many), file attachments (single + multi), and legacy
551
551
  // shapes (Number, polymorphic relations, TSVector/Object/List system columns).
552
- /** Stable enum bucket name for a migrated enum field (avoids cross-entity clashes). */
552
+ /**
553
+ * Stable enum bucket name for a migrated enum field (avoids cross-entity clashes).
554
+ *
555
+ * NOTE the separator: this is `Entity_field`, while everything on the CODE path
556
+ * uses `Entity.field` — the name @Enum()/@MultiEnum() derive from
557
+ * <ClassName>.<propertyName>, and the convention the tool descriptions teach.
558
+ * So an enum created by this migrator is NOT the one an entity class would bind
559
+ * to by default: code written later against a migrated tenant has to pass the
560
+ * underscore name explicitly as @Enum's first argument.
561
+ *
562
+ * Left as-is deliberately. Changing the separator would not rename the enums
563
+ * already created in migrated tenants — a re-run would create dot-named
564
+ * duplicates beside them and leave every previously migrated field bound to the
565
+ * old bucket. Aligning the two is a data-migration decision, not a rename.
566
+ */
553
567
  function _enumNameFor(entityName, fieldName) {
554
568
  return `${entityName}_${fieldName}`;
555
569
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.6.0",
3
+ "version": "1.7.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": {
@@ -54,8 +54,11 @@ Confirm all 5 before writing anything:
54
54
  13. `subType` is **immutable after creation**, with one exception: toggling `'encrypted'` on or off. The Builder API answers `Field subType cannot be changed.` to anything else — so choosing `Timestamp` where you needed `subType: 'date'` is not a conversion you can ship later, it is a NEW field plus a removal of the old one (see `references/registration.md` for what removal leaves behind). Get date-vs-timestamp right the first time. To CLEAR a subtype you must write `subType: null` explicitly — deleting the line does nothing, because an omitted key is dropped from the sync payload and the stored subtype survives.
55
55
  14. **Every relation property carries its TypeScript type, and the type says what the decorator says.** `@ManyToOne` holds ONE row — `owner: ProductMatrixEntity;` — while `@ManyToMany`, `@OneToMany` and `@ManyToManyBackRef` hold many — `envs: ApplicationEnvsEntity[];`. Type it optional (`owner?: Target`) unless the relation is `nullable: false`. An untyped relation property is `any` to every consumer of the entity. E114/E115/W610.
56
56
  15. **Enum member keys are PascalCase** — `NotFilled = 'Not filled'`. The key is the identifier the code reads; the string on the right is what the platform stores, and the two need not match. W611.
57
- 16. **Never write an option that already holds its default value.** The platform applies `canGroup: true`, `canSort: true`, `showInTable: true`, `editFromTable: true`, `canFilter: true`, `readOnly: false`, `searchable: false` on its own. Declare one of these ONLY where the field departs from it; repeating defaults on every field buries the one option that actually differs. W612.
58
- 17. **`@Enum`/`@MultiEnum` take the global name only when the enum is global.** Default is local: `@Enum(StageStatusEnum, StageStatus, { nullable: false })` — the decorator derives `<ClassName>.<propertyName>`. Pass the name as the FIRST argument only when the value set is shared across entities or referenced from a seed: `@Enum('StageWorkflows.status', StageStatusEnum, StageStatus, { … })`. W613.
57
+ 16. **Never write an option that already holds its default value.** The platform applies `canGroup: true`, `canSort: true`, `showInTable: true`, `editFromTable: true`, `canFilter: true`, `readOnly: false`, `searchable: false` on its own. Declare one of these ONLY where the field departs from it; repeating defaults on every field buries the one option that actually differs. W612, and it fails the gate.
58
+ **This rule outranks the surrounding code.** An existing app repo very often has entities that restate all seven on every field — that is the habit this rule exists to stop, not a local convention to match. Write the new file clean; leave the old ones alone unless asked. The same goes for the platform's captured API docs: `api-entity-builder-builder.txt:66-73` lists these defaults as `false`, which live tenants contradict — a field created with no options comes back visible, sortable, groupable, filterable and editable.
59
+ 17. **`@Enum`/`@MultiEnum` take the global name only when the enum is global.** Default is local: `@Enum(StageStatusEnum, StageStatus, { nullable: false })` — the decorator derives `<ClassName>.<propertyName>`. Pass the name as the FIRST argument only when the value set is shared across entities or referenced from a seed: `@Enum('StageWorkflows.status', StageStatusEnum, StageStatus, { … })`. W613, and it fails the gate.
60
+ **This rule overrides the platform doc**, which says flatly "Give the enum a global name (first argument)" (migrations.html → `references/entities.md`) and passes one in every example. Follow the rule, not the example.
61
+ **A field's `key` is not a reference.** `key: '<Entity>.<field>'` on the same field is the rename key (rule 11) and is spelled exactly like a global enum name — it does not make the enum shared, and it is not what a seed resolves against.
59
62
  18. Repeating rows owned by one parent record are a **tabular part**, never a plain entity: `type: 'tabular-part'` + `relationEntityName` (the parent's `@Entity()` name) + a `@ManyToOne` field named exactly `owner` pointing at the parent class — all three required, the platform infers none of them. Put `owner` FIRST in `importKeyFields` — it scopes the business key to the parent, or rows collide across different parents.
60
63
  19. **`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.
61
64
 
@@ -218,7 +221,11 @@ If that prints nothing, the entity is not registered.
218
221
 
219
222
  Step 1 exists to catch exactly this: an unregistered class is E301 and the gate fails. Never report done on an unrun gate.
220
223
 
221
- `validate-suppa-schema.mjs` exits `0` on a clean run, `1` when errors are found, `2` on a usage error or a missing path. The gate requires exit `0` — warnings alone do not block.
224
+ `validate-suppa-schema.mjs` exits `0` on a clean run, `1` on violations, `2` on a usage error or a missing path. The gate requires exit `0`.
225
+
226
+ **Two classes of finding block it.** Errors (`E…`) always do. So do the *rule violations* — `W607`, `W609`, `W610`, `W611`, `W612`, `W613` — because each names one line that the hard rules above say must be written differently, and a rule that only warns is a rule that gets ignored (that is exactly how an entity shipped with seven restated defaults on every field). Advisory warnings — `W601`-`W606`, `W608`, `W614`, `W615` — describe what the checker could not see and never block.
227
+
228
+ `--no-strict` demotes the rule violations back to warnings. It exists for a legacy repo you are not cleaning up in this pass; it is not for making your own new file pass. `W613` argues from absence ("nothing references this name"), so it only blocks when the validator was pointed at a DIRECTORY and walked the whole repo — on an explicit file list the referencing seed may simply be outside the set.
222
229
 
223
230
  The validator parses with the TypeScript compiler API, read from the app repo you point it at (a Suppa application compiles with `tsc`, so it has one). If it reports `cannot resolve 'typescript'`, run `npm install` in that repo — or `npm i -D typescript@5` if it genuinely has none. Pin the major: plain `typescript` now installs 7.x, whose main entry exports only version info and carries no compiler API.
224
231
 
@@ -238,11 +245,13 @@ The validator parses with the TypeScript compiler API, read from the app repo yo
238
245
  | `default` value is rejected | A JavaScript value was passed instead of a SQL expression string | E103 |
239
246
  | Generated relation has an inverse selector that fails to typecheck | An `inverse` was passed to `@ManyToOne`/`@ManyToMany`, where it's optional and usually omitted | W609/E111 — drop the selector, write `@ManyToOne(() => Target, { … })` |
240
247
  | A relation reads as `any`; nothing catches using it as the wrong shape | The property has no TypeScript type | E114 — write `owner: Target;` (`Target[]` for the to-many decorators) |
248
+ | A relation is typed `any` (or a union), so callers get nothing | An annotation that names no class — E114 does not fire, because there IS one | W615 — write the target class; platform entities such as `IconsEntity` are importable from `@suppa/sdk` |
241
249
  | A to-many relation is used as a single record (or the reverse) | The property's type contradicts the decorator's arity, or names a different class than the thunk | E115 — `@ManyToOne` → `Target`; `@ManyToMany`/`@OneToMany`/`@ManyToManyBackRef` → `Target[]` |
242
250
  | Callers never null-check a relation that can be empty | A nullable `@ManyToOne` is typed as always present (or a `nullable: false` one as optional) | W610 — `owner?: Target` when nullable, `owner: Target` when `nullable: false` |
243
251
  | Enum members read as data rather than identifiers | Member keys are not PascalCase | W611 — `NotFilled = 'Not filled'` |
244
- | Every field repeats the same five option lines | Options were written at their default values | W612 — delete them; declare an option only where it departs from the default |
245
- | An enum name is invented for a field nothing else references | The optional global name was passed to `@Enum`/`@MultiEnum` when the enum is local | W613 — omit the first argument; the decorator derives `<ClassName>.<propertyName>` |
252
+ | Every field repeats the same seven option lines | Options were written at their default values — often copied from the repo's older entities | W612 (blocks the gate) — delete them; declare an option only where it departs from the default |
253
+ | An enum name is invented for a field nothing else references | The optional global name was passed to `@Enum`/`@MultiEnum` when the enum is local | W613 (blocks the gate on a whole-repo run) — omit the first argument; the decorator derives `<ClassName>.<propertyName>` |
254
+ | An unreferenced enum global name passes the gate | The field also carries `key: '<Entity>.<field>'`; before 1.7.0 that identical literal counted as a reference and silenced W613 | fixed in 1.7.0 — a field's own `key`/`subType` is no longer a reference |
246
255
  | Migration rejects the column, or a date field ships as a full `timestamp` | The `(type, subType)` pair isn't one the doc allows — `Timestamp` takes `'date'`/`'time'`/`'timestamp'`, `Text` takes `'encrypted'`, nothing else | E112 |
247
256
  | `Encrypted subtype is only allowed on text fields` | `subType: 'encrypted'` on a non-Text column | E112 |
248
257
  | An enum field resolves to the wrong enum, or its values fail to insert | `subType` was written by hand on `@Enum`/`@MultiEnum` instead of being left to the decorator | E113 |
@@ -232,7 +232,7 @@ For an enum field, `subType` holds the enum's **global name** — the value that
232
232
  status: StageStatusEnum; // subType = 'StageWorkflows.status'
233
233
  ```
234
234
 
235
- Called without an explicit global name, the SDK derives `<ClassName>.<propertyName>`. Either way, do not pass `subType` yourself on an enum field.
235
+ Called without an explicit global name, the SDK derives `<ClassName>.<propertyName>` — so the field above, written `@Enum(StageStatusEnum, StageStatus, { nullable: false })` on class `StageWorkflows`, resolves to the same `subType`. That derived form is the one to write unless the enum is genuinely shared (see Enums below). Either way, do not pass `subType` yourself on an enum field.
236
236
 
237
237
  ### Changing a Subtype
238
238
 
@@ -272,6 +272,9 @@ export class StageWorkflows extends SystemBaseEntity {
272
272
  }
273
273
  ```
274
274
 
275
+ > **HOUSE RULE — the doc's `icon: any` is not the shape to copy (SKILL.md rule 14).**
276
+ > `any` names no class, so it tells callers nothing and the arity check cannot run (W615). `IconsEntity` is importable from the SDK, as the note below says — write `icon?: IconsEntity`. The `?` follows from the relation being nullable: this `@ManyToOne` sets no `nullable: false`, and the doc's `workflow: Workflows` above is right to omit it only because that one does.
277
+
275
278
  | Decorator | Signature | Use |
276
279
  |---|---|---|
277
280
  | @ManyToOne | (target, options?) or (target, inverse, options?) | Foreign key on this entity. |
@@ -285,7 +288,21 @@ Platform entities are importable from the SDK when you need to point at them —
285
288
 
286
289
  ## Enums
287
290
 
288
- @Enum and @MultiEnum accept a TypeScript enum with string values. Give the enum a global name (first argument) so it can be referenced from seeds and shared across entities:
291
+ @Enum and @MultiEnum accept a TypeScript enum with string values. The doc's own sentence here is *"Give the enum a global name (first argument) so it can be referenced from seeds and shared across entities"*, and every example in it passes one.
292
+
293
+ > **HOUSE RULE — overrides the sentence above (SKILL.md rule 17).**
294
+ > Pass the global name **only when the enum really is global**: shared by more than one entity, or referenced from a seed record (`{ name: 'StageWorkflows.status', value: 'active' }`). Otherwise omit the first argument and let the SDK derive `<ClassName>.<propertyName>`. A name that nothing references is a name that should not be there — W613, and it fails the close-out gate.
295
+ >
296
+ > Careful with `key`: a field conventionally carries `key: '<Entity>.<field>'`, spelled exactly like a global enum name. That is the **rename key**, an unrelated option — it is not a reference to the enum and does not make the enum global.
297
+
298
+ Local — the default, and what most enum fields should look like:
299
+
300
+ ```ts
301
+ @Enum(StageStatusEnum, StageStatus, { nullable: false })
302
+ status: StageStatusEnum; // subType resolves to 'StageWorkflows.status'
303
+ ```
304
+
305
+ Global — the same field, once a seed or a second entity refers to the value set by name:
289
306
 
290
307
  ```ts
291
308
  export enum StageStatusEnum {
@@ -15,7 +15,7 @@ The API migration path and this code path share one authority: `classifyV1Field(
15
15
  | `uuid` | `@Column({ type: FieldTypeEnum.UUID })` |
16
16
  | `multi-language` | `@Column({ type: FieldTypeEnum.MultiLang })` |
17
17
  | `icon` | `@Column({ type: FieldTypeEnum.Icon })` — scalar by default; use `@ManyToOne(() => IconsEntity)` only when v1 reports a relation |
18
- | `enum` | `@Enum('<Entity>.<field>', <Field>Enum, <Field>Titles, { … })` + a TypeScript string enum built from `suppa_read_v1_enum` values + a seed is NOT needed (enum values live in the decorator maps) |
18
+ | `enum` | `@Enum(<Field>Enum, <Field>Titles, { … })` + a TypeScript string enum built from `suppa_read_v1_enum` values (member keys PascalCase) + a seed is NOT needed (enum values live in the decorator maps). A ported v1 enum belongs to one field, so **no global name**: add the `'<Entity>.<field>'` first argument only if a seed or a second entity references the value set by name (SKILL.md rule 17) |
19
19
  | `multi-enum` | `@MultiEnum(…)` — same signature as `@Enum` |
20
20
  | `file` | `@File({ title: … })` |
21
21
  | `multi-file` | `@MultiFile({ title: … })` |
@@ -91,10 +91,12 @@ export class Orders extends SystemBaseEntity {
91
91
  @Column({ name: 'name', type: FieldTypeEnum.Text })
92
92
  name: string;
93
93
 
94
- @Enum('Orders.status', StatusEnum, StatusTitles)
94
+ // No global name: nothing outside this field references the value set.
95
+ @Enum(StatusEnum, StatusTitles)
95
96
  status: StatusEnum;
96
97
 
98
+ // Nullable (no `nullable: false`), so the property is optional.
97
99
  @ManyToOne(() => Customers)
98
- customer: Customers;
100
+ customer?: Customers;
99
101
  }
100
102
  ```
@@ -7,8 +7,15 @@
7
7
  * (docs.modern-expo.com/backend/application-developing/migrations.html):
8
8
  * these mistakes compile under tsc and only fail at migration time.
9
9
  *
10
- * Usage: node validate-suppa-schema.mjs <app-root-or-files...>
10
+ * Usage: node validate-suppa-schema.mjs [--no-strict] <app-root-or-files...>
11
11
  * Import: import { validateSchema } from "./validate-suppa-schema.mjs"
12
+ *
13
+ * Exit codes: 0 clean, 1 violations found, 2 usage/toolchain problem.
14
+ * By DEFAULT the authoring-rule warnings in RULE_WARNINGS block the run too —
15
+ * they are the house rules, and a rule that only warns is a rule that gets
16
+ * ignored (which is exactly how a generated entity ended up restating seven
17
+ * default options on every field). `--no-strict` downgrades them back to
18
+ * advisory, for a legacy repo you are not cleaning up in this pass.
12
19
  */
13
20
  import { createRequire } from "node:module";
14
21
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
@@ -33,6 +40,33 @@ export const DEFAULT_FIELD_OPTIONS = {
33
40
  readOnly: false,
34
41
  searchable: false,
35
42
  };
43
+ /**
44
+ * Warnings that are DETERMINISTIC violations of a stated authoring rule, not
45
+ * heuristics: each one names a concrete line of code that the rules say must be
46
+ * written differently, and each has a mechanical fix. These block the gate by
47
+ * default (see `--no-strict`), because the four house rules kept being violated
48
+ * for exactly one reason — they were warnings, and the gate only failed on
49
+ * errors.
50
+ *
51
+ * Deliberately NOT in this set: W601-W606 (heuristics and "cannot verify from
52
+ * the AST"), W608 (no tsconfig at the given root — an input problem), W614
53
+ * (membership unknown, so a check was skipped). Those describe what the checker
54
+ * could not see; they do not name a line that is wrong.
55
+ */
56
+ export const RULE_WARNINGS = [
57
+ "W607", // tabular part: `owner` present in importKeyFields but not first
58
+ "W609", // inverse selector passed where it is optional (@ManyToOne/@ManyToMany)
59
+ "W610", // relation typed optional/non-optional against its own `nullable`
60
+ "W611", // enum member key is not PascalCase
61
+ "W612", // field option written at its platform default
62
+ "W613", // enum global name passed for an enum nothing references
63
+ ];
64
+ /**
65
+ * W613 argues from ABSENCE — "nothing references this name". That only holds
66
+ * when the whole repo was analyzed; on an explicit file list the referencing
67
+ * seed may simply not be in the set, so it must not block.
68
+ */
69
+ export const RULE_WARNINGS_NEEDING_WHOLE_REPO = ["W613"];
36
70
  export const DOC_COLUMN_OPTIONS = ["type", "subType", "name", "nullable", "primary", "unique", "default", "length", "title", "comment", "key", "minLength", "minValue", "maxValue", "decimalPlaces", "isOnlyPositive", "mask",
37
71
  // Field options. The decorator tables do not list them, but migrations.txt:245
38
72
  // names four of them as options a column carries — encryption makes "the
@@ -184,8 +218,15 @@ function objectMap(ts, node) {
184
218
  if (!node || !ts.isObjectLiteralExpression(node)) return map;
185
219
  for (const p of node.properties) {
186
220
  if (ts.isPropertyAssignment(p)) {
187
- const name =
221
+ let name =
188
222
  ts.isIdentifier(p.name) || ts.isStringLiteral(p.name) ? p.name.text : null;
223
+ // A computed key whose expression is a literal is the same key written
224
+ // differently — `{ ['canGroup']: true }`. Dropping it made a computed key
225
+ // a blanket opt-out of EVERY option rule (W612, E501/E502, E103, E112,
226
+ // E113 all read through this function), silently.
227
+ if (name === null && ts.isComputedPropertyName(p.name)) {
228
+ name = stringValue(ts, unwrapExpr(ts, p.name.expression));
229
+ }
189
230
  if (name !== null) map.set(name, p.initializer);
190
231
  } else if (ts.isShorthandPropertyAssignment(p)) {
191
232
  map.set(p.name.text, p.name);
@@ -475,9 +516,14 @@ function analyzeEntities(ts, sf, model) {
475
516
  enumOptions: objectMap(ts, enumOptionsNode),
476
517
  });
477
518
  } else if (FILE_DECORATORS.has(d.name)) {
519
+ // @File/@MultiFile take an options object too (the template writes
520
+ // `@File({ title })`), and without optionsNode the default-option
521
+ // rule could never see an attachment field.
478
522
  info.properties.set(propName, {
479
523
  kind: d.name === "File" ? "file" : "multi-file",
480
524
  node: member, decorator: d,
525
+ optionsNode: d.args[0] ?? null,
526
+ nameNode: objectMap(ts, d.args[0]).get("name") ?? null,
481
527
  });
482
528
  } else if (d.name in RELATION_KIND_BY_DECORATOR) {
483
529
  // (target, options?) or (target, inverse, options?) — the options
@@ -496,6 +542,15 @@ function analyzeEntities(ts, sf, model) {
496
542
  inverseNode,
497
543
  relOptions,
498
544
  optionsNode: [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)) ?? null,
545
+ // The options SLOT, whatever sits in it — the last argument that
546
+ // is not the thunk and not an inverse selector. `optionsNode`
547
+ // above keeps only object literals, so on `@ManyToOne(() => T,
548
+ // OPTS)` it is null, which reads as "no options given" and is
549
+ // how an unreadable `nullable` was mistaken for `nullable: true`.
550
+ rawOptionsNode:
551
+ d.args.length > 1 && !isFunctionLike(ts, d.args[d.args.length - 1])
552
+ ? d.args[d.args.length - 1]
553
+ : null,
499
554
  typeInfo: propertyTypeInfo(ts, member),
500
555
  });
501
556
  }
@@ -710,7 +765,24 @@ function checkRelationTyping(ts, sf, propName, prop, findings) {
710
765
  ` an untyped relation property is 'any' to every consumer of this entity`));
711
766
  return;
712
767
  }
713
- if (info.name === null) return; // a shape this AST-only checker cannot read
768
+ // A type node exists but names no class: `any`, `unknown[]`, a union, a
769
+ // nested array. E114 does not cover it (there IS an annotation) and the arity
770
+ // checks below cannot run — which used to mean `owner: any` slipped through in
771
+ // total silence, the very hole E114 exists to close. Arity is still decidable
772
+ // from the brackets, so check that much, then say what could not be read.
773
+ if (info.name === null) {
774
+ if (arity === "many" && !info.isArray) {
775
+ findings.push(finding(ts, sf, info.node, "E115",
776
+ `'${propName}' (@${prop.decorator.name}) holds MANY rows but is not typed as an array — write '${expected ?? "Target[]"}'`));
777
+ } else if (arity === "one" && info.isArray) {
778
+ findings.push(finding(ts, sf, info.node, "E115",
779
+ `'${propName}' (@ManyToOne) holds ONE row but is typed as an array — write '${expected ?? "Target"}'. The many side is @OneToMany on the other class.`));
780
+ } else {
781
+ findings.push(finding(ts, sf, info.node, "W615",
782
+ `relation '${propName}' (@${prop.decorator.name}) is typed with a shape that names no class ('any', 'unknown', a union, …) — it tells callers nothing and the arity check cannot run. Write '${expected ?? (arity === "many" ? "Target[]" : "Target")}'. Platform entities are importable from @suppa/sdk (e.g. IconsEntity) when the target is one of theirs.`));
783
+ }
784
+ return;
785
+ }
714
786
 
715
787
  if (target && info.name !== target) {
716
788
  findings.push(finding(ts, sf, info.node, "E115",
@@ -728,9 +800,20 @@ function checkRelationTyping(ts, sf, propName, prop, findings) {
728
800
  }
729
801
 
730
802
  // Optionality should agree with the column: a NOT NULL relation always has a
731
- // value, anything else may be absent.
732
- if (arity === "one") {
733
- const notNull = booleanValue(ts, prop.relOptions?.get("nullable")) === false;
803
+ // value, anything else may be absent. This reads `nullable` off the options,
804
+ // so it can only run when the options are actually readable — with options
805
+ // passed by reference or carrying a spread, an absent `nullable` is UNKNOWN,
806
+ // not false, and treating it as false made the checker demand a '?' on a NOT
807
+ // NULL relation. W610 blocks the gate, so that was a rule violation the gate
808
+ // itself would have forced you to commit.
809
+ const slot = prop.rawOptionsNode ? unwrapExpr(ts, prop.rawOptionsNode) : null;
810
+ const optionsReadable =
811
+ !slot || (ts.isObjectLiteralExpression(slot) && spreadElements(ts, slot).length === 0);
812
+ if (arity === "one" && !optionsReadable) {
813
+ findings.push(finding(ts, sf, prop.rawOptionsNode, "W606",
814
+ `'${propName}' receives its relation options by reference or through a spread, so 'nullable' cannot be read — the optionality check (W610) is skipped. Inline the options object to restore it.`));
815
+ } else if (arity === "one") {
816
+ const notNull = booleanValue(ts, unwrapExpr(ts, prop.relOptions?.get("nullable"))) === false;
734
817
  if (notNull && info.nullable) {
735
818
  findings.push(finding(ts, sf, info.node, "W610",
736
819
  `'${propName}' is declared nullable: false but typed as optional — drop the '?' (and any '| null'): the column always has a value`));
@@ -746,17 +829,29 @@ function checkRelationTyping(ts, sf, propName, prop, findings) {
746
829
  * field is noise that hides the options that DO differ.
747
830
  */
748
831
  function checkDefaultFieldOptions(ts, sf, propName, prop, findings) {
832
+ // An options object delivered by reference reads as empty here, so every
833
+ // option rule silently stopped applying to that field — no W612, and no
834
+ // E501/E502 either. Say so instead of falling quiet: this file's convention
835
+ // is that content it cannot read is W606, not silence.
836
+ if (prop.optionsNode && !ts.isObjectLiteralExpression(unwrapExpr(ts, prop.optionsNode))) {
837
+ findings.push(finding(ts, sf, prop.optionsNode, "W606",
838
+ `'${propName}' receives its options by reference, so they cannot be read statically — the default-option check (W612) and the unknown-option checks (E501/E502) are skipped for this field. Inline the options object to restore them.`));
839
+ return;
840
+ }
749
841
  const scopes = [];
750
- if (prop.optionsNode) scopes.push(prop.optionsNode);
842
+ if (prop.optionsNode) scopes.push(unwrapExpr(ts, prop.optionsNode));
751
843
  // …and a nested `options: { … }` object, whichever shape the SDK takes.
752
844
  for (const scope of [...scopes]) {
753
845
  const nested = objectMap(ts, scope).get("options");
754
- if (nested && ts.isObjectLiteralExpression(nested)) scopes.push(nested);
846
+ const unwrapped = nested && unwrapExpr(ts, nested);
847
+ if (unwrapped && ts.isObjectLiteralExpression(unwrapped)) scopes.push(unwrapped);
755
848
  }
756
849
  for (const scope of scopes) {
757
850
  for (const [key, valNode] of objectMap(ts, scope)) {
758
851
  if (!(key in DEFAULT_FIELD_OPTIONS)) continue;
759
- const value = booleanValue(ts, valNode);
852
+ // `(true)`, `true as boolean`, `true!` are the same literal; every other
853
+ // value read in this file unwraps first, and this one did not.
854
+ const value = booleanValue(ts, unwrapExpr(ts, valNode));
760
855
  if (value !== null && value === DEFAULT_FIELD_OPTIONS[key]) {
761
856
  findings.push(finding(ts, sf, valNode, "W612",
762
857
  `'${propName}' sets '${key}: ${value}', which is already the platform default — remove it; ` +
@@ -777,14 +872,24 @@ function checkDefaultFieldOptions(ts, sf, propName, prop, findings) {
777
872
  function checkEnumGlobalName(ts, sf, propName, prop, model, findings) {
778
873
  const name = prop.enumGlobalName;
779
874
  if (!name) return; // local enum — the default, and nothing to check
780
- // The literal occurs once: here, in this decorator. Nothing — no seed record,
781
- // no other entity — refers to it, so the name buys nothing.
782
- const occurrences = model.stringLiteralCounts.get(name) ?? 0;
783
- if (occurrences <= 1) {
875
+ // A REFERENCE is an occurrence of the name somewhere other than the property
876
+ // that declares it. Occurrences inside this property do not count, however
877
+ // they are spelled: `key: 'Entity.field'` (the rename key, which by convention
878
+ // is spelled exactly like a global enum name), a hand-written `subType`, a
879
+ // `name`. Counting those as references is what let the shipped violation
880
+ // through — the field's own key made the name look shared.
881
+ const declStart = prop.node.getStart(sf);
882
+ const declEnd = prop.node.getEnd();
883
+ const sites = model.stringLiteralSites.get(name) ?? [];
884
+ const references = sites.filter(
885
+ (s) => !(s.file === sf.fileName && s.start >= declStart && s.end <= declEnd),
886
+ ).length;
887
+ if (references === 0) {
784
888
  findings.push(finding(ts, sf, prop.decorator.args[0], "W613",
785
- `'${propName}' (@${prop.decorator.name}) declares the global enum name '${name}', but nothing in the ` +
786
- `analyzed files references it. A global name is for enums shared across entities or referenced from ` +
787
- `seeds ({ name: '${name}', value: … }); for an enum used only by this field, omit the first argument ` +
889
+ `'${propName}' (@${prop.decorator.name}) declares the global enum name '${name}', but nothing outside this ` +
890
+ `field references it (its own 'key'/'subType' option does not count as a reference). A global name is for ` +
891
+ `enums shared across entities or referenced from seeds ({ name: '${name}', value: … }); for an enum used ` +
892
+ `only by this field, omit the first argument ` +
788
893
  `— @${prop.decorator.name}(${prop.decorator.name === "Enum" ? "StatusEnum, StatusTitles, " : "…, "}{ … }) — and the decorator derives the name`));
789
894
  }
790
895
  }
@@ -936,11 +1041,17 @@ function checkSubType(ts, sf, propName, prop, typeValue, findings) {
936
1041
  // ── extraction: string enums (createSeed(EnumName.Member) resolution) ──
937
1042
  function analyzeEnums(ts, sf, model) {
938
1043
  sf.forEachChild(function walk(node) {
939
- // Every string literal in the analyzed set, counted. A global enum name that
940
- // occurs exactly once is written in its decorator and referenced nowhere —
941
- // which is what W613 is looking for.
1044
+ // Every string literal in the analyzed set, with WHERE it occurs. Counting
1045
+ // alone was not enough: a field conventionally carries `key: 'Entity.field'`
1046
+ // — the same shape as an enum's global name — so a purely local enum whose
1047
+ // decorator ALSO set that key scored two occurrences and W613 stayed silent.
1048
+ // That is the exact shape that shipped. The site lets the check discount
1049
+ // occurrences inside the very property that declares the name.
942
1050
  if (ts.isStringLiteral(node)) {
943
1051
  model.stringLiteralCounts.set(node.text, (model.stringLiteralCounts.get(node.text) ?? 0) + 1);
1052
+ const sites = model.stringLiteralSites.get(node.text) ?? [];
1053
+ sites.push({ file: sf.fileName, start: node.getStart(sf), end: node.getEnd() });
1054
+ model.stringLiteralSites.set(node.text, sites);
944
1055
  }
945
1056
  if (ts.isEnumDeclaration(node)) {
946
1057
  const members = new Map();
@@ -1509,7 +1620,7 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
1509
1620
  const model = {
1510
1621
  entities: new Map(), entityByName: new Map(),
1511
1622
  seeds: [], modules: [], stringEnums: new Map(),
1512
- enumDeclarations: [], stringLiteralCounts: new Map(),
1623
+ enumDeclarations: [], stringLiteralCounts: new Map(), stringLiteralSites: new Map(),
1513
1624
  };
1514
1625
  const findings = [];
1515
1626
  // the CLI deduped; the exported API did not, and duplicated seeds duplicated findings
@@ -1543,6 +1654,9 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
1543
1654
  findings,
1544
1655
  errors: findings.filter((f) => f.level === "error"),
1545
1656
  warnings: findings.filter((f) => f.level === "warning"),
1657
+ // Deterministic authoring-rule violations, split out so the gate can block
1658
+ // on them without promoting the advisory warnings alongside.
1659
+ ruleWarnings: findings.filter((f) => RULE_WARNINGS.includes(f.code)),
1546
1660
  sdkSource: sdk.source,
1547
1661
  };
1548
1662
  }
@@ -1571,9 +1685,13 @@ export function discoverFiles(rootDir) {
1571
1685
  const isMain =
1572
1686
  process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
1573
1687
  if (isMain) {
1574
- const args = process.argv.slice(2);
1688
+ const argv = process.argv.slice(2);
1689
+ // Default is strict: the authoring rules block. --no-strict is the escape for
1690
+ // a legacy repo whose existing entities restate defaults everywhere.
1691
+ const strict = !argv.includes("--no-strict");
1692
+ const args = argv.filter((a) => a !== "--no-strict" && a !== "--strict");
1575
1693
  if (args.length === 0) {
1576
- console.error("usage: node validate-suppa-schema.mjs <app-root-or-files...>");
1694
+ console.error("usage: node validate-suppa-schema.mjs [--no-strict] <app-root-or-files...>");
1577
1695
  process.exit(2);
1578
1696
  }
1579
1697
  let rootDir = null;
@@ -1614,13 +1732,31 @@ if (isMain) {
1614
1732
  console.error(err.message);
1615
1733
  process.exit(2);
1616
1734
  }
1735
+ // W613 argues from absence, so it only blocks when the whole repo was walked:
1736
+ // on an explicit file list the seed that references the enum may simply be
1737
+ // outside the set.
1738
+ const wholeRepo = rootDir !== null;
1739
+ const blocks = (f) =>
1740
+ strict &&
1741
+ RULE_WARNINGS.includes(f.code) &&
1742
+ (wholeRepo || !RULE_WARNINGS_NEEDING_WHOLE_REPO.includes(f.code));
1617
1743
  for (const f of res.findings) {
1744
+ const level = blocks(f) ? "rule violation" : f.level;
1618
1745
  console.log(
1619
- `${displayPath(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`,
1746
+ `${displayPath(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${level}] ${f.message}`,
1620
1747
  );
1621
1748
  }
1749
+ const blocked = res.findings.filter(blocks);
1750
+ const advisory = res.warnings.length - blocked.length;
1622
1751
  console.log(
1623
- `\n${res.errors.length} error(s), ${res.warnings.length} warning(s) across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
1752
+ `\n${res.errors.length} error(s), ${blocked.length} rule violation(s), ${advisory} advisory warning(s) ` +
1753
+ `across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
1624
1754
  );
1625
- process.exit(res.errors.length > 0 ? 1 : 0);
1755
+ if (blocked.length) {
1756
+ const codes = [...new Set(blocked.map((f) => f.code))].sort().join(", ");
1757
+ console.log(
1758
+ `Rule violations (${codes}) fail the gate. Fix them, or pass --no-strict to record them as warnings instead.`,
1759
+ );
1760
+ }
1761
+ process.exit(res.errors.length + blocked.length > 0 ? 1 : 0);
1626
1762
  }