@jupiterone/jupiterone-mcp 2.8.0 → 2.9.1

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.
Files changed (138) hide show
  1. package/README.md +24 -10
  2. package/dist/client/graphql/mutations.d.ts +5 -0
  3. package/dist/client/graphql/mutations.d.ts.map +1 -1
  4. package/dist/client/graphql/mutations.js +20 -1
  5. package/dist/client/graphql/mutations.js.map +1 -1
  6. package/dist/client/graphql/queries.d.ts +15 -0
  7. package/dist/client/graphql/queries.d.ts.map +1 -1
  8. package/dist/client/graphql/queries.js +54 -1
  9. package/dist/client/graphql/queries.js.map +1 -1
  10. package/dist/client/jupiterone-client.d.ts +6 -0
  11. package/dist/client/jupiterone-client.d.ts.map +1 -1
  12. package/dist/client/jupiterone-client.js +16 -0
  13. package/dist/client/jupiterone-client.js.map +1 -1
  14. package/dist/client/services/criticality-service.d.ts +16 -0
  15. package/dist/client/services/criticality-service.d.ts.map +1 -0
  16. package/dist/client/services/criticality-service.js +72 -0
  17. package/dist/client/services/criticality-service.js.map +1 -0
  18. package/dist/generated/description-map.d.ts.map +1 -1
  19. package/dist/generated/description-map.js +277 -28
  20. package/dist/generated/description-map.js.map +1 -1
  21. package/dist/server/mcp-server.d.ts +10 -0
  22. package/dist/server/mcp-server.d.ts.map +1 -1
  23. package/dist/server/mcp-server.js +63 -0
  24. package/dist/server/mcp-server.js.map +1 -1
  25. package/dist/server/tools/compliance/attestations.d.ts.map +1 -1
  26. package/dist/server/tools/compliance/attestations.js +11 -10
  27. package/dist/server/tools/compliance/attestations.js.map +1 -1
  28. package/dist/server/tools/compliance/authoring.d.ts.map +1 -1
  29. package/dist/server/tools/compliance/authoring.js +36 -35
  30. package/dist/server/tools/compliance/authoring.js.map +1 -1
  31. package/dist/server/tools/compliance/controls.d.ts.map +1 -1
  32. package/dist/server/tools/compliance/controls.js +12 -11
  33. package/dist/server/tools/compliance/controls.js.map +1 -1
  34. package/dist/server/tools/compliance/exemptions.d.ts.map +1 -1
  35. package/dist/server/tools/compliance/exemptions.js +16 -15
  36. package/dist/server/tools/compliance/exemptions.js.map +1 -1
  37. package/dist/server/tools/compliance/framework.d.ts.map +1 -1
  38. package/dist/server/tools/compliance/framework.js +24 -23
  39. package/dist/server/tools/compliance/framework.js.map +1 -1
  40. package/dist/server/tools/compliance/graph.js +1 -1
  41. package/dist/server/tools/compliance/graph.js.map +1 -1
  42. package/dist/server/tools/compliance/requirements.d.ts.map +1 -1
  43. package/dist/server/tools/compliance/requirements.js +11 -10
  44. package/dist/server/tools/compliance/requirements.js.map +1 -1
  45. package/dist/server/tools/compliance/shared.d.ts +4 -32
  46. package/dist/server/tools/compliance/shared.d.ts.map +1 -1
  47. package/dist/server/tools/compliance/shared.js +11 -76
  48. package/dist/server/tools/compliance/shared.js.map +1 -1
  49. package/dist/server/tools/compliance/summary.d.ts.map +1 -1
  50. package/dist/server/tools/compliance/summary.js +16 -15
  51. package/dist/server/tools/compliance/summary.js.map +1 -1
  52. package/dist/server/tools/compliance/tests.d.ts.map +1 -1
  53. package/dist/server/tools/compliance/tests.js +26 -25
  54. package/dist/server/tools/compliance/tests.js.map +1 -1
  55. package/dist/server/tools/compliance/transitions.d.ts.map +1 -1
  56. package/dist/server/tools/compliance/transitions.js +15 -14
  57. package/dist/server/tools/compliance/transitions.js.map +1 -1
  58. package/dist/server/tools/criticality/context.d.ts +48 -0
  59. package/dist/server/tools/criticality/context.d.ts.map +1 -0
  60. package/dist/server/tools/criticality/context.js +90 -0
  61. package/dist/server/tools/criticality/context.js.map +1 -0
  62. package/dist/server/tools/criticality/index.d.ts +11 -0
  63. package/dist/server/tools/criticality/index.d.ts.map +1 -0
  64. package/dist/server/tools/criticality/index.js +15 -0
  65. package/dist/server/tools/criticality/index.js.map +1 -0
  66. package/dist/server/tools/criticality/ladder-delta.d.ts +86 -0
  67. package/dist/server/tools/criticality/ladder-delta.d.ts.map +1 -0
  68. package/dist/server/tools/criticality/ladder-delta.js +475 -0
  69. package/dist/server/tools/criticality/ladder-delta.js.map +1 -0
  70. package/dist/server/tools/criticality/levels-read.d.ts +43 -0
  71. package/dist/server/tools/criticality/levels-read.d.ts.map +1 -0
  72. package/dist/server/tools/criticality/levels-read.js +101 -0
  73. package/dist/server/tools/criticality/levels-read.js.map +1 -0
  74. package/dist/server/tools/criticality/read.d.ts +13 -0
  75. package/dist/server/tools/criticality/read.d.ts.map +1 -0
  76. package/dist/server/tools/criticality/read.js +214 -0
  77. package/dist/server/tools/criticality/read.js.map +1 -0
  78. package/dist/server/tools/criticality/resource.d.ts +35 -0
  79. package/dist/server/tools/criticality/resource.d.ts.map +1 -0
  80. package/dist/server/tools/criticality/resource.js +84 -0
  81. package/dist/server/tools/criticality/resource.js.map +1 -0
  82. package/dist/server/tools/criticality/schemas.d.ts +114 -0
  83. package/dist/server/tools/criticality/schemas.d.ts.map +1 -0
  84. package/dist/server/tools/criticality/schemas.js +99 -0
  85. package/dist/server/tools/criticality/schemas.js.map +1 -0
  86. package/dist/server/tools/criticality/update.d.ts +5 -0
  87. package/dist/server/tools/criticality/update.d.ts.map +1 -0
  88. package/dist/server/tools/criticality/update.js +243 -0
  89. package/dist/server/tools/criticality/update.js.map +1 -0
  90. package/dist/server/tools/errors.d.ts +3 -2
  91. package/dist/server/tools/errors.d.ts.map +1 -1
  92. package/dist/server/tools/errors.js +20 -5
  93. package/dist/server/tools/errors.js.map +1 -1
  94. package/dist/server/tools/index.d.ts.map +1 -1
  95. package/dist/server/tools/index.js +2 -0
  96. package/dist/server/tools/index.js.map +1 -1
  97. package/dist/server/tools/j1ql.d.ts.map +1 -1
  98. package/dist/server/tools/j1ql.js +70 -19
  99. package/dist/server/tools/j1ql.js.map +1 -1
  100. package/dist/server/tools/reference.d.ts +1 -1
  101. package/dist/server/tools/reference.d.ts.map +1 -1
  102. package/dist/server/tools/reference.js +1 -0
  103. package/dist/server/tools/reference.js.map +1 -1
  104. package/dist/server/tools/rule-preview.d.ts +0 -7
  105. package/dist/server/tools/rule-preview.d.ts.map +1 -1
  106. package/dist/server/tools/rule-preview.js +3 -20
  107. package/dist/server/tools/rule-preview.js.map +1 -1
  108. package/dist/server/tools/rules.d.ts.map +1 -1
  109. package/dist/server/tools/rules.js +2 -2
  110. package/dist/server/tools/rules.js.map +1 -1
  111. package/dist/server/tools/shared.d.ts +44 -0
  112. package/dist/server/tools/shared.d.ts.map +1 -0
  113. package/dist/server/tools/shared.js +95 -0
  114. package/dist/server/tools/shared.js.map +1 -0
  115. package/dist/server/tools/usage.d.ts +7 -0
  116. package/dist/server/tools/usage.d.ts.map +1 -1
  117. package/dist/server/tools/usage.js +128 -1
  118. package/dist/server/tools/usage.js.map +1 -1
  119. package/dist/server/tools/value-probe.d.ts +12 -1
  120. package/dist/server/tools/value-probe.d.ts.map +1 -1
  121. package/dist/server/tools/value-probe.js +6 -4
  122. package/dist/server/tools/value-probe.js.map +1 -1
  123. package/dist/types/jupiterone.d.ts +89 -0
  124. package/dist/types/jupiterone.d.ts.map +1 -1
  125. package/dist/utils/criticality-query.d.ts +97 -0
  126. package/dist/utils/criticality-query.d.ts.map +1 -0
  127. package/dist/utils/criticality-query.js +319 -0
  128. package/dist/utils/criticality-query.js.map +1 -0
  129. package/dist/utils/j1ql-filters.d.ts +3 -1
  130. package/dist/utils/j1ql-filters.d.ts.map +1 -1
  131. package/dist/utils/j1ql-filters.js +19 -7
  132. package/dist/utils/j1ql-filters.js.map +1 -1
  133. package/dist/utils/j1ql-validator.d.ts +19 -5
  134. package/dist/utils/j1ql-validator.d.ts.map +1 -1
  135. package/dist/utils/j1ql-validator.js +411 -39
  136. package/dist/utils/j1ql-validator.js.map +1 -1
  137. package/node_modules/dtrace-provider/build/Makefile +1 -1
  138. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.J1QLValidator = exports.J1qlSyntaxError = exports.RESERVED_WORDS = void 0;
