suppa-mcp-2 1.44.0 → 1.44.2

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
@@ -658,6 +658,9 @@ commit, a `.gitlab/suppa-schema-gate.yml` job refuses the merge request, and a
658
658
  managed section in `AGENTS.md` / `CLAUDE.md` carries the same rules to editors
659
659
  with no hook support. Re-running the installer is safe, `--dry-run` prints the
660
660
  plan, and details are in `skills/suppa-entity-code/references/enforcement.md`.
661
+ The hook layers count what a change brings — findings in the files it touches,
662
+ and anything HEAD did not have. Older findings are listed, not counted, and CI
663
+ counts everything.
661
664
 
662
665
  It also enforces the **authoring rules** the platform doc does not: a
663
666
  relation property must carry a TypeScript type that agrees with its decorator
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.44.0",
3
+ "version": "1.44.2",
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": {
@@ -158,7 +158,7 @@ Confirm all 6 before writing anything:
158
158
  24. **Names the platform keeps for itself, and the index it already builds.** Read from entity-builder, the platform's own repository, each one a refusal or a broken migration when ignored:
159
159
 
160
160
  - An entity name must not END in a companion-table suffix — `Comments`, `CommentReactions`, `Reactions`, `Favorites`, `Approves`, `Approvers`, `Folders`, `Checklists`, `CustomFields`, `StateHistory`. The platform generates `<Entity><Suffix>` tables when the matching option is switched on and refuses the name outright. **E131.**
161
- - A field must not be named `parent`, `parents`, `children`, `multiChildren`, `comments`, `reactions`, `favorites`, `approves`, `approvers`, `folders`, `items`, `checklists`, `customFields`, `pinned`, `timeTracking`, `spentTime`, `spentTimeTotal` or `searchVector` — those are generated by entity options or owned by search — nor shaped like a multi-type synthetic column (`f12Type`). The platform's field-name guard answers HTTP 400. **E132.**
161
+ - A field must not be named `parent`, `parents`, `children`, `multiChildren`, `comments`, `reactions`, `favorites`, `approves`, `approvers`, `folders`, `items`, `checklists`, `customFields`, `pinned`, `timeTracking`, `spentTime`, `spentTimeTotal` or `searchVector` — those are generated by entity options or owned by search — nor shaped like a multi-type synthetic column (`f12Type`). The builder's field-name guard answers HTTP 400; an application's sync passes it, and once the option is switched on the platform keeps the declared field as its own, whatever its shape. **E132.** One exception is only advisory: `parent` as a `@ManyToOne` or `parents` as a `@ManyToMany` onto the entity itself — and its `children` (`@OneToMany`) / `multiChildren` (`@ManyToManyBackRef`) back reference — with no `hierarchy` option on the entity. That is the pair the option creates; switching `hierarchy` on later keeps it and adds nothing. Without the option nothing refuses a loop (A → B → A). **W641 (advisory).** For a new tree, prefer the option itself.
162
162
  - A relation, enum or file field `owner` is stored in a physical column `ownerId`; a scalar column named `ownerId` beside it claims the same column, and the two silently fought over it until the guard learned to refuse. **E133.**
163
163
  - **Never `@Index` a single `@ManyToOne`, `@Enum` or `@File` column, or a single `unique` column.** metadata-sync registers an index for every one of them on its own — an enum and a file are many-to-one references to `Enums`/`Files` (`ColumnBuilderUtils.isManyToOne`, entity-builder `column-builder.util.ts:37-43`); a declared duplicate produces the same `IndexMetadata` key, the bulk insert during sync fails with `23505`, and the tenant migration rolls back — the database does not come up. Composite indexes that include a relation column (`['owner', 'type']`) are a different key and are fine. **W628, and it fails the gate.**
164
164
  - **Never two `@Index` over the same column set with the same `unique`/`where`.** An `IndexMetadata` key is the entity, the SORTED column names, `unique` and `where` — not the name, not the order — so `['a', 'b']` and `['b', 'a']` are one key and the import keeps one of them. The physical index follows the declared order (entity-builder `d69f0ee1`); on an existing tenant, reordering the columns alone rebuilds nothing, because the import compares the set. **W634, and it fails the gate.**
@@ -446,6 +446,7 @@ The validator parses with the TypeScript compiler API, read from the app repo yo
446
446
  | 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) |
447
447
  | The tenant migration fails with `23505 duplicate key value violates unique constraint "IndexMetadataKeyIndex"` and the database does not come up | An `@Index` over a single `@ManyToOne`, `@Enum`, `@File` or `unique` column — metadata-sync already indexes those | W628 (blocks the gate) |
448
448
  | `cannot declare field "X.parent"` / HTTP 400 from the field-name guard, or an entity name refused at start | A platform-owned field name, a multi-type-shaped name, a `<x>Id` scalar beside relation `<x>`, or a reserved entity suffix | E132 / E133 / E131 |
449
+ | `parent`/`parents` (or its `children`/`multiChildren` back reference) onto the entity itself, no `hierarchy` option, and the gate only warns | The pair the hierarchy option would create; switching the option on later keeps it | W641 (advisory) |
449
450
  | A label is blank in the Ukrainian UI, or a translation you wrote never appears | `title` was a plain string (stored as `en` only), used `ua` instead of `uk` (dropped silently), or carried an `id` (read as a reference) | W626 (blocks the gate); W627 for a title whose languages differ from the rest |
450
451
  | An extension declares `@OneToMany` / `@ManyToManyBackRef` | A reverse relation creates a field on the OTHER entity; declare the owning side here instead | E118 |
451
452
  | An extension declares `primary: true` | The owner's primary key is not yours to redefine | E119 |
@@ -487,10 +488,13 @@ The validator parses with the TypeScript compiler API, read from the app repo yo
487
488
  | A stub took an entity over: another application's deploy now gets extension mode on it | The entity had no owning application, so the stub ran in OWN mode and claimed it | rule 19 — read the owner before writing a stub |
488
489
  | 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 |
489
490
  | A relation names its target with a string (`@ManyToOne('Invoices', …)`), anywhere | The SDK types the target `() => Target` and calls it at registration — a string fails tsc and would throw. Use a thunk, or `@Column({ relationEntityName: 'Invoices', … })` for an entity you cannot import | W620 (blocks the gate) |
491
+ | A stub on a nobody's entity declares its representative column (an empty one wrote `id` there on import), and the gate refuses it as E117 | The stub ran in OWN mode and the entity is yours now (`application` = your application). It is not a stub any more: rename it to `<name>.entity.ts` and keep the class as it is. A class may declare part of an entity it owns; the tenant's own columns (initiator `client`) that it leaves out stay where they are | E117 — rule 19 |
490
492
  | 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 |
491
493
  | 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) |
