suppa-mcp-2 1.40.5 → 1.41.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.
Files changed (53) hide show
  1. package/README.md +53 -11
  2. package/dist/bin.js +68 -1
  3. package/dist/cli/api.js +238 -0
  4. package/dist/cli/help.js +1 -0
  5. package/dist/cli/run.js +12 -25
  6. package/dist/cli/tenantPoint.js +35 -0
  7. package/dist/config.js +30 -1
  8. package/dist/customFieldHints.js +19 -22
  9. package/dist/readEconomy.js +32 -3
  10. package/dist/server.js +236 -81
  11. package/dist/toolTable.js +3 -3
  12. package/dist/tools/customFieldSets.js +5 -2
  13. package/dist/tools/customFields.js +9 -3
  14. package/dist/tools/customFieldsAsCode.js +62 -19
  15. package/dist/tools/entity.js +417 -114
  16. package/dist/tools/fieldTypeChange.js +364 -0
  17. package/dist/tools/formLifecycle.js +567 -0
  18. package/dist/tools/formV2.js +311 -45
  19. package/dist/tools/nameMap.js +24 -4
  20. package/dist/tools/query.js +279 -0
  21. package/dist/utils.js +9 -1
  22. package/package.json +1 -1
  23. package/skills/suppa-cli/SKILL.md +9 -1
  24. package/skills/suppa-entity-code/SKILL.md +458 -416
  25. package/skills/suppa-entity-code/references/custom-fields.md +4 -1
  26. package/skills/suppa-entity-code/references/enforcement.md +2 -1
  27. package/skills/suppa-entity-code/references/entities.md +503 -482
  28. package/skills/suppa-entity-code/references/extensions.md +1 -1
  29. package/skills/suppa-entity-code/references/registration.md +66 -16
  30. package/skills/suppa-entity-code/references/runtime.md +136 -0
  31. package/skills/suppa-entity-code/references/seeds.md +38 -1
  32. package/skills/suppa-entity-code/references/tabular-parts.md +11 -11
  33. package/skills/suppa-entity-code/references/v1-mapping.md +1 -1
  34. package/skills/suppa-entity-code/scripts/house-rules.mjs +7 -1
  35. package/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs +1104 -38
  36. package/skills/suppa-entity-code/templates/AGENTS.entity-code.md +9 -6
  37. package/skills/suppa-entity-code/templates/custom-fields.template.ts +5 -3
  38. package/skills/suppa-entity-code/templates/entity-extension.template.ts +3 -0
  39. package/skills/suppa-entity-code/templates/relation-target-stub.template.ts +7 -1
  40. package/skills/suppa-entity-code/templates/seed.template.ts +27 -12
  41. package/skills/suppa-entity-code/templates/tabular-part.template.ts +14 -13
  42. package/skills/suppa-form-v2/SKILL.md +16 -15
  43. package/skills/suppa-form-v2/data/component-index.json +1 -1
  44. package/skills/suppa-form-v2/data/component-props.json +2 -1
  45. package/skills/suppa-form-v2/notes/embeddedForm.md +6 -4
  46. package/skills/suppa-form-v2/notes/table.md +1 -1
  47. package/skills/suppa-form-v2/references/charts.md +10 -2
  48. package/skills/suppa-form-v2/references/layout.md +2 -2
  49. package/skills/suppa-form-v2/references/publishing.md +34 -13
  50. package/skills/suppa-form-v2/references/tables.md +7 -7
  51. package/skills/suppa-form-v2/scripts/form-rules.mjs +8 -6
  52. package/skills/suppa-form-v2/scripts/manifest-corrections.mjs +56 -0
  53. package/skills/suppa-form-v2/scripts/validate-form-schema.mjs +195 -7
@@ -52,33 +52,30 @@ const ERROR_HINTS = [
52
52
  "or edit the one that is there with suppa_update_field(entity_name='<Entity>CustomFields').",
53
53
  },
54
54
  {
55
- // Verified live: the name of a REMOVED field stays taken. The platform says
56
- // so itself — "that field is DELETED — its column is parked as
57
- // <name>_<timestamp>, and restoring it would then fail" — so a removal frees
58
- // the column, never the name.
59
- match: /is already taken by field|metadata\.invalid_name/i,
60
- hint: "That name belongs to a custom field that was REMOVED but not purged: the platform keeps it " +
61
- "reserved so the parked column can still be restored. Either bring the original back with " +
62
- "suppa_restore_custom_field (its values come with it), or choose a different name.",
55
+ // Since entity-builder 08258a57 (2026-09-25) the name guard reads LIVE fields only: a removed
56
+ // field no longer holds its name. "already taken by field X (id N)" therefore means a live field
57
+ // has it — on an add or a rename, or on the restore of a removed field whose name was re-used.
58
+ match: /is already taken by field/i,
59
+ hint: "A LIVE field on the same entity already has that name — the platform names it and its id. On " +
60
+ "an add, pick another name. On a restore, the removed field's name was re-used since: its " +
61
+ "values can come back only after the live one is renamed (suppa_update_field) or removed.",
63
62
  },
64
63
  {
65
- // Verified 2026-09-11 on modern-expo.dev.suppa.me, four shapes, all on the
66
- // probe entity: a Localization object {en, uk} → 400 write.invalid_relation_value
67
- // on path 'title'; {en} → 400 'Field "key" is required'; {key, en} → 400
68
- // 'Field "category" is required' (the object is being written as a
69
- // Localizations RECORD); a plain string → 201, echoed back, and stored as
70
- // NULL; no title → 201. The last field whose title was stored dates from
71
- // 2026-09-10 13:41. builder.txt:56 still says 'title | object | Localization
72
- // object', so this is the platform, not the contract.
64
+ // The title reached the builder as a Localizations RECORD rather than as translations: an object
65
+ // with `id` is read as a reference ("must contain an integer id"), one with `key`/`category` as a
66
+ // new record. Measured 2026-09-11 and read as a backend regression; found 2026-09-30 to be this
67
+ // server's own doing — the tenant languages were taken from /schema title keys, which are
68
+ // `{id, key, en, name}` now, so every title went out as `{id: "<text>", key: …}`.
69
+ // resolvePlatformLanguages now keeps language columns only (entity.ts PLATFORM_LANGUAGES).
73
70
  // The message arrives inside a stringified JSON body, so the quotes around
74
71
  // the field name may carry a backslash: \"title\", \"key\".
75
72
  match: /.?"title.?" must contain an integer id|invalid_relation_value[^]*"path":"title"|Field .?"(key|category).?" is required/i,
76
- hint: "The builder is currently REJECTING field titles: the Localization object the doc prescribes " +
77
- "(builder.txt:56) is being written as a Localizations record and fails, and a plain string is " +
78
- "accepted but stored as null (verified on dev 2026-09-11; last title stored 2026-09-10 13:41). " +
79
- "NOTHING was created. Re-send WITHOUT title — the field is created untitled and works; set the " +
80
- "label in the UI or with suppa_update_field once the platform fix lands. This is a backend " +
81
- "regression worth reporting with the traceId above.",
73
+ hint: "NOTHING was created. The title reached the builder as a Localizations RECORD, not as " +
74
+ "translations: an object carrying `id` is read as a reference to an existing row, one carrying " +
75
+ "`key`/`category` as a new record. A title must hold language keys only (en, uk, pl, …). This " +
76
+ "server takes them from the tenant's enabled languages — check that SUPPA_LANGS, if set, lists " +
77
+ "language codes only (e.g. en,uk,pl,ro), and that a title object you pass has nothing else in " +
78
+ "it. Re-sending WITHOUT title also works; set the label afterwards with suppa_update_field.",
82
79
  },
