nexus-agents 11.4.2 → 11.4.4

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/dist/{ast-rule-runner-UZS3CBHO.js → ast-rule-runner-UIBITXDJ.js} +5 -5
  2. package/dist/{child-mcp-config-353PE3ID.js → child-mcp-config-EMNCNHKM.js} +4 -4
  3. package/dist/{chunk-ME7LKSBK.js → chunk-4DHC2TDC.js} +5 -5
  4. package/dist/{chunk-J7UDMLPP.js → chunk-4IN3DHXY.js} +2 -2
  5. package/dist/{chunk-DS6X6MFM.js → chunk-5FYSIB3L.js} +2 -2
  6. package/dist/{chunk-NSELDEAX.js → chunk-5TW3NLWA.js} +2 -2
  7. package/dist/{chunk-MPYHD4EV.js → chunk-6MOCJOKU.js} +2 -2
  8. package/dist/{chunk-HQ2SMW4Y.js → chunk-773AZVR3.js} +3 -3
  9. package/dist/chunk-773AZVR3.js.map +1 -0
  10. package/dist/{chunk-YZXCE5BB.js → chunk-AH4Y7Z6S.js} +5 -5
  11. package/dist/{chunk-JDL5WJDM.js → chunk-BCC27PGX.js} +2 -2
  12. package/dist/{chunk-BPO2LQ67.js → chunk-BGELNT5F.js} +4 -4
  13. package/dist/{chunk-5CSM473L.js → chunk-DFRQP7AM.js} +3 -3
  14. package/dist/{chunk-UMLKKXBD.js → chunk-FGR6O454.js} +3 -3
  15. package/dist/{chunk-CVOE6Q56.js → chunk-FQFCLNYM.js} +2 -2
  16. package/dist/{chunk-EOIUMPFK.js → chunk-FYXIWH62.js} +2 -2
  17. package/dist/{chunk-7LW3PMQS.js → chunk-HNGZ5AMV.js} +62 -45
  18. package/dist/chunk-HNGZ5AMV.js.map +1 -0
  19. package/dist/{chunk-JQ4JJVH2.js → chunk-JKYOZIDM.js} +2 -2
  20. package/dist/{chunk-KSGJB4AF.js → chunk-KXD7ZJWM.js} +2 -2
  21. package/dist/{chunk-ZSPGTD4X.js → chunk-LEPAOFIF.js} +7 -7
  22. package/dist/{chunk-Y5YOOAXF.js → chunk-MYWMM23M.js} +2 -2
  23. package/dist/{chunk-KCESFTXP.js → chunk-N5DHPHPE.js} +2 -2
  24. package/dist/{chunk-PAYKBSXM.js → chunk-NNVA7BZX.js} +13 -13
  25. package/dist/{chunk-MOILTUAB.js → chunk-OUU6EOZE.js} +13 -13
  26. package/dist/{chunk-2PN4CAL2.js → chunk-QBP4VHJF.js} +4 -4
  27. package/dist/{chunk-WTZULRPO.js → chunk-V2DJZZKS.js} +2 -2
  28. package/dist/{chunk-6U3GRS6B.js → chunk-VA247HQO.js} +8 -8
  29. package/dist/{chunk-RYSLBVMQ.js → chunk-VGRTBVWC.js} +3 -3
  30. package/dist/{chunk-RGDZIWGS.js → chunk-VMGKPEVR.js} +6 -6
  31. package/dist/{chunk-VKK7ZGSY.js → chunk-W56VP6JH.js} +4 -4
  32. package/dist/{chunk-M7JXKUFB.js → chunk-WM2BE65D.js} +7 -7
  33. package/dist/chunk-WM2BE65D.js.map +1 -0
  34. package/dist/{chunk-54UNI6GV.js → chunk-WSLPF7BX.js} +4 -4
  35. package/dist/{chunk-CVT26QN5.js → chunk-XBXLA6DJ.js} +8 -8
  36. package/dist/{chunk-6RP53JXS.js → chunk-Y3A3VVGT.js} +4 -4
  37. package/dist/{chunk-2FY4QM42.js → chunk-YC6QAHC2.js} +3 -3
  38. package/dist/{chunk-P3ZQVHQA.js → chunk-ZDNXBCOP.js} +2 -2
  39. package/dist/{chunk-V552SY6A.js → chunk-ZPCTULSZ.js} +3 -3
  40. package/dist/{cli-circuit-breaker-4SM3OLUD.js → cli-circuit-breaker-MBEEEQUD.js} +5 -5
  41. package/dist/{cli-readiness-JJVQULXD.js → cli-readiness-NQKW6M27.js} +8 -8
  42. package/dist/{cli-server-gateway-TYVCEQBQ.js → cli-server-gateway-UQC4FDQH.js} +12 -12
  43. package/dist/cli.js +44 -44
  44. package/dist/cli.js.map +1 -1
  45. package/dist/{composite-router-56G2NJCH.js → composite-router-VDDTC263.js} +4 -4
  46. package/dist/{consensus-vote-CE7X66SQ.js → consensus-vote-3AJ54VX3.js} +16 -16
  47. package/dist/{context-retriever-AUOD3LIJ.js → context-retriever-BJIUY6QW.js} +10 -10
  48. package/dist/{doctor-deep-KMMW2MTJ.js → doctor-deep-LGOSW75C.js} +5 -5
  49. package/dist/{doctor-gateway-report-AOH2I4UJ.js → doctor-gateway-report-WCPLTO7X.js} +7 -7
  50. package/dist/{doctor-live-2IVCCWSN.js → doctor-live-DFGOZPZ2.js} +12 -12
  51. package/dist/{expert-bridge-PREN4ZL3.js → expert-bridge-GFO6QWXL.js} +6 -6
  52. package/dist/{factory-KPCJR5RB.js → factory-P45WM7Y5.js} +7 -7
  53. package/dist/{factory-3YILRPOA.js → factory-RZVZ6BLF.js} +11 -11
  54. package/dist/{improvement-review-MZMOSJM2.js → improvement-review-HTSRGEF5.js} +7 -7
  55. package/dist/index.d.ts +21 -0
  56. package/dist/index.js +30 -30
  57. package/dist/{init-opencode-V4G5WYRL.js → init-opencode-UTUYKUJ5.js} +6 -6
  58. package/dist/{issue-triage-WZZTRX4K.js → issue-triage-RUA2254S.js} +8 -8
  59. package/dist/{model-config-helpers-BC4JYVUU.js → model-config-helpers-ZIVSTS76.js} +3 -3
  60. package/dist/{openai-compat-adapter-7NPALXRG.js → openai-compat-adapter-BAHSQKIS.js} +6 -6
  61. package/dist/{pr-reviewer-helpers-O6URR7XX.js → pr-reviewer-helpers-WUK6PQLA.js} +6 -6
  62. package/dist/{registry-command-T3NTED3I.js → registry-command-BCNWYA6P.js} +2 -2
  63. package/dist/{repo-security-plan-BACXPNX3.js → repo-security-plan-OZHFTQB3.js} +4 -4
  64. package/dist/{research-helpers-synthesize-IWS2XZQN.js → research-helpers-synthesize-BY7RH4B3.js} +6 -6
  65. package/dist/{routing-memory-EO7VG7R3.js → routing-memory-TVITESTN.js} +4 -4
  66. package/dist/{session-memory-4GX3WTEB.js → session-memory-C4R2RA4D.js} +5 -5
  67. package/dist/{setup-config-JYHG3SGD.js → setup-config-Q6MJ7HWN.js} +5 -5
  68. package/dist/{setup-custom-api-GF66FJBO.js → setup-custom-api-GOM3HW5G.js} +5 -5
  69. package/dist/{setup-data-dir-ZJMIJWQ2.js → setup-data-dir-UOKXLPTP.js} +15 -15
  70. package/dist/{tool-memory-IS2S7SYW.js → tool-memory-PHPWXWS3.js} +7 -7
  71. package/dist/{unified-registry-IZ46TOAY.js → unified-registry-GXELRMCT.js} +11 -11
  72. package/dist/{weather-report-MLERG4SM.js → weather-report-OIWO4BCH.js} +4 -4
  73. package/package.json +1 -1
  74. package/dist/chunk-7LW3PMQS.js.map +0 -1
  75. package/dist/chunk-HQ2SMW4Y.js.map +0 -1
  76. package/dist/chunk-M7JXKUFB.js.map +0 -1
  77. /package/dist/{ast-rule-runner-UZS3CBHO.js.map → ast-rule-runner-UIBITXDJ.js.map} +0 -0
  78. /package/dist/{child-mcp-config-353PE3ID.js.map → child-mcp-config-EMNCNHKM.js.map} +0 -0
  79. /package/dist/{chunk-ME7LKSBK.js.map → chunk-4DHC2TDC.js.map} +0 -0
  80. /package/dist/{chunk-J7UDMLPP.js.map → chunk-4IN3DHXY.js.map} +0 -0
  81. /package/dist/{chunk-DS6X6MFM.js.map → chunk-5FYSIB3L.js.map} +0 -0
  82. /package/dist/{chunk-NSELDEAX.js.map → chunk-5TW3NLWA.js.map} +0 -0
  83. /package/dist/{chunk-MPYHD4EV.js.map → chunk-6MOCJOKU.js.map} +0 -0
  84. /package/dist/{chunk-YZXCE5BB.js.map → chunk-AH4Y7Z6S.js.map} +0 -0
  85. /package/dist/{chunk-JDL5WJDM.js.map → chunk-BCC27PGX.js.map} +0 -0
  86. /package/dist/{chunk-BPO2LQ67.js.map → chunk-BGELNT5F.js.map} +0 -0
  87. /package/dist/{chunk-5CSM473L.js.map → chunk-DFRQP7AM.js.map} +0 -0
  88. /package/dist/{chunk-UMLKKXBD.js.map → chunk-FGR6O454.js.map} +0 -0
  89. /package/dist/{chunk-CVOE6Q56.js.map → chunk-FQFCLNYM.js.map} +0 -0
  90. /package/dist/{chunk-EOIUMPFK.js.map → chunk-FYXIWH62.js.map} +0 -0
  91. /package/dist/{chunk-JQ4JJVH2.js.map → chunk-JKYOZIDM.js.map} +0 -0
  92. /package/dist/{chunk-KSGJB4AF.js.map → chunk-KXD7ZJWM.js.map} +0 -0
  93. /package/dist/{chunk-ZSPGTD4X.js.map → chunk-LEPAOFIF.js.map} +0 -0
  94. /package/dist/{chunk-Y5YOOAXF.js.map → chunk-MYWMM23M.js.map} +0 -0
  95. /package/dist/{chunk-KCESFTXP.js.map → chunk-N5DHPHPE.js.map} +0 -0
  96. /package/dist/{chunk-PAYKBSXM.js.map → chunk-NNVA7BZX.js.map} +0 -0
  97. /package/dist/{chunk-MOILTUAB.js.map → chunk-OUU6EOZE.js.map} +0 -0
  98. /package/dist/{chunk-2PN4CAL2.js.map → chunk-QBP4VHJF.js.map} +0 -0
  99. /package/dist/{chunk-WTZULRPO.js.map → chunk-V2DJZZKS.js.map} +0 -0
  100. /package/dist/{chunk-6U3GRS6B.js.map → chunk-VA247HQO.js.map} +0 -0
  101. /package/dist/{chunk-RYSLBVMQ.js.map → chunk-VGRTBVWC.js.map} +0 -0
  102. /package/dist/{chunk-RGDZIWGS.js.map → chunk-VMGKPEVR.js.map} +0 -0
  103. /package/dist/{chunk-VKK7ZGSY.js.map → chunk-W56VP6JH.js.map} +0 -0
  104. /package/dist/{chunk-54UNI6GV.js.map → chunk-WSLPF7BX.js.map} +0 -0
  105. /package/dist/{chunk-CVT26QN5.js.map → chunk-XBXLA6DJ.js.map} +0 -0
  106. /package/dist/{chunk-6RP53JXS.js.map → chunk-Y3A3VVGT.js.map} +0 -0
  107. /package/dist/{chunk-2FY4QM42.js.map → chunk-YC6QAHC2.js.map} +0 -0
  108. /package/dist/{chunk-P3ZQVHQA.js.map → chunk-ZDNXBCOP.js.map} +0 -0
  109. /package/dist/{chunk-V552SY6A.js.map → chunk-ZPCTULSZ.js.map} +0 -0
  110. /package/dist/{cli-circuit-breaker-4SM3OLUD.js.map → cli-circuit-breaker-MBEEEQUD.js.map} +0 -0
  111. /package/dist/{cli-readiness-JJVQULXD.js.map → cli-readiness-NQKW6M27.js.map} +0 -0
  112. /package/dist/{cli-server-gateway-TYVCEQBQ.js.map → cli-server-gateway-UQC4FDQH.js.map} +0 -0
  113. /package/dist/{composite-router-56G2NJCH.js.map → composite-router-VDDTC263.js.map} +0 -0
  114. /package/dist/{consensus-vote-CE7X66SQ.js.map → consensus-vote-3AJ54VX3.js.map} +0 -0
  115. /package/dist/{context-retriever-AUOD3LIJ.js.map → context-retriever-BJIUY6QW.js.map} +0 -0
  116. /package/dist/{doctor-deep-KMMW2MTJ.js.map → doctor-deep-LGOSW75C.js.map} +0 -0
  117. /package/dist/{doctor-gateway-report-AOH2I4UJ.js.map → doctor-gateway-report-WCPLTO7X.js.map} +0 -0
  118. /package/dist/{doctor-live-2IVCCWSN.js.map → doctor-live-DFGOZPZ2.js.map} +0 -0
  119. /package/dist/{expert-bridge-PREN4ZL3.js.map → expert-bridge-GFO6QWXL.js.map} +0 -0
  120. /package/dist/{factory-3YILRPOA.js.map → factory-P45WM7Y5.js.map} +0 -0
  121. /package/dist/{factory-KPCJR5RB.js.map → factory-RZVZ6BLF.js.map} +0 -0
  122. /package/dist/{improvement-review-MZMOSJM2.js.map → improvement-review-HTSRGEF5.js.map} +0 -0
  123. /package/dist/{init-opencode-V4G5WYRL.js.map → init-opencode-UTUYKUJ5.js.map} +0 -0
  124. /package/dist/{issue-triage-WZZTRX4K.js.map → issue-triage-RUA2254S.js.map} +0 -0
  125. /package/dist/{model-config-helpers-BC4JYVUU.js.map → model-config-helpers-ZIVSTS76.js.map} +0 -0
  126. /package/dist/{openai-compat-adapter-7NPALXRG.js.map → openai-compat-adapter-BAHSQKIS.js.map} +0 -0
  127. /package/dist/{pr-reviewer-helpers-O6URR7XX.js.map → pr-reviewer-helpers-WUK6PQLA.js.map} +0 -0
  128. /package/dist/{registry-command-T3NTED3I.js.map → registry-command-BCNWYA6P.js.map} +0 -0
  129. /package/dist/{repo-security-plan-BACXPNX3.js.map → repo-security-plan-OZHFTQB3.js.map} +0 -0
  130. /package/dist/{research-helpers-synthesize-IWS2XZQN.js.map → research-helpers-synthesize-BY7RH4B3.js.map} +0 -0
  131. /package/dist/{routing-memory-EO7VG7R3.js.map → routing-memory-TVITESTN.js.map} +0 -0
  132. /package/dist/{session-memory-4GX3WTEB.js.map → session-memory-C4R2RA4D.js.map} +0 -0
  133. /package/dist/{setup-config-JYHG3SGD.js.map → setup-config-Q6MJ7HWN.js.map} +0 -0
  134. /package/dist/{setup-custom-api-GF66FJBO.js.map → setup-custom-api-GOM3HW5G.js.map} +0 -0
  135. /package/dist/{setup-data-dir-ZJMIJWQ2.js.map → setup-data-dir-UOKXLPTP.js.map} +0 -0
  136. /package/dist/{tool-memory-IS2S7SYW.js.map → tool-memory-PHPWXWS3.js.map} +0 -0
  137. /package/dist/{unified-registry-IZ46TOAY.js.map → unified-registry-GXELRMCT.js.map} +0 -0
  138. /package/dist/{weather-report-MLERG4SM.js.map → weather-report-OIWO4BCH.js.map} +0 -0