4
+ exports.namedAliases = namedAliases;
4
5
  const query_language_parser_1 = require("@jupiterone/query-language-parser");
5
6
  // The grammar's own keyword list (FIND, COUNT, AS, …) plus the literals the lexer reserves.
6
7
  // Sourced from the parser package so it can never drift from what the server actually rejects.
@@ -31,9 +32,11 @@ const KEYWORD_SELECTOR_FIXES = {
31
32
  };
32
33
  class J1qlSyntaxError extends Error {
33
34
  suggestion;
34
- constructor(message, suggestion) {
35
+ corrections;
36
+ constructor(message, suggestion, corrections) {
35
37
  super(message);
36
38
  this.suggestion = suggestion;
39
+ this.corrections = corrections;
37
40
  this.name = 'J1qlSyntaxError';
38
41
  }
39
42
  }
@@ -60,14 +63,20 @@ function mainChain(root) {
60
63
  * failure in 30 days of telemetry (2026-10-29), including an alias four hops past the negation.
61
64
  * WHERE may name them (`THAT !LOGS AS r * WHERE r.isMultiRegionTrail = true` runs in prod), and so
62
65
  * may ORDER BY (it ran on j1dev, 2026-10-29), so only RETURN is checked; optional traversals are
63
- * left out until they are probed.
66
+ * left out until they are probed. An unaliased term answers to its type name, which fails the
67
+ * same way (`THAT !HAS Device RETURN Device.displayName`, j1dev, 2026-11-03). A name cannot also
68
+ * be bound before the negation: the parser renames a repeated type name, and the engine refuses
69
+ * an alias that repeats one.
64
70
  */
65
71
  function negatedAliases(root) {
66
72
  const chain = mainChain(root);
67
73
  const first = chain.findIndex((step) => step.negate === true);
68
74
  if (first === -1)
69
75
  return [];
70
- return chain.slice(first).flatMap((step) => (step.identifier ? [step.identifier] : []));
76
+ return chain.slice(first).flatMap((step) => {
77
+ const name = step.identifier ?? step.defaultIdentifier;
78
+ return name ? [name] : [];
79
+ });
71
80
  }
72
81
  /** Every alias a subtree names (`sourceIdentifier`), aggregates included. */
73
82
  function namedAliases(node, found = new Set(), seen = new Set()) {
@@ -260,6 +269,363 @@ function undefinedSelectorHint(query, selector, valid) {
260
269
  (valid ? ` — or use one of: ${valid}` : '')
261
270
  : `${lead} FIND <Entity> WITH <property_filter> AS e RETURN e.${selector}`;
262
271
  }
272
+ /** Whether a LIMIT is outside the 1-250 the query service enforces at execution. */
273
+ function limitOutOfRange(ast) {
274
+ const limit = ast?.limit;
275
+ return typeof limit === 'number' && (limit < 1 || limit > 250);
276
+ }
277
+ /** Whether the static gate lets the query through: it parses, and no check in validateQuery fails. */
278
+ function passesGate(query) {
279
+ try {
280
+ const ast = (0, query_language_parser_1.parse)(query);
281
+ return !limitOutOfRange(ast) && !(ast && negatedAliasRejection(query, ast));
282
+ }
283
+ catch {
284
+ return false;
285
+ }
286
+ }
287
+ const PLACEHOLDER = /\uE000(\d+)\uE001/g;
288
+ /**
289
+ * Repairs skip longer queries. A hostile 100 KB query cost 11.7 s in one repair pattern and 26 s
290
+ * re-parsing its repair (red-team, 2026-11-04); the longest query an agent sent in the review
291
+ * window was about 2.6 KB.
292
+ */
293
+ const MAX_REPAIR_LENGTH = 10_000;
294
+ /**
295
+ * Whether the repairs may run on this query: it is short enough, and it holds neither
296
+ * placeholder character, so a literal cannot pose as a held span.
297
+ */
298
+ function repairable(query) {
299
+ return query.length <= MAX_REPAIR_LENGTH && !/[\uE000\uE001]/.test(query);
300
+ }
301
+ /**
302
+ * The query with every span no repair may touch held aside: string literals, comments, regex
303
+ * literals, bracketed keys and dashboard variables. Each becomes an index between two private-use
304
+ * characters, which `repairable` keeps out of the query and no repair pattern matches, and comes
305
+ * back on `restore`. A bracketed list of values (`= ['a','b']`) is not a key and stays visible to
306
+ * the value-list repair.
307
+ */
308
+ class HeldSpans {
309
+ spans = [];
310
+ code;
311
+ constructor(query) {
312
+ this.code = query
313
+ .replace(STRING_LITERAL, (span) => this.hold(span))
314
+ .replace(/\/\*[\s\S]*?\*\//g, (span) => this.hold(span))
315
+ .replace(/(!?=\s*)(\/(?:[^/\\\n]|\\.)+\/[a-z]*)/g, (_whole, op, span) => op + this.hold(span))
316
+ .replace(/\[[^\]\n,\uE000]*\]|\$\{[^}]*\}|\{\{[^}]*\}\}/g, (span) => this.hold(span));
317
+ }
318
+ hold(span) {
319
+ return `\uE000${this.spans.push(span) - 1}\uE001`;
320
+ }
321
+ /** A held span can hold an earlier one (a bracket around a literal), so restore to a fixpoint. */
322
+ restore(code) {
323
+ let out = code;
324
+ for (let pass = 0; pass < 4 && /\uE000\d+\uE001/.test(out); pass++) {
325
+ out = out.replace(PLACEHOLDER, (_whole, index) => this.spans[Number(index)]);
326
+ }
327
+ return out;
328
+ }
329
+ }
330
+ const DECLARED_ALIAS = /\bAS\s+([A-Za-z_]\w*)/gi;
331
+ const PLAIN_PATH = /^[A-Za-z_@][\w@]*(?:\.[A-Za-z_@][\w@]*)*$/;
332
+ /**
333
+ * `` e.`tag.Name` `` is invalid syntax: J1QL writes a plain path, and brackets a key holding other
334
+ * characters. 4 distinct rejections from 3 accounts on 2.6.1–2.8.0, none corrected.
335
+ */
336
+ const unquoteBackticks = (code, held, corrections) => code.replace(/`([^`\n]+)`/g, (_whole, path) => {
337
+ const plain = PLAIN_PATH.test(path);
338
+ corrections.push({
339
+ kind: 'backtick-path',
340
+ note: plain
341
+ ? `removed the backticks around ${path}`
342
+ : `bracketed ${path} instead of backticks`,
343
+ });
344
+ return plain ? path : held.hold(`[${path}]`);
345
+ });
346
+ /**
347
+ * A property key holding `-` or `/` (`h.tag.J1-ApplicationName`, `tag.kubernetes.io/service-name`)
348
+ * reads as arithmetic and fails, often far from the hyphen: ADC sent one such query 10 times in
349
+ * parallel and got "Unexpected token AS at column 290" each time (2026-11-03). 10 distinct
350
+ * rejections from 6 accounts on 2.6.1–2.8.0. Brackets make the key one name, `h.[tag.J1-…]` (both
351
+ * bracket forms read the flat key in WITH and RETURN, j1dev, 2026-11-04). A key goes on in bare
352
+ * words after its `-` or `/`. An operand with a dot, a leading digit or more selector after it is
353
+ * arithmetic (`h.cpu-h.mem`, `c.expiresOn-date.now`, `h.cpu-Device.cpu`, `h.a-h.[tag.x]`,
354
+ * `date.now-7days`), and a word straight after a comparison is an unquoted value, so both are
355
+ * left alone.
356
+ */
357
+ const bracketPaths = (code, held, corrections) => {
358
+ const aliases = new Set([...code.matchAll(DECLARED_ALIAS)].map((match) => match[1]));
359
+ return code.replace(/(?<![\w.@\-/:\uE001])[A-Za-z_@][\w@:]*(?:[.\-/][\w@:]+)+/g, (token, offset) => {
360
+ if (!/[-/]/.test(token) || /^date\./i.test(token))
361
+ return token;
362
+ const operands = token.split(/[-/]/).slice(1);
363
+ if (operands.some((operand) => operand.includes('.') || /^\d/.test(operand)))
364
+ return token;
365
+ if (/^[.[\uE000]/.test(code.slice(offset + token.length)))
366
+ return token;
367
+ const head = token.split('.')[0];
368
+ const qualified = aliases.has(head) && token[head.length] === '.';
369
+ if (!qualified && /(?:[=<>]|~=|\^=|\$=)\s*$/.test(code.slice(0, offset)))
370
+ return token;
371
+ const path = qualified ? token.slice(head.length + 1) : token;
372
+ corrections.push({ kind: 'bracket-path', note: `bracketed the property path ${path}` });
373
+ return qualified ? `${head}.${held.hold(`[${path}]`)}` : held.hold(`[${path}]`);
374
+ });
375
+ };
376
+ /** A value list's item: a held string literal or a number. */
377
+ const LIST_ITEM = String.raw `\uE000\d+\uE001|-?\d+(?:\.\d+)?`;
378
+ const VALUE_LIST = new RegExp(String.raw `(?<![\w@.:\uE001])((?:[A-Za-z_@][\w@:]*\.)?\uE000\d+\uE001|[A-Za-z_@][\w@.:]*)` +
379
+ String.raw `\s*(!=|=|\bIN\b)\s*[([]\s*((?:${LIST_ITEM})(?:\s*,\s*(?:${LIST_ITEM}))+)\s*[)\]]`, 'gi');
380
+ /**
381
+ * `prop IN ('a','b')`, `prop = ('a','b')` and their bracket forms, rewritten as the OR list J1QL
382
+ * reads (`prop = ('a' OR 'b')`; `!=` is kept, and excludes every listed value). Seen live on
383
+ * 2.6.0's first day from two accounts on two hosts, with the comma form drawing no usable hint.
384
+ * Matched against held literals, so a literal that reads like a list (`'tier IN (1, 2)'`) or holds
385
+ * `$` (`'C$'`) is never rewritten (red-team, 2026-11-04).
386
+ */
387
+ const rewriteValueLists = (code, held, corrections) => code.replace(VALUE_LIST, (whole, prop, op, list) => {
388
+ const items = list.split(/\s*,\s*/);
389
+ const literal = (item) => !item.startsWith('\uE000') || /^['"]/.test(held.spans[Number(item.slice(1, -1))]);
390
+ if (!items.every(literal))
391
+ return whole;
392
+ corrections.push({ kind: 'value-list', note: "wrote the value list as ('a' OR 'b')" });
393
+ return `${prop} ${op.toUpperCase() === 'IN' ? '=' : op} (${items.join(' OR ')})`;
394
+ });
395
+ /** Whether the query holds a SQL-style value list the value-list repair rewrites. */
396
+ function hasValueList(query) {
397
+ if (!repairable(query))
398
+ return false;
399
+ const held = new HeldSpans(query);
400
+ return rewriteValueLists(held.code, held, []) !== held.code;
401
+ }
402
+ /**
403
+ * `FIND (aws_lb OR aws_alb)` and `RELATES TO (a OR b)`: J1QL joins entity types with `|`. 6
404
+ * distinct rejections from 4 accounts on 2.6.1–2.8.0. A group after a comparison or a filter
405
+ * keyword is a value list or a condition (`= (true OR false)`), and stays; a direction arrow
406
+ * (`HAS >> (a OR b)`) is not a comparison.
407
+ */
408
+ const joinTypeLists = (code, _held, corrections) => code.replace(/\(\s*([A-Za-z_]\w*(?:\s+OR\s+[A-Za-z_]\w*)+)\s*\)/gi, (group, list, offset) => {
409
+ const before = code.slice(0, offset);
410
+ if (/(?:(?<![<>])[<>]|[=!~^$]|\b(?:WITH|AND|OR|NOT|WHERE))\s*$/i.test(before)) {
411
+ return group;
412
+ }
413
+ const types = list.split(/\s+OR\s+/i);
414
+ if (types.some((type) => exports.RESERVED_WORDS.has(type.toLowerCase())))
415
+ return group;
416
+ corrections.push({
417
+ kind: 'type-union',
418
+ note: `joined ${types.join(', ')} with | instead of OR`,
419
+ });
420
+ return `(${types.join('|')})`;
421
+ });
422
+ /**
423
+ * `THAT * AS r *` uses `*` as a verb; J1QL's verb for any relationship is `RELATES TO`. 4
424
+ * distinct rejections from 2 accounts on 2.6.1–2.8.0.
425
+ */
426
+ const thatWildcardVerb = (code, _held, corrections) => code.replace(/\bTHAT(\s+)\*(?=\s+(?:AS\s+[A-Za-z_]\w*\s+)?[*(A-Za-z_])/gi, (_whole, space) => {
427
+ corrections.push({
428
+ kind: 'that-wildcard-verb',
429
+ note: 'wrote THAT * as THAT RELATES TO, the verb for any relationship',
430
+ });
431
+ return `THAT${space}RELATES TO`;
432
+ });
433
+ /**
434
+ * `= /web|api/` fails to parse: the parser refuses `|` in a regex. A flat alternation becomes one
435
+ * regex per branch, `(name = /web/ OR name = /api/)`. A pattern with groups, anchors, a character
436
+ * class or an escaped `|` is left to the hint, and so is `!=`: whether `!=` on a list-valued
437
+ * property reads "no element matches" is unverified, and splitting it would depend on that. 9
438
+ * distinct rejections from 6 accounts on 2.6.1–2.8.0.
439
+ */
440
+ const splitRegexAlternation = (code, held, corrections) => code.replace(/(?<![\w@.:\uE001])([A-Za-z_@][\w@.:]*(?:\uE000\d+\uE001)?|\uE000\d+\uE001)\s*=\s*\uE000(\d+)\uE001/g, (whole, prop, index) => {
441
+ const parts = /^\/(.*)\/([a-z]*)$/s.exec(held.spans[Number(index)]);
442
+ if (!parts || !parts[1].includes('|') || /[()[\]^$]|\\\|/.test(parts[1]))
443
+ return whole;
444
+ const branches = parts[1].split('|');
445
+ if (branches.some((branch) => branch === ''))
446
+ return whole;
447
+ corrections.push({
448
+ kind: 'regex-alternation',
449
+ note: `split ${held.spans[Number(index)]} into one regex per alternative`,
450
+ });
451
+ const filters = branches.map((branch) => `${prop} = ${held.hold(`/${branch}/${parts[2]}`)}`);
452
+ return `(${filters.join(' OR ')})`;
453
+ });
454
+ const CLAUSE_END = /(?:THAT|RETURN|ORDER\s+BY|LIMIT|SKIP|WHERE|AS)\b/iy;
455
+ /** Where the WITH clause that starts at `from` ends: its first top-level clause keyword or alias. */
456
+ function withClauseEnd(code, from) {
457
+ let depth = 0;
458
+ for (let index = from; index < code.length; index++) {
459
+ if (code[index] === '(')
460
+ depth++;
461
+ else if (code[index] === ')')
462
+ depth--;
463
+ else if (depth === 0 && /\s/.test(code[index - 1])) {
464
+ CLAUSE_END.lastIndex = index;
465
+ if (CLAUSE_END.test(code))
466
+ return index;
467
+ }
468
+ }
469
+ return code.length;
470
+ }
471
+ /**
472
+ * `FIND aws_eks_cluster AS c WITH accountId = …` names the alias before its filter, which never
473
+ * parses ("Unexpected token WITH"): 18 distinct rejections from 5 accounts on 2.6.1–2.8.0, down
474
+ * from 75 on 2.5.x but not gone. The alias moves to the end of its WITH clause. A clause that
475
+ * repeats the alias (`AS f WITH … AS f`) loses the first one; a clause that ends in a different
476
+ * alias is ambiguous and stays.
477
+ */
478
+ const aliasAfterWith = (code, _held, corrections) => {
479
+ let out = code;
480
+ for (const match of [...code.matchAll(/\bAS\s+([A-Za-z_]\w*)\s+(?=WITH\b)/gi)].reverse()) {
481
+ const alias = match[1];
482
+ const start = match.index ?? 0;
483
+ const withAt = start + match[0].length;
484
+ const end = withClauseEnd(out, withAt + 'WITH'.length);
485
+ const repeated = /^AS\s+([A-Za-z_]\w*)/i.exec(out.slice(end));
486
+ if (repeated && repeated[1] !== alias)
487
+ continue;
488
+ const rest = out.slice(end).trimStart();
489
+ out = repeated
490
+ ? out.slice(0, start) + out.slice(withAt)
491
+ : `${out.slice(0, start)}${out.slice(withAt, end).trimEnd()} AS ${alias}${rest ? ` ${rest}` : ''}`;
492
+ corrections.push({
493
+ kind: 'alias-after-with',
494
+ note: repeated
495
+ ? `removed the repeated alias ${alias} before WITH`
496
+ : `moved the alias ${alias} after its WITH clause`,
497
+ });
498
+ }
499
+ return out;
500
+ };
501
+ const ALIAS_RENAMES = {
502
+ count: 'total',
503
+ desc: 'description',
504
+ asc: 'ascending',
505
+ min: 'minimum',
506
+ max: 'maximum',
507
+ avg: 'average',
508
+ sum: 'summed',
509
+ };
510
+ /** `base`, or `base2`, `base3`… whichever neither the query nor an earlier rename uses. */
511
+ function unusedName(code, base, assigned) {
512
+ const taken = (name) => assigned.has(name) || new RegExp(`(?<![.\\w])${name}(?!\\w)`).test(code);
513
+ let name = base;
514
+ for (let suffix = 2; taken(name); suffix++)
515
+ name = `${base}${suffix}`;
516
+ return name;
517
+ }
518
+ /** The ORDER BY list with every sort key named `from` renamed `to`; directions are untouched. */
519
+ function renameOrderKey(code, from, to) {
520
+ const order = /\bORDER\s+BY\s+/i.exec(code);
521
+ if (!order)
522
+ return code;
523
+ const listAt = order.index + order[0].length;
524
+ const tail = code.slice(listAt);
525
+ const listEnd = tail.search(/\b(?:LIMIT|SKIP)\b/i);
526
+ const list = listEnd < 0 ? tail : tail.slice(0, listEnd);
527
+ const renamed = list
528
+ .split(',')
529
+ .map((item) => item.replace(new RegExp(`^(\\s*)${from}(?=\\s|$)`), `$1${to}`))
530
+ .join(',');
531
+ return code.slice(0, listAt) + renamed + tail.slice(list.length);
532
+ }
533
+ const refusedAliases = new Map();
534
+ /**
535
+ * Whether the parser refuses `word` as an alias. Not every keyword is refused: `cidr` parses as
536
+ * one, and renaming it would rename a working column (red-team, 2026-11-04).
537
+ */
538
+ function aliasRefused(word) {
539
+ const key = word.toLowerCase();
540
+ if (!refusedAliases.has(key)) {
541
+ let refused = false;
542
+ try {
543
+ (0, query_language_parser_1.parse)(`FIND Host AS h RETURN h.name AS ${word}`);
544
+ }
545
+ catch {
546
+ refused = true;
547
+ }
548
+ refusedAliases.set(key, refused);
549
+ }
550
+ return refusedAliases.get(key) === true;
551
+ }
552
+ /**
553
+ * `count(h) AS count`: a reserved word cannot be an alias, and the description saying so has not
554
+ * stopped it (5 distinct rejections from 3 accounts on 2.6.1–2.8.0). The alias gets a free name
555
+ * (`count` → `total`), and the ORDER BY keys and property references that used it follow.
556
+ */
557
+ const renameReservedAliases = (code, _held, corrections) => {
558
+ const renames = new Map();
559
+ for (const match of code.matchAll(DECLARED_ALIAS)) {
560
+ const alias = match[1];
561
+ if (!exports.RESERVED_WORDS.has(alias.toLowerCase()) || renames.has(alias))
562
+ continue;
563
+ if (!aliasRefused(alias))
564
+ continue;
565
+ const base = ALIAS_RENAMES[alias.toLowerCase()] ?? `${alias.toLowerCase()}Value`;
566
+ renames.set(alias, unusedName(code, base, new Set(renames.values())));
567
+ }
568
+ let out = code;
569
+ for (const [alias, name] of renames) {
570
+ out = renameOrderKey(out, alias, name)
571
+ .replace(new RegExp(`(\\bAS\\s+)${alias}(?!\\w)`, 'gi'), (whole, lead) => whole.slice(lead.length) === alias ? `${lead}${name}` : whole)
572
+ .replace(new RegExp(`(?<![.\\w])${alias}\\.`, 'g'), `${name}.`);
573
+ corrections.push({
574
+ kind: 'reserved-alias',
575
+ note: `renamed the alias ${alias} to ${name}, since ${alias} is a reserved word`,
576
+ });
577
+ }
578
+ return out;
579
+ };
580
+ /**
581
+ * LIMIT above 250 parses, and the query service refuses it at execution (7 distinct rejections
582
+ * from 3 accounts on 2.6.1–2.8.0). It drops to 250; the cursor pages the rest.
583
+ */
584
+ const capLimit = (code, _held, corrections) => code.replace(/\b(LIMIT\s+)(\d+)\b/gi, (whole, lead, rows) => {
585
+ if (Number(rows) <= 250)
586
+ return whole;
587
+ corrections.push({
588
+ kind: 'limit-250',
589
+ note: `lowered LIMIT ${rows} to 250, the most one page returns; page with the cursor for the rest`,
590
+ });
591
+ return `${lead}250`;
592
+ });
593
+ /** In order: paths first, so later repairs see one token per key; the alias moves after the
594
+ * filters it follows are final. */
595
+ const REPAIRS = [
596
+ unquoteBackticks,
597
+ bracketPaths,
598
+ rewriteValueLists,
599
+ joinTypeLists,
600
+ thatWildcardVerb,
601
+ splitRegexAlternation,
602
+ aliasAfterWith,
603
+ renameReservedAliases,
604
+ capLimit,
605
+ ];
606
+ /**
607
+ * The caller's query with every mechanical mistake the repairs know repaired, or null when none
608
+ * applies. Not verified here: the caller offers it only if it passes the gate.
609
+ */
610
+ function repairQuery(query) {
611
+ if (!repairable(query))
612
+ return null;
613
+ const corrections = [];
614
+ const held = new HeldSpans(query);
615
+ let code = held.code;
616
+ for (const repair of REPAIRS)
617
+ code = repair(code, held, corrections);
618
+ const repaired = held.restore(code);
619
+ if (repaired === query || corrections.length === 0)
620
+ return null;
621
+ return {
622
+ query: repaired,
623
+ corrections: corrections.map((correction) => ({
624
+ ...correction,
625
+ note: held.restore(correction.note),
626
+ })),
627
+ };
628
+ }
263
629
  class J1QLValidator {
264
630
  /**
265
631
  * Statically validates a J1QL query using the same parser the JupiterOne query service runs
@@ -278,25 +644,56 @@ class J1QLValidator {
278
644
  const ast = (0, query_language_parser_1.parse)(query);
279
645
  // The grammar accepts any integer LIMIT; the query service enforces 1-250 at execution.
280
646
  // Pre-check it here (from the AST, so literals can't false-match) to keep the round-trip.
281
- const limit = ast?.limit;
282
- if (typeof limit === 'number' && (limit < 1 || limit > 250)) {
283
- return {
647
+ if (limitOutOfRange(ast)) {
648
+ return this.withRepair({
284
649
  isValid: false,
285
650
  error: '"limit" must be a value between 1 and 250.',
286
651
  suggestion: 'LIMIT must be between 1 and 250. For more rows, use LIMIT 250 and page with the ' +
287
652
  'cursor parameter; for totals, use count(entity).',
288
- };
653
+ }, query, true);
289
654
  }
290
655
  return (ast && negatedAliasRejection(query, ast)) ?? { isValid: true };
291
656
  }
292
657
  catch (error) {
293
- return this.handleQueryError(error, query);
658
+ return this.withRepair(this.hintFor(error, query), query, true);
294
659
  }
295
660
  }
296
661
  /**
297
662
  * Provides detailed error handling with suggestions
298
663
  */
299
664
  handleQueryError(error, query) {
665
+ return this.withRepair(this.hintFor(error, query), query);
666
+ }
667
+ /**
668
+ * The hint with the caller's own query repaired appended, when the gate refuses the query, a
669
+ * repair applies, and the repaired query passes the gate. The prose hint stays above it, so an
670
+ * agent that wants a different fix still has the rule. A hint that already carries a corrected
671
+ * query is left alone, and so is a query the gate accepts: its failure came from somewhere a
672
+ * syntax repair cannot reach (a timeout, a server error). `rejectedByGate` skips re-parsing a
673
+ * query the gate has just refused: the parser's time grows faster than the query (68 ms at
674
+ * 4.6 KB), and a query refused only for its LIMIT would otherwise be parsed in full three times.
675
+ *
676
+ * The prose alone left these mistakes uncorrected in every one of 2.6.1–2.8.0's rejections of
677
+ * them (66 distinct, 2026-11-04 log review), and one query often carries several, so the
678
+ * repairs run together and the agent gets one query that parses.
679
+ */
680
+ withRepair(result, query, rejectedByGate = false) {
681
+ if (result.suggestion?.includes('Use this query instead:\n'))
682
+ return result;
683
+ if (!rejectedByGate && passesGate(query))
684
+ return result;
685
+ const repair = repairQuery(query);
686
+ if (!repair || !passesGate(repair.query))
687
+ return result;
688
+ const notes = [...new Set(repair.corrections.map((correction) => correction.note))];
689
+ return {
690
+ ...result,
691
+ suggestion: `${result.suggestion ?? ''}\n\nFixed: ${notes.join('; ')}.\n` +
692
+ `Use this query instead:\n${repair.query}`,
693
+ corrections: [...new Set(repair.corrections.map((correction) => correction.kind))].sort(),
694
+ };
695
+ }
696
+ hintFor(error, query) {
300
697
  const errorMessage = error?.message || error?.toString() || 'Unknown error';
301
698
  // Check specific error patterns first
302
699
  for (const { pattern, suggestion } of this.getErrorPatterns()) {
@@ -334,22 +731,6 @@ class J1QLValidator {
334
731
  suggestion: this.getGenericSuggestions(query),
335
732
  };
336
733
  }
337
- /**
338
- * `prop IN ('a','b')`, `prop = ('a','b')` and their bracket forms, rewritten as the OR list J1QL
339
- * reads (`prop = ('a' OR 'b')`; `!=` is kept, and excludes every listed value). Seen live on
340
- * 2.6.0's first day from two accounts on two hosts, with the comma form drawing no usable hint.
341
- */
342
- rewriteValueList(query) {
343
- const match = query.match(/(\b[\w.[\]-]+)\s*(!=|=|\bIN\b)\s*[([]\s*((?:'[^']*'|"[^"]*"|-?\d+(?:\.\d+)?)(?:\s*,\s*(?:'[^']*'|"[^"]*"|-?\d+(?:\.\d+)?))+)\s*[)\]]/i);
344
- if (!match)
345
- return undefined;
346
- const [whole, prop, op, list] = match;
347
- const items = list.match(/'[^']*'|"[^"]*"|-?\d+(?:\.\d+)?/g) ?? [];
348
- if (items.length < 2)
349
- return undefined;
350
- const operator = op.toUpperCase() === 'IN' ? '=' : op;
351
- return query.replace(whole, `${prop} ${operator} (${items.join(' OR ')})`);
352
- }
353
734
  /**
354
735
  * Consolidated error patterns for better maintainability
355
736
  */
@@ -376,12 +757,10 @@ class J1QLValidator {
376
757
  },
377
758
  // Parser error patterns (the same messages the query service returns)
378
759
  {
379
- // SQL IN: say what J1QL reads and hand back the query rewritten, not a pattern to copy.
760
+ // SQL IN: say what J1QL reads; withRepair hands back the query rewritten, checked by the
761
+ // gate, so an IN list beside another mistake (`LIMIT 500`) is not offered half fixed.
380
762
  pattern: /Error parsing query\. Unexpected token "IN" at line \d+ column \d+/i,
381
- suggestion: (_match, query) => {
382
- const fixed = this.rewriteValueList(query);
383
- return fixed ? `${SQL_IN_MESSAGE}\nUse this query instead:\n${fixed}` : SQL_IN_MESSAGE;
384
- },
763
+ suggestion: SQL_IN_MESSAGE,
385
764
  },
386
765
  {
387
766
  pattern: /Error parsing query\. Unexpected token "(\w+)" at line \d+ column \d+/i,
@@ -406,10 +785,8 @@ class J1QLValidator {
406
785
  // the caller's own type list so it can be applied verbatim.
407
786
  pattern: /Error parsing query\. Unexpected token ","/i,
408
787
  suggestion: (_match, query) => {
409
- const valueList = this.rewriteValueList(query);
410
- if (valueList) {
411
- return ("J1QL value lists use OR, not commas: WITH prop = ('a' OR 'b' OR 'c').\n" +
412
- `Use this query instead:\n${valueList}`);
788
+ if (hasValueList(query)) {
789
+ return "J1QL value lists use OR, not commas: WITH prop = ('a' OR 'b' OR 'c').";
413
790
  }
414
791
  const findSegment = query.match(/\bFIND\s+([^]+?)(?=\s+(?:WITH|AS|THAT|RETURN|WHERE|ORDER|LIMIT|SKIP)\b|$)/i)?.[1];
415
792
  const types = findSegment
@@ -449,12 +826,7 @@ class J1QLValidator {
449
826
  // syntax that doesn't produce "Unexpected token" still fall through to analysis.
450
827
  {
451
828
  pattern: /invalid syntax at line \d+/i,
452
- suggestion: (_match, query) => {
453
- const valueList = this.rewriteValueList(query);
454
- return valueList
455
- ? `${BRACKET_LIST_MESSAGE}\nUse this query instead:\n${valueList}`
456
- : 'syntax_analysis';
457
- },
829
+ suggestion: (_match, query) => hasValueList(query) ? BRACKET_LIST_MESSAGE : 'syntax_analysis',
458
830
  },
459
831
  // Selector validation happens at parse time (RETURN / ORDER BY reference an unknown alias)
460
832
  {