suppa-mcp-2 1.2.1 → 1.2.3

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
@@ -293,18 +293,22 @@ node <this-skill-dir>/scripts/validate-suppa-schema.mjs <app-root>
293
293
  # (installed via npm: node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs)
294
294
  ```
295
295
 
296
- Checks: SQL-string defaults, decorator misuse, thunk-less relations, seed
297
- idempotency (importKeyFields / `$key`), forbidden seed keys, numeric relation
298
- ids, reverse `@OneToMany` references, `forFeature` membership, seed dependency
299
- order, `dist/` autoload paths, tsconfig decorator flags, unknown
300
- `@Entity()`/`@Column()` options or field types, and tabular-part rules —
296
+ Checks: SQL-string defaults, decorator misuse, thunk-less relations, an
297
+ `inverse` selector wrongly passed to `@ManyToOne`/`@ManyToMany` (W609) or
298
+ pointing at a non-relation property such as `id` on any of the four relation
299
+ decorators (E111), seed idempotency (importKeyFields / `$key`), forbidden
300
+ seed keys, numeric relation ids, reverse `@OneToMany` references, `forFeature`
301
+ membership, seed dependency order, `dist/` autoload paths, tsconfig decorator
302
+ flags, unknown `@Entity()`/`@Column()` options or field types, and tabular-part rules —
301
303
  the `type: 'tabular-part'` + `relationEntityName` + `owner` triad, `owner`
302
304
  resolving to the right parent, and `owner` first in `importKeyFields`
303
305
  (E108/E109/E110/W607) — validated against the installed `@suppa/sdk` typings
304
306
  when resolvable, falling back to the doc tables otherwise
305
307
  (E101/E102/E107/E501/E502). Options/records/registration arrays delivered via
306
308
  spread or by reference can't be statically checked and fire a W606 warning
307
- instead. Exit code 1 on any error. Use the `write_entity_code` MCP prompt to
309
+ instead. An entity or seed left out of `EntityModule.forFeature()` fires
310
+ E301/E302, naming the module file to edit so the fix is a find-and-add, not a
311
+ search. Exit code 1 on any error. Use the `write_entity_code` MCP prompt to
308
312
  drive it from any client.
309
313
 
310
314
  Tabular parts (owned child sub-tables like checklist items or order lines)
package/dist/server.js CHANGED
@@ -1655,16 +1655,21 @@ export function buildServer() {
1655
1655
  "2. Resolve the blocking questions BEFORE writing any file: importKeyFields (the stable business key — wrong means duplicate seed rows on every restart), " +
1656
1656
  "representativeFieldName, and per-field nullable.\n" +
1657
1657
  "3. Write src/common/database/entities/*.entity.ts — @Entity class extending SystemBaseEntity; scalars via @Column({ type: FieldTypeEnum.X }); " +
1658
- "relations via thunks (@ManyToOne(() => Target)); fixed choices via @Enum('Entity.field', ...); attachments via @File/@MultiFile; " +
1658
+ "relations via thunks (@ManyToOne(() => Target)) — pass the thunk and the options object only; do not add the optional inverse selector to @ManyToOne/@ManyToMany; " +
1659
+ "fixed choices via @Enum('Entity.field', ...); attachments via @File/@MultiFile; " +
1659
1660
  "'default' is a SQL expression STRING ('false', \"'draft'\") — never a JS value. Repeating rows owned by one parent record " +
1660
1661
  "(checklist items, order lines) are a TABULAR PART, not a plain entity: type: 'tabular-part' + relationEntityName + a @ManyToOne " +
1661
- "field named owner, with owner first in importKeyFields (see references/tabular-parts.md).\n" +
1662
+ "field named owner, with owner first in importKeyFields (see references/tabular-parts.md). " +
1663
+ "Registering the class is part of writing it: add it to EntityModule.forFeature([...]) in the app module " +
1664
+ '(find it with grep -rn "EntityModule.forFeature" src/) in the same step — an unregistered class gets no table.\n' +
1662
1665
  "4. Write matching *.seed.ts with createSeed(): every importKeyField in every record (or $key); relations referenced by import key " +
1663
1666
  "({ name: 'Default' }) — never numeric ids; never system columns, access metadata, or reverse @OneToMany fields.\n" +
1664
- "5. Register in EntityModule.forFeature([entities], { seeds }) — dependencies' seeds first.\n" +
1667
+ "5. Export the entity and seed from their barrels (entities/index.ts, seeds/index.ts), and add the seed to " +
1668
+ "EntityModule.forFeature()'s seeds array, positioned after the seeds of everything it references — dependencies first.\n" +
1665
1669
  "6. Gate before claiming done: node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root> " +
1666
1670
  "(or the skills/ dir of a checkout) reports 0 errors; npx tsc --noEmit passes; " +
1667
- "push, reload (POST /core/applications/:appId/reload), verify with suppa_describe_entity.\n" +
1671
+ "push, reload (POST /core/applications/:appId/reload), verify with suppa_describe_entity — " +
1672
+ "the gate fails with E301 if anything is unregistered — run it, do not assume.\n" +
1668
1673
  "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 — " +
1669
1674
  "never invent a mapping; record data stays with suppa_migrate_entities_from_v1.");
1670
1675
  return server;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
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": { "suppa-mcp": "dist/bin.js" },
@@ -40,15 +40,17 @@ 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. `default` is a SQL expression string — `'false'`, `"'draft'"` — never a JS value; a JS value is rejected at migration time.
44
- 3. 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.
45
- 4. Relation targets are thunks — `() => Target`, never the class itself — or circular imports break.
46
- 5. 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.
47
- 6. Every entity class must appear in some `forFeature()`'s `entities` array; every seed in its `seeds` array, dependencies first — `workflowsSeed` before `stageWorkflowsSeed`.
48
- 7. 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 `[]`.
49
- 8. Autoload paths (`entitiesPath`/`seedsPath`) point at `dist/`, never `src/` — autoloading reads compiled output.
50
- 9. Renames need `key` set on `@Entity()`/`@Column()` BEFORE the rename ships — otherwise it's a drop-and-create, not a rename.
51
- 10. Repeating rows owned by one parent record are a **tabular part**, never a plain entity: `type: 'tabular-part'` + `relationEntityName` (the parent's `@Entity()` name) + a `@ManyToOne` field named exactly `owner` pointing at the parent class — all three required, the platform infers none of them. Put `owner` FIRST in `importKeyFields` — it scopes the business key to the parent, or rows collide across different parents.
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.
44
+ 3. `default` is a SQL expression string — `'false'`, `"'draft'"` — never a JS value; a JS value is rejected at migration time.
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
+ 5. Relation targets are thunks — `() => Target`, never the class itself — or circular imports break.
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
+ 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 some `forFeature()`'s `entities` array; every seed in its `seeds` array, dependencies first — `workflowsSeed` before `stageWorkflowsSeed`.
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
+ 10. Autoload paths (`entitiesPath`/`seedsPath`) point at `dist/`, never `src/` — autoloading reads compiled output.
52
+ 11. Renames need `key` set on `@Entity()`/`@Column()` BEFORE the rename ships — otherwise it's a drop-and-create, not a rename.
53
+ 12. Repeating rows owned by one parent record are a **tabular part**, never a plain entity: `type: 'tabular-part'` + `relationEntityName` (the parent's `@Entity()` name) + a `@ManyToOne` field named exactly `owner` pointing at the parent class — all three required, the platform infers none of them. Put `owner` FIRST in `importKeyFields` — it scopes the business key to the parent, or rows collide across different parents.
52
54
 
53
55
  ## Decorator decision table
54
56
 
@@ -58,14 +60,14 @@ Confirm all 5 before writing anything:
58
60
  | Scalar column (text/numeric/integer/boolean/timestamp/json/uuid/multi-language/bytea/tsvector/multi-type/icon) | `@Column({ type: FieldTypeEnum.<Member> })` |
59
61
  | Fixed single-select value set | `@Enum('<Entity>.<field>', <Field>Enum, <Field>Titles?, options?)` |
60
62
  | Fixed multi-select value set | `@MultiEnum(...)` — same signature as `@Enum` |
61
- | Foreign key on this entity | `@ManyToOne(target, options?)` or `@ManyToOne(target, inverse, options?)` |
62
- | Pivot table between two entities | `@ManyToMany(target, options?)` or `@ManyToMany(target, inverse, options?)` |
63
- | Reverse side of a `@ManyToMany` | `@ManyToManyBackRef(target, inverse, options?)` |
64
- | Reverse side of a `@ManyToOne` | `@OneToMany(target, inverse, options?)` |
63
+ | Foreign key on this entity | `@ManyToOne(() => Target, options?)` — **no inverse** |
64
+ | Pivot table between two entities | `@ManyToMany(() => Target, options?)` — **no inverse** |
65
+ | Reverse side of a `@ManyToMany` | `@ManyToManyBackRef(() => Target, (t) => t.<thisRelationProp>, options?)` |
66
+ | Reverse side of a `@ManyToOne` | `@OneToMany(() => Target, (t) => t.<thisRelationProp>, options?)` |
65
67
  | Single attachment | `@File({ title })` |
66
68
  | Multiple attachments | `@MultiFile({ title })` |
67
69
 
68
- `target` is always a thunk, `() => Target`. `inverse` is a property selector on the target entity, e.g. `(task) => task.project`.
70
+ `target` is always a thunk, `() => Target`. The `inverse` selector is REQUIRED on `@OneToMany`/`@ManyToManyBackRef` and OPTIONAL on `@ManyToOne`/`@ManyToMany` — omit it there by default. When you do write one, it must select the property on the TARGET class that holds the other side of this relation (e.g. `(task) => task.project`) — never `.id`, never a scalar column.
69
71
 
70
72
  ## Naming conventions
71
73
 
@@ -84,10 +86,9 @@ Confirm all 5 before writing anything:
84
86
 
85
87
  1. Pre-flight (above) — confirm repo, SDK version, tsconfig, layout.
86
88
  2. Blocking questions (above) — get answers before writing any file.
87
- 3. Write the entity from `templates/entity.template.ts`, following `references/entities.md`.
88
- 4. Need default rows? Write the seed from `templates/seed.template.ts`, following `references/seeds.md`.
89
- 5. Update the `entities`/`seeds` barrels and the `EntityModule.forFeature()` call — `references/registration.md`.
90
- 6. Run the close-out gate (below) — do not report "done" before all 4 steps pass.
89
+ 3. Write the entity AND wire it in (one step, both files): write `*.entity.ts` from `templates/entity.template.ts` per `references/entities.md`, then immediately export it from the entities barrel and add it to `EntityModule.forFeature()`'s `entities` array — see "Wiring a new entity in" below. The class does not exist to the platform until this is done.
90
+ 4. Need default rows? Same deal for the seed: write it from `templates/seed.template.ts` per `references/seeds.md`, export it from the seeds barrel, and add it to the `seeds` array (dependencies first) in the same step. The seed is not done until it is in the `seeds` array.
91
+ 5. Run the close-out gate (below) — do not report "done" before all 4 steps pass.
91
92
 
92
93
  ## Flow B — port a Suppa 1.0 entity to v2 code
93
94
 
@@ -95,9 +96,47 @@ Confirm all 5 before writing anything:
95
96
  2. `suppa_read_v1_entity_props` (+ `suppa_read_v1_enum` for enum fields) -> read its fields.
96
97
  3. Map every field per `references/v1-mapping.md` — the same authority (`classifyV1Field`) as the API migration path.
97
98
  4. Never silently drop a field: anything unmapped or unsupported gets `// SKIPPED: <field> — <reason>` inside the class body.