492
494
  | Several stubs piled into one `relation-targets.ts` | Each existing-entity stub lives in its OWN file | W616 (blocks the gate) |
493
495
  | A stub was left out of `forFeature()` "so the migration can't touch the real table" | A stub is registered like any other entity — its EMPTY body is what protects the real table, not the missing registration | E301 |
494
496
  | The gate passes, but nobody ran it | Install the guards: `node scripts/install-entity-code-guards.mjs <app-root>` — hooks put the rules in front of an agent before it writes and the gate in front of it after, a pre-commit refusal catches whoever had no hooks, and a CI job catches whatever reached the branch. See `references/enforcement.md` | — |
497
+ | Every commit that touches an entity is refused over findings it did not add, so commits go in with `--no-verify` | Before 1.44.2 the hooks counted every finding in the application root. Now a finding counts when the change touches its file, or when HEAD does not have it; the rest are listed under *Not counted against this change*, and `--ci` still fails on them. Fix them in a change of their own, and drop `--no-verify`: it switches the gate off for the new findings too | `references/enforcement.md` |
498
+ | `node node_modules/suppa-mcp-2/…/validate-suppa-schema.mjs .` prints nothing and exits 0 | pnpm links `node_modules/suppa-mcp-2`, and before 1.44.2 the CLI compared its real path with the linked one and never ran. Fixed; on an older install, `entity-code-guard.mjs --ci .` (`npm run schema:gate`) was never affected | — |
495
499
  | Validator warns W606 | Content delivered via spread or reference — options, `default`, `subType`, `importKeyFields`, seed records, enum refs, `$key`, autoload paths, registration arrays, tabular-part `type`/`relationEntityName` — is not statically verifiable; the matching check is skipped. Inline it so the validator can check | W606 |
496
500
  | Validator warns W608 | No `tsconfig.json` at the given root, so `experimentalDecorators`/`emitDecoratorMetadata` could not be verified — point the validator at the app root | W608 |
@@ -45,7 +45,8 @@ The gate runs over the file's application root (nearest `package.json`). A
45
45
  failure exits `2`, which puts the findings — with the rules attached — in front
46
46
  of the agent as the next thing it reads. `PostToolUse` cannot undo the write;
47
47
  this makes the violation the agent's immediate problem instead of a surprise at