@@ -9,11 +9,11 @@ import {
9
9
  getBuiltInAstRulesPath,
10
10
  loadRules,
11
11
  runAstQaRules
12
- } from "./chunk-EOIUMPFK.js";
13
- import "./chunk-M7JXKUFB.js";
12
+ } from "./chunk-FYXIWH62.js";
13
+ import "./chunk-WM2BE65D.js";
14
14
  import "./chunk-XBEKMUTO.js";
15
- import "./chunk-DS6X6MFM.js";
16
- import "./chunk-NSELDEAX.js";
15
+ import "./chunk-5FYSIB3L.js";
16
+ import "./chunk-5TW3NLWA.js";
17
17
  import "./chunk-RUHKJC3X.js";
18
18
  import "./chunk-UFAK5UGH.js";
19
19
  import "./chunk-GR6WCJWY.js";
@@ -34,4 +34,4 @@ export {
34
34
  loadRules,
35
35
  runAstQaRules
36
36
  };
37
- //# sourceMappingURL=ast-rule-runner-UZS3CBHO.js.map
37
+ //# sourceMappingURL=ast-rule-runner-UIBITXDJ.js.map
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  nexusMkdtempSync
3
3
  } from "./chunk-U7HL7FGS.js";
4
- import "./chunk-M7JXKUFB.js";
4
+ import "./chunk-WM2BE65D.js";
5
5
  import "./chunk-XBEKMUTO.js";
6
- import "./chunk-DS6X6MFM.js";
7
- import "./chunk-NSELDEAX.js";
6
+ import "./chunk-5FYSIB3L.js";
7
+ import "./chunk-5TW3NLWA.js";
8
8
  import "./chunk-RUHKJC3X.js";
9
9
  import "./chunk-UFAK5UGH.js";
10
10
  import {
@@ -81,4 +81,4 @@ async function generateMcpConfig(options) {
81
81
  export {
82
82
  generateMcpConfig
83
83
  };
84
- //# sourceMappingURL=child-mcp-config-353PE3ID.js.map
84
+ //# sourceMappingURL=child-mcp-config-EMNCNHKM.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  GitHubProvider,
3
3
  ScmError
4
- } from "./chunk-J7UDMLPP.js";
4
+ } from "./chunk-4IN3DHXY.js";
5
5
  import {
6
6
  ReputationCache,
7
7
  assessReputation,
@@ -9,10 +9,10 @@ import {
9
9
  resolveEnvMode,
10
10
  resolveReputationGatingMode,
11
11
  sanitizeInput
12
- } from "./chunk-HQ2SMW4Y.js";
12
+ } from "./chunk-773AZVR3.js";
13
13
  import {
14
14
  hasToken
15
- } from "./chunk-KCESFTXP.js";
15
+ } from "./chunk-N5DHPHPE.js";
16
16
  import {
17
17
  toContentTrustProvenanceRecord
18
18
  } from "./chunk-ZO6ZKR7L.js";