98
- 5. Continue with Flow A from the blocking questions onward (steps 2-6 above).
99
+ 5. Continue with Flow A from the blocking questions onward (steps 2-5 above).
99
100
  6. Record data migrates separately, via `suppa_migrate_entities_from_v1` — this skill only produces schema code.
100
101
 
102
+ ## Wiring a new entity in (same step as writing it)
103
+
104
+ **Locate the registration first.** The entity and seed files are new files written from templates; registration is an edit to an existing module file you have not seen yet, so find it before you start.
105
+
106
+ ```
107
+ grep -rn "EntityModule.forFeature" src/
108
+ ```
109
+
110
+ Fallback: `src/app/app.module.ts`. If the call you find uses `entitiesPath`/`seedsPath` (autoload) instead of explicit arrays, there is nothing to edit here — the class is picked up from `dist/` — so verify the build output path instead.
111
+
112
+ Four edits, every time:
113
+
114
+ 1. Export the class from the entities barrel — `src/common/database/entities/index.ts`.
115
+ 2. Export the seed from the seeds barrel — `src/common/database/seeds/index.ts`.
116
+ 3. Import the class in the module and add it to the `entities` array.
117
+ 4. Add the seed to the `seeds` array, positioned AFTER the seeds of everything it references.
118
+
119
+ ```ts
120
+ // before
121
+ EntityModule.forFeature([Workflows], { seeds: [workflowsSeed] });
122
+
123
+ // after — new import, new entity, new seed
124
+ import { MyNewEntity } from '../common/database/entities';
125
+ import { myNewEntitySeed } from '../common/database/seeds';
126
+
127
+ EntityModule.forFeature([Workflows, MyNewEntity], {
128
+ seeds: [workflowsSeed, myNewEntitySeed],
129
+ });
130
+ ```
131
+
132
+ Self-check, no tooling required:
133
+
134
+ ```
135
+ grep -rn "MyNewEntity" src/ | grep -i module
136
+ ```
137
+
138
+ If that prints nothing, the entity is not registered.
139
+
101
140
  ## Close-out gate (all steps, in order — no "done" before all pass)
