suppa-mcp-2 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -104,6 +104,34 @@ Then run **`suppa_login`** once per tenant to authenticate.
104
104
 
105
105
  ---
106
106
 
107
+ ## Which version is running (and is it current)
108
+
109
+ An MCP client keeps whatever build it started with — an `npx` cache or a
110
+ `node_modules` copy — for the whole session. Publishing a fix changes nothing
111
+ for that session, so "the fix isn't working" and "I'm running last week's
112
+ server" look identical from the inside. Two mechanisms keep them apart:
113
+
114
+ - **`suppa_version`** — read-only, asks the npm registry live, and reports the
115
+ running version, the published one, and the upgrade command. Ask it first
116
+ whenever a tool or behaviour you expect is missing. `suppa_health_check` also
117
+ carries `version` in every report, so a bug report names its build without
118
+ anyone remembering to ask.
119
+ - **An automatic notice.** The server checks the registry in the background
120
+ (detached, cached for 6h, 4s timeout, silent when offline — startup never
121
+ waits). If the running build is behind, the next session's instructions open
122
+ with an `OUTDATED` banner telling the agent to say so in its first reply, and
123
+ to restart the client after updating.
124
+
125
+ Upgrading: `npm i -g suppa-mcp-2@latest`, or pin `suppa-mcp-2@latest` in the
126
+ client's MCP config — then **restart the client**. Without the restart the old
127
+ process, and its old code, keep serving the session.
128
+
129
+ On the source side, the version is stated in `package.json` **only**.
130
+ `scripts/check-version-literals.mjs` runs inside `npm test` (and so inside
131
+ `prepublishOnly`) and fails the build if a version string is typed into `src/`:
132
+ the handshake once announced a hardcoded `1.6.1` for every release after it,
133
+ which made the one diagnostic question unanswerable.
134
+
107
135
  ## Agent workflow
108
136
 
109
137
  When an AI agent connects, the server provides built-in instructions describing the correct workflow. Auth first, then discover schema before reading or writing data:
@@ -176,7 +204,8 @@ work normally. Erasing data for good is an admin action in the platform's own UI
176
204
  | `suppa_list_tenants` | List known tenants + which is active / authenticated |
177
205
  | `suppa_logout` | Remove stored credentials for a tenant |
178
206
  | `suppa_diagnostics` | Validate the whole multi-tenant setup |
179
- | `suppa_health_check` | Config + upstream connectivity check |
207
+ | `suppa_health_check` | Config + upstream connectivity check (reports `version`) |
208
+ | `suppa_version` | Running build vs newest published, and how to upgrade |
180
209
 
181
210
  ### Tasks
182
211
 
@@ -346,9 +375,11 @@ relation property must carry a TypeScript type that agrees with its decorator
346
375
  (E114/E115/W610; a type naming no class, such as `any`, is the advisory W615),
347
376
  enum member keys are PascalCase (W611), no field option
348
377
  may be written at its platform default (W612), and `@Enum`/`@MultiEnum` take a
349
- global name only when the enum is actually shared (W613). These are **rule
350
- violations**: like errors, they exit 1, because a rule that only warns is a rule
351
- that gets ignored. `--no-strict` demotes them to warnings for a legacy repo.
378
+ global name only when the enum is actually shared (W613). Those four, plus
379
+ `owner` first in a tabular part's `importKeyFields` (W607) and no `inverse` on
380
+ `@ManyToOne`/`@ManyToMany` (W609), are **rule violations**: like errors, they
381
+ exit 1, because a rule that only warns is a rule that gets ignored.
382
+ `--no-strict` demotes them to warnings for a legacy repo.
352
383
  Advisory warnings — W601-W606, W608, W614, W615 — never block; they report what
353
384
  the checker could not see.
354
385
 
package/dist/server.js CHANGED
@@ -19,6 +19,8 @@ import * as automation from "./tools/automation.js";
19
19
  import * as auth from "./auth.js";
20
20
  import * as tenants from "./tenants.js";
21
21
  import { confirmRequired, jsonResponse } from "./utils.js";
22
+ import { PACKAGE_NAME, PACKAGE_VERSION, knownLatest, isOutdated, refreshLatestVersion, refreshLatestVersionInBackground, upgradeNotice, } from "./version.js";
23
+ export { PACKAGE_VERSION };
22
24
  // ---------------------------------------------------------------------------