@@ -25,7 +25,7 @@ import {
25
25
  err,
26
26
  getErrorMessage,
27
27
  ok
28
- } from "./chunk-M7JXKUFB.js";
28
+ } from "./chunk-WM2BE65D.js";
29
29
  import {
30
30
  createLogger,
31
31
  getTimeProvider
@@ -2647,4 +2647,4 @@ export {
2647
2647
  IssueTriage,
2648
2648
  createIssueTriage
2649
2649
  };
2650
- //# sourceMappingURL=chunk-ME7LKSBK.js.map
2650
+ //# sourceMappingURL=chunk-4DHC2TDC.js.map
@@ -2,7 +2,7 @@ import {
2
2
  err,
3
3
  getErrorMessage,
4
4
  ok
5
- } from "./chunk-M7JXKUFB.js";
5
+ } from "./chunk-WM2BE65D.js";
6
6
  import {
7
7
  createLogger
8
8
  } from "./chunk-GR6WCJWY.js";
@@ -285,4 +285,4 @@ export {
285
285
  ScmError,
286
286
  GitHubProvider
287
287
  };
288
- //# sourceMappingURL=chunk-J7UDMLPP.js.map
288
+ //# sourceMappingURL=chunk-4IN3DHXY.js.map
@@ -5,7 +5,7 @@ import {
5
5
  getDefaultRegistry,
6
6
  peekDefaultRegistry,
7
7
  unpricedCliCostPer1M
8
- } from "./chunk-NSELDEAX.js";
8
+ } from "./chunk-5TW3NLWA.js";
9
9
  import {
10
10
  CLI_NAMES
11
11
  } from "./chunk-MTN5VMBX.js";
@@ -343,4 +343,4 @@ export {
343
343
  findBestModelForOutput,
344
344
  modelSupportsAll
345
345
  };
346
- //# sourceMappingURL=chunk-DS6X6MFM.js.map
346
+ //# sourceMappingURL=chunk-5FYSIB3L.js.map
@@ -1645,7 +1645,7 @@ function setDefaultRegistry(registry) {
1645
1645
  }
1646
1646
  async function reloadDefaultRegistry() {
1647
1647
  globalRegistry = buildDefaultRegistry();
1648
- const { resetGlobalRegistry } = await import("./unified-registry-IZ46TOAY.js");
1648
+ const { resetGlobalRegistry } = await import("./unified-registry-GXELRMCT.js");
1649
1649
  resetGlobalRegistry();
1650
1650
  return globalRegistry;
1651
1651
  }
@@ -1674,4 +1674,4 @@ export {
1674
1674
  setDefaultRegistry,
1675
1675
  reloadDefaultRegistry
1676
1676
  };
1677
- //# sourceMappingURL=chunk-NSELDEAX.js.map
1677
+ //# sourceMappingURL=chunk-5TW3NLWA.js.map
@@ -5,7 +5,7 @@ import {
5
5
  OPENAI_COMPAT_URL_ENV,
6
6
  err,
7
7
  ok
8
- } from "./chunk-M7JXKUFB.js";
8
+ } from "./chunk-WM2BE65D.js";
9
9
  import {
10
10
  createLogger
11
11
  } from "./chunk-GR6WCJWY.js";
@@ -307,4 +307,4 @@ export {
307
307
  hostnameOf,
308
308
  redactApiKey
309
309
  };