102
141
 
103
142
  ```
@@ -108,8 +147,12 @@ Confirm all 5 before writing anything:
108
147
  4. verify the tenant converged: suppa_describe_entity('<EntityName>')
109
148
  ```
110
149
 
150
+ Step 1 exists to catch exactly this: an unregistered class is E301 and the gate fails. Never report done on an unrun gate.
151
+
111
152
  `validate-suppa-schema.mjs` exits `0` on a clean run, `1` when errors are found, `2` on a usage error or a missing path. The gate requires exit `0` — warnings alone do not block.
112
153
 
154
+ The validator parses with the TypeScript compiler API, read from the app repo you point it at (a Suppa application compiles with `tsc`, so it has one). If it reports `cannot resolve 'typescript'`, run `npm install` in that repo — or `npm i -D typescript` if it genuinely has none.
155
+
113
156
  ## Troubleshooting
114
157
 
115
158
  | Symptom | Cause | Validator code |
@@ -121,6 +164,8 @@ Confirm all 5 before writing anything:
121
164
  | Back reference can't insert | A reverse `@OneToMany` field is present in a seed record, possibly as `[]` | E204 |
122
165
  | A renamed entity or field appears as a new one | No `key` option was set | W602 |
123
166
  | `default` value is rejected | A JavaScript value was passed instead of a SQL expression string | E103 |
