nexus-agents 8.41.1 → 8.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/{chunk-RT5GERSE.js → chunk-3LLTMGAU.js} +3 -3
  2. package/dist/{chunk-FT5ISHQZ.js → chunk-5HOMEIBV.js} +3 -3
  3. package/dist/{chunk-4CLPPSYW.js → chunk-6X6CJFL5.js} +2 -2
  4. package/dist/{chunk-NPBPUOPX.js → chunk-CGUFF47H.js} +2 -2
  5. package/dist/{chunk-RZ5YSYCB.js → chunk-FQUSU2QZ.js} +2 -2
  6. package/dist/{chunk-W2PU5DWN.js → chunk-HVQJRRZV.js} +2 -2
  7. package/dist/{chunk-LHR7WWWE.js → chunk-UOR2YWRA.js} +2 -2
  8. package/dist/{chunk-RT2MFYQC.js → chunk-WFW4LX3N.js} +10 -10
  9. package/dist/{chunk-KRD3OF3M.js → chunk-XJ33UMUQ.js} +24 -4
  10. package/dist/chunk-XJ33UMUQ.js.map +1 -0
  11. package/dist/cli.js +11 -11
  12. package/dist/{consensus-vote-Z7DN7TTD.js → consensus-vote-CHT7XUMY.js} +4 -4
  13. package/dist/{improvement-review-FHFPRZYL.js → improvement-review-SDXZS3GY.js} +4 -4
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.js +8 -8
  16. package/dist/{issue-triage-RL6AMSBZ.js → issue-triage-JEYSHESO.js} +3 -3
  17. package/dist/{pr-reviewer-helpers-FLBM5I6M.js → pr-reviewer-helpers-4RAI27NR.js} +3 -3
  18. package/dist/{setup-data-dir-YCSXZZBD.js → setup-data-dir-7D4PZTP2.js} +3 -3
  19. package/package.json +1 -1
  20. package/dist/chunk-KRD3OF3M.js.map +0 -1
  21. /package/dist/{chunk-RT5GERSE.js.map → chunk-3LLTMGAU.js.map} +0 -0
  22. /package/dist/{chunk-FT5ISHQZ.js.map → chunk-5HOMEIBV.js.map} +0 -0
  23. /package/dist/{chunk-4CLPPSYW.js.map → chunk-6X6CJFL5.js.map} +0 -0
  24. /package/dist/{chunk-NPBPUOPX.js.map → chunk-CGUFF47H.js.map} +0 -0
  25. /package/dist/{chunk-RZ5YSYCB.js.map → chunk-FQUSU2QZ.js.map} +0 -0
  26. /package/dist/{chunk-W2PU5DWN.js.map → chunk-HVQJRRZV.js.map} +0 -0
  27. /package/dist/{chunk-LHR7WWWE.js.map → chunk-UOR2YWRA.js.map} +0 -0
  28. /package/dist/{chunk-RT2MFYQC.js.map → chunk-WFW4LX3N.js.map} +0 -0
  29. /package/dist/{consensus-vote-Z7DN7TTD.js.map → consensus-vote-CHT7XUMY.js.map} +0 -0
  30. /package/dist/{improvement-review-FHFPRZYL.js.map → improvement-review-SDXZS3GY.js.map} +0 -0
  31. /package/dist/{issue-triage-RL6AMSBZ.js.map → issue-triage-JEYSHESO.js.map} +0 -0
  32. /package/dist/{pr-reviewer-helpers-FLBM5I6M.js.map → pr-reviewer-helpers-4RAI27NR.js.map} +0 -0
  33. /package/dist/{setup-data-dir-YCSXZZBD.js.map → setup-data-dir-7D4PZTP2.js.map} +0 -0
@@ -23,10 +23,10 @@ import {
23
23
  toolSuccessStructured,
24
24
  withProgressHeartbeat,
25
25
  wrapToolWithTimeout
26
- } from "./chunk-LHR7WWWE.js";
26
+ } from "./chunk-UOR2YWRA.js";
27
27
  import {
28
28
  VERSION
29
- } from "./chunk-NPBPUOPX.js";
29
+ } from "./chunk-CGUFF47H.js";
30
30
  import {
31
31
  assessPanelIndependence,
32
32
  countDistinctModels,
@@ -7830,4 +7830,4 @@ export {
7830
7830
  CONSENSUS_VOTE_TOOL_SCHEMA,
7831
7831
  registerConsensusVoteTool
7832
7832
  };
7833
- //# sourceMappingURL=chunk-RT5GERSE.js.map
7833
+ //# sourceMappingURL=chunk-3LLTMGAU.js.map
@@ -8,7 +8,7 @@ import {
8
8
  NODE_ENGINE_RANGE,
9
9
  VERSION,
10
10
  isNodeVersionSupported
11
- } from "./chunk-NPBPUOPX.js";
11
+ } from "./chunk-CGUFF47H.js";
12
12
  import {
13
13
  capitalize
14
14
  } from "./chunk-7LP6VJRP.js";