310
- //# sourceMappingURL=chunk-MPYHD4EV.js.map
310
+ //# sourceMappingURL=chunk-6MOCJOKU.js.map
@@ -14,7 +14,7 @@ import {
14
14
  // src/security/input-sanitizer.ts
15
15
  var DANGEROUS_HTML_PATTERN = /<(picture|source|img)\b[^>]*>[\s\S]*?<\/\1>|<(picture|source|img)\b[^>]*\/?>/gi;
16
16
  var XML_INJECTION_PATTERN = /<\/?(system|human|assistant|instructions|user|prompt|context|tool_use|tool_result)\b[^>]*>/gi;
17
- var HTML_COMMENT_PATTERN = /<!--[\s\S]*?-->/g;
17
+ var HTML_COMMENT_PATTERN = /\x3c!--[\s\S]*?-->/g;
18
18
  var INJECTION_PATTERNS = [
19
19
  {
20
20
  flag: "authority_claim",
@@ -177,7 +177,7 @@ function stripHtmlComments(content) {
177
177
  }
178
178
  return { cleaned, stripped };
179
179
  }
180
- var HTML_COMMENT_DETECT = /<!--[\s\S]*?-->/;
180
+ var HTML_COMMENT_DETECT = /\x3c!--[\s\S]*?-->/;
181
181
  function detectInjectionPatterns(content) {
182
182
  const flags = /* @__PURE__ */ new Set();
183
183
  if (HTML_COMMENT_DETECT.test(content)) {
@@ -511,4 +511,4 @@ export {
511
511
  resolveReputationGatingMode,
512
512
  gateWithReputation
513
513
  };
514
- //# sourceMappingURL=chunk-HQ2SMW4Y.js.map
514
+ //# sourceMappingURL=chunk-773AZVR3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/security/input-sanitizer.ts","../src/security/reputation-model.ts","../src/security/env-mode.ts"],"sourcesContent":["/**\n * nexus-agents/security - Input Sanitizer\n *\n * Sanitizes untrusted GitHub input by stripping dangerous HTML/XML tags,\n * detecting injection patterns, and producing a SanitizedInput result\n * with full audit trail.\n *\n * Defense layer 1 of the three-layer hardening architecture.\n * See: docs/architecture/UNTRUSTED_INPUT_HARDENING.md\n *\n * @module security/input-sanitizer\n * (Source: Issue #818, #819 — Phase 1: Input Sanitization)\n */\n\nimport type {\n InjectionFlag,\n SanitizedInput,\n SanitizerConfig,\n StrippedElement,\n TrustTier,\n GitHubUserRole,\n} from './trust-types.js';\nimport { ROLE_DEFAULT_TRUST, SanitizerConfigSchema } from './trust-types.js';\n\n// ============================================================================\n// Dangerous HTML Patterns (Trail of Bits / GitHub Copilot vectors)\n// ============================================================================\n\n/**\n * HTML tags to strip. These are known injection vectors:\n * - `<picture>` / `<source>`: Trail of Bits GitHub Copilot injection\n * - `<img>`: Can carry injection via alt text or onerror\n */\nconst DANGEROUS_HTML_PATTERN =\n /<(picture|source|img)\\b[^>]*>[\\s\\S]*?<\\/\\1>|<(picture|source|img)\\b[^>]*\\/?>/gi;\n\n// ============================================================================\n// XML-like Tags (Conversation History Injection)\n// ============================================================================\n\n/**\n * XML-like tags that mimic conversation structure or system prompts.\n */\nconst XML_INJECTION_PATTERN =\n /<\\/?(system|human|assistant|instructions|user|prompt|context|tool_use|tool_result)\\b[^>]*>/gi;\n\n// ============================================================================\n// HTML Comments with Instructions\n// ============================================================================\n\nconst HTML_COMMENT_PATTERN = /\\x3c!--[\\s\\S]*?-->/g;\n\n// ============================================================================\n// Injection Pattern Detectors\n// ============================================================================\n\ninterface PatternMatch {\n flag: InjectionFlag;\n pattern: RegExp;\n}\n\nconst INJECTION_PATTERNS: readonly PatternMatch[] = [\n {\n flag: 'authority_claim',\n pattern: /\\b(as (?:a|the) (?:maintainer|admin|owner|security lead|repo owner|developer))\\b/i,\n },\n {\n flag: 'authority_claim',\n pattern: /\\b(i(?:'m| am) the (?:repo |project )?(?:owner|maintainer|admin))\\b/i,\n },\n {\n flag: 'instruction_pattern',\n pattern: /\\b(please (?:close|merge|label|mark|apply|delete|remove|approve|reject))\\b/i,\n },\n {\n flag: 'instruction_pattern',\n pattern: /\\b(you (?:should|must|need to) (?:close|merge|label|apply|delete))\\b/i,\n },\n {\n flag: 'system_prompt_manipulation',\n pattern: /\\b(ignore (?:all )?previous (?:instructions|rules|prompts))\\b/i,\n },\n {\n flag: 'system_prompt_manipulation',\n pattern: /\\b(forget (?:your |all )?(?:instructions|rules|safety))\\b/i,\n },\n {\n flag: 'system_prompt_manipulation',\n pattern: /\\b(new (?:instructions|rules|system prompt|directives))\\b/i,\n },\n {\n flag: 'urgency_manipulation',\n pattern: /\\b(critical|emergency|urgent|must act now|immediately|time[- ]?sensitive)\\b/i,\n },\n {\n flag: 'fake_conversation',\n pattern: /<(?:assistant|human|user|system)>/i,\n },\n // base64_encoded is detected separately by `looksLikeBase64Payload` below.\n // The lookahead-based regex it replaced exhibited catastrophic backtracking\n // on long hex-only inputs (#2191) — see `looksLikeBase64Payload` for the\n // two-phase rewrite that preserves the #1811 SHA-hash false-positive guard.\n {\n flag: 'external_link_instruction',\n pattern: /(?:apply|run|execute|install)\\s+(?:this\\s+)?(?:from\\s+)?https?:\\/\\//i,\n },\n];\n\n/**\n * Two-phase base64-payload detection (#2191).\n *\n * The original `(?=[A-Za-z0-9+/]*[g-zG-Z+/=])[A-Za-z0-9+/]{40,}={0,2}` regex\n * was vulnerable to catastrophic backtracking — V8 took ~1.8s on a 50K\n * hex-only adversarial input. Splitting the check into two non-overlapping\n * phases removes the lookahead and makes the worst case linear.\n *\n * Phase 1: find a 40+ run of base64-alphabet chars (no lookahead).\n * Phase 2: confirm the matched substring contains a base64-discriminating\n * char (g-z, G-Z, +, /, =) so SHA-1 / SHA-256 hex hashes don't\n * false-positive (preserves #1811 behavior).\n *\n * Same detection coverage as the original; same false-positive resistance.\n */\nconst BASE64_RUN_GLOBAL = /[A-Za-z0-9+/]{40,}={0,2}/g;\nconst BASE64_DISCRIMINATOR = /[g-zG-Z+/=]/;\n\nfunction looksLikeBase64Payload(content: string): boolean {\n // Iterate every 40+ base64-alphabet run rather than just the first one,\n // so a long hex-only prefix doesn't mask a real base64 payload that\n // appears later in the content.\n for (const match of content.matchAll(BASE64_RUN_GLOBAL)) {\n if (BASE64_DISCRIMINATOR.test(match[0])) return true;\n }\n return false;\n}\n\n// ============================================================================\n// HTML Entity Decoding (evasion defense)\n// ============================================================================\n\n/**\n * Dangerous-tag names we will still match after entity decoding.\n * Kept in sync with DANGEROUS_HTML_PATTERN and XML_INJECTION_PATTERN above.\n */\nconst DANGEROUS_TAG_NAMES =\n 'picture|source|img|system|human|assistant|instructions|user|prompt|context|tool_use|tool_result';\n\n/**\n * Detects whether the input contains entity-encoded forms of any dangerous\n * tag (&lt;picture, &#60;system, &#x3c;img …). Used as a cheap pre-check so\n * that benign content with legitimate entities (e.g. \"AT&amp;T\") is passed\n * through untouched and wasModified stays false.\n */\nconst ENCODED_DANGEROUS_TAG_PATTERN = new RegExp(\n `&(?:lt|#0*60|#x0*3c);\\\\s*\\\\/?\\\\s*(?:${DANGEROUS_TAG_NAMES})\\\\b`,\n 'i'\n);\n\n/** Decodes the subset of HTML entities that can reconstruct tag syntax. */\nfunction decodeEntities(content: string): string {\n return (\n content\n // Numeric (decimal) references\n .replace(/&#(\\d+);/g, (_match, dec: string) => {\n const code = Number.parseInt(dec, 10);\n return Number.isFinite(code) ? String.fromCodePoint(code) : _match;\n })\n // Numeric (hex) references\n .replace(/&#x([0-9a-f]+);/gi, (_match, hex: string) => {\n const code = Number.parseInt(hex, 16);\n return Number.isFinite(code) ? String.fromCodePoint(code) : _match;\n })\n // Named entities most relevant to tag reconstruction\n .replace(/&lt;/gi, '<')\n .replace(/&gt;/gi, '>')\n .replace(/&quot;/gi, '\"')\n .replace(/&apos;/gi, \"'\")\n // &amp; must be decoded last so that &amp;lt; does not resurface as <\n .replace(/&amp;/gi, '&')\n );\n}\n\n/**\n * Runs decodeEntities only if the input contains an entity-encoded dangerous\n * tag. This keeps benign content with legitimate entities untouched.\n */\nfunction applyEntityEvasionDefense(content: string): {\n cleaned: string;\n stripped: StrippedElement[];\n} {\n if (!ENCODED_DANGEROUS_TAG_PATTERN.test(content)) {\n return { cleaned: content, stripped: [] };\n }\n const decoded = decodeEntities(content);\n return {\n cleaned: decoded,\n stripped: [\n {\n tag: '&…;',\n reason: 'HTML entity-encoded dangerous tag decoded for stripping (CWE-79)',\n startIndex: 0,\n length: content.length,\n },\n ],\n };\n}\n\n// ============================================================================\n// Core Sanitization Functions\n// ============================================================================\n\n/** Strips dangerous HTML tags and records what was removed.\n * Loops until stable to prevent reconstructed patterns after removal (#1496). */\nfunction stripDangerousHtml(content: string): {\n cleaned: string;\n stripped: StrippedElement[];\n /** True when the loop ran out of passes with the pattern still matching. */\n incomplete: boolean;\n} {\n const stripped: StrippedElement[] = [];\n let cleaned = content;\n const MAX_PASSES = 5;\n for (let pass = 0; pass < MAX_PASSES; pass++) {\n DANGEROUS_HTML_PATTERN.lastIndex = 0;\n if (!DANGEROUS_HTML_PATTERN.test(cleaned)) break;\n cleaned = cleaned.replace(DANGEROUS_HTML_PATTERN, (match, _g1, _g2, offset: number) => {\n stripped.push({\n tag: match.slice(0, 30) + (match.length > 30 ? '...' : ''),\n reason: 'Dangerous HTML tag (Trail of Bits injection vector)',\n startIndex: offset,\n length: match.length,\n });\n return '';\n });\n }\n // One more probe. The loop above exits either because the pattern stopped\n // matching or because it ran out of passes, and the caller could not tell\n // which — so unconverged content was returned as clean.\n DANGEROUS_HTML_PATTERN.lastIndex = 0;\n return { cleaned, stripped, incomplete: DANGEROUS_HTML_PATTERN.test(cleaned) };\n}\n\n/**\n * Strips XML-like tags that mimic conversation structure.\n *\n * Loops to remove a tag RECONSTRUCTED by an earlier removal (#1496):\n * `<sy` + `<system>` + `stem>` becomes `<system>` once the inner tag goes. Each\n * nesting level costs one pass, so depth N needs N+1 — and at depth 6 the loop\n * exhausted its budget and returned a live `<system>` tag as clean.\n */\nfunction stripXmlTags(content: string): {\n cleaned: string;\n stripped: StrippedElement[];\n /** True when the loop ran out of passes with the pattern still matching. */\n incomplete: boolean;\n} {\n const stripped: StrippedElement[] = [];\n let cleaned = content;\n const MAX_PASSES = 5;\n for (let pass = 0; pass < MAX_PASSES; pass++) {\n XML_INJECTION_PATTERN.lastIndex = 0;\n if (!XML_INJECTION_PATTERN.test(cleaned)) break;\n cleaned = cleaned.replace(XML_INJECTION_PATTERN, (match, _g1, offset: number) => {\n stripped.push({\n tag: match,\n reason: 'XML-like conversation injection tag',\n startIndex: offset,\n length: match.length,\n });\n return '';\n });\n }\n XML_INJECTION_PATTERN.lastIndex = 0;\n return { cleaned, stripped, incomplete: XML_INJECTION_PATTERN.test(cleaned) };\n}\n\n/** Strips HTML comments that may contain hidden instructions.\n * Loops until stable to prevent reconstructed comment patterns (#1496). */\nfunction stripHtmlComments(content: string): {\n cleaned: string;\n stripped: StrippedElement[];\n} {\n const stripped: StrippedElement[] = [];\n let cleaned = content;\n // Loop until stable: stripping may reveal new instruction-bearing comments\n const MAX_PASSES = 5;\n for (let pass = 0; pass < MAX_PASSES; pass++) {\n HTML_COMMENT_PATTERN.lastIndex = 0;\n const prevLength = cleaned.length;\n cleaned = cleaned.replace(HTML_COMMENT_PATTERN, (match, offset: number) => {\n // Unconditional: the old keyword list (ignore|execute|close|merge|delete|\n // apply) let agent-directed text phrased around it survive, invisible in\n // rendered markdown, into the prompt. The MCP-layer sanitizer already\n // strips every comment and documents itself as strictly stronger; the two\n // layers now agree, and a comment in a PR body is not content a reviewer\n // reads anyway.\n stripped.push({\n tag: '<!-- ... -->',\n reason: 'HTML comment (hidden content)',\n startIndex: offset,\n length: match.length,\n });\n return '';\n });\n if (cleaned.length === prevLength) break;\n }\n // Second pass: strip unclosed <!-- tags (incomplete comment injection)\n let searchFrom = 0;\n while (searchFrom < cleaned.length) {\n const openIdx = cleaned.indexOf('<!--', searchFrom);\n if (openIdx === -1) break;\n const closeIdx = cleaned.indexOf('-->', openIdx + 4);\n if (closeIdx === -1) {\n stripped.push({\n tag: '<!--',\n reason: 'Unclosed HTML comment (potential injection vector)',\n startIndex: openIdx,\n length: cleaned.length - openIdx,\n });\n cleaned = cleaned.slice(0, openIdx);\n break;\n }\n searchFrom = closeIdx + 3;\n }\n return { cleaned, stripped };\n}\n\n/** Non-global twin of HTML_COMMENT_PATTERN — `.test` must not carry lastIndex state. */\nconst HTML_COMMENT_DETECT = /\\x3c!--[\\s\\S]*?-->/;\n\n/**\n * Detects injection patterns in content without modifying it. `hidden_content`\n * is raised here for any HTML comment: the flag is in HOSTILE_INJECTION_FLAGS\n * and the reputation model acts on it, but nothing produced it, so that arm of\n * `hasHostileInjection` could never fire.\n */\nfunction detectInjectionPatterns(content: string): InjectionFlag[] {\n const flags = new Set<InjectionFlag>();\n if (HTML_COMMENT_DETECT.test(content)) {\n flags.add('hidden_content');\n }\n for (const { flag, pattern } of INJECTION_PATTERNS) {\n // Reset lastIndex for global patterns\n pattern.lastIndex = 0;\n if (pattern.test(content)) {\n flags.add(flag);\n }\n }\n if (looksLikeBase64Payload(content)) {\n flags.add('base64_encoded');\n }\n return Array.from(flags);\n}\n\n/** Lower-cases an arbitrary role literal and maps it to a known role. */\nfunction normalizeRole(userRole: string): GitHubUserRole {\n const lower = userRole.toLowerCase();\n if (lower in ROLE_DEFAULT_TRUST) return lower as GitHubUserRole;\n return 'unknown';\n}\n\n/**\n * Assigns trust tier based on user role and injection analysis.\n * Injection patterns can only DOWNGRADE trust, never upgrade.\n */\nfunction assignTrustTier(\n userRole: GitHubUserRole,\n injectionFlags: readonly InjectionFlag[],\n allowlisted: boolean\n): TrustTier {\n if (allowlisted) return '1';\n\n // Defensive lowercase — the type says GitHubUserRole, but callers\n // sometimes cast an unnormalized GitHub author_association literal\n // (e.g. 'OWNER', 'MEMBER') directly. Normalize here so the maintainer\n // exemption below matches regardless of case (CWE-178).\n const normalizedRole = normalizeRole(userRole);\n const baseTier = ROLE_DEFAULT_TRUST[normalizedRole];\n\n // Content with injection patterns is downgraded to Tier 4 (hostile)\n const hostileFlags: InjectionFlag[] = ['system_prompt_manipulation', 'fake_conversation'];\n if (injectionFlags.some((f) => hostileFlags.includes(f))) return '4';\n\n // Content with authority claims from non-maintainers is suspicious\n if (\n injectionFlags.includes('authority_claim') &&\n normalizedRole !== 'owner' &&\n normalizedRole !== 'maintainer'\n ) {\n return '4';\n }\n\n return baseTier;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Sanitizes untrusted GitHub input through the full Layer 1 pipeline:\n * 1. HTML stripping (picture/source/img tags)\n * 2. XML tag stripping (system/human/assistant)\n * 3. HTML comment stripping (instruction-bearing comments only)\n * 4. Injection pattern detection\n * 5. Trust tier assignment\n *\n * ⚠ **Use HostileInputFirewall.process() in agent code paths.** Calling\n * sanitizeInput() directly only runs Layer 1 — it does not evaluate the\n * Rule of Two and does not emit audit-trail events. An agent that processes\n * untrusted input while holding both write access and secrets violates the\n * Rule of Two; `evaluatePolicy` in policy-gate.ts enforces that per action,\n * and the firewall evaluates it per input as a signal (refusing only under\n * `NEXUS_FIREWALL_POLICY=enforce`). The live paths route their trust\n * decision through the firewall as of #4992 and keep direct sanitizeInput()\n * calls only for content cleaning of text they embed. Direct use of this\n * function is appropriate for unit tests and pure content analysis, not\n * for agent decision paths.\n *\n * @see packages/nexus-agents/src/security/firewall/firewall-pipeline.ts\n * @see packages/nexus-agents/src/security/policy-gate.ts\n * @param content - Raw untrusted content from GitHub\n * @param userRole - GitHub user's relationship to the repository\n * @param username - GitHub username (for allowlist check)\n * @param config - Optional sanitizer configuration\n * @returns SanitizedInput with cleaned content and audit data\n */\nexport function sanitizeInput(\n content: string,\n userRole: GitHubUserRole,\n username: string,\n config?: Partial<SanitizerConfig>\n): SanitizedInput {\n const cfg = SanitizerConfigSchema.parse(config ?? {});\n const truncatedContent = content.slice(0, cfg.maxInputLength);\n const truncated = truncatedContent.length < content.length;\n const allowlisted = cfg.allowlistedMaintainers.includes(username);\n\n try {\n // Pipeline: decode entity-encoded dangerous tags, then strip dangerous content\n const entityDecoded = applyEntityEvasionDefense(truncatedContent);\n const html = stripDangerousHtml(entityDecoded.cleaned);\n const xml = stripXmlTags(html.cleaned);\n const comments = stripHtmlComments(xml.cleaned);\n const allStripped = [\n ...entityDecoded.stripped,\n ...html.stripped,\n ...xml.stripped,\n ...comments.stripped,\n ];\n\n // Detect on the original AND on what survived stripping, unioned.\n //\n // Running only on the original meant a flag could never see a tag that\n // exists ONLY after stripping — which is exactly the unconverged case. A\n // six-deep `<sy<sy…<system foo>…stem>` payload left a live `<system>` in\n // `content` while `injectionFlags` was `[]` and the author kept tier 3, so\n // `assessPRReputation` and `assessReputation` saw no hostility at all. The\n // `foo` attribute is what made it slip: `XML_INJECTION_PATTERN` matches\n // `<system\\b[^>]*>` but the `fake_conversation` detector has no attribute\n // form, so the ORIGINAL raised nothing.\n const injectionFlags = [\n ...new Set([\n ...detectInjectionPatterns(truncatedContent),\n ...detectInjectionPatterns(comments.cleaned),\n ]),\n ];\n\n // Assign trust tier\n const trustTier = assignTrustTier(userRole, injectionFlags, allowlisted);\n\n return {\n content: comments.cleaned,\n originalLength: content.length,\n trustTier,\n contentTierMeasured: true,\n userRole,\n injectionFlags,\n // Omitted when every loop converged, so no existing record changes shape.\n ...(html.incomplete || xml.incomplete ? { sanitizationIncomplete: true } : {}),\n strippedElements: allStripped,\n truncated,\n wasModified: truncated || allStripped.length > 0,\n sanitizedAt: new Date().toISOString(),\n };\n } catch (err: unknown) {\n return buildFailClosedResult(err, content, truncatedContent, userRole, allowlisted);\n }\n}\n\n/**\n * Fail-closed result returned when the sanitizer pipeline throws.\n * Returns empty content at Tier-4 (or Tier-1 for allowlisted maintainers,\n * since their bypass is not regex-dependent) so downstream consumers\n * cannot act on untrusted content we could not validate.\n * CLAUDE.md: \"Fail closed on ambiguity.\"\n */\nfunction buildFailClosedResult(\n err: unknown,\n originalContent: string,\n truncated: string,\n userRole: GitHubUserRole,\n allowlisted: boolean\n): SanitizedInput {\n const message = err instanceof Error ? err.message : String(err);\n return {\n content: '',\n originalLength: originalContent.length,\n trustTier: allowlisted ? '1' : '4',\n contentTierMeasured: true,\n userRole,\n injectionFlags: [],\n strippedElements: [\n {\n tag: '(pipeline-failure)',\n reason: `Sanitizer pipeline threw; input discarded as fail-closed: ${message}`,\n startIndex: 0,\n length: truncated.length,\n },\n ],\n truncated: truncated.length < originalContent.length,\n wasModified: true,\n sanitizedAt: new Date().toISOString(),\n };\n}\n","/**\n * nexus-agents/security - Reputation Model\n *\n * Lightweight trust model for GitHub users that assesses reputation\n * based on account age, contribution history, and behavioral signals.\n * Integrates with the trust classifier for comprehensive trust assessment.\n *\n * @module security/reputation-model\n * (Source: Issue #818, #824 — Phase 3: Reputation Model)\n */\n\nimport { z } from 'zod';\n\nimport { getTimeProvider } from '../core/index.js';\nimport { resolveEnvMode } from './env-mode.js';\nimport type { TrustTier, GitHubUserRole, InjectionFlag } from './trust-types.js';\nimport { TRUST_TIER_NUMERIC, ROLE_DEFAULT_TRUST } from './trust-types.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Signals that indicate a suspicious actor.\n */\nexport const SuspiciousSignalSchema = z.enum([\n 'new_account',\n 'no_prior_contributions',\n 'injection_patterns_detected',\n 'rapid_comments',\n 'mismatched_authority_claim',\n]);\nexport type SuspiciousSignal = z.infer<typeof SuspiciousSignalSchema>;\n\n/**\n * GitHub user metadata for reputation assessment.\n */\nexport interface GitHubUserMetadata {\n readonly username: string;\n /**\n * Account/activity fields are OPTIONAL (#3106). When a field is absent (the\n * caller couldn't fetch it — e.g. the firewall before Phase 3 wiring), its\n * signal is SKIPPED rather than fabricated: an unknown value must never be\n * treated as benign (the old hardcoded `365`/`0`) nor as hostile. Only the\n * `authorAssociation` + `injectionFlags` signals fire on absent activity data.\n */\n readonly accountAgeDays?: number;\n readonly priorContributions?: number;\n readonly recentCommentCount?: number;\n readonly recentCommentWindowMinutes?: number;\n readonly authorAssociation: string;\n readonly injectionFlags: readonly InjectionFlag[];\n}\n\n/**\n * Result of a reputation assessment.\n */\nexport interface ReputationAssessment {\n readonly username: string;\n readonly userRole: GitHubUserRole;\n /** Measurement coverage; absent on assessments created before coverage tracking. */\n readonly coverage?: {\n readonly activity: 'measured' | 'unmeasured';\n };\n readonly suspiciousSignals: readonly SuspiciousSignal[];\n readonly isSuspicious: boolean;\n readonly effectiveTrustTier: TrustTier;\n readonly reputationScore: number;\n readonly reason: string;\n readonly assessedAt: string;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/** Thresholds for suspicious behavior detection. */\n/** Approximate days per year, used to normalize account age to a 0–10 scale. */\nconst DAYS_PER_YEAR_APPROX = 36.5;\n\nconst SUSPICIOUS_THRESHOLDS = {\n /** Account younger than this (days) is flagged. */\n newAccountDays: 30,\n /** Fewer contributions than this is flagged. */\n minContributions: 1,\n /** More comments than this in the window triggers rapid-comment flag. */\n rapidCommentThreshold: 5,\n /** Time window (minutes) for rapid comment detection. */\n rapidCommentWindowMinutes: 10,\n} as const;\n\n// ============================================================================\n// Reputation Cache\n// ============================================================================\n\ninterface CacheEntry {\n assessment: ReputationAssessment;\n expiresAt: number;\n}\n\n// Canonical source: config/timeouts.ts (Issue #1046)\nimport { CACHE_TIMEOUTS } from '../config/timeouts.js';\n\nconst DEFAULT_TTL_MS: number = CACHE_TIMEOUTS.reputationTtlMs;\nconst DEFAULT_MAX_SIZE = 1000;\n\n/**\n * In-memory reputation cache with TTL and max size.\n * Reduces redundant assessments for the same user within a short window.\n * Evicts oldest entries when max size is exceeded.\n */\nexport class ReputationCache {\n private readonly cache = new Map<string, CacheEntry>();\n private readonly ttlMs: number;\n private readonly maxSize: number;\n\n constructor(ttlMs = DEFAULT_TTL_MS, maxSize = DEFAULT_MAX_SIZE) {\n this.ttlMs = ttlMs;\n this.maxSize = maxSize;\n }\n\n get(username: string): ReputationAssessment | undefined {\n const entry = this.cache.get(username);\n if (entry === undefined) return undefined;\n if (getTimeProvider().now() > entry.expiresAt) {\n this.cache.delete(username);\n return undefined;\n }\n return entry.assessment;\n }\n\n set(username: string, assessment: ReputationAssessment): void {\n if (this.cache.size >= this.maxSize && !this.cache.has(username)) {\n this.evictOldest();\n }\n this.cache.set(username, {\n assessment,\n expiresAt: getTimeProvider().now() + this.ttlMs,\n });\n }\n\n /** Evict a batch of oldest entries (10% of maxSize, minimum 1). */\n private evictOldest(): void {\n const batchSize = Math.max(1, Math.floor(this.maxSize * 0.1));\n const keys = this.cache.keys();\n for (let i = 0; i < batchSize; i++) {\n const next = keys.next();\n if (next.done === true) break;\n this.cache.delete(next.value);\n }\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n get size(): number {\n return this.cache.size;\n }\n}\n\n// ============================================================================\n// Suspicious Signal Detection\n// ============================================================================\n\n/** Only hostile-tier injection flags count — benign flags like\n * instruction_pattern (\"please remove\") must not trip the injection signal. */\nconst HOSTILE_INJECTION_FLAGS: readonly InjectionFlag[] = [\n 'system_prompt_manipulation',\n 'fake_conversation',\n 'authority_claim',\n 'hidden_content',\n];\n\nfunction hasHostileInjection(flags: readonly InjectionFlag[]): boolean {\n return flags.some((f) => HOSTILE_INJECTION_FLAGS.includes(f));\n}\n\n/** Rapid-comment burst — only when both count and window are known (#3106). */\nfunction isRapidCommenting(m: GitHubUserMetadata): boolean {\n return (\n m.recentCommentCount !== undefined &&\n m.recentCommentWindowMinutes !== undefined &&\n m.recentCommentCount > SUSPICIOUS_THRESHOLDS.rapidCommentThreshold &&\n m.recentCommentWindowMinutes <= SUSPICIOUS_THRESHOLDS.rapidCommentWindowMinutes\n );\n}\n\n/** Authority claim from a non-maintainer role. */\nfunction isMismatchedAuthority(m: GitHubUserMetadata): boolean {\n if (!m.injectionFlags.includes('authority_claim')) return false;\n const association = m.authorAssociation.toUpperCase();\n return association !== 'OWNER' && association !== 'MEMBER';\n}\n\n/** Detect all suspicious signals from user metadata. #3106: account/activity\n * signals are skipped when their data is absent — never fabricated. */\nfunction detectSuspiciousSignals(metadata: GitHubUserMetadata): SuspiciousSignal[] {\n const signals: SuspiciousSignal[] = [];\n const { accountAgeDays, priorContributions } = metadata;\n\n if (accountAgeDays !== undefined && accountAgeDays < SUSPICIOUS_THRESHOLDS.newAccountDays) {\n signals.push('new_account');\n }\n if (\n priorContributions !== undefined &&\n priorContributions < SUSPICIOUS_THRESHOLDS.minContributions\n ) {\n signals.push('no_prior_contributions');\n }\n if (hasHostileInjection(metadata.injectionFlags)) signals.push('injection_patterns_detected');\n if (isRapidCommenting(metadata)) signals.push('rapid_comments');\n if (isMismatchedAuthority(metadata)) signals.push('mismatched_authority_claim');\n\n return signals;\n}\n\n/** Calculate a 0-100 reputation score. */\nfunction calculateReputationScore(\n metadata: GitHubUserMetadata,\n signals: readonly SuspiciousSignal[],\n userRole: GitHubUserRole\n): number {\n let score = 50; // baseline\n\n // Role bonus\n const roleBonus: Record<GitHubUserRole, number> = {\n owner: 40,\n maintainer: 35,\n collaborator: 25,\n contributor: 15,\n member: 5,\n unknown: 0,\n };\n score += roleBonus[userRole];\n\n // Account age bonus (max +10). #3106: absent → no bonus (avoid NaN; an\n // unknown account neither earns nor loses the age bonus).\n if (metadata.accountAgeDays !== undefined) {\n score += Math.min(metadata.accountAgeDays / DAYS_PER_YEAR_APPROX, 10);\n }\n\n // Contribution bonus (max +10). #3106: absent → no bonus.\n if (metadata.priorContributions !== undefined) {\n score += Math.min(metadata.priorContributions, 10);\n }\n\n // Suspicious signal penalties\n const signalPenalty: Record<SuspiciousSignal, number> = {\n new_account: -15,\n no_prior_contributions: -10,\n injection_patterns_detected: -25,\n rapid_comments: -20,\n mismatched_authority_claim: -30,\n };\n for (const signal of signals) {\n score += signalPenalty[signal];\n }\n\n return Math.max(0, Math.min(100, Math.round(score)));\n}\n\n/** Map role string to GitHubUserRole. */\nfunction mapRole(association: string): GitHubUserRole {\n switch (association.toUpperCase()) {\n case 'OWNER':\n return 'owner';\n case 'MEMBER':\n return 'member';\n case 'COLLABORATOR':\n return 'collaborator';\n case 'CONTRIBUTOR':\n return 'contributor';\n default:\n return 'unknown';\n }\n}\n\n/** Determine effective trust tier from signals and role. */\nfunction determineEffectiveTier(\n userRole: GitHubUserRole,\n signals: readonly SuspiciousSignal[]\n): TrustTier {\n const baseTier = ROLE_DEFAULT_TRUST[userRole];\n\n // Hostile signals → Tier 4\n const hostileSignals: SuspiciousSignal[] = [\n 'injection_patterns_detected',\n 'mismatched_authority_claim',\n ];\n if (signals.some((s) => hostileSignals.includes(s))) return '4';\n\n // Multiple suspicious signals → downgrade by 1, CLAMPED AT TIER 3 (#4681).\n //\n // Tier 4 is the HOSTILE tier — `.rules/untrusted-input.md` defines it as\n // \"injection patterns, hidden HTML, instruction-like content\". It is reached\n // ONLY via `hostileSignals` above. The generic downgrade must not manufacture\n // it, because the two most common signals (`new_account` and\n // `no_prior_contributions`) BOTH fire automatically for any genuine\n // first-time reporter — they are two readings of one fact, not independent\n // evidence of hostility. Clamping at 4 meant an `unknown` author (base 3)\n // filing an ordinary bug report was classified hostile; once enforce mode\n // became the default (#4675) that refused every new account's first issue\n // and escalated it to security.\n //\n // Tier 3 is the correct destination: \"untrusted\" — still processed, but\n // never treated as instructions.\n if (signals.length >= 2) {\n const baseNumeric = TRUST_TIER_NUMERIC[baseTier];\n const downgraded = Math.min(baseNumeric + 1, 3);\n return String(downgraded) as TrustTier;\n }\n\n return baseTier;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Assess a GitHub user's reputation for trust classification.\n *\n * @param metadata - User metadata from GitHub API or local context.\n * @param cache - Optional cache instance for TTL-based deduplication.\n * @returns ReputationAssessment with trust tier and suspicious signals.\n */\nexport function assessReputation(\n metadata: GitHubUserMetadata,\n cache?: ReputationCache\n): ReputationAssessment {\n // Check cache first\n const cached = cache?.get(metadata.username);\n if (cached !== undefined) return cached;\n\n const userRole = mapRole(metadata.authorAssociation);\n const signals = detectSuspiciousSignals(metadata);\n const score = calculateReputationScore(metadata, signals, userRole);\n const effectiveTier = determineEffectiveTier(userRole, signals);\n\n const assessment: ReputationAssessment = {\n username: metadata.username,\n userRole,\n coverage: {\n activity:\n metadata.priorContributions !== undefined &&\n metadata.recentCommentCount !== undefined &&\n metadata.recentCommentWindowMinutes !== undefined\n ? 'measured'\n : 'unmeasured',\n },\n suspiciousSignals: signals,\n isSuspicious: signals.length > 0,\n effectiveTrustTier: effectiveTier,\n reputationScore: score,\n reason: buildReason(userRole, signals, effectiveTier),\n assessedAt: new Date().toISOString(),\n };\n\n cache?.set(metadata.username, assessment);\n return assessment;\n}\n\n/**\n * Reconcile a trust-classifier tier with a reputation assessment into the\n * effective tier to enforce (#3119 / epic #3118). Demotion-only — reputation\n * can only RAISE the tier number (more restrictive), never lower it.\n *\n * Invariants:\n * - **Allowlist/Tier-1 wins**: a classifier Tier 1 (owner/allowlisted maintainer)\n * is authoritative — reputation never demotes it.\n * - **Absent reputation → classifier tier**: no assessment (stage off / not\n * fetched) keeps the classifier/role-default tier — never fabricate a benign\n * tier, never escalate on mere absence (fetch-failure ≠ hostile signal).\n * - **Score is advisory**: only `effectiveTrustTier` participates; the 0–100\n * `reputationScore` never moves the gate.\n */\nexport function reconcileTrustTier(\n classifierTier: TrustTier,\n reputation: ReputationAssessment | undefined\n): TrustTier {\n if (classifierTier === '1') return '1';\n const repTier = reputation?.effectiveTrustTier;\n if (repTier === undefined) return classifierTier;\n return TRUST_TIER_NUMERIC[repTier] > TRUST_TIER_NUMERIC[classifierTier]\n ? repTier\n : classifierTier;\n}\n\n// ============================================================================\n// Reputation gating rollout (#3122 / epic #3118 Phase 4)\n// ============================================================================\n\n/**\n * Rollout mode for reputation-based tier gating, the same `off`/`audit`/\n * `enforce` shape as `NEXUS_FIREWALL_POLICY`: `off` (no reputation effect), `audit`\n * (compute + report the would-be demotion but enforce the classifier tier), or\n * `enforce` (apply the demotion). Default `enforce` since #4667 — see\n * {@link DEFAULT_REPUTATION_GATING_MODE} for the measurement that justified the\n * flip. (This block previously still described the pre-flip `audit` default.)\n */\nexport const ReputationGatingModeSchema = z.enum(['off', 'audit', 'enforce']);\nexport type ReputationGatingMode = z.infer<typeof ReputationGatingModeSchema>;\n\n/**\n * Default gating mode.\n *\n * Flipped `audit` → `enforce` in #4667. `audit` computed the demotion, logged\n * \"would block under enforce\", and let the actions through — so a detected\n * prompt injection changed nothing in the shipped configuration.\n *\n * Measured before flipping, over the real triage path with only the SCM\n * provider mocked: 5/5 hostile inputs blocked, 0 false positives across five\n * real repository issues (as OWNER and as an unaffiliated author), and 0 across\n * ordinary maintainer language (\"please close this\", \"URGENT\", \"you should\n * merge #88 first\"). The one synthetic false-positive class is a body quoting\n * an injection payload verbatim, which is arguably correct fail-closed\n * behaviour for a security report — and is now visible, because a tier-4\n * outcome emits a `RefuseAction` rather than silently approving less.\n *\n * `NEXUS_REPUTATION_GATING=audit` remains available to roll back.\n */\nexport const DEFAULT_REPUTATION_GATING_MODE: ReputationGatingMode = 'enforce';\n\n/**\n * Resolve the gating mode from the environment (invalid → default + warn, never\n * throws — #3130). Delegates to the shared `resolveEnvMode` so this flag and\n * `NEXUS_FIREWALL_POLICY` coerce identically.\n */\nexport function resolveReputationGatingMode(\n env: NodeJS.ProcessEnv = process.env\n): ReputationGatingMode {\n return resolveEnvMode(\n env['NEXUS_REPUTATION_GATING'],\n ReputationGatingModeSchema,\n DEFAULT_REPUTATION_GATING_MODE,\n 'NEXUS_REPUTATION_GATING'\n );\n}\n\n/** Outcome of applying the gating mode to a reputation assessment. */\nexport interface ReputationGateDecision {\n /** Tier to actually enforce at the policy gate. */\n readonly enforcedTier: TrustTier;\n /** Tier reputation reconciliation computed (what `enforce` mode WOULD use). */\n readonly reconciledTier: TrustTier;\n /** True when reputation would demote but the mode (off/audit) did not enforce it. */\n readonly demotionSuppressed: boolean;\n readonly mode: ReputationGatingMode;\n}\n\n/**\n * Apply the rollout mode to a reputation assessment (#3122). `enforce` gates on\n * the reconciled (possibly demoted) tier; `audit`/`off` gate on the classifier\n * tier but report whether a demotion was suppressed (for telemetry). The\n * Tier-1/allowlist-wins and demotion-only invariants live in `reconcileTrustTier`,\n * so the allowlist remains the escape hatch in every mode.\n */\nexport function gateWithReputation(\n classifierTier: TrustTier,\n reputation: ReputationAssessment | undefined,\n mode: ReputationGatingMode\n): ReputationGateDecision {\n const reconciledTier =\n mode === 'off' ? classifierTier : reconcileTrustTier(classifierTier, reputation);\n const enforcedTier = mode === 'enforce' ? reconciledTier : classifierTier;\n return {\n enforcedTier,\n reconciledTier,\n demotionSuppressed: mode !== 'enforce' && reconciledTier !== classifierTier,\n mode,\n };\n}\n\n/** Build a human-readable reason string. */\nfunction buildReason(\n role: GitHubUserRole,\n signals: readonly SuspiciousSignal[],\n tier: TrustTier\n): string {\n if (signals.length === 0) {\n return `Role ${role} → Tier ${tier} (no suspicious signals)`;\n }\n const signalList = signals.join(', ');\n return `Role ${role} → Tier ${tier} (signals: ${signalList})`;\n}\n","/**\n * Shared resolver for `off`/`audit`/`enforce`-style security-mode env vars\n * (#3130). `resolveReputationGatingMode` (reputation gating, #3122) and\n * `resolveFirewallPolicyMode` (#5382) parse an enum env var, coerce an invalid\n * value to a safe default, and must NEVER throw — a security layer must not\n * fail-closed on a misconfiguration at startup. (`resolveAccessPolicyMode`,\n * the original second caller, went with the access-constraint deriver in\n * #5108.)\n *\n * Previously the coercion was silent: a typo'd `enforce` (`enfroce`) degraded\n * to the default with no signal. This helper keeps the never-throw coercion but\n * emits a one-line `warn` so the misconfiguration is observable, and guarantees\n * both flags behave identically.\n *\n * @module security/env-mode\n */\n\nimport type { ZodType } from 'zod';\nimport { createLogger } from '../core/index.js';\nimport type { ILogger } from '../core/index.js';\n\nconst defaultLogger = createLogger({ component: 'env-mode' });\n\n/**\n * Resolve an enum-valued env var to one of its allowed values, coercing an\n * invalid/typo'd value rather than throwing. Unset or empty → `fallback`\n * silently (absence is normal, not a misconfiguration). A non-empty value that\n * fails to parse → `invalidFallback` (default: `fallback`) plus a `warn`, since\n * an explicit-but-invalid value is an operator error worth surfacing. Never\n * throws.\n *\n * @param raw The raw env value (e.g. `process.env['NEXUS_X']`).\n * @param schema Zod enum schema for the allowed values.\n * @param fallback Returned when `raw` is absent or empty.\n * @param varName Env var name, for the warning message.\n * @param options `logger` (injectable for tests) and `invalidFallback` (the\n * mode an explicit-but-invalid value lands on; defaults to\n * `fallback`). See the inline docs on the parameter.\n */\nexport function resolveEnvMode<T extends string>(\n raw: string | undefined,\n schema: ZodType<T>,\n fallback: T,\n varName: string,\n options: {\n /** Injectable for testing; defaults to the module logger. */\n readonly logger?: ILogger;\n /**\n * The mode an explicit-but-UNPARSEABLE value lands on. Defaults to\n * `fallback`, so a caller that does not pass it is byte-identical to the\n * previous behaviour.\n *\n * It exists because `fallback` answers two different questions with one\n * value: what absence means, and what a typo means. For a flag whose unset\n * default is the permissive end those answers should differ —\n * `NEXUS_FIREWALL_POLICY=enfroce` used to resolve to `off`, so an operator\n * who explicitly asked for enforcement got a gate that refuses nothing\n * (refines #3130; ratified by a 7-voter panel at the supermajority bar,\n * 5 of 6 approvers — rationale in the changeset).\n *\n * Constrained deliberately: typed as the same `T` as `fallback`, so it can\n * only select among the flag's own modes and can never introduce a fourth\n * behaviour. It must never be MORE permissive than `fallback` — a typo may\n * tighten the gate, never loosen it. A caller whose unset default is\n * already the strictest mode (e.g. `NEXUS_REPUTATION_GATING`, which\n * defaults to `enforce`) has nothing to correct and should not pass it.\n *\n * Declared inline rather than as an exported interface: no caller needs the\n * name (they pass object literals), and exporting it would add a symbol\n * with no cross-file consumer, which the #3024 gate correctly rejects.\n */\n readonly invalidFallback?: T;\n } = {}\n): T {\n const { logger = defaultLogger, invalidFallback } = options;\n if (typeof raw !== 'string' || raw.length === 0) return fallback;\n const parsed = schema.safeParse(raw.toLowerCase());\n if (parsed.success) return parsed.data;\n const applied = invalidFallback ?? fallback;\n // Name the mode actually applied, not just \"the default\": when `applied`\n // differs from `fallback` a log line saying \"coercing to default\" would\n // describe a value the process did not use.\n logger.warn(`Invalid ${varName} value — coercing to ${applied}`, {\n raw,\n default: fallback,\n applied,\n });\n return applied;\n}\n"],"mappings":";;;;;;;;;;;;;;AAiCA,IAAM,yBACJ;AASF,IAAM,wBACJ;AAMF,IAAM,uBAAuB;AAW7B,IAAM,qBAA8C;AAA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AAK,CAAC,OAAO,SAAS,SAAS,CAAC;AAqBrE,IAAM,iCAAuD;AAO7D,SAAS,4BACd,MAAyB,QAAQ,KACX;AACtB,SAAO;AAAA,IACL,IAAI,yBAAyB;AAAA,IAC7B;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAoBO,SAAS,mBACd,gBACA,YACA,MACwB;AACxB,QAAM,iBACJ,SAAS,QAAQ,iBAAiB,mBAAmB,gBAAgB,UAAU;AACjF,QAAM,eAAe,SAAS,YAAY,iBAAiB;AAC3D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,oBAAoB,SAAS,aAAa,mBAAmB;AAAA,IAC7D;AAAA,EACF;AACF;AAGA,SAAS,YACP,MACA,SACA,MACQ;AACR,MAAI,QAAQ,WAAW,GAAG;AACxB,WAAO,QAAQ,IAAI,gBAAW,IAAI;AAAA,EACpC;AACA,QAAM,aAAa,QAAQ,KAAK,IAAI;AACpC,SAAO,QAAQ,IAAI,gBAAW,IAAI,cAAc,UAAU;AAC5D;","names":[]}
@@ -4,10 +4,10 @@ import {
4
4
  loadPapersRegistry,
5
5
  loadTechniquesRegistry,
6
6
  savePapersRegistry
7
- } from "./chunk-JDL5WJDM.js";
7
+ } from "./chunk-BCC27PGX.js";
8
8
  import {
9
9
  resolveToken
10
- } from "./chunk-KCESFTXP.js";
10
+ } from "./chunk-N5DHPHPE.js";
11
11
  import {
12
12
  getTsMorph
13
13
  } from "./chunk-W654ME6B.js";
@@ -18,7 +18,7 @@ import {
18
18
  rankedItemTrustTier,
19
19
  trustTierLabel,
20
20
  withoutUntrustedMemory
21
- } from "./chunk-6RP53JXS.js";
21
+ } from "./chunk-Y3A3VVGT.js";
22
22
  import {
23
23
  extractSystemPrompt,
24
24
  generateCacheKey,
@@ -41,7 +41,7 @@ import {
41
41
  sigmoidConfidence,
42
42
  tokenizeFiltered,
43
43
  truncateSentence
44
- } from "./chunk-M7JXKUFB.js";
44
+ } from "./chunk-WM2BE65D.js";
45
45
  import {
46
46
  ensureLearningDir,
47
47
  getRulesFile
@@ -4296,4 +4296,4 @@ export {
4296
4296
  DEFAULT_CONTEXT_BUDGET_TOKENS,
4297
4297
  getContextPromptPrefix
4298
4298
  };
4299
- //# sourceMappingURL=chunk-YZXCE5BB.js.map
4299
+ //# sourceMappingURL=chunk-AH4Y7Z6S.js.map
@@ -5,7 +5,7 @@ import {
5
5
  getErrorMessage,
6
6
  ok,
7
7
  resolveInsideRoot
8
- } from "./chunk-M7JXKUFB.js";
8
+ } from "./chunk-WM2BE65D.js";
9
9
  import {
10
10
  createLogger
11
11
  } from "./chunk-GR6WCJWY.js";
@@ -213,4 +213,4 @@ export {
213
213
  loadPapersRegistry,
214
214
  savePapersRegistry
215
215
  };
216
- //# sourceMappingURL=chunk-JDL5WJDM.js.map
216
+ //# sourceMappingURL=chunk-BCC27PGX.js.map
@@ -8,10 +8,10 @@ import {
8
8
  discoverGatewayCatalog,
9
9
  gatewayProxyUrl,
10
10
  readOpenAICompatEnv
11
- } from "./chunk-54UNI6GV.js";
11
+ } from "./chunk-WSLPF7BX.js";
12
12
  import {
13
13
  redactGatewaySecrets
14
- } from "./chunk-MPYHD4EV.js";
14
+ } from "./chunk-6MOCJOKU.js";
15
15
  import {
16
16
  DEFAULT_OPENAI_COMPAT_ENDPOINT,
17
17
  GATEWAY_COST_ENV,
@@ -28,7 +28,7 @@ import {
28
28
  isCliDisabled,
29
29
  symbols,
30
30
  writeLine
31
- } from "./chunk-M7JXKUFB.js";
31
+ } from "./chunk-WM2BE65D.js";
32
32
  import {
33
33
  getTimeProvider
34
34
  } from "./chunk-GR6WCJWY.js";