167
+ | Generated relation has an inverse selector that fails to typecheck | An `inverse` was passed to `@ManyToOne`/`@ManyToMany`, where it's optional and usually omitted | W609/E111 — drop the selector, write `@ManyToOne(() => Target, { … })` |
168
+ | `inverse` points at `id` | `id` is a system column, never a back-reference — an `inverse` must select the RELATION property on the target holding the other side | E111 |
124
169
  | A re-added field already contains old data | Same name means the same key, so the soft-deleted field was restored with its column — this is a runtime migration outcome, not statically checkable | documented-only, see references/registration.md |
125
170
  | A removed field is still present after a reload | The removal pass was skipped because the system user could not be resolved | documented-only, see references/registration.md |
126
171
  | The table has columns such as `title_1730457600000` | Leftovers from removed fields — renaming is how the platform removes a column; nothing cleans them up | documented-only, see references/registration.md |
@@ -12,7 +12,7 @@
12
12
  */
13
13
  import { createRequire } from "node:module";
14
14
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
15
- import { dirname, join, relative, resolve } from "node:path";
15
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
16
16
  import { pathToFileURL } from "node:url";
17
17
 
18
18
  // ── Doc-derived catalogs (fallback when @suppa/sdk typings are absent) ──
@@ -35,13 +35,21 @@ const RELATION_KIND_BY_DECORATOR = {
35
35
  ManyToOne: "many-to-one", ManyToMany: "many-to-many",
36
36
  ManyToManyBackRef: "many-to-many-backref", OneToMany: "one-to-many",
37
37
  };