48
- review time.
48
+ review time. Only what the change brought counts — see
49
+ [What a change answers for](#what-a-change-answers-for).
49
50
 
50
51
  If the gate cannot run (no `typescript` in the target repo), the guard says so
51
52
  as context and exits `0`. A guard that walls off unrelated edits gets
@@ -53,14 +54,14 @@ uninstalled, and then it protects nothing.
53
54
 
54
55
  ### 3. Before the turn ends — `Stop`
55
56
 
56
- If any schema file in the working tree is changed and its root fails the gate,
57
- the turn is refused. This is the layer that stops "I will fix the gate findings
57
+ If any schema file in the working tree is changed and the gate finds something
58
+ the change brought in its root, the turn is refused. This is the layer that stops "I will fix the gate findings
58
59
  later" — there is no later. `stop_hook_active` is honoured, so a turn that is
59
60
  already inside a Stop continuation is never blocked twice.
60
61
 
61
62
  ### 4. Before the commit — `.githooks/pre-commit`
62
63
 
63
- The same gate over **staged** schema files, exit `1`. This catches the case the
64
+ The same gate over **staged** schema files, counted the same way, exit `1`. This catches the case the
64
65
  hooks cannot: a human editing by hand, an agent in an editor with no hook
65
66
  support, a `--dangerously-skip-permissions` run with hooks disabled.
66
67
 
@@ -72,6 +73,32 @@ the call from the existing hook:
72
73
  node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/entity-code-guard.mjs --pre-commit
73
74
  ```
74
75
 
76
+ ### What a change answers for
77
+
78
+ Layers 2–4 run the gate over the whole application root, because a change in one
79
+ file breaks another: E308 lands in the module that still registers the class a
80
+ commit deleted, W635 in a runtime file a new import pulls into the bundle. What
81
+ they COUNT is narrower:
82
+
83
+ - every finding in a file the change touches — the staged files for the commit,
84
+ the changed files for the hooks. Touch a file and it has to pass;
85
+ - every finding anywhere else that HEAD does not have — same file, same code,
86
+ same message, matched as a multiset, positions ignored.
87
+
88
+ The rest were there before the change. They are listed under *Not counted against
89
+ this change* every time, and they do not block. `--ci` still counts them, so the
90
+ merge request shows the whole picture. Before 1.44.2 every finding in the root
91
+ counted: one old finding refused every commit that touched an entity, the only
92
+ way through was `--no-verify`, and `--no-verify` switched the gate off for the new
93
+ findings as well.
94
+
95
+ HEAD's findings come from a snapshot of the application root read with
96
+ `git cat-file` (the work tree, the index and the refs are never touched), judged
97
+ with the working tree's own compiler and SDK. It is computed only when a finding
98
+ sits outside the touched files, and once per HEAD tree: the answer is cached in
99
+ `<git-dir>/suppa-gate/`. With no commit to compare with, or a HEAD the gate
100
+ cannot run on, every finding counts, and the report says why.
101
+
75
102
  ### 5. Before the merge — CI
76
103
 
77
104
  `.gitlab/suppa-schema-gate.yml` runs `--ci` over the repo on merge-request
@@ -96,7 +96,12 @@ wrong type too (**E503**):
96
96
  feature off you omit the key. Every option is a schema change rather than a preference — "Enabling
97
97
  an option creates the side table that backs it" (builder doc) — and the fields an option generates
98
98
  (`parent`, `parents`, `children`, `multiChildren`, `spentTime`, `comments`, …) are names you may not
99
- declare yourself (**E132**).
99
+ declare yourself (**E132**): an application's sync passes the field-name guard, and once the option is
100
+ switched on the platform keeps the declared field as its own, whatever its shape. The one advisory
101
+ case is `parent` (`@ManyToOne`) or `parents` (`@ManyToMany`) onto the entity itself — with its
102
+ `children` / `multiChildren` back reference — while `hierarchy` is off: it is the pair the option
103
+ would create, and switching the option on later keeps it rather than adding a second one
104
+ (**W641**). Without the option nothing refuses a loop.
100
105
 
101
106
  On an entity you do **not** own, extension mode ignores `options` wholesale (**W618**), so a feature
102
107
  cannot be switched on from a file there — and not at runtime either. Since entity-builder c165fc4d
@@ -20,6 +20,10 @@
20
20
  * --ci one run over the repo, for a pipeline
21
21
  * --print-rules the digest, for a human or a doc
22
22
  *
23
+ * The three layers that judge a CHANGE (--post-tool-use, --stop, --pre-commit)
24
+ * count what the change brought, not every finding the repo already had — see
25
+ * splitByChange. --ci counts everything.
26
+ *
23
27
  * The hooks are safe to run anywhere: a repo with no schema files, no git and
24
28
  * no typescript exits 0 and says why, because a guard that breaks unrelated
25
29
  * work gets uninstalled. The two layers that decide what LANDS (--pre-commit,
@@ -28,7 +32,12 @@
28
32
  */
29
33
 
30
34
  import { execFileSync } from "node:child_process";
31
- import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
35
+ import { createHash } from "node:crypto";
36
+ import {
37
+ existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync,
38
+ unlinkSync, writeFileSync,
39
+ } from "node:fs";
40
+ import { tmpdir } from "node:os";
32
41
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
33
42
 
34
43
  // The checker is loaded, not statically imported, so that a truncated or half-installed file is
@@ -85,7 +94,11 @@ function readStdinJson() {
85
94
 
86
95
  function git(args, cwd) {
87
96
  try {
88
- return execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
97
+ // The default 1 MB buffer is a listing of a few thousand paths: past it the
98
+ // call threw, and every answer built on it read as "no git".
99
+ return execFileSync("git", args, {
100
+ cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 256 * 1024 * 1024,
101
+ });
89
102
  } catch {
90
103
  return null;
91
104
  }
@@ -161,17 +174,29 @@ function canonicalRoot(p) {
161
174
  return process.platform === "win32" ? abs.toLowerCase() : abs;
162
175
  }
163
176
 
177
+ /** The same, for a file: a changed path and a finding's file must meet however each was spelled. */
178
+ const fileKey = canonicalRoot;
179
+
180
+ function findingLine(root, f) {
181
+ const rel = relative(root, f.file);
182
+ const shown = !rel || rel.startsWith("..") || isAbsolute(rel) ? f.file : rel.replace(/\\/g, "/");
183
+ return `${shown}:${f.line}:${f.col} ${f.code} ${f.message}`;
184
+ }
185
+
164
186
  /**
165
187
  * Run the gate over one application root.
166
- * -> { ok } | { ok: false, blocking, lines } | { skipped } | { toolchain } | { unreadable }
188
+ * -> { ok, blocking, lines } | { skipped } | { toolchain } | { unreadable }
167
189
  *
168
190
  * `skipped` is "nothing to run on"; `toolchain` and `unreadable` are "could not
169
191
  * run". They used to be one answer: any failure to read the root became a skip,
170
192
  * and a skip is reported as clean — so a typo'd `--ci ./srcc`, a root that is a
171
193
  * file, or a dead junction anywhere under the app (statSync threw, the walk
172
194
  * aborted) printed "gate: clean" over a staged rule-breaking entity.
195
+ *
196
+ * `lookupRoot` is where the compiler and the SDK typings are found, when that is
197
+ * not the root itself — the HEAD snapshot has no node_modules of its own.
173
198
  */
174
- function runGate(root) {
199
+ function runGate(root, { lookupRoot = null } = {}) {
175
200
  let st;
176
201
  try {
177
202
  st = statSync(root);
@@ -191,7 +216,7 @@ function runGate(root) {
191
216
 
192
217
  let res;
193
218
  try {
194
- res = validateSchema({ files, rootDir: root });
219
+ res = validateSchema({ files, rootDir: root, ...(lookupRoot ? { lookupRoot } : {}) });
195
220
  } catch (e) {
196
221
  // A missing or unusable typescript in the target repo is the repo's to fix;
197
222
  // it must never turn into a wall in front of every edit.
@@ -202,21 +227,246 @@ function runGate(root) {
202
227
  const blocking = res.findings.filter(
203
228
  (f) => f.level === "error" || RULE_WARNINGS.includes(f.code),
204
229
  );
205
- const lines = blocking.map((f) => {
206
- const rel = relative(root, f.file);
207
- const shown = !rel || rel.startsWith("..") || isAbsolute(rel) ? f.file : rel.replace(/\\/g, "/");
208
- return `${shown}:${f.line}:${f.col} ${f.code} ${f.message}`;
230
+ return { ok: blocking.length === 0, blocking, lines: blocking.map((f) => findingLine(root, f)) };
231
+ }
232
+
233
+ // ── what a change answers for ──
234
+
235
+ /**
236
+ * Split a root's blocking findings into the ones this change brought and the
237
+ * ones it found already there.
238
+ *
239
+ * The write, Stop and pre-commit layers gate the WHOLE application root, and
240
+ * they must: a change in one file breaks another — E308 lands in the module
241
+ * that still registers the class a commit deleted, W635 in a runtime file a new
242
+ * import pulls into the bundle. They then refused on every finding in that
243
+ * root, which is more than they promise ("refused while a staged schema file
244
+ * fails"). One old finding anywhere refused every commit that touched an
245
+ * entity, the only way through was --no-verify, and --no-verify switched the
246
+ * gate off for the new findings too: modern-expo put every commit from
247
+ * 2026-10-21 to 2026-10-27 behind it, over twelve findings none of them added.
248
+ *
249
+ * A finding COUNTS when it sits in a file the change touches, or when the
250
+ * gate's answer for HEAD does not have it — same file, same code, same message,
251
+ * matched as a multiset, so a second copy of an old finding is new. Positions
252
+ * are left out of the match: an edit above an old finding moves it without
253
+ * making it new. The rest are OLDER: listed every time, never counted here.
254
+ *
255
+ * Without a HEAD to compare with — no git, no commit yet, a HEAD the gate
256
+ * cannot run on — every finding counts, as before, and the report says why.
257
+ * HEAD's findings are computed only when a finding sits outside the touched
258
+ * files, and once per HEAD tree (cachePath).
259
+ */
260
+ function splitByChange(root, blocking, touched) {
261
+ const outside = blocking.filter((f) => !touched.has(fileKey(f.file)));
262
+ if (!outside.length) return { counted: blocking, older: [] };
263
+ const head = headFindings(root);
264
+ if (head.reason) return { counted: blocking, older: [], uncompared: head.reason };
265
+ const left = new Map(head.keys);
266
+ const older = new Set();
267
+ for (const f of outside) {
268
+ const key = findingKey(root, f);
269
+ const n = left.get(key) ?? 0;
270
+ if (n > 0) {
271
+ left.set(key, n - 1);
272
+ older.add(f);
273
+ }
274
+ }
275
+ return { counted: blocking.filter((f) => !older.has(f)), older: blocking.filter((f) => older.has(f)) };
276
+ }
277
+
278
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
279
+
280
+ /** A finding as HEAD and the working tree can both spell it: root-relative, position-free. */
281
+ function findingKey(root, f) {
282
+ const win = process.platform === "win32";
283
+ const rel = relative(root, f.file).replace(/\\/g, "/");
284
+ let message = String(f.message ?? "");
285
+ for (const spelling of new Set([root, root.replace(/\\/g, "/")])) {
286
+ message = message.replace(new RegExp(escapeRe(spelling), win ? "gi" : "g"), "<root>");
287
+ }
288
+ message = message.replace(/(\.[cm]?tsx?):\d+(?::\d+)?/g, "$1");
289
+ return `${win ? rel.toLowerCase() : rel}\0${f.code}\0${message}`;
290
+ }
291
+
292
+ let checkerStamp = null;
293
+ /** What HEAD's findings depend on besides HEAD: this checker, and the SDK it reads option catalogs from. */
294
+ function stampFor(realRoot) {
295
+ if (checkerStamp === null) {
296
+ const h = createHash("sha1");
297
+ for (const f of ["entity-code-guard.mjs", "validate-suppa-schema.mjs", "house-rules.mjs"]) {
298
+ try {
299
+ h.update(readFileSync(new URL(`./${f}`, import.meta.url)));
300
+ } catch {
301
+ h.update(`missing:${f}`);
302
+ }
303
+ }
304
+ checkerStamp = h.digest("hex");
305
+ }
306
+ let sdk = "none";
307
+ for (let dir = realRoot; ; dir = dirname(dir)) {
308
+ const p = join(dir, "node_modules", "@suppa", "sdk", "package.json");
309
+ if (existsSync(p)) {
310
+ try {
311
+ sdk = `${dir}:${JSON.parse(readFileSync(p, "utf-8")).version}`;
312
+ } catch {
313
+ sdk = `${dir}:unreadable`;
314
+ }
315
+ break;
316
+ }
317
+ if (dirname(dir) === dir) break;
318
+ }
319
+ return `${checkerStamp}\0${sdk}`;
320
+ }
321
+
322
+ /** <git-dir>/suppa-gate/head-<tree>-<scope>.json, or null when git will not say where its dir is. */
323
+ function cachePath(top, tree, relPosix, realRoot) {
324
+ const gitDir = git(["rev-parse", "--absolute-git-dir"], top)?.trim();
325
+ if (!gitDir) return null;
326
+ const scope = createHash("sha1").update(`${stampFor(realRoot)}\0${relPosix}`).digest("hex").slice(0, 16);
327
+ return join(gitDir, "suppa-gate", `head-${tree}-${scope}.json`);
328
+ }
329
+
330
+ const CACHE_KEPT = 8;
331
+
332
+ /** A cache is an optimisation: failing to write or prune it never changes an answer. */
333
+ function saveCache(file, keys) {
334
+ try {
335
+ const dir = dirname(file);
336
+ mkdirSync(dir, { recursive: true });
337
+ const tmp = `${file}.${process.pid}.tmp`;
338
+ writeFileSync(tmp, JSON.stringify([...keys]));
339
+ renameSync(tmp, file);
340
+ const entries = readdirSync(dir)
341
+ .filter((n) => /^head-.*\.json$/.test(n))
342
+ .map((n) => ({ p: join(dir, n), t: statSync(join(dir, n)).mtimeMs }))
343
+ .sort((a, b) => b.t - a.t);
344
+ for (const old of entries.slice(CACHE_KEPT)) unlinkSync(old.p);
345
+ } catch {
346
+ /* read-only git dir, a concurrent prune — the next run computes it again */
347
+ }
348
+ }
349
+
350
+ /**
351
+ * The gate's blocking findings for this root as HEAD has it.
352
+ * -> { keys: Map<findingKey, count> } | { reason }
353
+ */
354
+ function headFindings(root) {
355
+ const top = git(["rev-parse", "--show-toplevel"], root)?.trim();
356
+ if (!top) return { reason: "this is not a git work tree" };
357
+ const tree = git(["rev-parse", "--verify", "--quiet", "HEAD^{tree}"], top)?.trim();
358
+ if (!tree) return { reason: "there is no commit yet" };
359
+ let realTop;
360
+ let realRoot;
361
+ try {
362
+ realTop = realpathSync.native(top);
363
+ realRoot = realpathSync.native(root);
364
+ } catch {
365
+ return { reason: `${root} cannot be resolved` };
366
+ }
367
+ const rel = relative(realTop, realRoot);
368
+ if (rel.startsWith("..") || isAbsolute(rel)) return { reason: `${root} is not inside ${top}` };
369
+ const relPosix = rel.replace(/\\/g, "/");
370
+
371
+ const cache = cachePath(top, tree, relPosix, realRoot);
372
+ if (cache && existsSync(cache)) {
373
+ try {
374
+ return { keys: new Map(JSON.parse(readFileSync(cache, "utf-8"))) };
375
+ } catch {
376
+ /* torn or foreign: compute it again */
377
+ }
378
+ }
379
+ let box = null;
380
+ try {
381
+ box = mkdtempSync(join(tmpdir(), "suppa-gate-head-"));
382
+ writeHeadSnapshot(realTop, relPosix, box);
383
+ const headRoot = relPosix ? join(box, ...relPosix.split("/")) : box;
384
+ const r = runGate(headRoot, { lookupRoot: realRoot });
385
+ if (r.toolchain || r.unreadable) return { reason: `the gate could not run on HEAD (${r.toolchain ?? r.unreadable})` };
386
+ const keys = new Map();
387
+ for (const f of r.blocking ?? []) {
388
+ const key = findingKey(headRoot, f);
389
+ keys.set(key, (keys.get(key) ?? 0) + 1);
390
+ }
391
+ if (cache) saveCache(cache, keys);
392
+ return { keys };
393
+ } catch (e) {
394
+ return { reason: `HEAD could not be read (${e?.message ?? e})` };
395
+ } finally {
396
+ if (box) {
397
+ try {
398
+ rmSync(box, { recursive: true, force: true });
399
+ } catch {
400
+ /* the OS's temp dir keeps it */
401
+ }
402
+ }
403
+ }
404
+ }
405
+
406
+ /** What the checker reads: TypeScript, package.json / tsconfig*.json / pnpm-workspace.yaml, the ignore list. */
407
+ const SNAPSHOT_NAME_RE = /\.(?:[cm]?tsx?|json|ya?ml)$/;
408
+
409
+ /**
410
+ * Write HEAD's copy of the application root into `box`, at the same path
411
+ * relative to the repository top — plus the config files of the directories
412
+ * above it, which a tsconfig `extends` or a workspace file may name. Read with
413
+ * `git cat-file --batch`, so nothing in the work tree, the index or the refs is
414
+ * touched while a commit is being made.
415
+ */
416
+ function writeHeadSnapshot(top, relPosix, box) {
417
+ const listing = git(["ls-tree", "-r", "-z", "--full-tree", "HEAD"], top);
418
+ if (listing === null) throw new Error("git ls-tree failed");
419
+ const prefix = relPosix ? `${relPosix}/` : "";
420
+ const above = new Set([""]);
421
+ for (let i = relPosix.indexOf("/"); i > 0; i = relPosix.indexOf("/", i + 1)) above.add(relPosix.slice(0, i));
422
+ const wanted = [];
423
+ for (const entry of listing.split("\0")) {
424
+ if (!entry) continue;
425
+ const tab = entry.indexOf("\t");
426
+ const [mode, type, sha] = entry.slice(0, tab).split(" ");
427
+ const path = entry.slice(tab + 1);
428
+ if (type !== "blob" || mode === "120000") continue; // submodules and symlinks hold no schema code
429
+ const segments = path.split("/");
430
+ if (segments.some((s) => !s || s === "." || s === ".." || s === "node_modules")) continue;
431
+ const name = segments[segments.length - 1];
432
+ if (!SNAPSHOT_NAME_RE.test(name) && name !== ".suppa-gate-ignore") continue;
433
+ const dir = segments.slice(0, -1).join("/");
434
+ if (prefix && !path.startsWith(prefix) && !above.has(dir)) continue;
435
+ wanted.push({ sha, segments });
436
+ }
437
+ if (!wanted.length) return;
438
+ const out = execFileSync("git", ["cat-file", "--batch"], {
439
+ cwd: top,
440
+ input: `${wanted.map((w) => w.sha).join("\n")}\n`,
441
+ stdio: ["pipe", "pipe", "ignore"],
442
+ maxBuffer: 1024 * 1024 * 1024,
209
443
  });
210
- return { ok: blocking.length === 0, blocking, lines };
444
+ let at = 0;
445
+ for (const w of wanted) {
446
+ const nl = out.indexOf(0x0a, at);
447
+ if (nl < 0) throw new Error("git cat-file: truncated answer");
448
+ const header = out.toString("utf-8", at, nl).split(" ");
449
+ if (header[1] !== "blob") throw new Error(`git cat-file: ${header.join(" ")}`);
450
+ const size = Number(header[2]);
451
+ const dest = join(box, ...w.segments);
452
+ mkdirSync(dirname(dest), { recursive: true });
453
+ writeFileSync(dest, out.subarray(nl + 1, nl + 1 + size));
454
+ at = nl + 1 + size + 1;
455
+ }
211
456
  }
212
457
 
213
458
  /**
214
459
  * Gate several roots at once, each physical root once.
215
- * -> { failures, notes, checked } — `checked` counts roots the gate actually ran on.
460
+ * -> { failures, notes, checked, older } — `checked` counts roots the gate actually ran on.
461
+ *
462
+ * With `touched` (fileKeys of the paths a change touches) each root's findings
463
+ * are split by splitByChange: `failures` carries only what counts, `older` what
464
+ * does not. Without it — --ci — every finding counts.
216
465
  */
217
- function gateRoots(roots) {
466
+ function gateRoots(roots, touched = null) {
218
467
  const failures = [];
219
468
  const notes = [];
469
+ const older = [];
220
470
  const seen = new Set();
221
471
  let checked = 0;
222
472
  for (const root of roots) {
@@ -231,13 +481,48 @@ function gateRoots(roots) {
231
481
  else if (r.skipped) notes.push({ kind: "skipped", root, text: `${root}: ${r.skipped}` });
232
482
  else {
233
483
  checked++;
234
- if (!r.ok) failures.push({ root, lines: r.lines });
484
+ if (r.ok) continue;
485
+ if (!touched) {
486
+ failures.push({ root, lines: r.lines });
487
+ continue;
488
+ }
489
+ const split = splitByChange(root, r.blocking, touched);
490
+ if (split.older.length) older.push({ root, lines: split.older.map((f) => findingLine(root, f)) });
491
+ if (split.counted.length) {
492
+ failures.push({ root, lines: split.counted.map((f) => findingLine(root, f)), uncompared: split.uncompared });
493
+ }
235
494
  }
236
495
  }
237
- return { failures, notes, checked };
496
+ return { failures, notes, checked, older };
238
497
  }
239
498
 
240
- function failureReport(failures) {
499
+ const OLDER_SHOWN = 10;
500
+ const OLDER_WIDTH = 160;
501
+
502
+ /** The findings a change found already there: named every time, so they stay somebody's to fix. */
503
+ function olderReport(older) {
504
+ const total = older.reduce((n, o) => n + o.lines.length, 0);
505
+ if (!total) return [];
506
+ const out = [
507
+ `Not counted against this change: ${total} finding(s) HEAD already has, in files the change does ` +
508
+ "not touch. --ci still fails on them; fix them in a change of their own.",
509
+ ];
510
+ let shown = 0;
511
+ for (const o of older) {
512
+ if (shown >= OLDER_SHOWN) break;
513
+ out.push(`${o.root}`);
514
+ for (const line of o.lines) {
515
+ if (shown >= OLDER_SHOWN) break;
516
+ out.push(` ${line.length > OLDER_WIDTH ? `${line.slice(0, OLDER_WIDTH - 1)}…` : line}`);
517
+ shown++;
518
+ }
519
+ }
520
+ if (total > shown) out.push(` … and ${total - shown} more (entity-code-guard.mjs --ci lists every one)`);
521
+ out.push("");
522
+ return out;
523
+ }
524
+
525
+ function failureReport(failures, older = []) {
241
526
  const out = [
242
527
  "SUPPA ENTITY-CODE GATE FAILED — the schema code below breaks the platform's house rules.",
243
528
  "",
@@ -245,8 +530,12 @@ function failureReport(failures) {
245
530
  for (const f of failures) {
246
531
  out.push(`${f.root}`);
247
532
  for (const line of f.lines) out.push(` ${line}`);
533
+ if (f.uncompared) {
534
+ out.push(` (Not compared with HEAD: ${f.uncompared}. So findings in files this change does not touch count too.)`);
535
+ }
248
536
  out.push("");
249
537
  }
538
+ out.push(...olderReport(older));
250
539
  out.push(`These block by design: ${BLOCKING_SUMMARY}.`);
251
540
  out.push("Fix every line above and re-run the gate; a failure is not advisory.");
252
541
  out.push("");
@@ -284,7 +573,8 @@ function gitPathsZ(raw, { porcelain }) {
284
573
  }
285
574
 
286
575
  /**
287
- * Schema files git reports as changed in the working tree (staged or not).
576
+ * Files git reports as changed in the working tree (staged or not), schema or
577
+ * not — a runtime file the change touched answers for its own W635.
288
578
  * -> [{ path, deleted }]
289
579
  *
290
580
  * A deletion is kept, not filtered out: the module that registered the class
@@ -292,28 +582,32 @@ function gitPathsZ(raw, { porcelain }) {
292
582
  * every path that no longer existed let a `git rm` of an entity file skip the
293
583
  * gate while the registration went stale.
294
584
  */
295
- function changedSchemaFiles(cwd) {
585
+ function changedFiles(cwd) {
296
586
  const top = git(["rev-parse", "--show-toplevel"], cwd)?.trim();
297
587
  if (!top) return [];
298
588
  const status = git(["status", "--porcelain", "-z", "--untracked-files=all"], cwd);
299
589
  if (status === null) return [];
300
590
  return gitPathsZ(status, { porcelain: true })
301
- .filter((p) => SCHEMA_NAME_RE.test(p))
302
591
  .map((p) => resolve(top, p))
303
592
  .map((p) => ({ path: p, deleted: !existsSync(p) }));
304
593
  }
305
594
 
306
- function stagedSchemaFiles(cwd) {
595
+ function stagedFiles(cwd) {
307
596
  const top = git(["rev-parse", "--show-toplevel"], cwd)?.trim();
308
597
  if (!top) return [];
309
598
  const names = git(["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMRD"], cwd);
310
599
  if (!names) return [];
311
600
  return gitPathsZ(names, { porcelain: false })
312
- .filter((p) => SCHEMA_NAME_RE.test(p))
313
601
  .map((p) => resolve(top, p))
314
602
  .map((p) => ({ path: p, deleted: !existsSync(p) }));
315
603
  }
316
604
 
605
+ /** The schema files among them that the gate must hear about, minus the declared exclusions. */
606
+ const schemaChanges = (files) =>
607
+ files.filter((c) => SCHEMA_NAME_RE.test(c.path) && !isIgnored(appRootFor(c.path), c.path));
608
+
609
+ const touchedSet = (paths) => new Set(paths.map(fileKey));
610
+
317
611
  function emitHookJson(event, context) {
318
612
  process.stdout.write(
319
613
  `${JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: context } })}\n`,
@@ -343,11 +637,14 @@ function postToolUse() {
343
637
  const root = appRootFor(p);
344
638
  if (isIgnored(root, p)) return 0;
345
639
 
346
- const { failures, notes } = gateRoots([root]);
640
+ // The file just written, and whatever else this session has changed: an
641
+ // earlier write's findings are this change's too.
642
+ const touched = touchedSet([p, ...changedFiles(dirname(resolve(p))).map((c) => c.path)]);
643
+ const { failures, notes, older } = gateRoots([root], touched);
347
644
  if (failures.length) {
348
645
  // PostToolUse cannot undo the write, but exit 2 puts this in front of the
349
646
  // agent as the next thing it reads — which is the point.
350
- process.stderr.write(`${failureReport(failures)}\n`);
647
+ process.stderr.write(`${failureReport(failures, older)}\n`);
351
648
  return 2;
352
649
  }
353
650
  if (notes.length) {
@@ -366,15 +663,16 @@ function stop() {
366
663
  // Blocking again from inside it is how a hook loops forever.
367
664
  if (input?.stop_hook_active) return 0;
368
665
  const cwd = input?.cwd || process.cwd();
369
- const changes = changedSchemaFiles(cwd).filter((c) => !isIgnored(appRootFor(c.path), c.path));
666
+ const changed = changedFiles(cwd);
667
+ const changes = schemaChanges(changed);
370
668
  if (!changes.length) return 0;
371
669
 
372
670
  // A deleted file has no content to judge; its ROOT does — the gate over the
373
671
  // whole root is what notices a module still registering the missing class.
374
- const { failures } = gateRoots(changes.map((c) => appRootFor(c.path)));
672
+ const { failures, older } = gateRoots(changes.map((c) => appRootFor(c.path)), touchedSet(changed.map((c) => c.path)));
375
673
  if (!failures.length) return 0;
376
674
  process.stderr.write(
377
- `${failureReport(failures)}\n\nYou changed schema files in this session, so this turn is not ` +
675
+ `${failureReport(failures, older)}\n\nYou changed schema files in this session, so this turn is not ` +
378
676
  `finished: fix the findings above, then re-run the gate.\n`,
379
677
  );
380
678
  return 2;
@@ -412,9 +710,10 @@ function couldNotRun(notes) {
412
710
  }
413
711
 
414
712
  function preCommit() {
415
- const changes = stagedSchemaFiles(process.cwd()).filter((c) => !isIgnored(appRootFor(c.path), c.path));
713
+ const staged = stagedFiles(process.cwd());
714
+ const changes = schemaChanges(staged);
416
715
  if (!changes.length) return 0;
417
- const { failures, notes } = gateRoots(changes.map((c) => appRootFor(c.path)));
716
+ const { failures, notes, older } = gateRoots(changes.map((c) => appRootFor(c.path)), touchedSet(staged.map((c) => c.path)));
418
717
  const broken = couldNotRun(notes);
419
718
  if (broken) {
420
719
  process.stderr.write(
@@ -424,11 +723,13 @@ function preCommit() {
424
723
  return 1;
425
724
  }
426
725
  if (!failures.length) {
427
- process.stdout.write("suppa entity-code gate: clean\n");
726
+ process.stdout.write(
727
+ older.length ? `suppa entity-code gate: clean for this commit\n${olderReport(older).join("\n")}` : "suppa entity-code gate: clean\n",
728
+ );
428
729
  return 0;
429
730
  }
430
731
  process.stderr.write(
431
- `${failureReport(failures)}\n\nCommit refused. Fix the findings, or pass --no-verify if you ` +
732
+ `${failureReport(failures, older)}\n\nCommit refused. Fix the findings, or pass --no-verify if you ` +
432
733
  `genuinely mean to commit code that will not converge.\n`,
433
734
  );
434
735
  return 1;
@@ -41,7 +41,7 @@ export const BLOCKING_SUMMARY =
41
41
  "duplicate key aborts the tenant migration (W628); an enum titles map keyed by the stored VALUE, or the title is " +
42
42
  "never stored (W637); a platform entity's name (Users, Forms, …) only in <name>.extension.entity.ts, where " +
43
43
  "extension mode's rules apply (W636); no entity name ending in a reserved companion-table suffix " +
44
- "(E131), no platform-owned field name such as parent/comments/customFields/searchVector (E132), no " +
44
+ "(E131), no platform-owned field name such as parent/comments/customFields/searchVector (E132; a self-referencing parent/parents and its back reference with hierarchy off is only advisory, W641), no " +
45
45
  "scalar `<x>Id` beside a relation `<x>` (E133); and inside @Entity({ options }) only the platform's " +
46
46
  "feature options, each with the type it takes — hierarchy and folders are \"single\" or \"multi\", never " +
47
47
  "a boolean (E503); no two @Index over one column set with the same unique/where — name and order are not " +
@@ -24,9 +24,9 @@
24
24
  * advisory, for a legacy repo you are not cleaning up in this pass.
25
25
  */
26
26
  import { builtinModules, createRequire } from "node:module";
27
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
27
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
28
28
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
29
- import { pathToFileURL } from "node:url";
29
+ import { fileURLToPath, pathToFileURL } from "node:url";
30
30
 
31
31
  // ── Doc-derived catalogs (fallback when @suppa/sdk typings are absent) ──
32
32
  export const SYSTEM_COLUMNS = ["id", "createdAt", "updatedAt", "deletedAt", "createdBy", "removedBy"];
@@ -137,6 +137,8 @@ export const RULE_WARNINGS = [
137
137
  // W638 (an enum value that is a field-option name) and W639 (definePermissions on a stand whose runner
138
138
  // has no such function) are ADVISORY: the first depends on a titles map the checker may not see whole,
139
139
  // the second on which stands the app deploys to, which nothing in the repo says.
140
+ // W641 (a self-referencing parent/parents, or its children/multiChildren back reference, with hierarchy
141
+ // off) is ADVISORY: it is the pair the option would create, and switching the option on keeps it.
140
142
  ];
141
143
  /**
142
144
  * The @suppa/sdk extension-runner ships, PER STAND — the copy an application's
@@ -1361,6 +1363,71 @@ function checkCustomFieldColumns(ts, info, cls, findings, model) {
1361
1363
  }
1362
1364
 
1363
1365
  // ── rules: tabular parts ──
1366
+ /**
1367
+ * The relation kind the hierarchy option creates under each name
1368
+ * (entity-builder hierarchy-option.service.ts: `parents` many-to-many for
1369
+ * "multi", `parent` many-to-one otherwise), always onto the entity itself.
1370
+ */
1371
+ const HIERARCHY_FIELD_KINDS = new Map([["parent", "many-to-one"], ["parents", "many-to-many"]]);
1372
+ /**
1373
+ * W641 — `parent`/`parents` declared as exactly the field the hierarchy option
1374
+ * would create, on an entity whose `hierarchy` is visibly off. The platform
1375
+ * takes it in its stride (entity-builder develop 3b05618cd; the files below
1376
+ * unchanged on develop bb7c35c4, 2026-10-27):
1377
+ *
1378
+ * - an application's sync never meets the field-name guard: the app's metadata
1379
+ * arrives as an import, whose writes carry importLogic, and the guard returns
1380
+ * under importLogic/migration (field-name-conflict-guard.extension.ts:101,
1381
+ * :151, :317); on update it checks reserved names only on a rename (:217);
1382
+ * - the hierarchy MACHINERY runs only with options.hierarchy — the loop and
1383
+ * depth guard (hierarchy-graph.service.ts:81, through hierarchy-depth-guard),
1384
+ * cascade remove (hierarchy-cascade-remove.extension.ts:57), the time-
1385
+ * tracking roll-up (time-tracking-spent-time-total.service.ts:42). Two READ
1386
+ * paths key on the name alone and treat such a field as a tree already — a
1387
+ * select that asks for `hierarchy` (modules/entity/hierarchy
1388
+ * resolveHierarchyField) and a manual order grouped by the field
1389
+ * (custom-order.service.ts isHierarchyField): harmless, and said;
1390
+ * - switching the option on later skips the option's setup when a field of
1391
+ * that name exists (entity-options.service.ts:448-460) — and that setup is
1392
+ * only the field and its back reference (hierarchy-option.service.ts).
1393
+ *
1394
+ * Renaming such a field is the expensive move — without a `key` it is a drop
1395
+ * and create of the relation's data — so the gate must not demand it. Off-
1396
+ * canonical spellings, another target, the other kind, extension mode, and
1397
+ * options that cannot be read all stay E132.
1398
+ */
1399
+ function isUnhierarchicalSelfParent(ts, info, name, prop) {
1400
+ if (info.isExtension || info.optionsUnreadable) return false;
1401
+ if (HIERARCHY_FIELD_KINDS.get(name) !== prop.kind) return false;
1402
+ if (prop.targetClass !== info.className) return false;
1403
+ if (spreadElements(ts, unwrapExpr(ts, info.optionsNode)).length) return false;
1404
+ const slot = info.options.get("options");
1405
+ if (!slot) return true;
1406
+ const obj = unwrapExpr(ts, slot);
1407
+ if (!ts.isObjectLiteralExpression(obj) || spreadElements(ts, obj).length) return false;
1408
+ return !objectMap(ts, obj).has("hierarchy");
1409
+ }
1410
+ /** The back reference the option pairs with each field (hierarchy-option.service.ts `backReference`). */
1411
+ const HIERARCHY_BACK_REFERENCES = new Map([
1412
+ ["children", { kind: "one-to-many", of: "parent" }],
1413
+ ["multiChildren", { kind: "many-to-many-backref", of: "parents" }],
1414
+ ]);
1415
+ /**
1416
+ * W641's back reference — `children` (@OneToMany) / `multiChildren`
1417
+ * (@ManyToManyBackRef) onto the entity itself whose inverse selects a W641
1418
+ * `parent` / `parents`: the pair the option would create, declared by hand
1419
+ * (crm Activities and Opportunities, 2026-10-27). Switching the option on later
1420
+ * skips its setup because the parent field exists, so no second back
1421
+ * reference appears; nothing keys on the back reference's name.
1422
+ */
1423
+ function isUnhierarchicalSelfChildren(ts, info, name, prop) {
1424
+ const back = HIERARCHY_BACK_REFERENCES.get(name);
1425
+ if (!back || prop.kind !== back.kind || prop.targetClass !== info.className) return false;
1426
+ const accessed = inverseAccessedProperty(ts, prop.inverseNode);
1427
+ const owner = accessed ? info.properties.get(accessed) : null;
1428
+ if (!owner || (stringValue(ts, owner.nameNode) ?? accessed) !== back.of) return false;
1429
+ return isUnhierarchicalSelfParent(ts, info, back.of, owner);
1430
+ }
1364
1431
  /**
1365
1432
  * E131 / E132 / E133 — names the platform will refuse or silently collide on.
1366
1433
  *
@@ -1375,6 +1442,8 @@ function checkCustomFieldColumns(ts, info, cls, findings, model) {
1375
1442
  * multi-type synthetic column (`f12Type`). The former is generated by the
1376
1443
  * platform when an option is enabled and the guard answers 400 on a client
1377
1444
  * field of that name; the latter collides with columns the platform mints.
1445
+ * The hierarchy pair is W641 instead when the option is off — see
1446
+ * isUnhierarchicalSelfParent and isUnhierarchicalSelfChildren.
1378
1447
  * - E133: a scalar column named `<x>Id` beside a relation/enum/file `<x>`
1379
1448
  * (or the reverse). The relation's PHYSICAL column is `<x>Id`; two fields
1380
1449
  * then claim one column, both sides of the DDL used to swallow it in
@@ -1405,12 +1474,35 @@ function checkReservedNames(ts, info, findings) {
1405
1474
  // with the platform's `parent` exactly as the canonical spelling does.
1406
1475
  const reserved = RESERVED_FIELD_NAMES_LOWER.get(name.toLowerCase());
1407
1476
  if (reserved) {
1477
+ if (isUnhierarchicalSelfParent(ts, info, name, prop)) {
1478
+ findings.push(finding(ts, sf, prop.nameNode ?? prop.node, "W641",
1479
+ `'${name}' on '${info.className}' is a ${prop.kind} onto the entity itself — the field the ` +
1480
+ `\`hierarchy\` option creates under that name, and the option is off here. The platform takes it as a ` +
1481
+ `plain relation: an application's sync is not subject to the field-name guard, and the hierarchy ` +
1482
+ `machinery (the loop and depth guard, cascade remove, the time-tracking roll-up) runs only with ` +
1483
+ `options.hierarchy — so nothing refuses a loop (A → B → A) here, while a select that asks for ` +
1484
+ `\`hierarchy\` and a manual order grouped by '${name}' already treat it as a tree. If \`hierarchy\` is ` +
1485
+ `switched on later, the platform keeps this field and skips its own setup, the ` +
1486
+ `${name === "parent" ? "children" : "multiChildren"} back reference with it. Advisory — for a new tree, ` +
1487
+ `switch the option on instead.`));
1488
+ continue;
1489
+ }
1490
+ if (isUnhierarchicalSelfChildren(ts, info, name, prop)) {
1491
+ const of = HIERARCHY_BACK_REFERENCES.get(name).of;
1492
+ findings.push(finding(ts, sf, prop.nameNode ?? prop.node, "W641",
1493
+ `'${name}' on '${info.className}' is the back reference of '${of}' — the pair the \`hierarchy\` option ` +
1494
+ `would create, declared by hand with the option off. It is a plain reverse relation, and switching the ` +
1495
+ `option on later adds no second one: the platform keeps '${of}' and skips its own setup. Advisory.`));
1496
+ continue;
1497
+ }
1408
1498
  findings.push(finding(ts, sf, prop.nameNode ?? prop.node, "E132",
1409
1499
  `'${name}' is a field name the platform owns${reserved !== name ? ` (its canonical spelling is '${reserved}')` : ""} — it is generated when the matching entity option is ` +
1410
1500
  `switched on (hierarchy → parent/children, comments, favorites, time tracking → spentTime, …) or held ` +
1411
- `by the search machinery (searchVector). The platform's field-name guard refuses a declared field of ` +
1412
- `that name with HTTP 400 on every builder and data write; a sync that carries schema authority passes ` +
1413
- `the guard and collides later, the moment the option is switched on. Rename it. ` +
1501
+ `by the search machinery (searchVector). The platform's field-name guard refuses a field of that ` +
1502
+ `name with HTTP 400 when the builder creates or renames one; an application's sync is not subject to ` +
1503
+ `the guard, so the declaration lands — and once the option is switched on, the platform keeps it as ` +
1504
+ `the option's own field whatever its shape (it creates a field of that name only when none exists), ` +
1505
+ `so the option runs on a field it did not shape. Rename it. ` +
1414
1506
  `Reserved: ${RESERVED_FIELD_NAMES.join(", ")}.`));