@@ -384,4 +384,4 @@ export {
384
384
  formatGatewayReport,
385
385
  formatGatewaySlotWarnings
386
386
  };
387
- //# sourceMappingURL=chunk-BPO2LQ67.js.map
387
+ //# sourceMappingURL=chunk-BGELNT5F.js.map
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  IN_FAMILY_FALLBACK_OPTION
3
- } from "./chunk-RGDZIWGS.js";
3
+ } from "./chunk-VMGKPEVR.js";
4
4
  import {
5
5
  sanitizeErrorDetails
6
6
  } from "./chunk-7LKX7AUQ.js";
7
7
  import {
8
8
  classifyExtractedError,
9
9
  isTimeoutText
10
- } from "./chunk-M7JXKUFB.js";
10
+ } from "./chunk-WM2BE65D.js";
11
11
  import {
12
12
  getTimeProvider
13
13
  } from "./chunk-GR6WCJWY.js";
@@ -158,4 +158,4 @@ export {
158
158
  SERVES_PROBE_PROMPT,
159
159
  probeServes
160
160
  };
161
- //# sourceMappingURL=chunk-5CSM473L.js.map
161
+ //# sourceMappingURL=chunk-DFRQP7AM.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  loadPapersRegistry
3
- } from "./chunk-JDL5WJDM.js";
3
+ } from "./chunk-BCC27PGX.js";
4
4
  import {
5
5
  getErrorMessage
6
- } from "./chunk-M7JXKUFB.js";
6
+ } from "./chunk-WM2BE65D.js";
7
7
 