38
+ const RELATION_KINDS = new Set(Object.values(RELATION_KIND_BY_DECORATOR));
39
+ // `inverse` is REQUIRED on these two (the reverse sides) and OPTIONAL — usually
40
+ // omitted — on @ManyToOne/@ManyToMany; W609 only ever fires on the latter pair.
41
+ const OPTIONAL_INVERSE_DECORATORS = new Set(["ManyToOne", "ManyToMany"]);
38
42
  const ENUM_DECORATORS = new Set(["Enum", "MultiEnum"]);
39
43
  const FILE_DECORATORS = new Set(["File", "MultiFile"]);
40
44
 
41
- // ── typescript resolution: target app first, this package as fallback ──
45
+ // ── typescript resolution: target app, then cwd, then this package ──
46
+ // The app repo is the expected source: a Suppa application compiles to dist/,
47
+ // so it has typescript. This package lists typescript as a devDependency only,
48
+ // so the last candidate resolves in a checkout but never in an install.
42
49
  export function loadTypescript(rootDir) {
43
50
  const froms = [];
44
51
  if (rootDir) froms.push(join(resolve(rootDir), "package.json"));
52
+ froms.push(join(process.cwd(), "package.json"));
45
53
  froms.push(import.meta.url);
46
54
  for (const from of froms) {
47
55
  try {
@@ -51,10 +59,22 @@ export function loadTypescript(rootDir) {
51
59
  }
52
60
  }
53
61
  throw new Error(
54
- "validate-suppa-schema: cannot resolve 'typescript' — run `npm install` in the app repo first.",
62
+ "validate-suppa-schema: cannot resolve 'typescript'. It is read from the app repo " +
63
+ "being validated (a Suppa application compiles with tsc, so it normally has it). " +
64
+ "Install it there — `npm i -D typescript` — or run this from a directory where it resolves.",
55
65
  );
56
66
  }
57
67
 
68
+ /**
69
+ * Path to print for a finding. A relative path is friendlier and clickable, but
70
+ * only when it actually stays inside cwd — across drives or above cwd, Windows
71
+ * `relative()` yields an unusable `..\..\..` chain with no drive letter.
72
+ */
73
+ export function displayPath(cwd, file) {
74
+ const rel = relative(cwd, file);
75
+ return !rel || rel.startsWith("..") || isAbsolute(rel) ? file : rel;
76
+ }
77
+
58
78
  // ── small AST helpers ──
59
79
  function finding(ts, sf, node, code, message) {
60
80
  const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
@@ -112,6 +132,36 @@ function thunkTarget(ts, sf, arg) {
112
132
  }
113
133
  return null;
114
134
  }
135
+ /**
136
+ * The `inverse` selector — `(target, inverse, options?)` — is whichever
137
+ * function expression sits in argument position 1; it is distinguished from
138
+ * `(target, options?)` by NOT being an object literal.
139
+ */
140
+ function isFunctionLike(ts, n) {
141
+ return !!n && (ts.isArrowFunction(n) || ts.isFunctionExpression(n));
142
+ }
143
+ /**
144
+ * The property name an inverse selector's body accesses off its own single
145
+ * parameter — `(t) => t.prop` (or `(t) => { return t.prop; }`) -> "prop".
146
+ * Anything else (destructuring, no single-parameter self-access, …) is not a
147
+ * shape this AST-only checker can read, so it returns null rather than guess.
148
+ */
149
+ function inverseAccessedProperty(ts, fn) {
150
+ if (!fn || fn.parameters.length !== 1) return null;
151
+ const param = fn.parameters[0].name;
152
+ if (!ts.isIdentifier(param)) return null;
153
+ let body = fn.body;
154
+ if (ts.isBlock(body)) {
155
+ const stmts = body.statements;
156
+ if (stmts.length !== 1 || !ts.isReturnStatement(stmts[0]) || !stmts[0].expression) return null;
157
+ body = stmts[0].expression;
158
+ }
159
+ if (ts.isPropertyAccessExpression(body) && ts.isIdentifier(body.expression) &&
160
+ body.expression.text === param.text) {
161
+ return body.name.text;
162
+ }
163
+ return null;
164
+ }
115
165
  function spreadElements(ts, node) {
116
166
  if (!node || !ts.isObjectLiteralExpression(node)) return [];
117
167
  return node.properties.filter((p) => ts.isSpreadAssignment(p));
@@ -255,15 +305,19 @@ function analyzeEntities(ts, sf, model) {
255
305
  });
256
306
  } else if (d.name in RELATION_KIND_BY_DECORATOR) {
257
307
  // (target, options?) or (target, inverse, options?) — the options
258
- // object is whichever trailing argument is an object literal
308
+ // object is whichever trailing argument is an object literal; the
309
+ // inverse (when present) is argument 1 whenever it is NOT that
310
+ // options object, i.e. it is an arrow/function expression instead.
259
311
  const relOptions = objectMap(
260
312
  ts, [...d.args].reverse().find((a) => ts.isObjectLiteralExpression(a)),
261
313
  );
314
+ const inverseNode = isFunctionLike(ts, d.args[1]) ? d.args[1] : null;
262
315
  info.properties.set(propName, {
263
316
  kind: RELATION_KIND_BY_DECORATOR[d.name],
264
317
  node: member, decorator: d,
265
318
  targetClass: thunkTarget(ts, sf, d.args[0]),
266
319
  nameNode: relOptions.get("name") ?? null,
320
+ inverseNode,
267
321
  });
268
322
  }