23
25
  // Tool-behavior hints (MCP spec): clients use these for auto-approval policies.
24
26
  // _READ touches nothing; _ADD only creates new data; _MUT changes or removes
@@ -265,6 +267,15 @@ ENTITY BUILDER (create + edit fields; removal is UI-only)
265
267
  - An enum value on a RECORD is a reference, not a string: write {"id": <Enums row id>} for enum and [{"id": ...}, ...] for multi-enum. A bare code like "red" is refused with 'field must contain id for many-to-one relationship'. Read the ids with suppa_search_records on 'Enums' filtered by name = the enum name.
266
268
  - Existing fields CAN be edited with suppa_update_field (name, title, notNull/unique/default, relation target, and the options above), within the platform's own limits: a field's TYPE can never be changed, its SUBTYPE only toggles 'encrypted' on/off (text fields only), and a system field takes just title + the options keys. Removing a field is still UI-only — this server has no remove-field call.
267
269
 
270
+ WRITING ENTITY CODE (*.entity.ts in an application repo — NOT the API tools above)
271
+ These four rules are house rules of this platform. They OVERRIDE the platform's own migrations doc, which contradicts two of them, and they override the style of the entities already in the repo you are editing — an existing file that breaks them is the habit these rules exist to stop, not a convention to match. The full skill is skills/suppa-entity-code/SKILL.md inside the installed suppa-mcp-2 package; these four bind whether or not you open it.
272
+ 1. TYPE EVERY RELATION PROPERTY to match its decorator: @ManyToOne -> \`owner: Target;\` (\`owner?: Target\` when the relation is nullable), @ManyToMany/@OneToMany/@ManyToManyBackRef -> \`peers: Target[];\`. Never \`any\`.
273
+ 2. ENUM MEMBER KEYS ARE PascalCase — \`NotFilled = 'Not filled'\`. The stored value is the string on the right and need not match the key.
274
+ 3. NEVER WRITE A FIELD OPTION AT ITS DEFAULT. canGroup, canSort, showInTable, editFromTable and canFilter are already true; readOnly and searchable are already false. Write one ONLY where the field departs from that (usually just \`searchable: true\`). A field with all seven spelled out is wrong even though it works.
275
+ 4. @Enum/@MultiEnum TAKE THE GLOBAL NAME ONLY WHEN THE ENUM IS GLOBAL — shared by another entity, or referenced from a seed record. Otherwise omit the first argument entirely: \`@Enum(StatusEnum, StatusTitles, { … })\`, and the decorator derives <ClassName>.<propertyName>. A field's own \`key: 'Entity.field'\` is the rename key, NOT a reference, and does not make the enum global.
276
+ Before reporting the file done, run the gate — it fails (exit 1) on every one of the four:
277
+ node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs <app-root>
278
+
268
279
  ATTACHMENTS (files on a record)
269
280
  - A record can carry files only if its entity has a 'file' or 'multi-file' field; check with suppa_describe_entity and add one with suppa_add_field if it has none.
270
281
  - WRITE: suppa_attach_file_to_record(entity, record_id, absolute_path) uploads from the local disk and returns file_ids — keep them, they are the only handle that gets the bytes back.
@@ -305,7 +316,11 @@ export function buildServer() {
305
316
  // Reset so repeated buildServer() calls (e.g. in tests) do not double-count.
306
317
  TOOL_NAMES.length = 0;
307
318
  PROMPT_NAMES.length = 0;
308
- const server = new McpServer({ name: "suppa-2.0", version: "1.6.1" }, { instructions: INSTRUCTIONS });
319
+ // Detached, cached, TTL-limited: this session's instructions carry whatever
320
+ // the last check found, and this call keeps the answer fresh for the next
321
+ // one. Startup must never wait on the network.
322
+ refreshLatestVersionInBackground();
323
+ const server = new McpServer({ name: "suppa-2.0", version: PACKAGE_VERSION }, { instructions: INSTRUCTIONS + upgradeNotice() });
309
324
  const reg = (name, cfg, handler) => {
310
325
  server.registerTool(name, {
311
326
  description: cfg.description,
@@ -2152,6 +2167,40 @@ export function buildServer() {
2152
2167
  description: "List known Suppa tenants — which one is active and whether each is authenticated.",
2153
2168
  annotations: _READ,
2154
2169
  }, async () => text(tenants.listTenants()));
2170
+ reg("suppa_version", {
2171
+ description: "Which suppa-mcp-2 build this session is actually running, and whether a newer one is\n" +
2172
+ " published. Ask this FIRST whenever a fix, tool or behaviour you were told exists is\n" +
2173
+ " missing or behaves the old way: an MCP client keeps whatever version it started with\n" +
2174
+ " (npx cache / node_modules) for the whole session, so a release changes nothing until\n" +
2175
+ " the client is restarted on the new package. Reports running, latest, whether an\n" +
2176
+ " upgrade is available, and the command to run.",
2177
+ annotations: _READ,
2178
+ }, async () => {
2179
+ // Force a live lookup: this tool is the one place staleness must be
2180
+ // answered from the registry, not from a cache that may predate a release.
2181
+ const latest = await refreshLatestVersion(true);
2182
+ const outdated = isOutdated();
2183
+ return text(jsonResponse({
2184
+ package: PACKAGE_NAME,
2185
+ running: PACKAGE_VERSION,
2186
+ latest: latest ?? knownLatest(),
2187
+ up_to_date: latest ? !outdated : null,
2188
+ checked: latest !== null,
2189
+ upgrade: outdated
2190
+ ? {
2191
+ command: `npm i -g ${PACKAGE_NAME}@latest`,
2192
+ then: "RESTART the MCP client — a running server keeps its old code for the whole session.",
2193
+ note: "If the client launches this server via npx, pin @latest in its MCP config; npx " +
2194
+ "reuses a cached copy otherwise.",
2195
+ }
2196
+ : null,
2197
+ note: latest === null
2198
+ ? "The npm registry could not be reached, so 'latest' is the last value this machine cached (or null). The running version is exact."
2199
+ : outdated
2200
+ ? `Running ${PACKAGE_VERSION}; ${latest} is published. Tell the user, and treat any behaviour that contradicts newer docs as this build's behaviour.`
2201
+ : "This is the newest published build.",
2202
+ }));
2203
+ });
2155
2204
  reg("suppa_logout", {
2156
2205
  description: "Remove stored keychain credentials for a tenant (default: the active one).\n\n" +
2157
2206
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
@@ -2312,6 +2361,12 @@ async function healthCheck(deep = true) {
2312
2361
  const token = ctx.getToken();
2313
2362
  const body = {
2314
2363
  service: "suppa-mcp",
2364
+ // Every health report names the build it came from: a bug report or a
2365
+ // "that fix isn't working" carries its version without anyone remembering
2366
+ // to ask. `outdated` is from the cached registry check (suppa_version
2367
+ // re-checks live).
2368
+ version: PACKAGE_VERSION,
2369
+ outdated: isOutdated() ? { latest: knownLatest(), action: "restart the client on the new package" } : false,
2315
2370
  tenant: ctx.host,
2316
2371
  base_url: ctx.baseUrl,
2317
2372
  token_configured: Boolean(token),
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Which version is running, and is it the current one.
3
+ *
4
+ * Two failures this module exists to make impossible to miss:
5
+ *
6
+ * 1. A version typed into the source. The MCP handshake announced a literal
7
+ * "1.6.1" for every release after it, so a client running the fix and a
8
+ * client running six releases behind reported the same string — the one
9
+ * question you ask when a fix appears not to have landed had a useless
10
+ * answer. PACKAGE_VERSION reads package.json; the release gate
11
+ * (scripts/check-version-literals.mjs) refuses any other spelling in src/.
12
+ *
13
+ * 2. An old version installed. A client pins whatever npx cached or
14
+ * node_modules holds; publishing a fix changes nothing until that client is
15
+ * restarted with the new package, and NOTHING in the session says so. The
16
+ * check below compares the running version against the registry and puts the
17
+ * answer where an agent cannot miss it: the server instructions, and the
18
+ * suppa_version tool.
19
+ *
20
+ * The registry lookup never blocks and never throws: it runs detached from
21
+ * startup, writes a cache, and the next session reads it. A machine with no
22
+ * network keeps working and simply never reports an upgrade.
23
+ */
24
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
25
+ import { dirname, join } from "node:path";
26
+ import { fileURLToPath } from "node:url";
27
+ import { homeDir } from "./registry.js";
28
+ /** The running package's own version, from its package.json. Never a literal. */
29
+ export const PACKAGE_VERSION = readOwnVersion();
30
+ function readOwnVersion() {
31
+ // dist/version.js -> ../package.json; src/version.ts (tests) -> ../package.json
32
+ const here = dirname(fileURLToPath(import.meta.url));
33
+ for (const candidate of [join(here, "..", "package.json"), join(here, "..", "..", "package.json")]) {
34
+ try {
35
+ const pkg = JSON.parse(readFileSync(candidate, "utf-8"));
36
+ if (pkg?.name === "suppa-mcp-2" && typeof pkg.version === "string")
37
+ return pkg.version;
38
+ }
39
+ catch {
40
+ /* try the next candidate */
41
+ }
42
+ }
43
+ return "unknown";
44
+ }
45
+ export const PACKAGE_NAME = "suppa-mcp-2";
46
+ const REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`;
47
+ /** How long a registry answer is trusted before it is fetched again. */
48
+ const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
49
+ function cachePath() {
50
+ return join(homeDir(), "version-check.json");
51
+ }
52
+ function readCache() {
53
+ try {
54
+ const data = JSON.parse(readFileSync(cachePath(), "utf-8"));
55
+ if (typeof data?.latest === "string" && typeof data?.checked_at === "number")
56
+ return data;
57
+ }
58
+ catch {
59
+ /* absent or unreadable — treat as "never checked" */
60
+ }
61
+ return null;
62
+ }
63
+ function writeCache(cache) {
64
+ try {
65
+ mkdirSync(homeDir(), { recursive: true });
66
+ // Same write-then-rename the tenant registry uses: two servers starting at
67
+ // once must never read a half-written file.
68
+ const tmp = `${cachePath()}.${process.pid}.tmp`;
69
+ writeFileSync(tmp, `${JSON.stringify(cache, null, 2)}\n`, "utf-8");
70
+ renameSync(tmp, cachePath());
71
+ }
72
+ catch {
73
+ /* a cache that cannot be written just means the next session re-checks */
74
+ }
75
+ }
76
+ /** -1 / 0 / 1 by semver precedence; prerelease tags are ignored (we publish none). */
77
+ export function compareVersions(a, b) {
78
+ const parse = (v) => String(v)
79
+ .replace(/^v/, "")
80
+ .split("-")[0]
81
+ .split(".")
82
+ .map((n) => Number.parseInt(n, 10) || 0);
83
+ const [x, y] = [parse(a), parse(b)];
84
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
85
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
86
+ if (d !== 0)
87
+ return d < 0 ? -1 : 1;
88
+ }
89
+ return 0;
90
+ }
91
+ /** The newest version this machine has ever seen, or null if it never looked. */
92
+ export function knownLatest() {
93
+ return readCache()?.latest ?? null;
94
+ }
95
+ /** Is the running build behind the newest version we know of? */
96
+ export function isOutdated() {
97
+ const latest = knownLatest();
98
+ if (!latest || PACKAGE_VERSION === "unknown")
99
+ return false;
100
+ return compareVersions(PACKAGE_VERSION, latest) < 0;
101
+ }
102
+ /**
103
+ * Ask the registry for the latest version, at most once per TTL, and cache it.
104
+ * Detached on purpose — the caller never awaits it, so a slow or blocked
105
+ * registry cannot delay a single tool call.
106
+ */
107
+ export async function refreshLatestVersion(force = false) {
108
+ const cached = readCache();
109
+ if (!force && cached && Date.now() - cached.checked_at < CACHE_TTL_MS)
110
+ return cached.latest;
111
+ try {
112
+ const controller = new AbortController();
113
+ const timer = setTimeout(() => controller.abort(), 4000);
114
+ const res = await fetch(REGISTRY_URL, {
115
+ signal: controller.signal,
116
+ headers: { accept: "application/vnd.npm.install-v1+json, application/json" },
117
+ });
118
+ clearTimeout(timer);
119
+ if (!res.ok)
120
+ return cached?.latest ?? null;
121
+ const body = (await res.json());
122
+ if (typeof body?.version !== "string")
123
+ return cached?.latest ?? null;
124
+ writeCache({ latest: body.version, checked_at: Date.now() });
125
+ return body.version;
126
+ }
127
+ catch {
128
+ // Offline, blocked, or slow. The running version is still perfectly usable.
129
+ return cached?.latest ?? null;
130
+ }
131
+ }
132
+ /** Fire the check without awaiting it, swallowing everything. */
133
+ export function refreshLatestVersionInBackground() {
134
+ void refreshLatestVersion().catch(() => undefined);
135
+ }
136
+ /**
137
+ * The line that goes into the server instructions when the running build is
138
+ * behind — empty otherwise, so a current install carries no noise.
139
+ */
140
+ export function upgradeNotice() {
141
+ if (!isOutdated())
142
+ return "";
143
+ return (`\n\nVERSION — YOU ARE RUNNING AN OUTDATED suppa-mcp-2 (${PACKAGE_VERSION}; ${knownLatest()} is published).\n` +
144
+ "Everything below describes THIS build, and fixes released since it are absent — behaviour you " +
145
+ "were told is fixed may not be. Before doing anything else, tell the user, in your first reply, " +
146
+ `that suppa-mcp-2 ${knownLatest()} is available and that the MCP client must be restarted after ` +
147
+ "updating (a running server keeps its old code for the whole session). Upgrade with " +
148
+ `\`npm i -g ${PACKAGE_NAME}@latest\` or by pinning @latest in the client's MCP config; ` +
149
+ "confirm with suppa_version.");
150
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "MCP server for the Suppa platform (modern.suppa.me) — Tasks, Docs/Pages, Entities & Schema, Forms, Automations, and file attachments, with multi-tenant Google auth. Node port of PyPI suppa-mcp.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -22,7 +22,7 @@
22
22
  "rebuild": "npm run clean && npm run build",
23
23
  "start": "node dist/bin.js",
24
24
  "dev": "tsc --watch",
25
- "test": "vitest run",
25
+ "test": "node scripts/check-version-literals.mjs && vitest run",
26
26
  "test:watch": "vitest",
27
27
  "prepublishOnly": "npm run build && npm test",
28
28
  "inspect": "npx @modelcontextprotocol/inspector node dist/bin.js"
@@ -60,6 +60,7 @@ export const RULE_WARNINGS = [
60
60
  "W611", // enum member key is not PascalCase
61
61
  "W612", // field option written at its platform default
62
62
  "W613", // enum global name passed for an enum nothing references
63
+ "W615", // relation typed with a shape that names no class ('any', a union, …)
63
64
  ];
64
65
  /**
65
66
  * W613 argues from ABSENCE — "nothing references this name". That only holds
@@ -234,6 +235,20 @@ function objectMap(ts, node) {
234
235
  }
235
236
  return map;
236
237
  }
238
+ /**
239
+ * Computed keys objectMap could NOT resolve — `{ [KEY]: true }`, where KEY is a
240
+ * const. The key exists but its name is unknowable here, so every option rule
241
+ * silently stops applying to it; callers report that rather than fall quiet.
242
+ */
243
+ function unreadableComputedKeys(ts, node) {
244
+ if (!node || !ts.isObjectLiteralExpression(node)) return [];
245
+ return node.properties.filter(
246
+ (p) =>
247
+ ts.isPropertyAssignment(p) &&
248
+ ts.isComputedPropertyName(p.name) &&
249
+ stringValue(ts, unwrapExpr(ts, p.name.expression)) === null,
250
+ );
251
+ }
237
252
  function stringValue(ts, node) {
238
253
  return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
239
254
  ? node.text
@@ -396,6 +411,17 @@ function analyzeImports(ts, sf) {
396
411
  }
397
412
  }
398
413
  }
414
+ // A local `type Customer = Customers;` names the same class as the thunk
415
+ // returns, so a property typed with it is correct — reading only the written
416
+ // identifier made E115 (an ERROR) fire on code that is right.
417
+ for (const st of sf.statements) {
418
+ if (!ts.isTypeAliasDeclaration(st)) continue;
419
+ let t = st.type;
420
+ while (t && ts.isParenthesizedTypeNode(t)) t = t.type;
421
+ if (t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && !t.typeArguments) {
422
+ alias.set(st.name.text, alias.get(t.typeName.text) ?? t.typeName.text);
423
+ }
424
+ }
399
425
  sf.suppaImports = { alias, namespaces };
400
426
  }
401
427
  function importsOf(sf) {
@@ -508,10 +534,24 @@ function analyzeEntities(ts, sf, model) {
508
534
  const last = d.args[d.args.length - 1];
509
535
  const enumOptionsNode =
510
536
  d.args.length >= 2 && last && ts.isObjectLiteralExpression(last) ? last : null;
537
+ // Argument 0 is EITHER the global name (a string) or the enum
538
+ // itself (an identifier / namespace access). Anything else — a
539
+ // concatenation, a substituting template — is a name being passed
540
+ // that this checker cannot read, and reading it as "no name given"
541
+ // turned one token into a bypass of W613 AND of E206's seed
542
+ // cross-check.
543
+ const first = d.args[0] ? unwrapExpr(ts, d.args[0]) : null;
544
+ const nameIsUnreadable =
545
+ !!first &&
546
+ stringValue(ts, first) === null &&
547
+ !ts.isIdentifier(first) &&
548
+ !ts.isPropertyAccessExpression(first);
511
549
  info.properties.set(propName, {
512
550
  kind: d.name === "Enum" ? "enum" : "multi-enum",
513
551
  node: member, decorator: d,
514
- enumGlobalName: stringValue(ts, d.args[0]),
552
+ enumGlobalName: stringValue(ts, first),
553
+ enumGlobalNameUnreadable: nameIsUnreadable,
554
+ enumGlobalNameNode: d.args[0] ?? null,
515
555
  optionsNode: enumOptionsNode,
516
556
  enumOptions: objectMap(ts, enumOptionsNode),
517
557
  });
@@ -846,6 +886,18 @@ function checkDefaultFieldOptions(ts, sf, propName, prop, findings) {
846
886
  const unwrapped = nested && unwrapExpr(ts, nested);
847
887
  if (unwrapped && ts.isObjectLiteralExpression(unwrapped)) scopes.push(unwrapped);
848
888
  }
889
+ // Not for @Enum/@MultiEnum: their options slot is ambiguous with an inline
890
+ // TITLES map (see the extractor), and a titles map is BUILT from computed
891
+ // keys — `{ [StatusEnum.Active]: { title } }`. Reporting those would be noise
892
+ // on correct code. Enum options are only ever read for `subType` (E113), so
893
+ // nothing is lost.
894
+ const enumKind = prop.kind === "enum" || prop.kind === "multi-enum";
895
+ for (const scope of enumKind ? [] : scopes) {
896
+ for (const keyNode of unreadableComputedKeys(ts, scope)) {
897
+ findings.push(finding(ts, sf, keyNode, "W606",
898
+ `'${propName}' has an option under a computed key whose name cannot be read statically — the default-option check (W612) and the unknown-option checks (E501/E502) are skipped for it. Write the key literally.`));
899
+ }
900
+ }
849
901
  for (const scope of scopes) {
850
902
  for (const [key, valNode] of objectMap(ts, scope)) {
851
903
  if (!(key in DEFAULT_FIELD_OPTIONS)) continue;
@@ -871,7 +923,13 @@ function checkDefaultFieldOptions(ts, sf, propName, prop, findings) {
871
923
  */
872
924
  function checkEnumGlobalName(ts, sf, propName, prop, model, findings) {
873
925
  const name = prop.enumGlobalName;
874
- if (!name) return; // local enum — the default, and nothing to check
926
+ if (!name) {
927
+ if (prop.enumGlobalNameUnreadable) {
928
+ findings.push(finding(ts, sf, prop.enumGlobalNameNode, "W606",
929
+ `'${propName}' (@${prop.decorator.name}) passes a global enum name this checker cannot read (it is built at runtime, not written as a literal) — the local-vs-global rule (W613) and the seed cross-check (E206) are both skipped for this field. Write the name as a plain string, or omit it if the enum is local.`));
930
+ }
931
+ return; // local enum — the default, and nothing to check
932
+ }
875
933
  // A REFERENCE is an occurrence of the name somewhere other than the property
876
934
  // that declares it. Occurrences inside this property do not count, however
877
935
  // they are spelled: `key: 'Entity.field'` (the rename key, which by convention
@@ -884,7 +942,12 @@ function checkEnumGlobalName(ts, sf, propName, prop, model, findings) {
884
942
  const references = sites.filter(
885
943
  (s) => !(s.file === sf.fileName && s.start >= declStart && s.end <= declEnd),
886
944
  ).length;
887
- if (references === 0) {
945
+ // …and application code outside the schema files counts too: a query that
946
+ // filters by { name: 'Orders.status', value: … } lives in a service, which is
947
+ // never parsed here.
948
+ const referencedElsewhere =
949
+ references === 0 && model.externalTexts.some((text) => text.includes(name));
950
+ if (references === 0 && !referencedElsewhere) {
888
951
  findings.push(finding(ts, sf, prop.decorator.args[0], "W613",
889
952
  `'${propName}' (@${prop.decorator.name}) declares the global enum name '${name}', but nothing outside this ` +
890
953
  `field references it (its own 'key'/'subType' option does not count as a reference). A global name is for ` +
@@ -1621,6 +1684,7 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
1621
1684
  entities: new Map(), entityByName: new Map(),
1622
1685
  seeds: [], modules: [], stringEnums: new Map(),
1623
1686
  enumDeclarations: [], stringLiteralCounts: new Map(), stringLiteralSites: new Map(),
1687
+ externalTexts: [],
1624
1688
  };
1625
1689
  const findings = [];
1626
1690
  // the CLI deduped; the exported API did not, and duplicated seeds duplicated findings
@@ -1628,6 +1692,7 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
1628
1692
  const sources = uniqueFiles.map((f) =>
1629
1693
  ts.createSourceFile(f, readFileSync(f, "utf-8"), ts.ScriptTarget.Latest, true),
1630
1694
  );
1695
+ model.externalTexts = collectExternalTexts(rootDir, uniqueFiles);
1631
1696
  for (const sf of sources) analyzeImports(ts, sf);
1632
1697
  for (const sf of sources) analyzeEnums(ts, sf, model);
1633
1698
  for (const sf of sources) {
@@ -1661,6 +1726,58 @@ export function validateSchema({ files = [], rootDir = null } = {}) {
1661
1726
  };
1662
1727
  }
1663
1728
 
1729
+ /**
1730
+ * Raw text of every OTHER TypeScript file under the app root — the ones that
1731
+ * carry no schema and so are never parsed: services, controllers, DTOs.
1732
+ *
1733
+ * W613 argues that nothing references an enum's global name. The analyzed set is
1734
+ * entities, seeds and modules only, but an application legitimately names an
1735
+ * enum outside all three — `{ name: 'Orders.status', value: 'new' }` in a query
1736
+ * lives in a service. Without this the check called a genuinely global enum
1737
+ * unreferenced and, now that it blocks, stopped a correct repo from shipping.
1738
+ * A substring scan is enough: the question is only "does this name appear
1739
+ * anywhere else at all", so no parsing is needed.
1740
+ *
1741
+ * The trade is deliberate and one-sided. A mention inside a COMMENT counts as a
1742
+ * reference, so a name that only a comment uses escapes W613 — a false negative.
1743
+ * The alternative, parsing every file in the repo to be exact, buys precision in
1744
+ * a check that BLOCKS the gate, where a false positive costs far more than a
1745
+ * missed warning.
1746
+ */
1747
+ function collectExternalTexts(rootDir, analyzed) {
1748
+ if (!rootDir) return [];
1749
+ const skip = new Set(analyzed.map((f) => resolve(f)));
1750
+ const texts = [];
1751
+ (function walk(dir) {
1752
+ let entries;
1753
+ try {
1754
+ entries = readdirSync(dir);
1755
+ } catch {
1756
+ return; // unreadable directory: absence of evidence, not evidence of absence
1757
+ }
1758
+ for (const name of entries) {
1759
+ if (name === "node_modules" || name === "dist" || name.startsWith(".")) continue;
1760
+ const p = join(dir, name);
1761
+ let st;
1762
+ try {
1763
+ st = statSync(p);
1764
+ } catch {
1765
+ continue;
1766
+ }
1767
+ if (st.isDirectory()) {
1768
+ walk(p);
1769
+ } else if ((name.endsWith(".ts") || name.endsWith(".tsx")) && !skip.has(resolve(p))) {
1770
+ try {
1771
+ texts.push(readFileSync(p, "utf-8"));
1772
+ } catch {
1773
+ /* unreadable file — skip */
1774
+ }
1775
+ }
1776
+ }
1777
+ })(resolve(rootDir));
1778
+ return texts;
1779
+ }
1780
+
1664
1781
  // ── discovery ──
1665
1782
  export function discoverFiles(rootDir) {
1666
1783
  const files = [];