83
80
  {
84
81
  match: /HTTP 409|statusCode":409/,
@@ -48,8 +48,26 @@ const FIELD_FLAG_DEFAULTS = Object.freeze({
48
48
  notNull: false,
49
49
  decimalPlaces: 0,
50
50
  });
51
- /** The keys of a platform localisation record that are bookkeeping, not text. */
52
- const I18N_BOOKKEEPING = new Set(["id", "key", "name"]);
51
+ /**
52
+ * The keys of a platform localisation record that are bookkeeping, not text: every non-language
53
+ * column of Localizations (entity-builder localizations entity), plus the row's timestamps.
54
+ */
55
+ const I18N_BOOKKEEPING = new Set([
56
+ "id",
57
+ "key",
58
+ "name",
59
+ "application",
60
+ "category",
61
+ "entity",
62
+ "field",
63
+ "form",
64
+ "initiator",
65
+ "parent",
66
+ "children",
67
+ "createdAt",
68
+ "updatedAt",
69
+ "deletedAt",
70
+ ]);
53
71
  export const SCHEMA_LEGEND = "Compact schema: a field omits constraints that are null, flags that are false/0 " +
54
72
  "(isArray, isPrimary, isOnlyPositive, unique, notNull, decimalPlaces) and options at the " +
55
73
  "platform defaults (canGroup/canSort/showInTable/editFromTable/canFilter true; " +
@@ -63,13 +81,24 @@ export const SCHEMA_LEGEND = "Compact schema: a field omits constraints that are
63
81
  export function slimTitle(title) {
64
82
  if (!isObj(title))
65
83
  return title;
84
+ const out = titleLanguages(title);
85
+ return Object.keys(out).length > 0 ? out : title;
86
+ }
87
+ /**
88
+ * Only the translations of a title — `{}` when it has none. What search and naming read: an
89
+ * untranslated record's key "entity.<Name>" and name "Entity: <Name>" are not its label, and
90
+ * slimTitle's "left whole" fallback (right for display) would make them one.
91
+ */
92
+ export function titleLanguages(title) {
66
93
  const out = {};
94
+ if (!isObj(title))
95
+ return out;
67
96
  for (const [k, v] of Object.entries(title)) {
68
97
  if (I18N_BOOKKEEPING.has(k) || v === null || v === undefined)
69
98
  continue;
70
99
  out[k] = v;
71
100
  }
72
- return Object.keys(out).length > 0 ? out : title;
101
+ return out;
73
102
  }
74
103
  /** Field options with the platform defaults removed. */
75
104
  export function compactOptions(options) {
package/dist/server.js CHANGED
@@ -17,12 +17,15 @@ import * as customFieldSets from "./tools/customFieldSets.js";
17
17
  import * as customFieldsAsCode from "./tools/customFieldsAsCode.js";
18
18
  import * as entityCode from "./tools/entityCode.js";
19
19
  import * as formV2 from "./tools/formV2.js";
20
+ import * as formLifecycle from "./tools/formLifecycle.js";
21
+ import * as fieldTypeChange from "./tools/fieldTypeChange.js";
20
22
  import { houseRulesDigest } from "./tools/entityCode.js";
21
23
  import * as files from "./tools/files.js";
22
24
  import * as forms from "./tools/forms.js";
23
25
  import * as migrate from "./tools/migrate.js";
24
26
  import * as workspace from "./tools/workspace.js";
25
27
  import * as automation from "./tools/automation.js";
28
+ import * as query from "./tools/query.js";
26
29
  import * as auth from "./auth.js";
27
30
  import * as tenants from "./tenants.js";
28
31
  import { confirmRequired, jsonResponse } from "./utils.js";
@@ -66,6 +69,13 @@ const _MUT = {
66
69
  // the wrong thing to show in front of a recovery action (a user who hesitates
67
70
  // there loses the record they were trying to save). It keeps the confirm gate:
68
71
  // restoring still changes what every normal read returns.
72
+ // A write that destroys what it replaces and is not safe to repeat: publishing twice freezes two
73
+ // versions, rolling back twice publishes twice.
74
+ const _ONCE = {
75
+ readOnlyHint: false,
76
+ destructiveHint: true,
77
+ idempotentHint: false,
78
+ };
69
79
  const _UNDO = {
70
80
  readOnlyHint: false,
71
81
  destructiveHint: false,
@@ -194,9 +204,9 @@ const EntityOptionsJson = z
194
204
  '"hierarchy": "multi"}. Keys: comments, reactions, hierarchy ("single"|"multi"), ' +
195
205
  'folders ("single"|"multi"), trackChangeHistory, browsingHistory (boolean or number), ' +
196
206
  "globalSearch, timeTracking, favorites, pinned, approvals, checklists, recurrence, " +
197
- "reminders, notificationMutes, customFields — everything but hierarchy, folders and " +
198
- "browsingHistory " +
199
- "is a boolean. Unknown keys are refused (the platform would drop them silently). " +
207
+ "reminders, notificationMutes, customFields, stateHistory (booleans), hierarchyDepthLimit " +
208
+ '(integer 1-20, needs hierarchy), commentsPrivacy (object), externalSource ({"sourceEntity": <id>}). ' +
209
+ "Unknown keys are refused (the platform would drop them silently). " +
200
210
  "Enabling an option creates the side table that backs it, and recurrence, reminders, " +
201
211
  "notificationMutes, timeTracking and pinned also refresh the corresponding system " +
202
212
  "entity's cache — so this is not a free toggle. Options can also be changed later " +
@@ -288,47 +298,47 @@ if (!HOUSE_RULES_DIGEST) {
288
298
  process.stderr.write("[suppa-mcp] warning: skills/suppa-entity-code/scripts/house-rules.mjs is missing or unreadable — " +
289
299
  "the server instructions carry no entity-code house rules. Reinstall suppa-mcp-2.\n");
290
300
  }
291
- const INSTRUCTIONS = `Suppa Platform MCP Server — Tasks, Docs/Pages, Entities, Forms, Automations and file attachments on Suppa tenants.
292
-
293
- AUTHENTICATION — RESOLVE THIS BEFORE ANY OTHER SUPPA WORK
294
- - Sign-in is an interactive Google flow in the browser. There is NO API key for a user to find or paste — NEVER ask for a token, key or password; call suppa_login instead.
295
- - Signed in? suppa_list_tenants shows the STORED "authenticated"/"needs_login" (no network; a revoked session still reads signed in); suppa_diagnostics makes the live call that settles it.
296
- - When not signed in — or any tool answers "No credentials" / HTTP 401 / "session could not be refreshed" / ReloginRequired — DO NOT STOP and DO NOT ask for a key:
297
- 1. Call suppa_login (suppa_login(tenant="<alias|host|url>") targets another instance; default is the active tenant). It OPENS A GOOGLE SIGN-IN PAGE in the default browser, served locally at http://localhost:${config.LOGIN_PORT}.
298
- 2. Tell the user: "I've opened a Google sign-in page in your browser — pick your account to finish signing in." If the browser did not open, the result carries the URL for them to open by hand.
299
- 3. It blocks until they finish and returns {"status":"ok"} — THEN retry the original action. Tokens go to the OS keychain and auto-refresh: one login per tenant, not per session.
300
- - A static SUPPA_API_KEY in the client env (CI / single tenant) means no login is needed; it is optional and most users have none.
301
- - suppa_diagnostics validates the whole setup and reports the login_origin to whitelist. ONE-TIME ORG SETUP: http://localhost:${config.LOGIN_PORT} must be in the Google OAuth client's "Authorized JavaScript origins" — a sign-in page that opens but never completes is almost always this; tell the user so an admin can add it.
302
- - suppa_use_tenant switches the active instance for ALL later calls; suppa_list_tenants shows what is known and authenticated.
303
-
304
- DATA BASICS
305
- - IDs are integers, not UUIDs. Dates are ISO-8601; a naive datetime (no offset) is read as UTC, so pass an explicit offset (+03:00) or convert local times yourself. Task deadlines also accept 'today', 'tomorrow', '+3d', '+2h', '+30m', '+1w'.
306
- - Each write tool's description states the shapes it demands — relations and enums as {"id": N}, list fields REPLACED unless merge_json says otherwise — and validates against the live schema before writing. Read it before calling: a bare number where a reference belongs returns 201 and stores null.
307
- - DELETE IS A SOFT DELETE — every delete tool sets deletedAt and leaves the row in place, reversible with suppa_restore_record(entity_name, record_id); never tell the user their data was destroyed. It still needs confirm=true because the row leaves all normal reads; find it again with deleted_scope='deleted'.
308
- - PERMANENT DELETE IS UNAVAILABLE HERE, BY DESIGN — this server performs REVERSIBLE deletes only. The platform's PERMANENT delete (POST /core/data/:entityName/delete — rows leave the table and cannot be restored) is BLOCKED in the HTTP client itself: no tool, flag, confirm=true or direct call reaches it, and an attempt is refused before any request is sent. Do not look for a tool, a parameter or a workaround — there is none. Asked to erase data for good, say so plainly and offer the soft delete (suppa_delete_record → /remove, undone by suppa_restore_record); permanent removal is an admin action in the platform's own UI.
309
- - Reads are compact: relation objects omit deletedAt when null (a live row); schema reads omit nulls, false flags and default options and carry a _legend (full=true returns the raw form).
310
-
311
- SEARCH & FILTERS — suppa_search_records' description carries the comparators, nested AND/OR groups, dotted field paths, "$current-user", paging and the auto-diagnosis of an empty result. Read it before your first search.
312
- - PROJECT ONLY THE FIELDS YOU NEED: fields_json is on suppa_search_records AND on every task/doc read (suppa_get_task, suppa_search_tasks — which also takes task_ids, so several tasks are ONE call, never one suppa_get_task each — suppa_get_doc, suppa_list_pages, …). A 600-character answer instead of a 50 000-character one, re-sent on every later turn.
313
- - Unsure of the schema: suppa_list_entities → suppa_describe_entity → suppa_search_records. One record by id needs no filters: suppa_get_record / suppa_get_task / suppa_get_doc.
314
-
315
- APPROVAL GATES (human-in-the-loop)
316
- - Every update/move/close/delete tool called without confirm=true returns {"status": "confirmation_required"} and performs NOTHING. Show the user what will change, get explicit approval, then re-call the same tool with confirm=true — never set it on the first call without their go-ahead. Create/read tools and comments need no confirmation.
317
- - A value shown as <N chars — …> is NOT the stored text: the marker stands in for a long string you supplied in this same call, and the reason after the dash says which. Quote it to the user from your own arguments; never report the marker as the record's content.
318
-
319
- ENTITY BUILDER (create + edit fields; core-field removal is UI-only) — suppa_add_field's description carries the real field types, the sub_type matrix and the field options; suppa_update_field's carries what may still be changed on a field that exists. Two things those cannot decide for you:
320
- - OWNED CHILD COLLECTIONS ARE TABULAR PARTS: repeating rows that belong to ONE parent record (a part's BOM items) go through suppa_create_tabular_part(parent_entity, name), which creates the child's 'owner' relation and the parent link. Never model it by hand — suppa_add_field REFUSES field_type='one-to-many'; 'many-to-many' is for a shared lookup referenced by many records.
321
- - An enum value on a RECORD is a reference, {"id": <Enums row id>} (an array of those for multi-enum), never a bare code like "red" — that is refused. Read the ids with suppa_search_records on 'Enums' filtered by name.
322
-
323
- CUSTOM FIELDS — ANY entity, not just Tasks: one whose options.customFields is on (an admin enables it; suppa_describe_entity shows it) carries extra columns that vary BY CONTEXT, so which are live differs from record to record — suppa_resolve_custom_fields answers for a given record. Their values ride on the OWNER record under the reserved key customFields, e.g. fields_json {"customFields": {"budget": 600}}.
324
-
325
- ${formV2.FORM_V2_INSTRUCTION_LINE}
326
-
327
- ${HOUSE_RULES_DIGEST}
328
-
329
- ATTACHMENTS — an entity holds files only through a 'file' or 'multi-file' field (add one with suppa_add_field). suppa_attach_file_to_record uploads from local disk and returns the file_ids that are the only handle to the bytes; suppa_list_record_files lists what a record carries; suppa_download_file and suppa_download_files_zip fetch them. Those descriptions carry the rest.
330
-
331
- MIGRATION (Suppa 1.0 → 2.0) — always dry-run first: suppa_migrate_entities_from_v1(dry_run=true, output_file="plan.json"), review/edit the plan, then execute with plan_file="plan.json", dry_run=false.
301
+ const INSTRUCTIONS = `Suppa Platform MCP Server — Tasks, Docs/Pages, Entities, Forms, Automations and file attachments on Suppa tenants.
302
+
303
+ AUTHENTICATION — RESOLVE THIS BEFORE ANY OTHER SUPPA WORK
304
+ - Sign-in is an interactive Google flow in the browser. There is NO API key for a user to find or paste — NEVER ask for a token, key or password; call suppa_login instead.
305
+ - Signed in? suppa_list_tenants shows the STORED "authenticated"/"needs_login" (no network; a revoked session still reads signed in); suppa_diagnostics makes the live call that settles it.
306
+ - When not signed in — or any tool answers "No credentials" / HTTP 401 / "session could not be refreshed" / ReloginRequired — DO NOT STOP and DO NOT ask for a key:
307
+ 1. Call suppa_login (suppa_login(tenant="<alias|host|url>") targets another instance; default is the active tenant). It OPENS A GOOGLE SIGN-IN PAGE in the default browser, served locally at http://localhost:${config.LOGIN_PORT}.
308
+ 2. Tell the user: "I've opened a Google sign-in page in your browser — pick your account to finish signing in." If the browser did not open, the result carries the URL for them to open by hand.
309
+ 3. It blocks until they finish and returns {"status":"ok"} — THEN retry the original action. Tokens go to the OS keychain and auto-refresh: one login per tenant, not per session.
310
+ - A static SUPPA_API_KEY in the client env (CI / single tenant) means no login is needed; it is optional and most users have none.
311
+ - suppa_diagnostics validates the whole setup and reports the login_origin to whitelist. ONE-TIME ORG SETUP: http://localhost:${config.LOGIN_PORT} must be in the Google OAuth client's "Authorized JavaScript origins" — a sign-in page that opens but never completes is almost always this; tell the user so an admin can add it.
312
+ - suppa_use_tenant switches the active instance for ALL later calls; suppa_list_tenants shows what is known and authenticated.
313
+
314
+ DATA BASICS
315
+ - IDs are integers, not UUIDs. Dates are ISO-8601; a naive datetime (no offset) is read as UTC, so pass an explicit offset (+03:00) or convert local times yourself. Task deadlines also accept 'today', 'tomorrow', '+3d', '+2h', '+30m', '+1w'.
316
+ - Each write tool's description states the shapes it demands — relations and enums as {"id": N}, list fields REPLACED unless merge_json says otherwise — and validates against the live schema before writing. Read it before calling: a bare number where a reference belongs returns 201 and stores null.
317
+ - DELETE IS A SOFT DELETE — every delete tool sets deletedAt and leaves the row in place, reversible with suppa_restore_record(entity_name, record_id); never tell the user their data was destroyed. It still needs confirm=true because the row leaves all normal reads; find it again with deleted_scope='deleted'.
318
+ - PERMANENT DELETE IS UNAVAILABLE HERE, BY DESIGN — this server performs REVERSIBLE deletes only. The platform's PERMANENT delete (POST /core/data/:entityName/delete — rows leave the table and cannot be restored) is BLOCKED in the HTTP client itself: no tool, flag, confirm=true or direct call reaches it, and an attempt is refused before any request is sent. Do not look for a tool, a parameter or a workaround — there is none. Asked to erase data for good, say so plainly and offer the soft delete (suppa_delete_record → /remove, undone by suppa_restore_record); permanent removal is an admin action in the platform's own UI.
319
+ - Reads are compact: relation objects omit deletedAt when null (a live row); schema reads omit nulls, false flags and default options and carry a _legend (full=true returns the raw form).
320
+
321
+ SEARCH & FILTERS — suppa_search_records' description carries the comparators, nested AND/OR groups, dotted field paths, "$current-user", paging and the auto-diagnosis of an empty result. Read it before your first search.
322
+ - PROJECT ONLY THE FIELDS YOU NEED: fields_json is on suppa_search_records AND on every task/doc read (suppa_get_task, suppa_search_tasks — which also takes task_ids, so several tasks are ONE call, never one suppa_get_task each — suppa_get_doc, suppa_list_pages, …). A 600-character answer instead of a 50 000-character one, re-sent on every later turn.
323
+ - Unsure of the schema: suppa_list_entities → suppa_describe_entity → suppa_search_records. One record by id needs no filters: suppa_get_record / suppa_get_task / suppa_get_doc.
324
+
325
+ APPROVAL GATES (human-in-the-loop)
326
+ - Every update/move/close/delete tool called without confirm=true returns {"status": "confirmation_required"} and performs NOTHING. Show the user what will change, get explicit approval, then re-call the same tool with confirm=true — never set it on the first call without their go-ahead. Create/read tools and comments need no confirmation.
327
+ - A value shown as <N chars — …> is NOT the stored text: the marker stands in for a long string you supplied in this same call, and the reason after the dash says which. Quote it to the user from your own arguments; never report the marker as the record's content.
328
+
329
+ ENTITY BUILDER (create + edit fields; core-field removal is UI-only) — suppa_add_field's description carries the real field types, the sub_type matrix and the field options; suppa_update_field's carries what may still be changed on a field that exists. Two things those cannot decide for you:
330
+ - OWNED CHILD COLLECTIONS ARE TABULAR PARTS: repeating rows that belong to ONE parent record (a part's BOM items) go through suppa_create_tabular_part(parent_entity, name), which creates the child's 'owner' relation and the parent link. Never model it by hand — suppa_add_field REFUSES field_type='one-to-many'; 'many-to-many' is for a shared lookup referenced by many records.
331
+ - An enum value on a RECORD is a reference, {"id": <Enums row id>} (an array of those for multi-enum), never a bare code like "red" — that is refused. Read the ids with suppa_search_records on 'Enums' filtered by name.
332
+
333
+ CUSTOM FIELDS — ANY entity, not just Tasks: one whose options.customFields is on (an admin enables it; suppa_describe_entity shows it) carries extra columns that vary BY CONTEXT, so which are live differs from record to record — suppa_resolve_custom_fields answers for a given record. Their values ride on the OWNER record under the reserved key customFields, e.g. fields_json {"customFields": {"budget": 600}}.
334
+
335
+ ${formV2.FORM_V2_INSTRUCTION_LINE}
336
+
337
+ ${HOUSE_RULES_DIGEST}
338
+
339
+ ATTACHMENTS — an entity holds files only through a 'file' or 'multi-file' field (add one with suppa_add_field). suppa_attach_file_to_record uploads from local disk and returns the file_ids that are the only handle to the bytes; suppa_list_record_files lists what a record carries; suppa_download_file and suppa_download_files_zip fetch them. Those descriptions carry the rest.
340
+
341
+ MIGRATION (Suppa 1.0 → 2.0) — always dry-run first: suppa_migrate_entities_from_v1(dry_run=true, output_file="plan.json"), review/edit the plan, then execute with plan_file="plan.json", dry_run=false.
332
342
  `;
333
343
  // ---------------------------------------------------------------------------
334
344
  // Registered tool + prompt names (tests assert the counts).
@@ -1005,6 +1015,33 @@ export function buildToolTable() {
1005
1015
  },
1006
1016
  annotations: _READ,
1007
1017
  }, async (a) => text(await entity.validateSelectQuery(a.entity_name, a.filters_json, a.fields_json, a.order_by, a.match_any)));
1018
+ reg("suppa_query", {
1019
+ description: "Run ONE read-only SuppaSQL statement — POST /core/data/query, the endpoint the\n" +
1020
+ " builder's SQL charts and tables use. Check a chart/table SQL source with it before\n" +
1021
+ " writing the form: an incomplete one shows demo data, a wrong one fails at runtime.\n\n" +
1022
+ " SELECT / WITH only, one statement; anything else is refused and nothing is sent.\n" +
1023
+ " Runs with the caller's read permissions; deleted rows are excluded. A missing LIMIT\n" +
1024
+ " is added and a bigger literal one clamped, so at most `limit` rows come back, with\n" +
1025
+ " `truncated` and `columns` — the result keys, nested ones as dot paths\n" +
1026
+ " (owner.firstName), which is what sqlValueColumns[].key and table columns must use.",
1027
+ inputSchema: {
1028
+ query: z
1029
+ .string()
1030
+ .describe('The SuppaSQL statement, e.g. SELECT "stage.name" AS stage, COUNT(id) AS n FROM Tasks GROUP BY "stage.name".'),
1031
+ bind_params_json: z
1032
+ .string()
1033
+ .optional()
1034
+ .describe('JSON object of bind values for $name / $1 / = ANY($arr), e.g. {"owner": 479}. $current-user is set by the server.'),
1035
+ limit: z
1036
+ .number()
1037
+ .int()
1038
+ .min(1)
1039
+ .max(query.QUERY_MAX_LIMIT)
1040
+ .default(query.QUERY_DEFAULT_LIMIT)
1041
+ .describe("Rows to show (1-500)."),
1042
+ },
1043
+ annotations: _READ,
1044
+ }, async (a) => text(await query.runQuery(a.query, a.bind_params_json ?? null, a.limit)));
1008
1045
  reg("suppa_get_record", {
1009
1046
  description: "Get a single record of any entity by id. fields_json: {field: true} projection —\n" +
1010
1047
  ' request only the fields you need (relations as nested objects, e.g. {"owner": {"id": true, "fullName": true}}).\n\n' +
@@ -1061,12 +1098,12 @@ export function buildToolTable() {
1061
1098
  " NOT A FREE TOGGLE: enabling an option CREATES the side table that backs it, and\n" +
1062
1099
  " recurrence / reminders / notificationMutes / timeTracking / pinned also refresh\n" +
1063
1100
  " the cache of the corresponding system entity. It is a schema change.\n\n" +
1064
- " RESTRICTIONS (builder.txt:250-264): on an entity created by the system\n" +
1065
- " (initiator='system') only options.globalSearch is accepted — the rest is dropped\n" +
1066
- " silently, so this server refuses the call instead. On a system-GENERATED entity\n" +
1067
- " (reserved suffix) enabling comments, timeTracking, pinned, favorites, approvals or\n" +
1068
- " checklists is forbidden; the docs do not list the suffixes, so that one can only\n" +
1069
- " be reported as a warning. The platform answers with the APPLIED options, which\n" +
1101
+ " RESTRICTIONS: on an entity the tenant does not own (initiator 'system' or\n" +
1102
+ " 'application') only options.stateHistory and options.externalSource may change —\n" +
1103
+ " the platform answers 403 to the rest, so this server refuses the call first. A\n" +
1104
+ " system-GENERATED entity (a reserved suffix: Comments, Folders, CustomFields…)\n" +
1105
+ " refuses comments, customFields and six more — refused here too. The platform\n" +
1106
+ " answers with the APPLIED options, which\n" +
1070
1107
  " may be a subset of the request — anything missing is called out in the result.\n\n" +
1071
1108
  " APPROVAL GATE: without confirm=true this returns a confirmation request and changes nothing.",
1072
1109
  inputSchema: {
@@ -1077,8 +1114,9 @@ export function buildToolTable() {
1077
1114
  "Keys: comments, reactions, hierarchy (\"single\"|\"multi\"), folders " +
1078
1115
  '("single"|"multi"), trackChangeHistory, browsingHistory (boolean or number), ' +
1079
1116
  "globalSearch, timeTracking, favorites, pinned, approvals, checklists, " +
1080
- "recurrence, reminders, notificationMutes, customFields — everything but hierarchy, folders " +
1081
- "and browsingHistory is a boolean. Unknown keys are refused (the platform would " +
1117
+ "recurrence, reminders, notificationMutes, customFields, stateHistory (booleans), " +
1118
+ "hierarchyDepthLimit (integer 1-20), commentsPrivacy (object), externalSource " +
1119
+ '({"sourceEntity": <id>}). Unknown keys are refused (the platform would ' +
1082
1120
  "drop them silently). Enabling an option creates the side table that backs it, " +
1083
1121
  "and recurrence/reminders/notificationMutes/timeTracking/pinned also refresh the " +
1084
1122
  "corresponding system entity's cache — so this is not a free toggle."),
@@ -1087,6 +1125,11 @@ export function buildToolTable() {
1087
1125
  annotations: _MUT,
1088
1126
  }, async (a) => {
1089
1127
  if (!a.confirm) {
1128
+ // Refuse in the preview what the confirmed call would refuse — never ask a user to approve
1129
+ // a call that is malformed or that the platform answers 403.
1130
+ const refusal = await entity.entityOptionsRefusal(a.entity_name, a.options_json);
1131
+ if (refusal)
1132
+ return text(refusal);
1090
1133
  return text(confirmRequired("update entity options", { entity: a.entity_name }, {
1091
1134
  options: a.options_json,
1092
1135
  side_effects: "Enabling an option creates the side table that backs it; recurrence, reminders, " +
@@ -1145,7 +1188,7 @@ export function buildToolTable() {
1145
1188
  " parameters — read them; enum/multi-enum take no sub_type (the platform sets it).\n" +
1146
1189
  " Constraints: max_length/min_length (text),\n" +
1147
1190
  " decimal_places / min_value / max_value / only_positive (numeric). Options can be\n" +
1148
- " changed later with suppa_update_field; the field's TYPE never can.\n" +
1191
+ " changed later with suppa_update_field; a plain TYPE with suppa_change_field_type.\n" +
1149
1192
  " required=true makes the column NOT NULL. Where a defaultValue APPLIES it is\n" +
1150
1193
  " also required, and the call is refused before any request if missing — no\n" +
1151
1194
  " default is ever invented for you. defaultValue does NOT apply to relations,\n" +
@@ -1277,16 +1320,15 @@ export function buildToolTable() {
1277
1320
  " searchable (+searchPriority), or turning one of the others OFF.\n\n" +
1278
1321
  " WHAT THE PLATFORM DOES NOT ALLOW (refused here BEFORE any request, so a rejected\n" +
1279
1322
  " call changes nothing):\n" +
1280
- " - The TYPE of a field can never be changed ('Field type cannot be changed.') —\n" +
1281
- " there is no type parameter. Add a new field and move the data instead.\n" +
1282
- " - The SUBTYPE cannot be changed either ('Field subType cannot be changed.'). The\n" +
1283
- " ONE permitted transition is encryption: encrypt=true sets sub_type 'encrypted',\n" +
1284
- " encrypt=false clears it. A date/time choice is fixed at creation.\n" +
1323
+ " - The TYPE (and a timestamp's date/time/timestamp) is NOT changed here — use\n" +
1324
+ " suppa_change_field_type, which shows the platform's conversion plan first.\n" +
1325
+ " - Of the other subtypes only encryption toggles: encrypt=true sets 'encrypted',\n" +
1326
+ " encrypt=false clears it.\n" +
1285
1327
  " - 'encrypted' is only allowed on a TEXT field, and it forces searchable, canFilter,\n" +
1286
1328
  " canSort and canGroup off (plus unique, max_length, min_length, mask), so it\n" +
1287
1329
  " cannot be combined with them in one call. Encrypting rewrites the existing rows.\n" +
1288
- " - A SYSTEM field (initiator='system') accepts only title and options.{canGroup,\n" +
1289
- " canSort, showInTable, editFromTable, canFilter, readOnly, searchable}.\n" +
1330
+ " - A field the tenant does not own (initiator 'system' or 'application') takes only\n" +
1331
+ " a title and options.trackStateHistory; the platform answers 403 to the rest.\n" +
1290
1332
  " Removing a CORE field is still UI-only — this server has no remove-field call for\n" +
1291
1333
  " one. A CUSTOM field is different: suppa_remove_custom_field parks it reversibly.\n" +
1292
1334
  " This tool edits a custom field too — pass entity_name='<Entity>CustomFields'.\n\n" +
@@ -1346,7 +1388,7 @@ export function buildToolTable() {
1346
1388
  .default(null)
1347
1389
  .describe('Field options as a JSON object, e.g. {"searchable": true, "searchPriority": 3} ' +
1348
1390
  'or {"showInTable": false}. Keys: searchable, searchPriority (1-4), readOnly, ' +
1349
- "canGroup, canSort, showInTable, editFromTable, canFilter. Send only what " +
1391
+ "canGroup, canSort, showInTable, editFromTable, canFilter, trackStateHistory. Send only what " +
1350
1392
  "CHANGES — the platform already applies canGroup/canSort/showInTable/" +
1351
1393
  "editFromTable/canFilter true and readOnly/searchable false, so restating one " +
1352
1394
  "of those is a no-op. Unknown keys are refused (the platform would drop them " +
@@ -1378,10 +1420,7 @@ export function buildToolTable() {
1378
1420
  changes.encrypt = a.encrypt;
1379
1421
  if (a.options_json !== null)
1380
1422
  changes.options = a.options_json;
1381
- if (!a.confirm) {
1382
- return text(confirmRequired("update field", { entity: a.entity_name, field: a.field_name }, changes));
1383
- }
1384
- return text(await entity.updateField(a.entity_name, a.field_name, {
1423
+ const opts = {
1385
1424
  newName: a.new_name,
1386
1425
  title: a.title,
1387
1426
  required: a.required,
@@ -1393,8 +1432,72 @@ export function buildToolTable() {
1393
1432
  isArray: a.is_array,
1394
1433
  encrypt: a.encrypt,
1395
1434
  options: a.options_json,
1396
- }));
1435
+ };
1436
+ if (!a.confirm) {
1437
+ // Refuse in the preview what the confirmed call would refuse (reads only).
1438
+ const refusal = await entity.updateFieldRefusal(a.entity_name, a.field_name, opts);
1439
+ if (refusal)
1440
+ return text(refusal);
1441
+ return text(confirmRequired("update field", { entity: a.entity_name, field: a.field_name }, changes));
1442
+ }
1443
+ return text(await entity.updateField(a.entity_name, a.field_name, opts));
1397
1444
  });
1445
+ reg("suppa_change_field_type", {
1446
+ description: "Change a field's TYPE, converting every row (POST /core/builder/<entity>/<field>/\n" +
1447
+ " update-field, planned first by /change-plan). Converts only plain types: text,\n" +
1448
+ " numeric, integer, boolean, timestamp, json, icon, uuid, multi-language — never a\n" +
1449
+ " relation, enum, file, serial or multi-type (add a new field instead). sub_type\n" +
1450
+ " date|time|timestamp on a timestamp field is a type change too.\n\n" +
1451
+ " Without confirm it is a DRY RUN: the platform's own plan comes back — decision\n" +
1452
+ " (ready / needs-input / refused), rows, and every conflict with sample values and\n" +
1453
+ " what it does. A refused plan is never sent. A LOSS is sent only when accepted by\n" +
1454
+ " name: accept_locale_loss (multi-language → text keeps one language per row; json\n" +
1455
+ " keeps all), accept_stash_restore (changing BACK to an earlier type restores the\n" +
1456
+ " column saved then — later edits reverted, newer rows NULL). A default the new type\n" +
1457
+ " cannot hold needs default_value or drop_default in the same call. The column\n" +
1458
+ " converts under an ACCESS EXCLUSIVE lock, and even the dry run holds that lock while\n" +
1459
+ " it scans; tables over 500,000 rows are refused. Show the plan to the user first.\n\n" +
1460
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and changes nothing.",
1461
+ inputSchema: {
1462
+ entity_name: EntityName,
1463
+ field_name: z.string().describe("The field to convert."),
1464
+ type: z
1465
+ .string()
1466
+ .describe("The new field type — 'timestamp' too when only a timestamp's sub_type changes."),
1467
+ sub_type: z
1468
+ .enum(["date", "time", "timestamp"])
1469
+ .nullable()
1470
+ .default(null)
1471
+ .describe("A timestamp field's new subtype (date → timestamp converts; the reverse is refused)."),
1472
+ default_value: z
1473
+ .string()
1474
+ .nullable()
1475
+ .default(null)
1476
+ .describe("New default, sent with the change. Omit to keep the stored one."),
1477
+ drop_default: z
1478
+ .boolean()
1479
+ .default(false)
1480
+ .describe("Drop the default with the change."),
1481
+ accept_locale_loss: z
1482
+ .boolean()
1483
+ .default(false)
1484
+ .describe("Accept that multi-language → text keeps one language per row."),
1485
+ accept_stash_restore: z
1486
+ .boolean()
1487
+ .default(false)
1488
+ .describe("Accept restoring the column saved at an earlier conversion."),
1489
+ confirm: Confirm,
1490
+ },
1491
+ annotations: _MUT,
1492
+ }, async (a) => text(await fieldTypeChange.changeFieldType(a.entity_name, a.field_name, {
1493
+ type: a.type,
1494
+ subType: a.sub_type,
1495
+ defaultValue: a.default_value,
1496
+ dropDefault: a.drop_default,
1497
+ acceptLocaleLoss: a.accept_locale_loss,
1498
+ acceptStashRestore: a.accept_stash_restore,
1499
+ confirm: a.confirm,
1500
+ })));
1398
1501
  reg("suppa_add_enum_values", {
1399
1502
  description: "Add values to an enum (lookup table). values: comma-separated 'code' or\n" +
1400
1503
  " 'code:Label' — a value with no label is stored with the code as its label.\n" +
@@ -1567,8 +1670,8 @@ export function buildToolTable() {
1567
1670
  ' declaration: {"entity","context_field","fields":[{"name","type","title","contexts":["PL"]}]}.\n' +
1568
1671
  " Idempotent — a second run answers already_converged. Creates per context in ONE atomic\n" +
1569
1672
  " batch, then links existing fields into their other contexts.\n" +
1570
- " NEVER deletes (a dropped field is reported as not_declared; removal reserves its name for\n" +
1571
- " good) and never changes a type (type_drift — that is a data migration).\n" +
1673
+ " NEVER deletes (a dropped field → not_declared), never re-creates a REMOVED one (→ parked:\n" +
1674
+ " restore it) and never changes a type (type_drift — that is a data migration).\n" +
1572
1675
  " Dry run by default; confirm=true applies.",
1573
1676
  inputSchema: {
1574
1677
  declaration: z
@@ -1704,7 +1807,7 @@ export function buildToolTable() {
1704
1807
  " this server does not expose; every delete tool here is the reversible one.\n\n" +
1705
1808
  " Removes a single instance, not the entity/schema. Entities and fields are\n" +
1706
1809
  " created with suppa_create_entity / suppa_add_field and edited with\n" +
1707
- " suppa_update_field (a field's type is never changeable); REMOVING a core field\n" +
1810
+ " suppa_update_field (its type with suppa_change_field_type); REMOVING a core field\n" +
1708
1811
  " is UI-only. Custom fields have their own reversible pair:\n" +
1709
1812
  " suppa_remove_custom_field / suppa_restore_custom_field.\n\n" +
1710
1813
  " APPROVAL GATE: without confirm=true this returns a confirmation request and deletes nothing.",
@@ -2512,18 +2615,19 @@ export function buildToolTable() {
2512
2615
  annotations: _READ,
2513
2616
  }, async (a) => text(await formV2.validateFormSchema(a.path, a.baseline_path ?? null, a.normalize ?? false)));
2514
2617
  reg("suppa_write_form_draft", {
2515
- description: "Save a Suppa 2.0 form as a DRAFT on the tenant. It never publishes.\n\n" +
2516
- " Measured on a 2.1 tenant: `Forms.schema` is the working draft (11 of 12 forms in\n" +
2517
- " `editing` hold a column that differs from their own published snapshot), and a\n" +
2518
- " FormVersions row is the published form. This writes the column and creates no version,\n" +
2519
- " so nothing anyone else sees changes until a human publishes in the builder.\n\n" +
2618
+ description: "Save a Suppa 2.0 form as a DRAFT on the tenant, through the builder's own save\n" +
2619
+ " (PUT /core/forms/:id/schema). It never publishes: what others see stays the published\n" +
2620
+ " version; a published form reads `editing`. The save appears in the builder's History.\n\n" +
2520
2621
  " The gate runs first on the same file: a refusal or any error and nothing is written.\n" +
2521
2622
  " The row is read first and a read that does not clearly succeed ABORTS — merging over a\n" +
2522
2623
  " failed read is how a saved mobile layout and code-form vanish on a call returning 200.\n" +
2523
- " `status`, mobileSchema, code, variables, localizations, entity, alias, parent and\n" +
2524
- " parentVersion are never in the payload; a child form's `schema.overrides` is preserved.\n\n" +
2525
- " Refuses while someone else has the form open in the builder (lockedBy).\n" +
2526
- " Without confirm=true it returns the plan and writes nothing.",
2624
+ " Writes schema and settings; `variables` only when the draft lists some — the list is the\n" +
2625
+ " FULL state (an omitted variable is deleted), so an empty one is never sent and one that\n" +
2626
+ " drops the form's default variable is refused. mobileSchema, code, localizations, entity,\n" +
2627
+ " alias and parent are never sent; a child form's `schema.overrides` is preserved.\n\n" +
2628
+ " Refuses while someone else has the form open in the builder (lockedBy). Without\n" +
2629
+ " confirm=true it returns the plan and a `revision`; pass it back as expected_revision and\n" +
2630
+ " a form that moved since the preview is refused, not overwritten.",
2527
2631
  inputSchema: {
2528
2632
  form_id: z.number().describe("The Forms row id — the `form=` in the builder URL."),
2529
2633
  path: z
@@ -2537,9 +2641,58 @@ export function buildToolTable() {
2537
2641
  .boolean()
2538
2642
  .optional()
2539
2643
  .describe("Run the repair pipeline before checking AND saving, so what is stored is what was verified."),
2644
+ expected_revision: z
2645
+ .string()
2646
+ .optional()
2647
+ .describe("The `revision` from the preview: the save is refused if the form changed since."),
2540
2648
  },
2541
2649
  annotations: _MUT,
2542
- }, async (a) => text(await formV2.writeFormDraft(a.form_id, a.path, a.confirm ?? false, a.normalize ?? false)));
2650
+ }, async (a) => text(await formV2.writeFormDraft(a.form_id, a.path, a.confirm ?? false, a.normalize ?? false, a.expected_revision ?? null)));
2651
+ reg("suppa_create_form_v2", {
2652
+ description: "Create a Suppa 2.0 form: the row and its draft in one transaction (POST /core/forms/schema),\n" +
2653
+ " as the builder does — isFormBuilderV2 stamped, the default variable added (a relation named\n" +
2654
+ " after the entity, or `submitData` on an entity-less form). A draft, nothing is published.\n" +
2655
+ " `path` (optional) is a draft file, gated first. A duplicate name or an unknown entity or\n" +
2656
+ " folder is refused before any write. `workspace` forms inherit the base form: builder only.\n" +
2657
+ " A dashboard is `custom` with folder='dashboards'. Without confirm=true: the plan only.",
2658
+ inputSchema: {
2659
+ name: z.string().describe("Unique on the tenant."),
2660
+ type: z.enum(formLifecycle.CREATABLE_FORM_TYPES).describe("create / update need an entity; custom may have none."),
2661
+ entity: z.string().optional().describe("Entity system name the form edits."),
2662
+ path: z.string().optional().describe("Absolute path to a draft JSON { schema, settings, variables }."),
2663
+ folder: z.string().optional().describe("FormsFolders alias or id to file the form into."),
2664
+ confirm: z.boolean().default(false).describe("true = create. Omitted means NO."),
2665
+ },
2666
+ annotations: _ADD,
2667
+ }, async (a) => text(await formLifecycle.createFormV2(a.name, a.type, a.entity ?? null, a.path ?? null, a.folder ?? null, a.confirm ?? false)));
2668
+ reg("suppa_form_versions", {
2669
+ description: "A Suppa 2.0 form's published versions (newest first, which one users see), optionally the\n" +
2670
+ " component diff between two of THIS form's versions, and a summary of the last N draft\n" +
2671
+ " saves (change-sets, without their patches). Read-only.",
2672
+ inputSchema: {
2673
+ form_id: z.number().int(),
2674
+ diff_from: z.number().int().optional().describe("Version id to diff from (with diff_to)."),
2675
+ diff_to: z.number().int().optional().describe("Version id to diff to."),
2676
+ change_sets: z.number().int().min(1).max(50).optional().describe("How many recent draft saves to summarize."),
2677
+ },
2678
+ annotations: _READ,
2679
+ }, async (a) => text(await formLifecycle.formVersions(a.form_id, a.diff_from ?? null, a.diff_to ?? null, a.change_sets ?? null)));
2680
+ reg("suppa_form_lifecycle", {
2681
+ description: "Publish, roll back, discard or promote a Suppa 2.0 form. publish freezes the draft as the\n" +
2682
+ " new default version, live for every user. rollback RESTORES an old version over the draft\n" +
2683
+ " and PUBLISHES it. discard overwrites the draft with the live version — unrecoverable, no\n" +
2684
+ " history. promote makes a version the one users see. publish and rollback are refused when\n" +
2685
+ " the form gate finds errors the live version does not have; rollback and promote refuse a\n" +
2686
+ " version of another form (the platform would act on THAT form). Without confirm=true: the\n" +
2687
+ " preview only.",
2688
+ inputSchema: {
2689
+ form_id: z.number().int(),
2690
+ action: z.enum(formLifecycle.LIFECYCLE_ACTIONS),
2691
+ version_id: z.number().int().optional().describe("rollback / promote: the FormVersions id (suppa_form_versions)."),
2692
+ confirm: z.boolean().default(false).describe("true = do it. Omitted means NO."),
2693
+ },
2694
+ annotations: _ONCE,
2695
+ }, async (a) => text(await formLifecycle.formLifecycle(a.form_id, a.action, a.version_id ?? null, a.confirm ?? false)));
2543
2696
  reg("suppa_validate_entity_code", {
2544
2697
  description: "Run the schema gate over an application repo's *.entity.ts / *.seed.ts / module files.\n\n" +
2545
2698
  " CALL THIS BEFORE REPORTING ANY ENTITY OR SEED FILE DONE. It is the same checker the\n" +
@@ -2765,7 +2918,8 @@ export function buildServer() {
2765
2918
  },
2766
2919
  }, (a) => `Write Suppa 2.0 application schema code for: ${a.entity_purpose}\n\n` +
2767
2920
  "Follow the bundled 'suppa-entity-code' skill (skills/suppa-entity-code/SKILL.md inside the installed suppa-mcp-2 package):\n" +
2768
- "1. Pre-flight: the target app repo exists, uses @suppa/sdk@latest, and its tsconfig enables experimentalDecorators + emitDecoratorMetadata.\n" +
2921
+ "1. Pre-flight: the target app repo exists, its src/index.ts exports a named AppModule, @suppa/sdk is in dependencies at the version extension-runner ships (1.38.7 as of 2026-09-29 — newer APIs compile but are missing at runtime), " +
2922
+ "every runtime import is in dependencies, imports are relative (the platform build ignores the app tsconfig's paths/baseUrl), and its tsconfig enables experimentalDecorators + emitDecoratorMetadata for local tsc.\n" +
2769
2923
  "2. Resolve the blocking questions BEFORE writing any file: importKeyFields (the stable business key — wrong means duplicate seed rows on every restart), " +
2770
2924
  "representativeFieldName, and per-field nullable.\n" +
2771
2925
  "3. Write src/common/database/entities/*.entity.ts — @Entity class extending SystemBaseEntity; scalars via @Column({ type: FieldTypeEnum.X }); " +
@@ -2790,7 +2944,8 @@ export function buildServer() {
2790
2944
  "6. Gate before claiming done: node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root> " +
2791
2945
  "(strict by default — restated default options and unreferenced enum global names fail it, exit 1) " +
2792
2946
  "(or the skills/ dir of a checkout) reports 0 errors; npx tsc --noEmit passes; " +
2793
- "push, reload (POST /core/applications/:appId/reload), verify with suppa_describe_entity — " +
2947
+ "push, reload (POST /core/applications/:appId/reload), then read the Applications row (suppa_search_records on 'Applications': status, statusDetails, buildStatus, buildError, buildVersion — artifactRef is sudo-only and never comes back) " +
2948
+ "until buildStatus = ready and status = running — FAIL on status = failed or a statusDetails starting with 'Migration failed:', 'Migration did not run:' or 'Entity/Seeds import failed:' — and only then verify with suppa_describe_entity — " +
2794
2949
  "the gate fails with E301 if anything is unregistered — run it, do not assume.\n" +
2795
2950
  "Porting from Suppa 1.0? Read the schema with suppa_read_v1_entity_props / suppa_read_v1_enum and map per references/v1-mapping.md — " +
2796
2951
  "never invent a mapping; record data stays with suppa_migrate_entities_from_v1.");