269
323
  }
@@ -426,14 +480,52 @@ function checkEntity(ts, info, sdk, model, findings) {
426
480
  `column name '${colName}' on property '${propName}' collides with the system column of the same name provided by SystemBaseEntity — "you never declare them yourself"`));
427
481
  }
428
482
  if (prop.kind === "column") checkColumn(ts, sf, prop, sdk, findings);
429
- if (prop.kind in { "many-to-one": 1, "many-to-many": 1, "many-to-many-backref": 1, "one-to-many": 1 } &&
430
- prop.targetClass === null) {
431
- findings.push(finding(ts, sf, prop.node, "E105",
432
- `relation '${propName}' must receive a thunk returning the target class — write @${prop.decorator.name}(() => Target); a direct class reference breaks circular imports`));
483
+ if (RELATION_KINDS.has(prop.kind)) {
484
+ if (prop.targetClass === null) {
485
+ findings.push(finding(ts, sf, prop.node, "E105",
486
+ `relation '${propName}' must receive a thunk returning the target class — write @${prop.decorator.name}(() => Target); a direct class reference breaks circular imports`));
487
+ }
488
+ if (prop.inverseNode) {
489
+ if (OPTIONAL_INVERSE_DECORATORS.has(prop.decorator.name)) {
490
+ findings.push(finding(ts, sf, prop.inverseNode, "W609",
491
+ `'${propName}' (@${prop.decorator.name}) passes an inverse selector — it is optional on @ManyToOne/@ManyToMany and usually omitted; pass only the thunk and the options object (@${prop.decorator.name}(() => Target, { ... })) unless you are deliberately pairing an explicit back-reference declared on the target`));
492
+ }
493
+ checkInverseSelector(ts, sf, propName, prop, model, findings);
494
+ }
433
495
  }
434
496
  }
