suppa-mcp-2 1.12.1 → 1.13.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
@@ -404,10 +404,24 @@ target is chased through its import (relative, `.js`-suffixed or tsconfig-aliase
404
404
  into the file that declares it and reported as E116. A stub that kept its fields
405
405
  is E117, because each field is a column the migration would create on a table
406
406
  another application owns; the `.stub.entity.ts` name is what makes that rule
407
- checkable (W617 when it is missing, W616 when stubs share a file). Those, plus
407
+ checkable (W617 when it is missing, W616 when stubs share a file).
408
+
409
+ A stub stands in for a table so a relation can reach it. To **add columns** to an
410
+ entity you do not own — a platform system entity, or another application's — the
411
+ platform supports an **extension**: the entity's existing name, only your own
412
+ columns, in `<owner>.extension.entity.ts` (SKILL.md rule 20,
413
+ `references/extensions.md`). The mode is chosen by ownership at start, so the
414
+ filename is what lets the gate apply extension mode's restrictions before the
415
+ build does: entity options are ignored there (W618), `@OneToMany` /
416
+ `@ManyToManyBackRef` (E118) and `primary: true` (E119) are refused, `nullable:
417
+ false` needs a `default` (E120), and `@Index`/`@Check` may cover only the columns
418
+ you declare (E121). A relation to an entity you do not own names its target by
419
+ string and is typed by shape — right there, W620 anywhere else.
420
+
421
+ Those, plus
408
422
  `owner` first in a tabular part's `importKeyFields` (W607) and no `inverse` on
409
423
  `@ManyToOne`/`@ManyToMany` (W609), are the **rule violations** — W607, W609,
410
- W610, W611, W612, W613, W615, W616, W617 — and like errors they exit 1, because a
424
+ W610, W611, W612, W613, W615, W616, W617, W618, W620 — and like errors they exit 1, because a
411
425
  rule that only warns is a rule that gets ignored. `--no-strict` demotes them for a legacy repo, and says so:
412
426
  they print as `[rule violation, demoted]` and the summary ends `NOT a clean
413
427
  run`. Advisory warnings — W601-W606, W608, W614 — never block; they report what
package/dist/server.js CHANGED
@@ -12,6 +12,7 @@ import * as tasks from "./tools/tasks.js";
12
12
  import * as docs from "./tools/docs.js";
13
13
  import * as entity from "./tools/entity.js";
14
14
  import * as entityCode from "./tools/entityCode.js";
15
+ import { houseRulesDigest } from "./tools/entityCode.js";
15
16
  import * as files from "./tools/files.js";
16
17
  import * as forms from "./tools/forms.js";
17
18
  import * as migrate from "./tools/migrate.js";
@@ -213,6 +214,8 @@ const EntityQuery = z
213
214
  // ---------------------------------------------------------------------------
214
215
  // Server instructions — reproduced VERBATIM from server.py.
215
216
  // ---------------------------------------------------------------------------
217
+ /** Read once, from the one file that states the rules (see houseRulesDigest). */
218
+ const HOUSE_RULES_DIGEST = houseRulesDigest();
216
219
  const INSTRUCTIONS = `Suppa Platform MCP Server — manage Tasks, Docs/Pages, Entities, Forms, and file attachments on modern.suppa.me.
217
220
 
218
221
  AUTHENTICATION — RESOLVE THIS BEFORE ANY OTHER SUPPA WORK
@@ -268,14 +271,7 @@ ENTITY BUILDER (create + edit fields; removal is UI-only)
268
271
  - An enum value on a RECORD is a reference, not a string: write {"id": <Enums row id>} for enum and [{"id": ...}, ...] for multi-enum. A bare code like "red" is refused with 'field must contain id for many-to-one relationship'. Read the ids with suppa_search_records on 'Enums' filtered by name = the enum name.
269
272
  - Existing fields CAN be edited with suppa_update_field (name, title, notNull/unique/default, relation target, and the options above), within the platform's own limits: a field's TYPE can never be changed, its SUBTYPE only toggles 'encrypted' on/off (text fields only), and a system field takes just title + the options keys. Removing a field is still UI-only — this server has no remove-field call.
270
273
 
271
- WRITING ENTITY CODE (*.entity.ts in an application repo — NOT the API tools above)
272
- These five rules are house rules of this platform. They OVERRIDE the platform's own migrations doc, which contradicts two of them, and they override the style of the entities already in the repo you are editing — an existing file that breaks them is the habit these rules exist to stop, not a convention to match. The full skill is skills/suppa-entity-code/SKILL.md inside the installed suppa-mcp-2 package; these five bind whether or not you open it.
273
- 1. TYPE EVERY RELATION PROPERTY to match its decorator: @ManyToOne -> \`owner: Target;\` (\`owner?: Target\` when the relation is nullable), @ManyToMany/@OneToMany/@ManyToManyBackRef -> \`peers: Target[];\`. Never \`any\`.
274
- 2. ENUM MEMBER KEYS ARE PascalCase — \`NotFilled = 'Not filled'\`. The stored value is the string on the right and need not match the key.
275
- 3. NEVER WRITE A FIELD OPTION AT ITS DEFAULT. canGroup, canSort, showInTable, editFromTable and canFilter are already true; readOnly and searchable are already false. Write one ONLY where the field departs from that (usually just \`searchable: true\`). A field with all seven spelled out is wrong even though it works.
276
- 4. @Enum/@MultiEnum TAKE THE GLOBAL NAME ONLY WHEN THE ENUM IS GLOBAL — shared by another entity, or referenced from a seed record. Otherwise omit the first argument entirely: \`@Enum(StatusEnum, StatusTitles, { … })\`, and the decorator derives <ClassName>.<propertyName>. A field's own \`key: 'Entity.field'\` is the rename key, NOT a reference, and does not make the enum global.
277
- 5. A RELATION TARGET THAT ALREADY EXISTS on the tenant (created earlier, or owned by another application) gets a STUB, and a stub is three things at once: \`@Entity({ name: 'Accounts', key: 'Accounts' }) export class Accounts extends SystemBaseEntity {}\` with an EMPTY body, ALONE in a file named \`accounts.stub.entity.ts\`, and REGISTERED in forFeature() with the entities you create. Never a bare \`export class Accounts {}\` — it satisfies the thunk but registers nothing, so the platform cannot resolve the relation (E116). Never fields on a stub — every field is a column the migration would create on a table you do not own (E117). Platform system entities need no stub — import UsersEntity/FilesEntity/IconsEntity from @suppa/sdk.
278
- Before reporting the file done, run the gate: call suppa_validate_entity_code(path=<app-root>). It fails on every one of the five and names file:line. passed=false means fix and re-run, not "note and move on". (Same checker on the command line: node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root>.)
274
+ ${HOUSE_RULES_DIGEST}
279
275
 
280
276
  ATTACHMENTS (files on a record)
281
277
  - 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.
@@ -2186,6 +2182,13 @@ export function buildServer() {
2186
2182
  " + extends SystemBaseEntity, EMPTY body, its own file, registered in forFeature();\n" +
2187
2183
  " a bare 'export class Accounts {}' registers nothing (E116), and stubs sharing a file\n" +
2188
2184
  " are W616;\n" +
2185
+ " * to ADD columns to an entity you do NOT own (a system entity, or another\n" +
2186
+ " application's), declare an EXTENSION — the entity's existing name, only your own\n" +
2187
+ " columns, in <owner>.extension.entity.ts. Extension mode ignores entity options\n" +
2188
+ " (W618), refuses @OneToMany/@ManyToManyBackRef (E118) and primary: true (E119),\n" +
2189
+ " requires a default with nullable: false (E120), and allows @Index/@Check over your\n" +
2190
+ " own columns only (E121). A relation there names its target by string and is typed\n" +
2191
+ " by shape — that form is W620 anywhere else;\n" +
2189
2192
  " * 'owner' comes first in a tabular part's importKeyFields, and no 'inverse' is passed\n" +
2190
2193
  " to @ManyToOne/@ManyToMany.\n" +
2191
2194
  ' Pass the app ROOT, not one file: several rules read the whole repo ("nothing references\n' +
@@ -17,7 +17,7 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
17
17
  import { fileURLToPath, pathToFileURL } from "node:url";
18
18
  import { jsonResponse } from "../utils.js";
19
19
  /** A bundled skill script, from dist/tools/ or src/tools/ alike. */
20
- function skillScript(name) {
20
+ export function skillScript(name) {
21
21
  const here = dirname(fileURLToPath(import.meta.url));
22
22
  for (const root of [join(here, "..", ".."), join(here, "..", "..", "..")]) {
23
23
  const p = join(root, "skills", "suppa-entity-code", "scripts", name);
@@ -26,6 +26,45 @@ function skillScript(name) {
26
26
  }
27
27
  return null;
28
28
  }
29
+ /**
30
+ * The house-rules digest, READ from the file that defines it.
31
+ *
32
+ * The server instructions used to carry a pasted copy. Editing the rules then
33
+ * meant editing two files, and the copy fell behind — it still said "these five
34
+ * rules" after the sixth existed, so the text every agent reads first was the
35
+ * one text that was wrong. Read synchronously: the instructions are built when
36
+ * the server is constructed, and there is nothing to await at that point.
37
+ */
38
+ const BACKTICK = String.fromCharCode(96);
39
+ export function houseRulesDigest() {
40
+ const p = skillScript("house-rules.mjs");
41
+ if (!p)
42
+ return "";
43
+ try {
44
+ const src = readFileSync(p, "utf-8");
45
+ // A plain read, not an import: the instructions are assembled synchronously,
46
+ // and there is nothing to await when the server is being constructed.
47
+ // Sliced between markers rather than matched by regex — the text itself is a
48
+ // template literal full of backticks and backslashes.
49
+ const open = "export const HOUSE_RULES_DIGEST = " + BACKTICK;
50
+ const from = src.indexOf(open);
51
+ if (from === -1)
52
+ return "";
53
+ const to = src.indexOf(BACKTICK + ";", from + open.length);
54
+ if (to === -1)
55
+ return "";
56
+ // Undo the escaping the template literal needed to hold this text.
57
+ return src
58
+ .slice(from + open.length, to)
59
+ .split("\\" + BACKTICK)
60
+ .join(BACKTICK)
61
+ .split("\\$")
62
+ .join("$");
63
+ }
64
+ catch {
65
+ return "";
66
+ }
67
+ }
29
68
  function validatorPath() {
30
69
  return skillScript("validate-suppa-schema.mjs");
31
70
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.12.1",
3
+ "version": "1.13.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": {
@@ -40,13 +40,13 @@ Confirm all 5 before writing anything:
40
40
  ## Hard rules
41
41
 
42
42
  1. Every entity extends `SystemBaseEntity`; never declare `id`, `createdAt`, `updatedAt`, `deletedAt`, `createdBy`, `removedBy` yourself — it already provides them.
43
- 2. An entity class that is not in `EntityModule.forFeature()` does not exist — the platform creates no table for it (doc: "An entity class that is never passed to forFeature() is invisible"). Write the entity and register it in the SAME step; never move on to the next entity, or report progress, with an unregistered class. Being *named* in a `forFeature()` is not enough: the call's result must be consumed by an `@Module`'s `imports` (rule 20), or nothing is registered at all.
43
+ 2. An entity class that is not in `EntityModule.forFeature()` does not exist — the platform creates no table for it (doc: "An entity class that is never passed to forFeature() is invisible"). Write the entity and register it in the SAME step; never move on to the next entity, or report progress, with an unregistered class. Being *named* in a `forFeature()` is not enough: the call's result must be consumed by an `@Module`'s `imports` (rule 21), or nothing is registered at all.
44
44
  3. `default` is a SQL expression string — `'false'`, `"'draft'"` — never a JS value; a JS value is rejected at migration time.
45
45
  4. Scalars only via `@Column({ type: FieldTypeEnum.X })`; relations/enums/files are NEVER declared via `@Column` — use the `@ManyToOne`/`@ManyToMany`/`@OneToMany`/`@ManyToManyBackRef`/`@Enum`/`@MultiEnum`/`@File`/`@MultiFile` families.
46
46
  5. Relation targets are thunks — `() => Target`, never the class itself — or circular imports break.
47
47
  6. Do not pass the optional `inverse` selector to `@ManyToOne`/`@ManyToMany` — write `@ManyToOne(() => Target, { … })`. Add one only when the target class declares the paired back-reference and you are deliberately linking the two sides. An `inverse` must select a RELATION property on the target (`(task) => task.project`); `(e) => e.id` is always wrong — `id` is a system column, not a back-reference.
48
48
  7. If an option isn't in the reference tables (`references/entities.md`, `references/seeds.md`, `references/registration.md`), it doesn't exist — stop and ask, don't guess.
49
- 8. Every entity class must appear in the class array passed as `forFeature()`'s FIRST argument (there is no `entities` option — rule 20); every seed in the options object's `seeds` array, dependencies first — `workflowsSeed` before `stageWorkflowsSeed`.
49
+ 8. Every entity class must appear in the class array passed as `forFeature()`'s FIRST argument (there is no `entities` option — rule 21); every seed in the options object's `seeds` array, dependencies first — `workflowsSeed` before `stageWorkflowsSeed`.
50
50
  9. Seeds: every record carries all `importKeyFields` (or `$key`); relations are referenced by the target's import-key object, never a numeric id; no system columns; no `$readAccess`/`$updateAccess`/`$instanceAccess`; no reverse `@OneToMany` field, even as `[]`.
51
51
  10. Autoload paths (`entitiesPath`/`seedsPath`) point at `dist/`, never `src/` — autoloading reads compiled output.
52
52
  11. Renames need `key` set on `@Entity()`/`@Column()` BEFORE the rename ships — otherwise it's a drop-and-create, not a rename.
@@ -78,7 +78,22 @@ Confirm all 5 before writing anything:
78
78
  ```
79
79
 
80
80
  `.stub.entity.ts` still ends in `.entity.ts`, so discovery and `entitiesPath` autoload are unchanged. **Registration is not what protects the real table — the empty body is.** Leaving a stub out of `forFeature()` to "keep the migration away from it" only makes the relation unresolvable (E301); a *fielded* stub that is registered is the actual disaster, and E117 is the rule that stops it. Platform system entities (`Users`, `Files`, `Icons`, …) need no stub at all — import `UsersEntity`/`FilesEntity`/`IconsEntity` from `@suppa/sdk`. Template: `templates/relation-target-stub.template.ts`.
81
- 20. **`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.
81
+ 20. **To ADD columns to an entity you do not own, declare an EXTENSION — a stub cannot do it.** A stub stands in for a table so a relation can point at it, and its body stays empty (rule 19). An extension is the opposite: it exists to contribute columns to an entity the platform or another application owns — `accountId` on `Users`, `plan` on another application's `Tasks` — "without touching that entity or the fields someone else declared on it". There is no separate API: declare `@Entity({ name: 'Users' })` by the entity's existing name, list ONLY the columns you are adding, and register it in `forFeature()` like any other class. The platform decides the mode by ownership at start — yours or nobody's → own mode (create/update in full); someone else's → extension mode (only your fields are applied).
82
+ Because nothing in the code says which mode you will get, **the filename does**: `<entity-name>.extension.entity.ts`, class `<EntityName>Extension`. That is what makes the mode's restrictions checkable before the build:
83
+
84
+ | In extension mode | Why | Code |
85
+ |---|---|---|
86
+ | Entity options are IGNORED — `title`, `icon`, `type`, `options`, `representativeFieldName`, `importKeyFields`, localization | "silently and by design — they belong to the owner" | **W618** |
87
+ | No `@OneToMany` / `@ManyToManyBackRef` | "a reverse relation creates a field on the other entity" | **E118** |
88
+ | No `primary: true` | "the owner's primary key is not yours to redefine" | **E119** |
89
+ | No `nullable: false` without a `default` | the table already has rows, and each needs a value | **E120** |
90
+ | `@Index` / `@Check` only over columns YOU declare | anything else reaches into another owner's schema | **E121** |
91
+
92
+ Allowed, and unchanged from your own entities: `@Column()` of any type, `@ManyToOne`, `@ManyToMany`, `@Enum`, `@MultiEnum`, `@File`, `@MultiFile`. Your columns are real columns on the owner's table — selectable, filterable, in metadata, in history — and they follow the same remove/restore semantics as your own. You cannot remove a field you do not own; it is not in your declaration to begin with.
93
+ **A name collision fails the build and applies nothing** — `cannot declare field "Tasks.plan": it already exists and is owned by application "Planner"` — by NAME, not by key, and a soft-deleted field keeps its name reserved. A field a user added through the UI is *not* an owner: your declaration takes it over, data and all.
94
+ **Point a relation at an entity you do not own by NAME**: `@ManyToOne('Invoices', { … })` → `invoice?: { id: number }` — there is no class to import, so the string form is right here and only here (W620 everywhere else). Template: `templates/entity-extension.template.ts`; the doc's own section is transcribed in `references/extensions.md`.
95
+ **Prefer an entity-scoped enum in an extension.** A global enum name has no owning entity, so two applications using the same name write to the same rows — which is rule 18's default anyway: pass no name.
96
+ 21. **`EntityModule.forFeature()` must be consumed by an `@Module`, and has exactly two shapes.** It RETURNS a module: put it in `@Module({ imports: [...] })` and export that class from `src/index.ts` as `AppModule` — a bare `EntityModule.forFeature(...);` statement discards the result and registers nothing (E307). The two shapes (`references/registration.md`) are `forFeature([A, B], { seeds: [...] })` — classes FIRST, options second — and `forFeature({ entitiesPath, seedsPath })` for autoloading. The options object accepts only `seeds`, `entitiesPath` and `seedsPath`. `forFeature({ entities: [...] })` looks reasonable and registers NOTHING: the classes are dropped with the unknown option and no table is created for any of them. E306.
82
97
 
83
98
  ## Decorator decision table
84
99
 
@@ -94,6 +109,7 @@ Confirm all 5 before writing anything:
94
109
  | …the same, but shared across entities or referenced from a seed | `@Enum('<Entity>.<field>', <Field>Enum, <Field>Titles?, options?)` |
95
110
  | Fixed multi-select value set | `@MultiEnum(...)` — same signatures as `@Enum` |
96
111
  | Foreign key on this entity | `@ManyToOne(() => Target, options?)` → `prop: Target;` — **no inverse** |
112
+ | ADD a column to an entity the platform or another application owns | **Extension** — `@Entity({ name: 'Users' }) export class UsersExtension extends SystemBaseEntity { … your columns only … }` in `users.extension.entity.ts`, registered in `forFeature()`; see `templates/entity-extension.template.ts` (rule 20) |
97
113
  | Relation to an entity that ALREADY EXISTS on the tenant (another application's, or created outside this package) | **Stub** — `@Entity({ name, key }) export class X extends SystemBaseEntity {}`, EMPTY body, its own file, registered in `forFeature()`; see `templates/relation-target-stub.template.ts` (rule 19). System entities: import `UsersEntity`/`FilesEntity`/… from `@suppa/sdk` instead |
98
114
  | Pivot table between two entities | `@ManyToMany(() => Target, options?)` → `prop: Target[];` — **no inverse** |
99
115
  | Reverse side of a `@ManyToMany` | `@ManyToManyBackRef(() => Target, (t) => t.<thisRelationProp>, options?)` → `prop: Target[];` |
@@ -139,6 +155,7 @@ A `@ManyToOne` without `nullable: false` is written `owner?: ProductMatrixEntity
139
155
  | Thing | Convention | Example |
140
156
  |---|---|---|
141
157
  | Entity/seed file | kebab-case, plural | `stage-workflows.entity.ts` / `stage-workflows.seed.ts` |
158
+ | **Extension file** (rule 20) | kebab-case of the OWNER's entity name + `.extension.entity.ts`; class `<EntityName>Extension` | `users.extension.entity.ts` -> `UsersExtension` |
142
159
  | **Stub file** (rule 19) | kebab-case + `.stub.entity.ts` — one stub per file; the suffix is what makes the empty-body rule checkable | `accounts.stub.entity.ts` |
143
160
  | Entity class | PascalCase, plural = `@Entity()`'s `name` | `StageWorkflows` |
144
161
  | Seed export | camelCase plural + `Seed` | `stageWorkflowsSeed` |
@@ -288,6 +305,15 @@ The validator parses with the TypeScript compiler API, read from the app repo yo
288
305
  | A tabular part's rows land on/read from the wrong parent | `owner`'s `@ManyToOne` target resolves to an entity whose `@Entity()` name doesn't match `relationEntityName` | E109 |
289
306
  | A tabular part's business key isn't scoped to its parent | `owner` is present in `importKeyFields` but not first | W607 |
290
307
  | A relation targets a bare class (`export class Accounts {}`), or one respelled as `const Accounts = class {}` | Not an `@Entity` class — the thunk compiles but the platform cannot resolve the relation. Declare a stub per rule 19 | E116 |
308
+ | Columns must be added to an entity the platform or another application owns | Not a stub — a stub's body is empty. Declare an EXTENSION: `@Entity({ name: '<Owner>' })` + only your columns, in `<owner>.extension.entity.ts` (rule 20) | E117 points here |
309
+ | An extension sets `title` / `representativeFieldName` / `importKeyFields` and nothing happens | Extension mode ignores every entity-level option — they belong to the owner | W618 (blocks the gate) |
310
+ | An extension declares `@OneToMany` / `@ManyToManyBackRef` | A reverse relation creates a field on the OTHER entity; declare the owning side here instead | E118 |
311
+ | An extension declares `primary: true` | The owner's primary key is not yours to redefine | E119 |
312
+ | `nullable: false` on an extension column | The table already has rows; each needs a value, so a `default` is mandatory (and on a big table, ship it nullable and backfill separately) | E120 |
313
+ | An extension's `@Index`/`@Check` names a column it does not declare | An extension may only index or constrain its OWN columns | E121 |
314
+ | The build stops with `cannot declare field "X.y": it already exists and is owned by application "Z"` | Field names have exactly one owner, matched by NAME (not key) — and a soft-deleted field keeps its name reserved. Nothing is applied. Rename yours, or agree with that team | not statically checkable |
315
+ | The build stops with `refusing to build system metadata: this is an application build but applicationId is missing` | The platform is older than extension mode, or the runner does not pass the application id. Update the platform — there is nothing to change in the code | not statically checkable |
316
+ | A relation names its target with a string (`@ManyToOne('Invoices', …)`) in an ordinary entity | That form is for extensions, where the target belongs to another application and there is no class to import | W620 (blocks the gate) |
291
317
  | A stub kept its fields, and the migration altered a table another application owns | The empty body is the whole point of a stub — a fielded one converges columns onto the real table | E117 |
292
318
  | A field-less entity that is really a stub, in an ordinary `*.entity.ts` | Nothing marks it as a stub, so E117 cannot apply — rename to `<name>.stub.entity.ts` | W617 (blocks the gate) |
293
319
  | Several stubs piled into one `relation-targets.ts` | Each existing-entity stub lives in its OWN file | W616 (blocks the gate) |
@@ -0,0 +1,138 @@
1
+ # Extending an entity you do not own — verbatim rules
2
+
3
+ Transcribed from docs.modern-expo.com/backend/application-developing/migrations.html, section "Extending an Entity You Do Not Own" (captured 2026-08-18). The full capture is `docs/superpowers/specs/captures/migrations-extending-an-entity.txt` in the suppa-mcp-2 repository. If a rule is not here, it does not exist — stop and ask.
4
+
5
+ ## What it is
6
+
7
+ > Your application can add its own columns to an entity that belongs to the platform or to another application — `accountId` on `Users`, `plan` on another application's `Tasks` — without touching that entity or the fields someone else declared on it.
8
+
9
+ There is **no separate API**. Declare the entity by its existing name and list only the columns you are adding:
10
+
11
+ ```ts
12
+ import { Column, Entity, FieldTypeEnum, SystemBaseEntity } from '@suppa/sdk';
13
+
14
+ @Entity({ name: 'Users' })
15
+ export class UsersExtension extends SystemBaseEntity {
16
+ @Column({
17
+ type: FieldTypeEnum.Numeric,
18
+ nullable: true,
19
+ title: { en: 'Account', uk: 'Акаунт' },
20
+ })
21
+ accountId?: number;
22
+ }
23
+ ```
24
+
25
+ Register it in `EntityModule.forFeature()` like any other entity. On start the platform looks up who owns `Users`; because it is not yours, the declaration is applied in **extension mode** — only `accountId` is created, recorded as belonging to your application.
26
+
27
+ ## Own mode and extension mode
28
+
29
+ The mode is decided **per declared entity, by ownership**, not by anything you write:
30
+
31
+ | Situation | Mode | Result |
32
+ |---|---|---|
33
+ | No entity with that name exists | own | The entity is created and belongs to your application |
34
+ | The entity exists and is already yours | own | Full update: title, options, icon, fields — everything converges as usual |
35
+ | The entity exists and belongs to the platform or another application | extension | Only your new fields are applied; the entity itself is left exactly as its owner declared it |
36
+
37
+ In extension mode the entity-level options of your declaration are **ignored, silently and by design** — they belong to the owner: `title`, `icon`, `type`, `options`, `representativeFieldName`, `importKeyFields`, and the entity's localization.
38
+
39
+ Everything else works as it does for your own entities. Your extension columns are real columns on the owner's table: selectable and filterable through Query Manager, present in metadata and forms, and taking part in history like any other field.
40
+
41
+ ## What you may declare
42
+
43
+ | Allowed | Not allowed in extension mode |
44
+ |---|---|
45
+ | `@Column()` of any type | `primary: true` — the owner's primary key is not yours to redefine |
46
+ | `@ManyToOne()`, `@ManyToMany()` | `@OneToMany()`, `@ManyToManyBackRef()` — a reverse relation creates a field on the other entity |
47
+ | `@Enum()`, `@MultiEnum()`, `@File()`, `@MultiFile()` | `nullable: false` without a default |
48
+ | `@Index()` / `@Check()` over your own fields | `@Index()` / `@Check()` covering a field you do not own |
49
+
50
+ `nullable: false` is the one worth understanding: adding a NOT NULL column to a table that already has rows requires a value for those rows, so a default is mandatory.
51
+
52
+ > **WARNING**
53
+ > On a large table — `Users` in a mature workspace — backfilling that default holds a lock for as long as the migration transaction runs. If the table is big, ship the column as nullable first and fill it separately.
54
+
55
+ ## Name collisions fail the build
56
+
57
+ A field name on an entity has exactly one owner. If the name you declare belongs to the platform or to another application, the build fails and names the owner:
58
+
59
+ ```txt
60
+ [suppa:migrations] cannot declare field "Tasks.plan": it already exists and is
61
+ owned by application "Planner".
62
+ ```
63
+
64
+ Nothing is applied — no partial artifact. The check is **by name, not only by key**: a collision is reported even when the other owner declared that name with an explicit key. A name stays taken while a soft-deleted row still holds it, which is why removing a field does not immediately free its name for someone else.
65
+
66
+ **Custom fields are not a collision.** A field a user added through the workspace UI is not an owner for this check. When your declaration catches up with such a field — same entity, same name — you take it over: the field becomes part of your application's schema, keeping its column and its data, and from then on it follows your declaration.
67
+
68
+ ## Removing and restoring your extension columns
69
+
70
+ They follow exactly the remove / re-add semantics of your own entities: dropping the property soft-deletes the field and renames the column, re-declaring it restores the same row with its data. What you cannot do is remove a field you do not own — it is not in your declaration in the first place, and the owner's fields are never part of your diff.
71
+
72
+ ## Requirements
73
+
74
+ Extension mode needs a platform new enough to store per-row ownership and a runner that passes your application's id to the SDK. If the platform is older, the build refuses to produce an artifact rather than write rows that could never be attributed afterwards:
75
+
76
+ ```txt
77
+ [suppa:migrations] refusing to build system metadata: this is an application
78
+ build but applicationId is missing.
79
+ ```
80
+
81
+ Update the platform if you see it — there is nothing to change in your code.
82
+
83
+ ## Known limits
84
+
85
+ - **Global enum names are shared.** `@Enum('SharedStatus', …)` has no owning entity, so two applications using the same global name write to the same enum rows. Prefer an entity-scoped enum (the default, when you pass no name) unless sharing is what you want — which is also SKILL.md rule 18.
86
+ - **Uninstalling an application does not remove its extension columns.** They stay on the owner's table until someone removes them by hand.
87
+
88
+ ## Example: two applications on one entity
89
+
90
+ Application **Planner** owns `Tasks`:
91
+
92
+ ```ts
93
+ @Entity({
94
+ name: 'Tasks',
95
+ title: { en: 'Tasks', uk: 'Задачі' },
96
+ representativeFieldName: 'name',
97
+ })
98
+ export class Tasks extends SystemBaseEntity {
99
+ @Column({ type: FieldTypeEnum.Text, nullable: false })
100
+ name: string;
101
+ }
102
+ ```
103
+
104
+ Application **Billing** adds two columns of its own to the same entity, and an index over them:
105
+
106
+ ```ts
107
+ import {
108
+ Column,
109
+ Entity,
110
+ FieldTypeEnum,
111
+ Index,
112
+ ManyToOne,
113
+ SystemBaseEntity,
114
+ } from '@suppa/sdk';
115
+
116
+ @Entity({ name: 'Tasks' })
117
+ @Index('idx_tasks_billing_plan', ['plan'])
118
+ export class TasksBillingExtension extends SystemBaseEntity {
119
+ @Column({
120
+ type: FieldTypeEnum.Text,
121
+ nullable: true,
122
+ title: { en: 'Billing plan', uk: 'Тарифний план' },
123
+ })
124
+ plan?: string;
125
+
126
+ @ManyToOne('Invoices', {
127
+ title: { en: 'Invoice', uk: 'Рахунок' },
128
+ })
129
+ invoice?: { id: number };
130
+ }
131
+ ```
132
+
133
+ After both applications start, the `Tasks` table has `name`, `plan` and `invoiceId`. Planner's declaration is unchanged and unaware of the two extra columns; Billing owns them and can alter, remove or restore them. Neither application can modify the other's fields, and `Tasks` itself — its title, its representative field — still belongs to Planner.
134
+
135
+ > **HOUSE RULE — the filename declares the intent (SKILL.md rule 20).**
136
+ > Nothing in the code above says which mode it will get: the platform decides by ownership at start. Name the file `<owner-entity>.extension.entity.ts` and the class `<EntityName>Extension`, as the doc's own examples do. That is what lets the validator apply the restrictions in this section BEFORE the build refuses them — W618, E118, E119, E120, E121 — instead of after.
137
+ >
138
+ > Note the relation form: `@ManyToOne('Invoices', …)` names the target by STRING, because there is no class to import for an entity another application owns, and the property is typed by shape — `invoice?: { id: number }`. That is right here and only here; in your own entities a relation target is a thunk (rule 5), and the string form is W620.
@@ -95,21 +95,38 @@ function appRootFor(file) {
95
95
  * ONLY for fixtures. An exclusion over real schema code is a rule you have
96
96
  * turned off.
97
97
  */
98
- function ignorePatterns(root) {
98
+ function ignoreSpec(root) {
99
99
  const p = join(root, ".suppa-gate-ignore");
100
- if (!existsSync(p)) return [];
100
+ if (!existsSync(p)) {
101
+ // …then every ancestor's. An exclusion the repository declared must not be
102
+ // defeated by a nested package.json: a fixture APP inside test/fixtures is
103
+ // its own application root, so the root-level exclusion stopped applying to
104
+ // it and the guard refused commits that touched the very fixtures it was
105
+ // told to leave alone. Patterns are matched relative to the directory that
106
+ // DECLARED them, which is the only reading under which they still mean what
107
+ // they said.
108
+ const parent = dirname(root);
109
+ return parent && parent !== root ? ignoreSpec(parent) : { dir: root, patterns: [] };
110
+ }
101
111
  // No blanket catch: a missing file is answered above, and anything else here
102
112
  // is a bug in this script. Swallowing it silently is how an unimported `join`
103
113
  // turned every exclusion into "no exclusions" without a word.
104
- return readFileSync(p, "utf-8")
114
+ const patterns = readFileSync(p, "utf-8")
105
115
  .split(/\r?\n/)
106
116
  .map((l) => l.trim())
107
117
  .filter((l) => l && !l.startsWith("#"));
118
+ return { dir: root, patterns };
119
+ }
120
+
121
+ function ignorePatterns(root) {
122
+ return ignoreSpec(root).patterns;
108
123
  }
109
124
 
110
- function isIgnored(root, file, patterns = ignorePatterns(root)) {
125
+ function isIgnored(root, file, spec = ignoreSpec(root)) {
126
+ const patterns = Array.isArray(spec) ? spec : spec.patterns;
127
+ const base = Array.isArray(spec) ? root : spec.dir;
111
128
  if (!patterns.length) return false;
112
- const rel = relative(root, resolve(file)).replace(/\\/g, "/");
129
+ const rel = relative(base, resolve(file)).replace(/\\/g, "/");
113
130
  return patterns.some((pat) => {
114
131
  const p = pat.replace(/\/+$/, "");
115
132
  return rel === p || rel.startsWith(`${p}/`) || rel.includes(p);
@@ -127,8 +144,8 @@ function runGate(root) {
127
144
  } catch {
128
145
  return { skipped: `cannot read ${root}` };
129
146
  }
130
- const patterns = ignorePatterns(root);
131
- if (patterns.length) files = files.filter((f) => !isIgnored(root, f, patterns));
147
+ const spec = ignoreSpec(root);
148
+ if (spec.patterns.length) files = files.filter((f) => !isIgnored(root, f, spec));
132
149
  if (!files.length) return { skipped: `no schema files under ${root}` };
133
150
 
134
151
  let res;
@@ -14,17 +14,20 @@
14
14
  */
15
15
 
16
16
  export const HOUSE_RULES_DIGEST = `WRITING ENTITY CODE (*.entity.ts in an application repo — NOT the API tools above)
17
- These five rules are house rules of this platform. They OVERRIDE the platform's own migrations doc, which contradicts two of them, and they override the style of the entities already in the repo you are editing — an existing file that breaks them is the habit these rules exist to stop, not a convention to match. The full skill is skills/suppa-entity-code/SKILL.md inside the installed suppa-mcp-2 package; these five bind whether or not you open it.
17
+ These six rules are house rules of this platform. They OVERRIDE the platform's own migrations doc, which contradicts two of them, and they override the style of the entities already in the repo you are editing — an existing file that breaks them is the habit these rules exist to stop, not a convention to match. The full skill is skills/suppa-entity-code/SKILL.md inside the installed suppa-mcp-2 package; these six bind whether or not you open it.
18
18
  1. TYPE EVERY RELATION PROPERTY to match its decorator: @ManyToOne -> \`owner: Target;\` (\`owner?: Target\` when the relation is nullable), @ManyToMany/@OneToMany/@ManyToManyBackRef -> \`peers: Target[];\`. Never \`any\`.
19
19
  2. ENUM MEMBER KEYS ARE PascalCase — \`NotFilled = 'Not filled'\`. The stored value is the string on the right and need not match the key.
20
20
  3. NEVER WRITE A FIELD OPTION AT ITS DEFAULT. canGroup, canSort, showInTable, editFromTable and canFilter are already true; readOnly and searchable are already false. Write one ONLY where the field departs from that (usually just \`searchable: true\`). A field with all seven spelled out is wrong even though it works.
21
21
  4. @Enum/@MultiEnum TAKE THE GLOBAL NAME ONLY WHEN THE ENUM IS GLOBAL — shared by another entity, or referenced from a seed record. Otherwise omit the first argument entirely: \`@Enum(StatusEnum, StatusTitles, { … })\`, and the decorator derives <ClassName>.<propertyName>. A field's own \`key: 'Entity.field'\` is the rename key, NOT a reference, and does not make the enum global.
22
- 5. A RELATION TARGET THAT ALREADY EXISTS on the tenant (created earlier, or owned by another application) gets a STUB, and a stub is three things at once: \`@Entity({ name: 'Accounts', key: 'Accounts' }) export class Accounts extends SystemBaseEntity {}\` with an EMPTY body, ALONE in a file named \`accounts.stub.entity.ts\`, and REGISTERED in forFeature() with the entities you create. Never a bare \`export class Accounts {}\` — it satisfies the thunk but registers nothing, so the platform cannot resolve the relation (E116). Never fields on a stub — every field is a column the migration would create on a table you do not own (E117). Platform system entities need no stub — import UsersEntity/FilesEntity/IconsEntity from @suppa/sdk.
23
- Before reporting the file done, run the gate: call suppa_validate_entity_code(path=<app-root>). It fails on every one of the five and names file:line. passed=false means fix and re-run, not "note and move on". (Same checker on the command line: node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root>.)`;
22
+ 5. A RELATION TARGET THAT ALREADY EXISTS on the tenant (created earlier, or owned by another application) gets a STUB, and a stub is three things at once: \`@Entity({ name: 'Accounts', key: 'Accounts' }) export class Accounts extends SystemBaseEntity {}\` with an EMPTY body, ALONE in a file named \`accounts.stub.entity.ts\`, and REGISTERED in forFeature() with the entities you create. Never a bare \`export class Accounts {}\` — it satisfies the thunk but registers nothing, so the platform cannot resolve the relation (E116). Never fields on a stub — a stub only stands in so a relation can point at the table (E117); to ADD columns there, see rule 6. Platform system entities need no stub — import UsersEntity/FilesEntity/IconsEntity from @suppa/sdk.
23
+ 6. TO ADD COLUMNS TO AN ENTITY YOU DO NOT OWN, DECLARE AN EXTENSION — not a stub, and there is no separate API. Declare the entity by its EXISTING name with only your own columns, in a file named \`<owner-entity>.extension.entity.ts\` (class \`<OwnerEntity>Extension\`), and register it like any other entity: \`@Entity({ name: 'Users' }) export class UsersExtension extends SystemBaseEntity { @Column({ type: FieldTypeEnum.Numeric, nullable: true }) accountId?: number; }\`. The platform picks the mode by OWNERSHIP at start. In extension mode: entity options are IGNORED (title/icon/type/options/representativeFieldName/importKeyFields — W618), no @OneToMany or @ManyToManyBackRef (E118), no \`primary: true\` (E119), no \`nullable: false\` without a default (E120), and @Index/@Check only over your own columns (E121). A relation to an entity you do not own is named by STRING and typed by shape — \`@ManyToOne('Invoices', { … }) invoice?: { id: number };\` — which is right there and nowhere else (W620).
24
+ Before reporting the file done, run the gate: call suppa_validate_entity_code(path=<app-root>). It fails on every one of the six and names file:line. passed=false means fix and re-run, not "note and move on". (Same checker on the command line: node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root>.)`;
24
25
 
25
26
  /** What the gate blocks on, for a message that must not understate it. */
26
27
  export const BLOCKING_SUMMARY =
27
28
  "relation typing (E114/E115/W610/W615), PascalCase enum keys (W611), no option written at its " +
28
29
  "default (W612), no global enum name on a local enum (W613), existing-entity stubs " +
29
- "(E116/E117/W616/W617), `owner` first in a tabular part's importKeyFields (W607), and no " +
30
+ "(E116/E117/W616/W617), extension mode — ignored entity options, no reverse relations, no primary, " +
31
+ "no NOT NULL without a default, indexes over your own columns only (W618/E118/E119/E120/E121/W620), " +
32
+ "`owner` first in a tabular part's importKeyFields (W607), and no " +
30
33
  "`inverse` on @ManyToOne/@ManyToMany (W609)";