1415
1507
  continue;
1416
1508
  }
@@ -5209,12 +5301,15 @@ function parseSchemaFile(ts, file) {
5209
5301
  }
5210
5302
 
5211
5303
  // ── public API ──
5212
- export function validateSchema({ files = [], rootDir = null } = {}) {
5304
+ export function validateSchema({ files = [], rootDir = null, lookupRoot: lookupAt = null } = {}) {
5213
5305
  // Where the compiler and the SDK typings are looked up: the repo being validated. For named
5214
5306
  // files that is the first file's own directory — without it an INSTALLED gate (no typescript
5215
5307
  // of its own) refused a file whose app had one, and the SDK catalog came back empty. rootDir
5216
5308
  // stays null: it switches on the whole-repo rules, which one file cannot satisfy.
5217
- const lookupRoot = rootDir ?? (files.length ? dirname(resolve(files[0])) : null);
5309
+ // `lookupRoot` names it for a copy of an app that has no node_modules of its own — the
5310
+ // guard's HEAD snapshot, which must be judged with the compiler and the SDK catalog of the
5311
+ // working tree it is compared with, or the two answers differ by more than the change.
5312
+ const lookupRoot = lookupAt ?? rootDir ?? (files.length ? dirname(resolve(files[0])) : null);
5218
5313
  const ts = loadTypescript(lookupRoot);
5219
5314
  const sdk = loadSdkCatalog(ts, lookupRoot);
5220
5315
  const model = {
@@ -5509,9 +5604,27 @@ function importedEnumModules(files) {
5509
5604
  }
5510
5605
 
5511
5606
  // ── CLI ──
5512
- const isMain =
5513
- process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
5514
- if (isMain) {
5607
+ /**
5608
+ * Was this file STARTED, or imported?
5609
+ *
5610
+ * Node resolves the main module through symlinks, so import.meta.url names the REAL file while
5611
+ * argv[1] keeps the path as typed. Under pnpm, node_modules/suppa-mcp-2 is a symlink (a junction
5612
+ * on Windows), and `node node_modules/suppa-mcp-2/…/validate-suppa-schema.mjs .` — the command the
5613
+ * house rules print — compared the two, found them different, never ran, and exited 0 having
5614
+ * printed nothing: a pass nobody computed. Compare realpaths, as validate-form-schema.mjs already
5615
+ * does, falling back to the encoded URL when a path cannot be resolved.
5616
+ */
5617
+ function startedDirectly() {
5618
+ const arg = process.argv[1];
5619
+ if (!arg) return false;
5620
+ try {
5621
+ return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(arg);
5622
+ } catch {
5623
+ return pathToFileURL(resolve(arg)).href === import.meta.url;
5624
+ }
5625
+ }
5626
+
5627
+ if (startedDirectly()) {
5515
5628
  const argv = process.argv.slice(2);
5516
5629
  // Default is strict: the authoring rules block. --no-strict is the escape for
5517
5630
  // a legacy repo whose existing entities restate defaults everywhere. Flags are