435
497
  }
436
498
 
499
+ /**
500
+ * "An inverse must select the property on the target that holds the OTHER
501
+ * SIDE of this relation" — e.g. (task) => task.project. Applies to the
502
+ * `inverse` argument of any of the four relation decorators, required or not.
503
+ * Skipped silently when the target class is not among the analyzed entities
504
+ * (platform/SDK entities such as IconsEntity) — no guessing without a model
505
+ * of that class, and when the selector's shape (destructuring, a computed
506
+ * body, …) is not one this AST-only checker can read.
507
+ */
508
+ function checkInverseSelector(ts, sf, propName, prop, model, findings) {
509
+ if (!prop.targetClass) return;
510
+ const target = model.entities.get(prop.targetClass);
511
+ if (!target) return;
512
+ const accessed = inverseAccessedProperty(ts, prop.inverseNode);
513
+ if (accessed === null) return;
514
+ const targetProp = target.properties.get(accessed);
515
+ if (targetProp && RELATION_KINDS.has(targetProp.kind)) return; // valid pairing
516
+
517
+ let reason;
518
+ if (SYSTEM_COLUMNS.includes(accessed)) {
519
+ reason = `'${accessed}' is a system column provided by SystemBaseEntity, not a relation`;
520
+ } else if (!targetProp) {
521
+ reason = `'${target.entityName}' declares no property named '${accessed}'`;
522
+ } else {
523
+ reason = `'${target.entityName}.${accessed}' is a '${targetProp.kind}' property, not a relation`;
524
+ }
525
+ findings.push(finding(ts, sf, prop.inverseNode, "E111",
526
+ `inverse selector on '${propName}' (@${prop.decorator.name}) targets '${target.entityName}.${accessed}', but ${reason} — an inverse selector must select the RELATION property on the target that holds the OTHER SIDE of this relation, e.g. (task) => task.project`));
527
+ }
528
+
437
529
  function checkColumn(ts, sf, prop, sdk, findings) {
438
530
  const opts = prop.columnOptions;
439
531
  for (const [opt, valNode] of opts) {
@@ -756,7 +848,29 @@ function analyzeModules(ts, sf, model) {
756
848
  }
757
849
 
758
850
  // ── rules: registration ──
759
- function checkRegistration(ts, model, findings) {
851
+ /**
852
+ * E301/E302 fire on the entity/seed source file, far from the module file
853
+ * that actually needs the edit — name it explicitly so the finding is
854
+ * actionable instead of just "unregistered". `side` selects which half of
855
+ * forFeature() (`entities` or `seeds`) determines the classes-shape modules;
856
+ * paths are shown relative to rootDir when derivable, else just the basename,
857
+ * deduped, capped at 3 so the message stays short.
858
+ */
859
+ function classShapeModulePaths(modules, side, rootDir) {
860
+ const shapeModules = modules.filter((m) => m[side].mode === "explicit");
861
+ if (shapeModules.length === 0) return "";
862
+ const root = rootDir ? resolve(rootDir).replace(/\\/g, "/") : null;
863
+ const raw = [...new Set(shapeModules.map((m) => m.sf.fileName))];
864
+ const shown = raw.map((p) => {
865
+ const norm = p.replace(/\\/g, "/");
866
+ if (root && norm.startsWith(`${root}/`)) return norm.slice(root.length + 1);
867
+ const parts = norm.split("/");
868
+ return parts[parts.length - 1];
869
+ });
870
+ return shown.slice(0, 3).join(", ");
871
+ }
872
+
873
+ function checkRegistration(ts, model, findings, rootDir) {
760
874
  // E303/W606 on autoload paths — only for the side that actually autoloads:
761
875
  // a path the resolution order ignores is dead config, not a mistake.
762
876
  for (const m of model.modules) {
@@ -810,19 +924,23 @@ function checkRegistration(ts, model, findings) {
810
924
 
811
925
  if (!entitiesUnknown) {
812
926
  const registeredEntities = new Set(model.modules.flatMap((m) => m.entities.names));
927
+ const modulePaths = classShapeModulePaths(model.modules, "entities", rootDir);
813
928
  for (const [className, info] of model.entities) {
814
929
  if (!registeredEntities.has(className)) {
815
930
  findings.push(finding(ts, info.sf, info.node.name ?? info.node, "E301",
816
- `entity class '${className}' is not in any forFeature() entities array — no table will be created for it`));
931
+ `entity class '${className}' is not in any forFeature() entities array — no table will be created for it` +
932
+ (modulePaths ? ` — add it to the entities array in ${modulePaths}` : "")));
817
933
  }
818
934
  }
819
935
  }
820
936
  if (!seedsUnknown) {
821
937
  const registeredSeeds = new Set(model.modules.flatMap((m) => m.seeds.names));
938
+ const modulePaths = classShapeModulePaths(model.modules, "seeds", rootDir);
822
939
  for (const seed of model.seeds) {
823
940
  if (!registeredSeeds.has(seed.exportName)) {
824
941
  findings.push(finding(ts, seed.sf, seed.node, "E302",
825
- `seed '${seed.exportName}' is not in any forFeature() seeds array — it will never run`));
942
+ `seed '${seed.exportName}' is not in any forFeature() seeds array — it will never run` +
943
+ (modulePaths ? ` — add it to the seeds array in ${modulePaths}` : "")));
826
944
  }
827
945
  }
828
946
  }
@@ -996,7 +1114,7 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
996
1114
  }
997
1115
  for (const info of model.entities.values()) checkEntity(ts, info, sdk, model, findings);
998
1116
  for (const seed of model.seeds) checkSeed(ts, seed, model, findings);
999
- checkRegistration(ts, model, findings);
1117
+ checkRegistration(ts, model, findings, rootDir);
1000
1118
  checkTsconfig(ts, rootDir, findings);
1001
1119
  findings.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.col - b.col);