@@ -1228,7 +1228,7 @@ async function runDoctorFix(result) {
1228
1228
  writeLine2("\u2500".repeat(40));
1229
1229
  let fixCount = 0;
1230
1230
  if (!result.dataDirectory.rootExists || result.dataDirectory.subdirectories.some((d) => !d.exists || !d.writable)) {
1231
- const { initDataDirectories: initDataDirectories2, describeDataDirFix: describeDataDirFix2 } = await import("./setup-data-dir-YCSXZZBD.js");
1231
+ const { initDataDirectories: initDataDirectories2, describeDataDirFix: describeDataDirFix2 } = await import("./setup-data-dir-7D4PZTP2.js");
1232
1232
  const outcome = describeDataDirFix2(initDataDirectories2());
1233
1233
  writeLine2(outcome.line);
1234
1234
  if (outcome.counted) fixCount++;
@@ -1330,4 +1330,4 @@ export {
1330
1330
  startStdioServer,
1331
1331
  closeServer
1332
1332
  };
1333
- //# sourceMappingURL=chunk-FT5ISHQZ.js.map
1333
+ //# sourceMappingURL=chunk-5HOMEIBV.js.map
@@ -10,7 +10,7 @@ import {
10
10
  import {
11
11
  assessReputation,
12
12
  sanitizeInput
13
- } from "./chunk-KRD3OF3M.js";
13
+ } from "./chunk-XJ33UMUQ.js";
14
14
  import {
15
15
  createLogger,
16
16
  err,
@@ -416,4 +416,4 @@ export {
416
416
  createFailedReview,
417
417
  reviewPostingBlock
418
418
  };
419
- //# sourceMappingURL=chunk-4CLPPSYW.js.map
419
+ //# sourceMappingURL=chunk-6X6CJFL5.js.map
@@ -1,6 +1,6 @@
1
1
  // src/version.ts
2
2
  import semver from "semver";
3
- var VERSION = true ? "8.41.1" : "dev";
3
+ var VERSION = true ? "8.42.0" : "dev";
4
4
  var NODE_ENGINE_RANGE = ">=22.5.0";
5
5
  function isNodeVersionSupported(version) {
6
6
  return semver.satisfies(version, NODE_ENGINE_RANGE);
@@ -11,4 +11,4 @@ export {
11
11
  NODE_ENGINE_RANGE,
12
12
  isNodeVersionSupported
13
13
  };
14
- //# sourceMappingURL=chunk-NPBPUOPX.js.map
14
+ //# sourceMappingURL=chunk-CGUFF47H.js.map
@@ -12,7 +12,7 @@ import {
12
12
  resolveEnvMode,
13
13
  resolveReputationGatingMode,
14
14
  sanitizeInput
15
- } from "./chunk-KRD3OF3M.js";
15
+ } from "./chunk-XJ33UMUQ.js";
16
16
  import {
17
17
  MAX_STRIPPED_ELEMENTS_PER_EVENT,
18
18
  createAuditTrail,
@@ -2162,4 +2162,4 @@ export {
2162
2162
  IssueTriage,
2163
2163
  createIssueTriage
2164
2164
  };
2165
- //# sourceMappingURL=chunk-RZ5YSYCB.js.map
2165
+ //# sourceMappingURL=chunk-FQUSU2QZ.js.map
@@ -7,7 +7,7 @@ import {
7
7
  toolStructuredError,
8
8
  toolSuccessStructured,
9
9
  wrapToolWithTimeout
10
- } from "./chunk-LHR7WWWE.js";
10
+ } from "./chunk-UOR2YWRA.js";
11
11
  import {
12
12
  JsonlStore,
13
13
  SECURITY_KEYWORDS,
@@ -2173,4 +2173,4 @@ export {
2173
2173
  runImprovementReview,
2174
2174
  registerImprovementReviewTool
2175
2175
  };
2176
- //# sourceMappingURL=chunk-W2PU5DWN.js.map
2176
+ //# sourceMappingURL=chunk-HVQJRRZV.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  VERSION
3
- } from "./chunk-NPBPUOPX.js";
3
+ } from "./chunk-CGUFF47H.js";
4
4
  import {
5
5
  emitClawGuardViolation
6
6
  } from "./chunk-SCIVDNY5.js";
@@ -2306,4 +2306,4 @@ export {
2306
2306
  VOTING_THRESHOLDS,
2307
2307
  ConsensusMetricsSchema
2308
2308
  };
2309
- //# sourceMappingURL=chunk-LHR7WWWE.js.map
2309
+ //# sourceMappingURL=chunk-UOR2YWRA.js.map
@@ -21,7 +21,7 @@ import {
21
21
  import {
22
22
  DEFAULT_TASK_TTL_MS,
23
23
  clampTaskTtl
24
- } from "./chunk-FT5ISHQZ.js";
24
+ } from "./chunk-5HOMEIBV.js";
25
25
  import {
26
26
  executeExpert
27
27
  } from "./chunk-WBU27C3E.js";
@@ -55,7 +55,7 @@ import {
55
55
  toJobSummary,
56
56
  updateStage,
57
57
  writeJobCancelled
58
- } from "./chunk-RT5GERSE.js";
58
+ } from "./chunk-3LLTMGAU.js";
59
59
  import {
60
60
  allOf,
61
61
  anyOf
@@ -68,14 +68,14 @@ import {
68
68
  IssueTriage,
69
69
  createDurableAuditSink,
70
70
  createDurableAuditTrail
71
- } from "./chunk-RZ5YSYCB.js";
71
+ } from "./chunk-FQUSU2QZ.js";
72
72
  import {
73
73
  resolveEnvMode,
74
74
  sanitizeInput
75
- } from "./chunk-KRD3OF3M.js";
75
+ } from "./chunk-XJ33UMUQ.js";
76
76
  import {
77
77
  withPrerequisite
78
- } from "./chunk-W2PU5DWN.js";
78
+ } from "./chunk-HVQJRRZV.js";
79
79
  import {
80
80
  NOOP_NOTIFIER,
81
81
  RateLimiter,
@@ -100,7 +100,7 @@ import {
100
100
  withAuditTrail,
101
101
  withProgressHeartbeat,
102
102
  wrapToolWithTimeout
103
- } from "./chunk-LHR7WWWE.js";
103
+ } from "./chunk-UOR2YWRA.js";
104
104
  import {
105
105
  createAuditTrail,
106
106
  createGraphAuditBridge,
@@ -45533,7 +45533,7 @@ async function tryIssueTriage(task) {
45533
45533
  try {
45534
45534
  const issueMatch = task.match(/github\.com\/([^/]+\/[^/]+)\/issues\/(\d+)/);
45535
45535
  if (issueMatch === null) return null;
45536
- const { createIssueTriage } = await import("./issue-triage-RL6AMSBZ.js");
45536
+ const { createIssueTriage } = await import("./issue-triage-JEYSHESO.js");
45537
45537
  const triage = createIssueTriage();
45538
45538
  const owner = issueMatch[1] ?? "";
45539
45539
  const num = issueMatch[2] ?? "";
@@ -45935,7 +45935,7 @@ function buildVotingInput(plan, config) {
45935
45935
  }
45936
45936
  async function executeSingleVote(plan, config, log) {
45937
45937
  try {
45938
- const { executeVoting } = await import("./consensus-vote-Z7DN7TTD.js");
45938
+ const { executeVoting } = await import("./consensus-vote-CHT7XUMY.js");
45939
45939
  const input = buildVotingInput(plan, config);
45940
45940
  const result = await executeVoting(input, log);
45941
45941
  return parseVotingResult(result);
@@ -47727,7 +47727,7 @@ ${contextBlock}`;
47727
47727
  const strategy = config.votingStrategy ?? "higher_order";
47728
47728
  await postProgress(config, "Vote", `Running consensus with ${strategy} strategy...`);
47729
47729
  try {
47730
- const { executeVoting } = await import("./consensus-vote-Z7DN7TTD.js");
47730
+ const { executeVoting } = await import("./consensus-vote-CHT7XUMY.js");
47731
47731
  const votingResult = await executeVoting(
47732
47732
  {
47733
47733
  proposal: buildVoteProposal(plan, research),
@@ -56408,4 +56408,4 @@ export {
56408
56408
  startPipelineEventBridge,
56409
56409
  shutdownPipelineEventBridge
56410
56410
  };
56411
- //# sourceMappingURL=chunk-RT2MFYQC.js.map
56411
+ //# sourceMappingURL=chunk-WFW4LX3N.js.map
@@ -79,6 +79,17 @@ var SanitizedInputSchema = z.object({
79
79
  truncated: z.boolean().optional(),
80
80
  /** Whether any dangerous content was detected and stripped. */
81
81
  wasModified: z.boolean(),
82
+ /**
83
+ * True when a strip loop exhausted its pass budget with its own pattern still
84
+ * matching — i.e. `content` still carries markup the sanitizer removes.
85
+ *
86
+ * Absent on records that predate this field, and absent means converged, so
87
+ * no existing record changes meaning. Treat `true` as "do not hand this to a
88
+ * model": `wasModified` is `true` and `strippedElements.length` is at the cap
89
+ * in BOTH the converged and the unconverged case, so nothing else separated
90
+ * them. Mirrors `sanitizationIncomplete` on the MCP-layer sanitizer (#5788).
91
+ */
92
+ sanitizationIncomplete: z.boolean().optional(),
82
93
  /** Timestamp of sanitization (ISO 8601). */
83
94
  sanitizedAt: z.iso.datetime()
84
95
  });
@@ -197,7 +208,8 @@ function stripDangerousHtml(content) {
197
208
  return "";
198
209
  });
199
210
  }
200
- return { cleaned, stripped };
211
+ DANGEROUS_HTML_PATTERN.lastIndex = 0;
212
+ return { cleaned, stripped, incomplete: DANGEROUS_HTML_PATTERN.test(cleaned) };
201
213
  }
202
214
  function stripXmlTags(content) {
203
215
  const stripped = [];
@@ -216,7 +228,8 @@ function stripXmlTags(content) {
216
228
  return "";
217
229
  });
218
230
  }
219
- return { cleaned, stripped };
231
+ XML_INJECTION_PATTERN.lastIndex = 0;
232
+ return { cleaned, stripped, incomplete: XML_INJECTION_PATTERN.test(cleaned) };
220
233
  }
221
234
  function stripHtmlComments(content) {
222
235
  const stripped = [];
@@ -304,7 +317,12 @@ function sanitizeInput(content, userRole, username, config) {
304
317
  ...xml.stripped,
305
318
  ...comments.stripped
306
319
  ];
307
- const injectionFlags = detectInjectionPatterns(truncatedContent);
320
+ const injectionFlags = [
321
+ .../* @__PURE__ */ new Set([
322
+ ...detectInjectionPatterns(truncatedContent),
323
+ ...detectInjectionPatterns(comments.cleaned)
324
+ ])
325
+ ];
308
326
  const trustTier = assignTrustTier(userRole, injectionFlags, allowlisted);
309
327
  return {
310
328
  content: comments.cleaned,
@@ -313,6 +331,8 @@ function sanitizeInput(content, userRole, username, config) {
313
331
  contentTierMeasured: true,
314
332
  userRole,
315
333
  injectionFlags,
334
+ // Omitted when every loop converged, so no existing record changes shape.
335
+ ...html.incomplete || xml.incomplete ? { sanitizationIncomplete: true } : {},
316
336
  strippedElements: allStripped,
317
337
  truncated,
318
338
  wasModified: truncated || allStripped.length > 0,
@@ -590,4 +610,4 @@ export {
590
610
  resolveReputationGatingMode,
591
611
  gateWithReputation
592
612
  };
593
- //# sourceMappingURL=chunk-KRD3OF3M.js.map
613
+ //# sourceMappingURL=chunk-XJ33UMUQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/security/trust-types.ts","../src/security/input-sanitizer.ts","../src/security/reputation-model.ts","../src/security/env-mode.ts"],"sourcesContent":["/**\n * nexus-agents/security - Trust Types\n *\n * Zod schemas and TypeScript types for the untrusted input hardening\n * framework. Defines trust tiers, sanitized input, user roles, and\n * injection detection flags.\n *\n * @module security/trust-types\n * (Source: Issue #818, #819 — Phase 1: Input Sanitization)\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Trust Tiers\n// ============================================================================\n\n/**\n * Trust tier classification for input sources.\n * Lower number = higher trust.\n *\n * 1 = Authoritative (repo files, CI, CLAUDE.md, allowlisted maintainers)\n * 2 = Semi-trusted (collaborator issue body, contributor PR metadata)\n * 3 = Untrusted (unknown user comments, non-collaborator issue body)\n * 4 = Hostile (injection patterns, hidden HTML, instruction-like content)\n */\nexport const TrustTierSchema = z.enum(['1', '2', '3', '4']);\nexport type TrustTier = z.infer<typeof TrustTierSchema>;\n\n/** Numeric trust tier for comparisons. Higher number = lower trust. */\nexport const TRUST_TIER_NUMERIC: Record<TrustTier, number> = {\n '1': 1,\n '2': 2,\n '3': 3,\n '4': 4,\n};\n\n// ============================================================================\n// GitHub User Roles\n// ============================================================================\n\n/**\n * GitHub user relationship to the repository.\n */\nexport const GitHubUserRoleSchema = z.enum([\n 'owner',\n 'maintainer',\n 'collaborator',\n 'contributor',\n 'member',\n 'unknown',\n]);\nexport type GitHubUserRole = z.infer<typeof GitHubUserRoleSchema>;\n\n/**\n * Default trust tier mapping for each GitHub role.\n * Can be overridden by injection pattern detection (downgrade only).\n */\nexport const ROLE_DEFAULT_TRUST: Record<GitHubUserRole, TrustTier> = {\n owner: '1',\n maintainer: '1',\n collaborator: '2',\n contributor: '2',\n member: '3',\n unknown: '3',\n};\n\n// ============================================================================\n// Injection Detection\n// ============================================================================\n\n/**\n * Categories of injection patterns detected in content.\n */\nexport const InjectionFlagSchema = z.enum([\n 'authority_claim',\n 'instruction_pattern',\n 'system_prompt_manipulation',\n 'hidden_content',\n 'urgency_manipulation',\n 'fake_conversation',\n 'base64_encoded',\n 'external_link_instruction',\n]);\nexport type InjectionFlag = z.infer<typeof InjectionFlagSchema>;\n\n/**\n * An element stripped during sanitization, preserved for audit trail.\n */\nexport const StrippedElementSchema = z.object({\n /** Type of element stripped. */\n tag: z.string().min(1),\n /** Reason for stripping. */\n reason: z.string().min(1),\n /** Start index in original content. */\n startIndex: z.number().int().nonnegative(),\n /** Length of stripped content. */\n length: z.number().int().positive(),\n});\nexport type StrippedElement = z.infer<typeof StrippedElementSchema>;\n\n// ============================================================================\n// Sanitized Input\n// ============================================================================\n\n/**\n * The result of sanitizing untrusted input.\n * Contains cleaned content, trust classification, and audit data.\n */\nexport const SanitizedInputSchema = z.object({\n /** Sanitized content with dangerous elements removed. */\n content: z.string(),\n /** Original content before sanitization (for audit). */\n originalLength: z.number().int().nonnegative(),\n /**\n * Assigned trust tier based on user role and content analysis.\n *\n * Deprecation note: required today; a future major makes it absent when\n * unmeasured (see the next-major issue named in the changeset).\n */\n trustTier: TrustTierSchema,\n /**\n * True when `trustTier` is the sanitizer's measured content tier; false when\n * the sanitization stage was disabled and `trustTier` is only the\n * role-derived base tier. Absent on records that predate this field; an\n * absent value MUST be treated as measured so legacy content downgrades are\n * preserved fail-closed.\n */\n contentTierMeasured: z.boolean().optional(),\n /** GitHub user role of the input source. */\n userRole: GitHubUserRoleSchema,\n /** Injection patterns detected in content. */\n injectionFlags: z.array(InjectionFlagSchema),\n /** Elements stripped during sanitization (audit trail). */\n strippedElements: z.array(StrippedElementSchema),\n /** Whether content exceeded the configured limit. Absent on records that predate this field. */\n truncated: z.boolean().optional(),\n /** Whether any dangerous content was detected and stripped. */\n wasModified: z.boolean(),\n /**\n * True when a strip loop exhausted its pass budget with its own pattern still\n * matching — i.e. `content` still carries markup the sanitizer removes.\n *\n * Absent on records that predate this field, and absent means converged, so\n * no existing record changes meaning. Treat `true` as \"do not hand this to a\n * model\": `wasModified` is `true` and `strippedElements.length` is at the cap\n * in BOTH the converged and the unconverged case, so nothing else separated\n * them. Mirrors `sanitizationIncomplete` on the MCP-layer sanitizer (#5788).\n */\n sanitizationIncomplete: z.boolean().optional(),\n /** Timestamp of sanitization (ISO 8601). */\n sanitizedAt: z.iso.datetime(),\n});\nexport type SanitizedInput = z.infer<typeof SanitizedInputSchema>;\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Configuration for the input sanitizer.\n */\nexport const SanitizerConfigSchema = z.object({\n /** GitHub usernames that are always Tier 1 (allowlisted maintainers). */\n allowlistedMaintainers: z.array(z.string().min(1)).default([]),\n /** Whether to fail open (log only) or fail closed (block). Phase 1 = open. */\n failOpen: z.boolean().default(true),\n /** Maximum input length before truncation. */\n maxInputLength: z.number().int().positive().default(50_000),\n});\nexport type SanitizerConfig = z.infer<typeof SanitizerConfigSchema>;\n","/**\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 = /<!--[\\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 = /<!--[\\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, mirroring\n * `NEXUS_ACCESS_POLICY_MODE` (#1977): `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_ACCESS_POLICY_MODE` 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). Both `resolveAccessPolicyMode` (ClawGuard, #1977) and\n * `resolveReputationGatingMode` (reputation gating, #3122) parse an enum env\n * var, coerce an invalid value to a safe default, and must NEVER throw — a\n * security layer must not fail-closed on a misconfiguration at startup.\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":";;;;;;;AAWA,SAAS,SAAS;AAeX,IAAM,kBAAkB,EAAE,KAAK,CAAC,KAAK,KAAK,KAAK,GAAG,CAAC;AAInD,IAAM,qBAAgD;AAAA,EAC3D,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AASO,IAAM,uBAAuB,EAAE,KAAK;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOM,IAAM,qBAAwD;AAAA,EACnE,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,SAAS;AACX;AASO,IAAM,sBAAsB,EAAE,KAAK;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAMM,IAAM,wBAAwB,EAAE,OAAO;AAAA;AAAA,EAE5C,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAErB,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAExB,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAAA;AAAA,EAEzC,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AACpC,CAAC;AAWM,IAAM,uBAAuB,EAAE,OAAO;AAAA;AAAA,EAE3C,SAAS,EAAE,OAAO;AAAA;AAAA,EAElB,gBAAgB,EAAE,OAAO,EAAE,I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AiB;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":["z","z"]}
package/dist/cli.js CHANGED
@@ -23,7 +23,7 @@ import {
23
23
  parseExpertReview,
24
24
  reviewPostingBlock,
25
25
  sumFindings
26
- } from "./chunk-4CLPPSYW.js";
26
+ } from "./chunk-6X6CJFL5.js";
27
27
  import "./chunk-O6IUVD3H.js";
28
28
  import {
29
29
  runConfigInitSync
@@ -157,7 +157,7 @@ import {
157
157
  validateNexusEnv,
158
158
  validateWorkflow,
159
159
  wrapInMarkdownFence
160
- } from "./chunk-RT2MFYQC.js";
160
+ } from "./chunk-WFW4LX3N.js";
161
161
  import "./chunk-IVHR3QEK.js";
162
162
  import "./chunk-DGWT7DXX.js";
163
163
  import "./chunk-64GMIUM5.js";
@@ -177,7 +177,7 @@ import {
177
177
  doctorCommand,
178
178
  initDataDirectories,
179
179
  runDoctor
180
- } from "./chunk-FT5ISHQZ.js";
180
+ } from "./chunk-5HOMEIBV.js";
181
181
  import {
182
182
  buildOpenAICompatAdapters,
183
183
  readOpenAICompatEnv
@@ -196,7 +196,7 @@ import {
196
196
  recordAuthenticVote,
197
197
  registerConsensusVoteTool,
198
198
  toRecordDecision
199
- } from "./chunk-RT5GERSE.js";
199
+ } from "./chunk-3LLTMGAU.js";
200
200
  import {
201
201
  loadUsageEvents,
202
202
  rollupByModel
@@ -217,12 +217,12 @@ import {
217
217
  runUntrustedInputFirewall,
218
218
  validateAgentAction,
219
219
  validateCorroboration
220
- } from "./chunk-RZ5YSYCB.js";
220
+ } from "./chunk-FQUSU2QZ.js";
221
221
  import "./chunk-ZMPQVOAO.js";
222
222
  import {
223
223
  ReputationCache,
224
224
  sanitizeInput
225
- } from "./chunk-KRD3OF3M.js";
225
+ } from "./chunk-XJ33UMUQ.js";
226
226
  import {
227
227
  ImprovementReviewInputSchema,
228
228
  calculateFitnessScore,
@@ -236,18 +236,18 @@ import {
236
236
  registerImprovementReviewTool,
237
237
  runImprovementReview,
238
238
  scanForSecrets
239
- } from "./chunk-W2PU5DWN.js";
239
+ } from "./chunk-HVQJRRZV.js";
240
240
  import {
241
241
  createDefaultPolicyFirewall,
242
242
  setGlobalPolicyFirewall,
243
243
  setSecureHandlerAuditLogger,
244
244
  stagePolicyFirewallForRollout
245
- } from "./chunk-LHR7WWWE.js";
245
+ } from "./chunk-UOR2YWRA.js";
246
246
  import {
247
247
  NODE_ENGINE_RANGE,
248
248
  VERSION,
249
249
  isNodeVersionSupported
250
- } from "./chunk-NPBPUOPX.js";
250
+ } from "./chunk-CGUFF47H.js";
251
251
  import "./chunk-SCIVDNY5.js";
252
252
  import {
253
253
  createUnifiedRegistry,
@@ -4502,7 +4502,7 @@ Provide a structured review with:
4502
4502
  * (Source: Issue #828 — Wire policy gate into production pipeline)
4503
4503
  */
4504
4504
  async postReviewToGitHub(provider, pr, result, gateDecision) {
4505
- const { formatReviewComment: formatReviewComment2 } = await import("./pr-reviewer-helpers-FLBM5I6M.js");
4505
+ const { formatReviewComment: formatReviewComment2 } = await import("./pr-reviewer-helpers-4RAI27NR.js");
4506
4506
  const formattedBody = formatReviewComment2(result);
4507
4507
  const body = truncateText(formattedBody, DRAFT_REPLY_BODY_MAX_LENGTH, "\u2026[review truncated]");
4508
4508
  const sources = buildReviewCitations(pr.files);
@@ -19928,7 +19928,7 @@ function startImprovementReviewScheduler(options) {
19928
19928
  let running = false;
19929
19929
  const runOnce = async () => {
19930
19930
  try {
19931
- const { runImprovementReview: runImprovementReview2, ImprovementReviewInputSchema: ImprovementReviewInputSchema2 } = await import("./improvement-review-FHFPRZYL.js");
19931
+ const { runImprovementReview: runImprovementReview2, ImprovementReviewInputSchema: ImprovementReviewInputSchema2 } = await import("./improvement-review-SDXZS3GY.js");
19932
19932
  const input = ImprovementReviewInputSchema2.parse({ fileIssues });
19933
19933
  const result = await runImprovementReview2(input, { logger: logger22 });
19934
19934
  logger22.info("Scheduled improvement_review complete", {
@@ -11,11 +11,11 @@ import {
11
11
  resetCorrelationTracker,
12
12
  runConsensusForGoal,
13
13
  unwrapVoteOrThrow
14
- } from "./chunk-RT5GERSE.js";
14
+ } from "./chunk-3LLTMGAU.js";
15
15
  import "./chunk-O6IFENDU.js";
16
16
  import "./chunk-OQB3XC5O.js";
17
- import "./chunk-LHR7WWWE.js";
18
- import "./chunk-NPBPUOPX.js";
17
+ import "./chunk-UOR2YWRA.js";
18
+ import "./chunk-CGUFF47H.js";
19
19
  import "./chunk-SCIVDNY5.js";
20
20
  import "./chunk-2EHPCU5R.js";
21
21
  import "./chunk-7FA6RW5Z.js";
@@ -50,4 +50,4 @@ export {
50
50
  runConsensusForGoal,
51
51
  unwrapVoteOrThrow
52
52
  };
53
- //# sourceMappingURL=consensus-vote-Z7DN7TTD.js.map
53
+ //# sourceMappingURL=consensus-vote-CHT7XUMY.js.map
@@ -11,9 +11,9 @@ import {
11
11
  loadSelfEvalSignals,
12
12
  registerImprovementReviewTool,
13
13
  runImprovementReview
14
- } from "./chunk-W2PU5DWN.js";
15
- import "./chunk-LHR7WWWE.js";
16
- import "./chunk-NPBPUOPX.js";
14
+ } from "./chunk-HVQJRRZV.js";
15
+ import "./chunk-UOR2YWRA.js";
16
+ import "./chunk-CGUFF47H.js";
17
17
  import "./chunk-SCIVDNY5.js";
18
18
  import "./chunk-E7HUVU7E.js";
19
19
  import "./chunk-3HELETAQ.js";
@@ -33,4 +33,4 @@ export {
33
33
  registerImprovementReviewTool,
34
34
  runImprovementReview
35
35
  };
36
- //# sourceMappingURL=improvement-review-FHFPRZYL.js.map
36
+ //# sourceMappingURL=improvement-review-SDXZS3GY.js.map
package/dist/index.d.ts CHANGED
@@ -19045,6 +19045,7 @@ declare const SanitizedInputSchema: z.ZodObject<{
19045
19045
  }, z.core.$strip>>;
19046
19046
  truncated: z.ZodOptional<z.ZodBoolean>;
19047
19047
  wasModified: z.ZodBoolean;
19048
+ sanitizationIncomplete: z.ZodOptional<z.ZodBoolean>;
19048
19049
  sanitizedAt: z.ZodISODateTime;
19049
19050
  }, z.core.$strip>;
19050
19051
  type SanitizedInput = z.infer<typeof SanitizedInputSchema>;
package/dist/index.js CHANGED
@@ -552,7 +552,7 @@ import {
552
552
  withLogging,
553
553
  withRetry,
554
554
  withRetryWrapper
555
- } from "./chunk-RT2MFYQC.js";
555
+ } from "./chunk-WFW4LX3N.js";
556
556
  import {
557
557
  FALLBACK_SCANNER_DATA,
558
558
  buildPlanFromAnalysis,
@@ -585,7 +585,7 @@ import {
585
585
  connectTransport,
586
586
  createServer,
587
587
  startStdioServer
588
- } from "./chunk-FT5ISHQZ.js";
588
+ } from "./chunk-5HOMEIBV.js";
589
589
  import {
590
590
  OPENAI_MODELS,
591
591
  OPENAI_MODEL_ALIASES,
@@ -643,7 +643,7 @@ import {
643
643
  generateProposalId,
644
644
  parseAgentPairKey,
645
645
  registerConsensusVoteTool
646
- } from "./chunk-RT5GERSE.js";
646
+ } from "./chunk-3LLTMGAU.js";
647
647
  import "./chunk-O6IFENDU.js";
648
648
  import {
649
649
  allOf
@@ -678,7 +678,7 @@ import {
678
678
  resolveFirewallPolicyMode,
679
679
  validateAgentAction,
680
680
  validateCorroboration
681
- } from "./chunk-RZ5YSYCB.js";
681
+ } from "./chunk-FQUSU2QZ.js";
682
682
  import {
683
683
  GitHubProvider,
684
684
  ScmError
@@ -697,11 +697,11 @@ import {
697
697
  assessReputation,
698
698
  resolveReputationGatingMode,
699
699
  sanitizeInput
700
- } from "./chunk-KRD3OF3M.js";
700
+ } from "./chunk-XJ33UMUQ.js";
701
701
  import {
702
702
  ImprovementReviewInputSchema,
703
703
  registerImprovementReviewTool
704
- } from "./chunk-W2PU5DWN.js";
704
+ } from "./chunk-HVQJRRZV.js";
705
705
  import {
706
706
  AgentPerformanceSchema,
707
707
  ConsensusAlgorithmSchema,
@@ -737,10 +737,10 @@ import {
737
737
  toolSuccess,
738
738
  toolSuccessStructured,
739
739
  validateToolInput
740
- } from "./chunk-LHR7WWWE.js";
740
+ } from "./chunk-UOR2YWRA.js";
741
741
  import {
742
742
  VERSION
743
- } from "./chunk-NPBPUOPX.js";
743
+ } from "./chunk-CGUFF47H.js";
744
744
  import {
745
745
  AuditTrail,
746
746
  createAuditTrail,
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  IssueTriage,
3
3
  createIssueTriage
4
- } from "./chunk-RZ5YSYCB.js";
4
+ } from "./chunk-FQUSU2QZ.js";
5
5
  import "./chunk-ZMPQVOAO.js";
6
- import "./chunk-KRD3OF3M.js";
6
+ import "./chunk-XJ33UMUQ.js";
7
7
  import "./chunk-SCIVDNY5.js";
8
8
  import "./chunk-HYESPHTE.js";
9
9
  import "./chunk-E7HUVU7E.js";
@@ -14,4 +14,4 @@ export {
14
14
  IssueTriage,
15
15
  createIssueTriage
16
16
  };
17
- //# sourceMappingURL=issue-triage-RL6AMSBZ.js.map
17
+ //# sourceMappingURL=issue-triage-JEYSHESO.js.map
@@ -20,10 +20,10 @@ import {
20
20
  parseSeverity,
21
21
  reviewPostingBlock,
22
22
  sumFindings
23
- } from "./chunk-4CLPPSYW.js";
23
+ } from "./chunk-6X6CJFL5.js";
24
24
  import "./chunk-3KDQKVCJ.js";
25
25
  import "./chunk-OQB3XC5O.js";
26
- import "./chunk-KRD3OF3M.js";
26
+ import "./chunk-XJ33UMUQ.js";
27
27
  import "./chunk-E7HUVU7E.js";
28
28
  import "./chunk-3HELETAQ.js";
29
29
  import "./chunk-JVNJJ2VL.js";
@@ -51,4 +51,4 @@ export {
51
51
  reviewPostingBlock,
52
52
  sumFindings
53
53
  };
54
- //# sourceMappingURL=pr-reviewer-helpers-FLBM5I6M.js.map
54
+ //# sourceMappingURL=pr-reviewer-helpers-4RAI27NR.js.map
@@ -2,11 +2,11 @@ import {
2
2
  NEXUS_DATA_DIR,
3
3
  describeDataDirFix,
4
4
  initDataDirectories
5
- } from "./chunk-FT5ISHQZ.js";
5
+ } from "./chunk-5HOMEIBV.js";
6
6
  import "./chunk-FJRVJZSZ.js";
7
7
  import "./chunk-O6IFENDU.js";
8
8
  import "./chunk-OQB3XC5O.js";
9
- import "./chunk-NPBPUOPX.js";
9
+ import "./chunk-CGUFF47H.js";
10
10
  import "./chunk-7LP6VJRP.js";
11
11
  import "./chunk-Q2NGSVGI.js";
12
12
  import "./chunk-UDSIIRAE.js";
@@ -26,4 +26,4 @@ export {
26
26
  describeDataDirFix,
27
27
  initDataDirectories
28
28
  };
29
- //# sourceMappingURL=setup-data-dir-YCSXZZBD.js.map
29
+ //# sourceMappingURL=setup-data-dir-7D4PZTP2.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexus-agents",
3
- "version": "8.41.1",
3
+ "version": "8.42.0",
4
4
  "description": "Governance substrate for AI coding agents — adversarial PR review, drift-detected rules, tamper-evident audit, and closed-loop outcome routing for Claude, Codex, Gemini, and OpenCode",
5
5
  "mcpName": "io.github.nexus-substrate/nexus-agents",
6
6
  "license": "MIT",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/security/trust-types.ts","../src/security/input-sanitizer.ts","../src/security/reputation-model.ts","../src/security/env-mode.ts"],"sourcesContent":["/**\n * nexus-agents/security - Trust Types\n *\n * Zod schemas and TypeScript types for the untrusted input hardening\n * framework. Defines trust tiers, sanitized input, user roles, and\n * injection detection flags.\n *\n * @module security/trust-types\n * (Source: Issue #818, #819 — Phase 1: Input Sanitization)\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Trust Tiers\n// ============================================================================\n\n/**\n * Trust tier classification for input sources.\n * Lower number = higher trust.\n *\n * 1 = Authoritative (repo files, CI, CLAUDE.md, allowlisted maintainers)\n * 2 = Semi-trusted (collaborator issue body, contributor PR metadata)\n * 3 = Untrusted (unknown user comments, non-collaborator issue body)\n * 4 = Hostile (injection patterns, hidden HTML, instruction-like content)\n */\nexport const TrustTierSchema = z.enum(['1', '2', '3', '4']);\nexport type TrustTier = z.infer<typeof TrustTierSchema>;\n\n/** Numeric trust tier for comparisons. Higher number = lower trust. */\nexport const TRUST_TIER_NUMERIC: Record<TrustTier, number> = {\n '1': 1,\n '2': 2,\n '3': 3,\n '4': 4,\n};\n\n// ============================================================================\n// GitHub User Roles\n// ============================================================================\n\n/**\n * GitHub user relationship to the repository.\n */\nexport const GitHubUserRoleSchema = z.enum([\n 'owner',\n 'maintainer',\n 'collaborator',\n 'contributor',\n 'member',\n 'unknown',\n]);\nexport type GitHubUserRole = z.infer<typeof GitHubUserRoleSchema>;\n\n/**\n * Default trust tier mapping for each GitHub role.\n * Can be overridden by injection pattern detection (downgrade only).\n */\nexport const ROLE_DEFAULT_TRUST: Record<GitHubUserRole, TrustTier> = {\n owner: '1',\n maintainer: '1',\n collaborator: '2',\n contributor: '2',\n member: '3',\n unknown: '3',\n};\n\n// ============================================================================\n// Injection Detection\n// ============================================================================\n\n/**\n * Categories of injection patterns detected in content.\n */\nexport const InjectionFlagSchema = z.enum([\n 'authority_claim',\n 'instruction_pattern',\n 'system_prompt_manipulation',\n 'hidden_content',\n 'urgency_manipulation',\n 'fake_conversation',\n 'base64_encoded',\n 'external_link_instruction',\n]);\nexport type InjectionFlag = z.infer<typeof InjectionFlagSchema>;\n\n/**\n * An element stripped during sanitization, preserved for audit trail.\n */\nexport const StrippedElementSchema = z.object({\n /** Type of element stripped. */\n tag: z.string().min(1),\n /** Reason for stripping. */\n reason: z.string().min(1),\n /** Start index in original content. */\n startIndex: z.number().int().nonnegative(),\n /** Length of stripped content. */\n length: z.number().int().positive(),\n});\nexport type StrippedElement = z.infer<typeof StrippedElementSchema>;\n\n// ============================================================================\n// Sanitized Input\n// ============================================================================\n\n/**\n * The result of sanitizing untrusted input.\n * Contains cleaned content, trust classification, and audit data.\n */\nexport const SanitizedInputSchema = z.object({\n /** Sanitized content with dangerous elements removed. */\n content: z.string(),\n /** Original content before sanitization (for audit). */\n originalLength: z.number().int().nonnegative(),\n /**\n * Assigned trust tier based on user role and content analysis.\n *\n * Deprecation note: required today; a future major makes it absent when\n * unmeasured (see the next-major issue named in the changeset).\n */\n trustTier: TrustTierSchema,\n /**\n * True when `trustTier` is the sanitizer's measured content tier; false when\n * the sanitization stage was disabled and `trustTier` is only the\n * role-derived base tier. Absent on records that predate this field; an\n * absent value MUST be treated as measured so legacy content downgrades are\n * preserved fail-closed.\n */\n contentTierMeasured: z.boolean().optional(),\n /** GitHub user role of the input source. */\n userRole: GitHubUserRoleSchema,\n /** Injection patterns detected in content. */\n injectionFlags: z.array(InjectionFlagSchema),\n /** Elements stripped during sanitization (audit trail). */\n strippedElements: z.array(StrippedElementSchema),\n /** Whether content exceeded the configured limit. Absent on records that predate this field. */\n truncated: z.boolean().optional(),\n /** Whether any dangerous content was detected and stripped. */\n wasModified: z.boolean(),\n /** Timestamp of sanitization (ISO 8601). */\n sanitizedAt: z.iso.datetime(),\n});\nexport type SanitizedInput = z.infer<typeof SanitizedInputSchema>;\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Configuration for the input sanitizer.\n */\nexport const SanitizerConfigSchema = z.object({\n /** GitHub usernames that are always Tier 1 (allowlisted maintainers). */\n allowlistedMaintainers: z.array(z.string().min(1)).default([]),\n /** Whether to fail open (log only) or fail closed (block). Phase 1 = open. */\n failOpen: z.boolean().default(true),\n /** Maximum input length before truncation. */\n maxInputLength: z.number().int().positive().default(50_000),\n});\nexport type SanitizerConfig = z.infer<typeof SanitizerConfigSchema>;\n","/**\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 = /<!--[\\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} {\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 return { cleaned, stripped };\n}\n\n/** Strips XML-like tags that mimic conversation structure.\n * Loops until stable to prevent reconstructed patterns after removal (#1496). */\nfunction stripXmlTags(content: string): {\n cleaned: string;\n stripped: StrippedElement[];\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 return { cleaned, stripped };\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 = /<!--[\\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 injection patterns on ORIGINAL content (before stripping)\n const injectionFlags = detectInjectionPatterns(truncatedContent);\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 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, mirroring\n * `NEXUS_ACCESS_POLICY_MODE` (#1977): `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_ACCESS_POLICY_MODE` 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). Both `resolveAccessPolicyMode` (ClawGuard, #1977) and\n * `resolveReputationGatingMode` (reputation gating, #3122) parse an enum env\n * var, coerce an invalid value to a safe default, and must NEVER throw — a\n * security layer must not fail-closed on a misconfiguration at startup.\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":";;;;;;;AAWA,SAAS,SAAS;AAeX,IAAM,kBAAkB,EAAE,KAAK,CAAC,KAAK,KAAK,KAAK,GAAG,CAAC;AAInD,IAAM,qBAAgD;AAAA,EAC3D,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AASO,IAAM,uBAAuB,EAAE,KAAK;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOM,IAAM,qBAAwD;AAAA,EACnE,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,aAAa;AAAA,EACb,QAAQ;AAAA,EACR,SAAS;AACX;AASO,IAAM,sBAAsB,EAAE,KAAK;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAMM,IAAM,wBAAwB,EAAE,OAAO;AAAA;AAAA,EAE5C,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAErB,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAExB,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAAA;AAAA,EAEzC,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AACpC,CAAC;AAWM,IAAM,uBAAuB,EAAE,OAAO;AAAA;AAAA,EAE3C,SAAS,EAAE,OAAO;AAAA;AAAA,EAElB,gBAAgB,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;A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