8
8
  // src/cli/research-helpers-synthesize.ts
9
9
  import { z } from "zod";
@@ -876,4 +876,4 @@ export {
876
876
  AttributedInsightSchema,
877
877
  synthesizeResearch
878
878
  };
879
- //# sourceMappingURL=chunk-UMLKKXBD.js.map
879
+ //# sourceMappingURL=chunk-FGR6O454.js.map
@@ -5,7 +5,7 @@ import {
5
5
  err,
6
6
  getErrorMessage,
7
7
  ok
8
- } from "./chunk-M7JXKUFB.js";
8
+ } from "./chunk-WM2BE65D.js";
9
9
  import {
10
10
  createLogger,
11
11
  getTimeProvider
@@ -376,4 +376,4 @@ export {
376
376
  SessionMemory,
377
377
  createSessionMemory
378
378
  };
379
- //# sourceMappingURL=chunk-CVOE6Q56.js.map
379
+ //# sourceMappingURL=chunk-FQFCLNYM.js.map
@@ -3,7 +3,7 @@ import {
3
3
  ValidationError,
4
4
  formatZodError,
5
5
  resolveInsideRoot
6
- } from "./chunk-M7JXKUFB.js";
6
+ } from "./chunk-WM2BE65D.js";
7
7
  import {
8
8
  createLogger
9
9
  } from "./chunk-GR6WCJWY.js";
@@ -249,4 +249,4 @@ export {
249
249
  collectAstQaFindings,
250
250
  runAstQaRules
251
251
  };
252
- //# sourceMappingURL=chunk-EOIUMPFK.js.map
252
+ //# sourceMappingURL=chunk-FYXIWH62.js.map