1002
1120
  return {
@@ -1054,7 +1172,9 @@ if (isMain) {
1054
1172
  const dedupedFiles = [...new Set(files)];
1055
1173
  const res = validateSchema({ files: dedupedFiles, rootDir });
1056
1174
  for (const f of res.findings) {
1057
- console.log(`${relative(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`);
1175
+ console.log(
1176
+ `${displayPath(process.cwd(), f.file)}:${f.line}:${f.col} ${f.code} [${f.level}] ${f.message}`,
1177
+ );
1058
1178
  }
1059
1179
  console.log(
1060
1180
  `\n${res.errors.length} error(s), ${res.warnings.length} warning(s) across ${dedupedFiles.length} file(s) (option catalog: ${res.sdkSource}).`,
@@ -56,6 +56,7 @@ export class __EntityName__ extends SystemBaseEntity {
56
56
  amount: number;
57
57
 
58
58
  // Relation — ALWAYS a thunk (() => Target), never the class itself.
59
+ // No inverse passed — it's optional on @ManyToOne and omitted by default.
59
60
  @ManyToOne(() => __TargetEntity__, { nullable: false })
60
61
  __target__: __TargetEntity__;
61
62
 
@@ -44,6 +44,7 @@ export class __EntityName__ extends SystemBaseEntity {
44
44
  // (SystemBaseEntity provides them).
45
45
 
46
46
  // 3/3 — the property MUST be named `owner`, pointing at the parent via a thunk.
47
+ // No inverse passed — it's optional on @ManyToOne and omitted by default.
47
48
  @ManyToOne(() => __ParentEntity__, {
48
49
  name: 'owner',
49
50
  title: { en: '__Parent title__', uk: '__Батьківська назва__' },