suppa-mcp-2 1.44.1 → 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.1",
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": {
@@ -488,10 +488,13 @@ The validator parses with the TypeScript compiler API, read from the app repo yo
488
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 |
489
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 |
490
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 |
491
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 |
492
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) |
493
494
  | Several stubs piled into one `relation-targets.ts` | Each existing-entity stub lives in its OWN file | W616 (blocks the gate) |
494
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 |
495
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 | — |
496
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 |
497
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
@@ -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;
@@ -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"];
@@ -5301,12 +5301,15 @@ function parseSchemaFile(ts, file) {
5301
5301
  }
5302
5302
 
5303
5303
  // ── public API ──
5304
- export function validateSchema({ files = [], rootDir = null } = {}) {
5304
+ export function validateSchema({ files = [], rootDir = null, lookupRoot: lookupAt = null } = {}) {
5305
5305
  // Where the compiler and the SDK typings are looked up: the repo being validated. For named
5306
5306
  // files that is the first file's own directory — without it an INSTALLED gate (no typescript
5307
5307
  // of its own) refused a file whose app had one, and the SDK catalog came back empty. rootDir
5308
5308
  // stays null: it switches on the whole-repo rules, which one file cannot satisfy.
5309
- 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);
5310
5313
  const ts = loadTypescript(lookupRoot);
5311
5314
  const sdk = loadSdkCatalog(ts, lookupRoot);
5312
5315
  const model = {
@@ -5601,9 +5604,27 @@ function importedEnumModules(files) {
5601
5604
  }
5602
5605
 
5603
5606
  // ── CLI ──
5604
- const isMain =
5605
- process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
5606
- 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()) {
5607
5628
  const argv = process.argv.slice(2);
5608
5629
  // Default is strict: the authoring rules block. --no-strict is the escape for
5609
5630
  // a legacy repo whose existing entities restate defaults everywhere. Flags are