nexus-agents 2.95.0 → 2.97.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 (120) hide show
  1. package/README.md +4 -4
  2. package/dist/{child-mcp-config-NW7JMSDK.js → child-mcp-config-WVPJIK2J.js} +2 -2
  3. package/dist/chunk-5LGAPYX7.js +2133 -0
  4. package/dist/chunk-5LGAPYX7.js.map +1 -0
  5. package/dist/{chunk-LXROEQAO.js → chunk-65LE457J.js} +2 -2
  6. package/dist/{chunk-47Z3YPOK.js → chunk-674NONPG.js} +2 -2
  7. package/dist/{chunk-2X24T4ZD.js → chunk-6IN4MKDA.js} +7 -7
  8. package/dist/{chunk-FYGZ4MEQ.js → chunk-76FTBRUS.js} +415 -1410
  9. package/dist/chunk-76FTBRUS.js.map +1 -0
  10. package/dist/{chunk-YYXJ6RTO.js → chunk-7BLBXITB.js} +3 -3
  11. package/dist/{chunk-GC5FH2IA.js → chunk-APLZRTYC.js} +7 -7
  12. package/dist/{chunk-TEKWQNQ2.js → chunk-D3OT7TOA.js} +3 -3
  13. package/dist/{chunk-3HXWI34V.js → chunk-E43RUPLP.js} +3 -3
  14. package/dist/{chunk-LZOTH2GI.js → chunk-EY7LL4F4.js} +2 -2
  15. package/dist/{chunk-5HBDXW44.js → chunk-FDTIRCSL.js} +2 -2
  16. package/dist/{chunk-VTMQND6B.js → chunk-GAIUXYF4.js} +366 -2470
  17. package/dist/chunk-GAIUXYF4.js.map +1 -0
  18. package/dist/{chunk-D3JSXVX3.js → chunk-GERVGPTF.js} +2 -2
  19. package/dist/{chunk-6IWPN5UB.js → chunk-HIWO2WWP.js} +2 -2
  20. package/dist/{chunk-WGA4VGIR.js → chunk-HWCMNFIS.js} +3 -3
  21. package/dist/{chunk-G42N55ZR.js → chunk-HZGHPBTV.js} +2 -2
  22. package/dist/{chunk-KHZGMF2W.js → chunk-IHKPGTF3.js} +4 -4
  23. package/dist/{chunk-ECBH5INZ.js → chunk-JTQLV374.js} +71 -6
  24. package/dist/chunk-JTQLV374.js.map +1 -0
  25. package/dist/{chunk-PFOY5ML6.js → chunk-JX6VL7JF.js} +3 -3
  26. package/dist/{chunk-4NVYN2MB.js → chunk-KKVH3PDK.js} +4 -4
  27. package/dist/{chunk-3H6Q3RZM.js → chunk-ML4IF3PS.js} +4 -4
  28. package/dist/{chunk-QUPPV6UO.js → chunk-N5656LE3.js} +2 -2
  29. package/dist/{chunk-FXVJLJUF.js → chunk-NTBVUWU4.js} +2 -2
  30. package/dist/{chunk-ZICVVBDW.js → chunk-OKRTOMKX.js} +2 -2
  31. package/dist/{chunk-Y3OOHHKQ.js → chunk-OSHCOBDK.js} +2 -2
  32. package/dist/chunk-P2BKWVKF.js +1095 -0
  33. package/dist/chunk-P2BKWVKF.js.map +1 -0
  34. package/dist/{chunk-FTDVA33Z.js → chunk-SAUBPHQ7.js} +4 -4
  35. package/dist/{chunk-55G7KQ7F.js → chunk-SWNOQW7Y.js} +5 -5
  36. package/dist/{chunk-O4LVC4MQ.js → chunk-SZNNT2DH.js} +2 -2
  37. package/dist/{chunk-ECZW5FXN.js → chunk-T5TYWM5S.js} +2 -2
  38. package/dist/{chunk-7GUP6KQQ.js → chunk-UNOOL6EN.js} +2 -2
  39. package/dist/{chunk-BSHDI4BH.js → chunk-WXDWDGVL.js} +2 -2
  40. package/dist/{cli-circuit-breaker-LNU5DQSB.js → cli-circuit-breaker-STKW4DTL.js} +4 -4
  41. package/dist/cli.js +149 -52
  42. package/dist/cli.js.map +1 -1
  43. package/dist/{composite-router-DJ54ND5X.js → composite-router-POFAM7T4.js} +2 -2
  44. package/dist/{consensus-vote-XLEQFVE7.js → consensus-vote-EQAYX53Z.js} +13 -12
  45. package/dist/{context-retriever-6O6TREXH.js → context-retriever-H22L3WFV.js} +6 -6
  46. package/dist/{doctor-deep-PSNJPELP.js → doctor-deep-HGAC6N5Y.js} +3 -3
  47. package/dist/{expert-bridge-Q3OWPD4L.js → expert-bridge-IAQPOJAQ.js} +4 -4
  48. package/dist/{factory-PSMTMC7V.js → factory-P2SQS7UM.js} +5 -5
  49. package/dist/{factory-43RVPRT5.js → factory-ZIZYUDKH.js} +5 -5
  50. package/dist/improvement-review-G2HAMGZP.js +27 -0
  51. package/dist/index.d.ts +8 -1
  52. package/dist/index.js +52 -49
  53. package/dist/index.js.map +1 -1
  54. package/dist/{init-opencode-25AUARJH.js → init-opencode-RHCYZDZW.js} +5 -5
  55. package/dist/{issue-triage-KZTENUDH.js → issue-triage-VVNQIQW5.js} +5 -5
  56. package/dist/{pr-reviewer-helpers-XENJ4E2T.js → pr-reviewer-helpers-UN7RDPDN.js} +4 -4
  57. package/dist/{registry-command-X3O34FAK.js → registry-command-OVRRKYHO.js} +2 -2
  58. package/dist/{repo-security-plan-XCX7EFJR.js → repo-security-plan-X74TBYOV.js} +3 -3
  59. package/dist/{research-helpers-synthesize-CGVR6M4S.js → research-helpers-synthesize-OSP6FGNV.js} +3 -3
  60. package/dist/{routing-memory-YZRYGXQC.js → routing-memory-5T5QJF47.js} +2 -2
  61. package/dist/{session-memory-SXQAA2EN.js → session-memory-X7CJ6X4A.js} +3 -3
  62. package/dist/{setup-command-VG7JZI6O.js → setup-command-ZWJCGPJ5.js} +11 -11
  63. package/dist/{setup-config-VJAK6AA2.js → setup-config-YVIKUNOB.js} +3 -3
  64. package/dist/{setup-custom-api-KSF2JMTS.js → setup-custom-api-FLV4SELI.js} +4 -4
  65. package/dist/{tool-memory-L7SDFSF5.js → tool-memory-QNEAKRKV.js} +5 -5
  66. package/dist/{weather-report-D6HFOK7S.js → weather-report-SUVIXWKI.js} +2 -2
  67. package/dist/weather-report-SUVIXWKI.js.map +1 -0
  68. package/package.json +12 -2
  69. package/dist/chunk-ECBH5INZ.js.map +0 -1
  70. package/dist/chunk-FYGZ4MEQ.js.map +0 -1
  71. package/dist/chunk-VTMQND6B.js.map +0 -1
  72. /package/dist/{child-mcp-config-NW7JMSDK.js.map → child-mcp-config-WVPJIK2J.js.map} +0 -0
  73. /package/dist/{chunk-LXROEQAO.js.map → chunk-65LE457J.js.map} +0 -0
  74. /package/dist/{chunk-47Z3YPOK.js.map → chunk-674NONPG.js.map} +0 -0
  75. /package/dist/{chunk-2X24T4ZD.js.map → chunk-6IN4MKDA.js.map} +0 -0
  76. /package/dist/{chunk-YYXJ6RTO.js.map → chunk-7BLBXITB.js.map} +0 -0
  77. /package/dist/{chunk-GC5FH2IA.js.map → chunk-APLZRTYC.js.map} +0 -0
  78. /package/dist/{chunk-TEKWQNQ2.js.map → chunk-D3OT7TOA.js.map} +0 -0
  79. /package/dist/{chunk-3HXWI34V.js.map → chunk-E43RUPLP.js.map} +0 -0
  80. /package/dist/{chunk-LZOTH2GI.js.map → chunk-EY7LL4F4.js.map} +0 -0
  81. /package/dist/{chunk-5HBDXW44.js.map → chunk-FDTIRCSL.js.map} +0 -0
  82. /package/dist/{chunk-D3JSXVX3.js.map → chunk-GERVGPTF.js.map} +0 -0
  83. /package/dist/{chunk-6IWPN5UB.js.map → chunk-HIWO2WWP.js.map} +0 -0
  84. /package/dist/{chunk-WGA4VGIR.js.map → chunk-HWCMNFIS.js.map} +0 -0
  85. /package/dist/{chunk-G42N55ZR.js.map → chunk-HZGHPBTV.js.map} +0 -0
  86. /package/dist/{chunk-KHZGMF2W.js.map → chunk-IHKPGTF3.js.map} +0 -0
  87. /package/dist/{chunk-PFOY5ML6.js.map → chunk-JX6VL7JF.js.map} +0 -0
  88. /package/dist/{chunk-4NVYN2MB.js.map → chunk-KKVH3PDK.js.map} +0 -0
  89. /package/dist/{chunk-3H6Q3RZM.js.map → chunk-ML4IF3PS.js.map} +0 -0
  90. /package/dist/{chunk-QUPPV6UO.js.map → chunk-N5656LE3.js.map} +0 -0
  91. /package/dist/{chunk-FXVJLJUF.js.map → chunk-NTBVUWU4.js.map} +0 -0
  92. /package/dist/{chunk-ZICVVBDW.js.map → chunk-OKRTOMKX.js.map} +0 -0
  93. /package/dist/{chunk-Y3OOHHKQ.js.map → chunk-OSHCOBDK.js.map} +0 -0
  94. /package/dist/{chunk-FTDVA33Z.js.map → chunk-SAUBPHQ7.js.map} +0 -0
  95. /package/dist/{chunk-55G7KQ7F.js.map → chunk-SWNOQW7Y.js.map} +0 -0
  96. /package/dist/{chunk-O4LVC4MQ.js.map → chunk-SZNNT2DH.js.map} +0 -0
  97. /package/dist/{chunk-ECZW5FXN.js.map → chunk-T5TYWM5S.js.map} +0 -0
  98. /package/dist/{chunk-7GUP6KQQ.js.map → chunk-UNOOL6EN.js.map} +0 -0
  99. /package/dist/{chunk-BSHDI4BH.js.map → chunk-WXDWDGVL.js.map} +0 -0
  100. /package/dist/{cli-circuit-breaker-LNU5DQSB.js.map → cli-circuit-breaker-STKW4DTL.js.map} +0 -0
  101. /package/dist/{composite-router-DJ54ND5X.js.map → composite-router-POFAM7T4.js.map} +0 -0
  102. /package/dist/{consensus-vote-XLEQFVE7.js.map → consensus-vote-EQAYX53Z.js.map} +0 -0
  103. /package/dist/{context-retriever-6O6TREXH.js.map → context-retriever-H22L3WFV.js.map} +0 -0
  104. /package/dist/{doctor-deep-PSNJPELP.js.map → doctor-deep-HGAC6N5Y.js.map} +0 -0
  105. /package/dist/{expert-bridge-Q3OWPD4L.js.map → expert-bridge-IAQPOJAQ.js.map} +0 -0
  106. /package/dist/{factory-43RVPRT5.js.map → factory-P2SQS7UM.js.map} +0 -0
  107. /package/dist/{factory-PSMTMC7V.js.map → factory-ZIZYUDKH.js.map} +0 -0
  108. /package/dist/{issue-triage-KZTENUDH.js.map → improvement-review-G2HAMGZP.js.map} +0 -0
  109. /package/dist/{init-opencode-25AUARJH.js.map → init-opencode-RHCYZDZW.js.map} +0 -0
  110. /package/dist/{pr-reviewer-helpers-XENJ4E2T.js.map → issue-triage-VVNQIQW5.js.map} +0 -0
  111. /package/dist/{repo-security-plan-XCX7EFJR.js.map → pr-reviewer-helpers-UN7RDPDN.js.map} +0 -0
  112. /package/dist/{registry-command-X3O34FAK.js.map → registry-command-OVRRKYHO.js.map} +0 -0
  113. /package/dist/{research-helpers-synthesize-CGVR6M4S.js.map → repo-security-plan-X74TBYOV.js.map} +0 -0
  114. /package/dist/{routing-memory-YZRYGXQC.js.map → research-helpers-synthesize-OSP6FGNV.js.map} +0 -0
  115. /package/dist/{session-memory-SXQAA2EN.js.map → routing-memory-5T5QJF47.js.map} +0 -0
  116. /package/dist/{setup-command-VG7JZI6O.js.map → session-memory-X7CJ6X4A.js.map} +0 -0
  117. /package/dist/{setup-config-VJAK6AA2.js.map → setup-command-ZWJCGPJ5.js.map} +0 -0
  118. /package/dist/{tool-memory-L7SDFSF5.js.map → setup-config-YVIKUNOB.js.map} +0 -0
  119. /package/dist/{setup-custom-api-KSF2JMTS.js.map → setup-custom-api-FLV4SELI.js.map} +0 -0
  120. /package/dist/{weather-report-D6HFOK7S.js.map → tool-memory-QNEAKRKV.js.map} +0 -0
@@ -1,25 +1,22 @@
1
+ import {
2
+ CodebaseIndex,
3
+ extractSymbolIndex,
4
+ extractSymbols
5
+ } from "./chunk-3ACDP4E6.js";
1
6
  import {
2
7
  getTokenEnvVars,
3
8
  resolveToken
4
- } from "./chunk-5HBDXW44.js";
9
+ } from "./chunk-FDTIRCSL.js";
5
10
  import {
6
11
  executeExpert
7
- } from "./chunk-2X24T4ZD.js";
12
+ } from "./chunk-6IN4MKDA.js";
8
13
  import {
9
14
  EventTopics,
10
15
  JobStatusSchema,
11
- NOOP_NOTIFIER,
12
- RateLimiter,
13
- abortSignalStorage,
14
16
  collectRealVotes,
15
- createDefaultRateLimiter,
16
17
  createEvent,
17
- createMcpNotifier,
18
- createSecureHandler,
19
18
  getGlobalEventBus,
20
19
  getGlobalRegistry,
21
- getToolAnnotations,
22
- getToolTimeout,
23
20
  isRateLimitError,
24
21
  listJobs,
25
22
  readJobResult,
@@ -27,22 +24,13 @@ import {
27
24
  release,
28
25
  shortCircuitOrFreshJobId,
29
26
  suggestRetryAfterMs,
30
- toSdkCallback,
31
- toSdkCallbackWithBudgetCheck,
32
- toolError,
33
- toolStructuredError,
34
- toolSuccess,
35
- toolSuccessStructured,
36
27
  tryAcquire,
37
28
  warnIfSimulatedOutsideTests,
38
- withAccessPolicy,
39
- withProgressHeartbeat,
40
- wrapToolWithTimeout,
41
29
  writeJobCancelled,
42
30
  writeJobComplete,
43
31
  writeJobFailed,
44
32
  writeJobPending
45
- } from "./chunk-VTMQND6B.js";
33
+ } from "./chunk-GAIUXYF4.js";
46
34
  import {
47
35
  REGISTRY_PATH,
48
36
  getProjectRoot,
@@ -51,51 +39,68 @@ import {
51
39
  normalizeTopicToCanonical,
52
40
  savePapersRegistry,
53
41
  synthesizeResearch
54
- } from "./chunk-ECZW5FXN.js";
42
+ } from "./chunk-T5TYWM5S.js";
55
43
  import {
56
44
  IssueTriage,
57
45
  createAuditTrail,
58
46
  createGraphAuditBridge
59
- } from "./chunk-4NVYN2MB.js";
47
+ } from "./chunk-KKVH3PDK.js";
60
48
  import {
61
49
  resolveEnvMode,
62
50
  sanitizeInput
63
- } from "./chunk-O4LVC4MQ.js";
51
+ } from "./chunk-SZNNT2DH.js";
52
+ import {
53
+ withPrerequisite
54
+ } from "./chunk-P2BKWVKF.js";
55
+ import {
56
+ NOOP_NOTIFIER,
57
+ RateLimiter,
58
+ abortSignalStorage,
59
+ createDefaultRateLimiter,
60
+ createMcpNotifier,
61
+ createSecureHandler,
62
+ getToolAnnotations,
63
+ getToolTimeout,
64
+ toSdkCallback,
65
+ toSdkCallbackWithBudgetCheck,
66
+ toolError,
67
+ toolStructuredError,
68
+ toolSuccess,
69
+ toolSuccessStructured,
70
+ withAccessPolicy,
71
+ withProgressHeartbeat,
72
+ wrapToolWithTimeout
73
+ } from "./chunk-5LGAPYX7.js";
64
74
  import {
65
75
  generateSecurityPlan
66
- } from "./chunk-BSHDI4BH.js";
76
+ } from "./chunk-WXDWDGVL.js";
67
77
  import {
68
78
  analyzeGitHubRepo
69
79
  } from "./chunk-HFOQKCD2.js";
70
- import {
71
- CodebaseIndex,
72
- extractSymbolIndex,
73
- extractSymbols
74
- } from "./chunk-3ACDP4E6.js";
75
80
  import {
76
81
  getContextForTask,
77
82
  inferTaskCategory,
78
83
  summarizeContextForPrompt
79
- } from "./chunk-TEKWQNQ2.js";
84
+ } from "./chunk-D3OT7TOA.js";
80
85
  import {
81
86
  DEFAULT_RELEVANCE_CONFIG,
82
87
  MemoryImportance,
83
88
  calculateTextJaccardSimilarity,
84
89
  getToolMemory
85
- } from "./chunk-KHZGMF2W.js";
90
+ } from "./chunk-IHKPGTF3.js";
86
91
  import {
87
92
  DEFAULT_TASK_TTL_MS,
88
93
  DEFAULT_TOOL_RATE_LIMITS,
89
94
  clampTaskTtl
90
- } from "./chunk-GC5FH2IA.js";
95
+ } from "./chunk-APLZRTYC.js";
91
96
  import {
92
97
  getAvailabilityCache,
93
98
  getCliForModelId,
94
99
  resolveFallback
95
- } from "./chunk-QUPPV6UO.js";
100
+ } from "./chunk-N5656LE3.js";
96
101
  import {
97
102
  DEFAULTS
98
- } from "./chunk-7GUP6KQQ.js";
103
+ } from "./chunk-UNOOL6EN.js";
99
104
  import {
100
105
  resolveInsideRoot
101
106
  } from "./chunk-NUBSJGQZ.js";
@@ -111,11 +116,11 @@ import {
111
116
  getAvailableClis,
112
117
  sleep,
113
118
  withTimeout
114
- } from "./chunk-3H6Q3RZM.js";
119
+ } from "./chunk-ML4IF3PS.js";
115
120
  import {
116
121
  generateHyphenId,
117
122
  generateUUID
118
- } from "./chunk-G42N55ZR.js";
123
+ } from "./chunk-HZGHPBTV.js";
119
124
  import {
120
125
  BUILT_IN_EXPERTS,
121
126
  BuiltInExpertTypeSchema,
@@ -127,7 +132,7 @@ import {
127
132
  } from "./chunk-PQHVC4BD.js";
128
133
  import {
129
134
  createSessionMemory
130
- } from "./chunk-6IWPN5UB.js";
135
+ } from "./chunk-HIWO2WWP.js";
131
136
  import {
132
137
  AGENT_ROUTER_TIMEOUTS,
133
138
  API_TIMEOUTS,
@@ -199,9 +204,8 @@ import {
199
204
  resolveModelIdentitySync,
200
205
  toExpertTaskAnalysisResult,
201
206
  withStep
202
- } from "./chunk-ECBH5INZ.js";
207
+ } from "./chunk-JTQLV374.js";
203
208
  import {
204
- getNexusDataDir,
205
209
  nexusDataPath,
206
210
  nexusDataPathEnsure
207
211
  } from "./chunk-CH7QIDHQ.js";
@@ -2063,9 +2067,9 @@ var TASK_CATEGORY_KEYWORDS = [
2063
2067
  [["document", "doc"], "documentation"],
2064
2068
  [["refactor"], "refactoring"]
2065
2069
  ];
2066
- function categorizeTaskByKeywords(description2) {
2070
+ function categorizeTaskByKeywords(description) {
2067
2071
  for (const [keywords, category] of TASK_CATEGORY_KEYWORDS) {
2068
- if (keywords.some((kw) => description2.includes(kw))) {
2072
+ if (keywords.some((kw) => description.includes(kw))) {
2069
2073
  return category;
2070
2074
  }
2071
2075
  }
@@ -2599,8 +2603,8 @@ async function persistMemoryAfterTask(params) {
2599
2603
  });
2600
2604
  return updatedState;
2601
2605
  }
2602
- function categorizeTaskType(description2) {
2603
- const desc = description2.toLowerCase();
2606
+ function categorizeTaskType(description) {
2607
+ const desc = description.toLowerCase();
2604
2608
  return categorizeTaskByKeywords(desc);
2605
2609
  }
2606
2610
  async function persistMemoryOnCleanup(params) {
@@ -6270,8 +6274,8 @@ function scoreRoleCapabilities(subtask, role, expertWeights) {
6270
6274
  const weight = expertWeights[role] ?? 1;
6271
6275
  return score * weight;
6272
6276
  }
6273
- function applyKeywordBoosts(scores, description2) {
6274
- const desc = description2.toLowerCase();
6277
+ function applyKeywordBoosts(scores, description) {
6278
+ const desc = description.toLowerCase();
6275
6279
  const boosts = [
6276
6280
  { keywords: ["code", "implement"], role: "code_expert" },
6277
6281
  { keywords: ["architecture", "design"], role: "architecture_expert" },
@@ -6335,7 +6339,7 @@ function selectExpertForSubtask(subtask, expertWeights) {
6335
6339
  }
6336
6340
 
6337
6341
  // src/agents/tech-lead-helpers.ts
6338
- function inferTaskType(description2) {
6342
+ function inferTaskType(description) {
6339
6343
  const typeKeywords = {
6340
6344
  implementation: ["implement", "create", "build", "develop", "write code"],
6341
6345
  refactoring: ["refactor", "improve", "optimize", "clean up"],
@@ -6347,16 +6351,16 @@ function inferTaskType(description2) {
6347
6351
  };
6348
6352
  for (const [taskType, keywords] of Object.entries(typeKeywords)) {
6349
6353
  for (const keyword of keywords) {
6350
- if (description2.includes(keyword)) {
6354
+ if (description.includes(keyword)) {
6351
6355
  return taskType;
6352
6356
  }
6353
6357
  }
6354
6358
  }
6355
6359
  return "general";
6356
6360
  }
6357
- function extractRequirements(description2) {
6361
+ function extractRequirements(description) {
6358
6362
  const requirements = [];
6359
- const lines = description2.split(/[.\n]/);
6363
+ const lines = description.split(/[.\n]/);
6360
6364
  for (const line of lines) {
6361
6365
  const trimmed = line.trim();
6362
6366
  if (trimmed.length > 10 && (trimmed.includes("must") || trimmed.includes("should") || trimmed.includes("need") || trimmed.includes("require"))) {
@@ -6365,21 +6369,21 @@ function extractRequirements(description2) {
6365
6369
  }
6366
6370
  return requirements.slice(0, 5);
6367
6371
  }
6368
- function identifyRisks(description2) {
6372
+ function identifyRisks(description) {
6369
6373
  const risks = [];
6370
- if (description2.includes("database") || description2.includes("migration")) {
6374
+ if (description.includes("database") || description.includes("migration")) {
6371
6375
  risks.push("Data integrity during changes");
6372
6376
  }
6373
- if (description2.includes("security")) {
6377
+ if (description.includes("security")) {
6374
6378
  risks.push("Security vulnerabilities if not thorough");
6375
6379
  }
6376
- if (description2.includes("performance")) {
6380
+ if (description.includes("performance")) {
6377
6381
  risks.push("Performance regression");
6378
6382
  }
6379
- if (description2.includes("api") || description2.includes("interface")) {
6383
+ if (description.includes("api") || description.includes("interface")) {
6380
6384
  risks.push("Breaking API changes");
6381
6385
  }
6382
- if (description2.includes("concurrent") || description2.includes("parallel")) {
6386
+ if (description.includes("concurrent") || description.includes("parallel")) {
6383
6387
  risks.push("Race conditions");
6384
6388
  }
6385
6389
  return risks;
@@ -6394,23 +6398,23 @@ function suggestApproach(taskType, complexity) {
6394
6398
  return `Low complexity ${taskType} task. Direct implementation with basic validation.`;
6395
6399
  }
6396
6400
  function heuristicAnalysis(task, options) {
6397
- const description2 = task.description.toLowerCase();
6401
+ const description = task.description.toLowerCase();
6398
6402
  const wordCount = task.description.split(/\s+/).length;
6399
6403
  let complexity = 3;
6400
6404
  if (wordCount > 100) complexity += 2;
6401
6405
  if (wordCount > 200) complexity += 2;
6402
- if (description2.includes("security")) complexity += 1;
6403
- if (description2.includes("architecture")) complexity += 1;
6404
- if (description2.includes("refactor")) complexity += 1;
6406
+ if (description.includes("security")) complexity += 1;
6407
+ if (description.includes("architecture")) complexity += 1;
6408
+ if (description.includes("refactor")) complexity += 1;
6405
6409
  complexity = Math.min(10, complexity);
6406
- const taskType = inferTaskType(description2);
6407
- const requirements = extractRequirements(description2);
6410
+ const taskType = inferTaskType(description);
6411
+ const requirements = extractRequirements(description);
6408
6412
  return {
6409
6413
  taskId: task.id,
6410
6414
  complexity,
6411
6415
  taskType,
6412
6416
  requirements,
6413
- risks: identifyRisks(description2),
6417
+ risks: identifyRisks(description),
6414
6418
  needsDecomposition: complexity >= options.decompositionThreshold,
6415
6419
  approach: suggestApproach(taskType, complexity),
6416
6420
  estimatedEffort: Math.ceil(complexity * 1.5)
@@ -6488,7 +6492,7 @@ function createSubtask(params) {
6488
6492
  baseId,
6489
6493
  num,
6490
6494
  parentTaskId,
6491
- description: description2,
6495
+ description,
6492
6496
  expectedOutput,
6493
6497
  deps,
6494
6498
  priority,
@@ -6498,7 +6502,7 @@ function createSubtask(params) {
6498
6502
  return {
6499
6503
  id: `${baseId}-${String(num)}`,
6500
6504
  parentTaskId,
6501
- description: description2,
6505
+ description,
6502
6506
  expectedOutput,
6503
6507
  dependencies: deps.map((d) => `${baseId}-${d}`),
6504
6508
  priority,
@@ -6819,13 +6823,13 @@ function buildBaseWorkflow(plan, steps, options) {
6819
6823
  };
6820
6824
  }
6821
6825
  function addDescription(workflow, plan, options) {
6822
- const description2 = generateDescription(
6826
+ const description = generateDescription(
6823
6827
  plan.analysis,
6824
6828
  options?.description,
6825
6829
  options?.includeAnalysis
6826
6830
  );
6827
- if (description2 !== void 0) {
6828
- workflow.description = description2;
6831
+ if (description !== void 0) {
6832
+ workflow.description = description;
6829
6833
  }
6830
6834
  }
6831
6835
  function addTimeout(workflow, estimatedDuration) {
@@ -8079,8 +8083,8 @@ function buildCodeExpertBaseOptions(options, expertOpts) {
8079
8083
  if (options.logger !== void 0) baseOptions.logger = options.logger;
8080
8084
  return baseOptions;
8081
8085
  }
8082
- function inferOperationType(description2) {
8083
- const desc = description2.toLowerCase();
8086
+ function inferOperationType(description) {
8087
+ const desc = description.toLowerCase();
8084
8088
  if (desc.includes("debug") || desc.includes("fix bug") || desc.includes("error")) {
8085
8089
  return "debugging";
8086
8090
  }
@@ -8107,9 +8111,9 @@ function generateHeuristicRecommendations(operationType) {
8107
8111
  return baseRecs;
8108
8112
  }
8109
8113
  }
8110
- function detectHeuristicWarnings(description2) {
8114
+ function detectHeuristicWarnings(description) {
8111
8115
  const warnings = [];
8112
- const desc = description2.toLowerCase();
8116
+ const desc = description.toLowerCase();
8113
8117
  if (desc.includes("database") || desc.includes("sql")) {
8114
8118
  warnings.push("Database changes may require migration");
8115
8119
  }
@@ -9088,9 +9092,9 @@ var VULNERABILITY_PATTERNS = [
9088
9092
  cweId: "CWE-942"
9089
9093
  }
9090
9094
  ];
9091
- function detectHeuristicVulnerabilities(description2, options = {}) {
9095
+ function detectHeuristicVulnerabilities(description, options = {}) {
9092
9096
  const vulnerabilities = [];
9093
- const desc = description2.toLowerCase();
9097
+ const desc = description.toLowerCase();
9094
9098
  let vulnId = 1;
9095
9099
  for (const p of VULNERABILITY_PATTERNS) {
9096
9100
  if (p.pattern.test(desc)) {
@@ -9411,9 +9415,9 @@ var COMPONENT_PATTERNS = [
9411
9415
  responsibilities: ["Business rules", "Domain operations", "Workflow management"]
9412
9416
  }
9413
9417
  ];
9414
- function identifyHeuristicPatterns(description2) {
9418
+ function identifyHeuristicPatterns(description) {
9415
9419
  const patterns = [];
9416
- const desc = description2.toLowerCase();
9420
+ const desc = description.toLowerCase();
9417
9421
  for (const match of ARCHITECTURE_PATTERNS) {
9418
9422
  if (match.pattern.test(desc)) {
9419
9423
  patterns.push({
@@ -9426,9 +9430,9 @@ function identifyHeuristicPatterns(description2) {
9426
9430
  }
9427
9431
  return patterns.slice(0, 5);
9428
9432
  }
9429
- function identifyHeuristicComponents(description2) {
9433
+ function identifyHeuristicComponents(description) {
9430
9434
  const components = [];
9431
- const desc = description2.toLowerCase();
9435
+ const desc = description.toLowerCase();
9432
9436
  for (const cp of COMPONENT_PATTERNS) {
9433
9437
  if (cp.pattern.test(desc)) {
9434
9438
  components.push({
@@ -9459,8 +9463,8 @@ function generateHeuristicADRs(task, patterns) {
9459
9463
  }
9460
9464
  ];
9461
9465
  }
9462
- function inferAnalysisType(description2) {
9463
- const desc = description2.toLowerCase();
9466
+ function inferAnalysisType(description) {
9467
+ const desc = description.toLowerCase();
9464
9468
  if (desc.includes("pattern") || desc.includes("which approach")) {
9465
9469
  return "pattern_selection";
9466
9470
  }
@@ -9487,9 +9491,9 @@ function generateHeuristicRecommendations3(analysisType) {
9487
9491
  return base;
9488
9492
  }
9489
9493
  }
9490
- function detectArchitectureWarnings(description2) {
9494
+ function detectArchitectureWarnings(description) {
9491
9495
  const warnings = [];
9492
- const desc = description2.toLowerCase();
9496
+ const desc = description.toLowerCase();
9493
9497
  if (desc.includes("monolith") && desc.includes("microservice")) {
9494
9498
  warnings.push("Migration from monolith to microservices is complex - plan carefully");
9495
9499
  }
@@ -9815,8 +9819,8 @@ function createHeuristicCoverage() {
9815
9819
  ]
9816
9820
  };
9817
9821
  }
9818
- function assessHeuristicQuality(description2) {
9819
- const desc = description2.toLowerCase();
9822
+ function assessHeuristicQuality(description) {
9823
+ const desc = description.toLowerCase();
9820
9824
  const issues = [];
9821
9825
  if (desc.includes("flaky") || desc.includes("intermittent")) {
9822
9826
  issues.push("Flaky tests detected - improve test isolation");
@@ -9862,9 +9866,9 @@ function generateHeuristicRecommendations4(operationType) {
9862
9866
  return base;
9863
9867
  }
9864
9868
  }
9865
- function detectTestingWarnings(description2) {
9869
+ function detectTestingWarnings(description) {
9866
9870
  const warnings = [];
9867
- const desc = description2.toLowerCase();
9871
+ const desc = description.toLowerCase();
9868
9872
  if (desc.includes("database") || desc.includes("external")) {
9869
9873
  warnings.push("Integration tests with external dependencies need careful setup/teardown");
9870
9874
  }
@@ -9879,8 +9883,8 @@ function detectTestingWarnings(description2) {
9879
9883
  }
9880
9884
  return warnings;
9881
9885
  }
9882
- function inferOperationType2(description2) {
9883
- const desc = description2.toLowerCase();
9886
+ function inferOperationType2(description) {
9887
+ const desc = description.toLowerCase();
9884
9888
  if (desc.includes("coverage") || desc.includes("uncovered")) {
9885
9889
  return "coverage_analysis";
9886
9890
  }
@@ -10191,9 +10195,9 @@ function generateHeuristicRecommendations5(docType) {
10191
10195
  return base;
10192
10196
  }
10193
10197
  }
10194
- function detectDocumentationWarnings(description2) {
10198
+ function detectDocumentationWarnings(description) {
10195
10199
  const warnings = [];
10196
- const desc = description2.toLowerCase();
10200
+ const desc = description.toLowerCase();
10197
10201
  if (desc.includes("internal") || desc.includes("private")) {
10198
10202
  warnings.push("Document internal APIs carefully - they may change");
10199
10203
  }
@@ -10208,8 +10212,8 @@ function detectDocumentationWarnings(description2) {
10208
10212
  }
10209
10213
  return warnings;
10210
10214
  }
10211
- function inferDocumentationType(description2) {
10212
- const desc = description2.toLowerCase();
10215
+ function inferDocumentationType(description) {
10216
+ const desc = description.toLowerCase();
10213
10217
  if (desc.includes("api") || desc.includes("endpoint") || desc.includes("function doc")) {
10214
10218
  return "api";
10215
10219
  }
@@ -11796,14 +11800,14 @@ var TrinityStopReasonSchema = z13.enum(["verified", "max_iterations", "timeout",
11796
11800
  // src/agents/collaboration/trinity-helpers.ts
11797
11801
  function buildRoleTask(baseTask, role, context) {
11798
11802
  const rolePrompt = TRINITY_ROLE_PROMPTS[role];
11799
- const description2 = `${rolePrompt}
11803
+ const description = `${rolePrompt}
11800
11804
 
11801
11805
  ---
11802
11806
 
11803
11807
  Original Task: ${baseTask.description}
11804
11808
 
11805
11809
  ${context}`;
11806
- return { id: `${baseTask.id}-${role}`, description: description2, context: baseTask.context };
11810
+ return { id: `${baseTask.id}-${role}`, description, context: baseTask.context };
11807
11811
  }
11808
11812
  function extractSections(text) {
11809
11813
  const sections = {};
@@ -13256,8 +13260,8 @@ var SkillComposer = class {
13256
13260
  /**
13257
13261
  * Extracts keywords from task description.
13258
13262
  */
13259
- extractTaskKeywords(description2) {
13260
- return description2.toLowerCase().split(/\W+/).filter((word) => word.length > 2);
13263
+ extractTaskKeywords(description) {
13264
+ return description.toLowerCase().split(/\W+/).filter((word) => word.length > 2);
13261
13265
  }
13262
13266
  /**
13263
13267
  * Scores skills for a specific task.
@@ -16503,8 +16507,8 @@ var AGENT_PATTERN_MAP = {
16503
16507
  executor: "execution",
16504
16508
  terminator: "termination"
16505
16509
  };
16506
- function extractKeywords3(description2) {
16507
- return description2.toLowerCase().split(/\W+/).filter((word) => word.length > 2 && !STOPWORDS.has(word)).slice(0, 10);
16510
+ function extractKeywords3(description) {
16511
+ return description.toLowerCase().split(/\W+/).filter((word) => word.length > 2 && !STOPWORDS.has(word)).slice(0, 10);
16508
16512
  }
16509
16513
  function computeSimilarity(strings) {
16510
16514
  if (strings.length < 2) return 0;
@@ -23555,10 +23559,10 @@ function calculateZStatistic(params) {
23555
23559
  function calculateDifferenceCI(p1, p2, total1, total2, confidence) {
23556
23560
  const difference = p1 - p2;
23557
23561
  const seDiff = Math.sqrt(p1 * (1 - p1) / (total1 || 1) + p2 * (1 - p2) / (total2 || 1));
23558
- const z112 = getZScore(confidence);
23562
+ const z111 = getZScore(confidence);
23559
23563
  return {
23560
- lower: difference - z112 * seDiff,
23561
- upper: difference + z112 * seDiff,
23564
+ lower: difference - z111 * seDiff,
23565
+ upper: difference + z111 * seDiff,
23562
23566
  estimate: difference,
23563
23567
  confidence,
23564
23568
  n: total1 + total2,
@@ -23581,11 +23585,11 @@ function proportionConfidenceInterval(successes, total, options = {}) {
23581
23585
  standardError: 0
23582
23586
  };
23583
23587
  }
23584
- const z112 = getZScore(opts.confidence);
23585
- const z210 = z112 * z112;
23588
+ const z111 = getZScore(opts.confidence);
23589
+ const z210 = z111 * z111;
23586
23590
  const denominator = 1 + z210 / n;
23587
23591
  const center = (p + z210 / (2 * n)) / denominator;
23588
- const margin = z112 / denominator * Math.sqrt(p * (1 - p) / n + z210 / (4 * n * n));
23592
+ const margin = z111 / denominator * Math.sqrt(p * (1 - p) / n + z210 / (4 * n * n));
23589
23593
  const lower = Math.max(0, center - margin);
23590
23594
  const upper = Math.min(1, center + margin);
23591
23595
  const standardError = Math.sqrt(p * (1 - p) / n);
@@ -23615,8 +23619,8 @@ function meanConfidenceInterval(values, options = {}) {
23615
23619
  const variance = values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / (n - 1 || 1);
23616
23620
  const stdDev = Math.sqrt(variance);
23617
23621
  const standardError = stdDev / Math.sqrt(n);
23618
- const z112 = getZScore(opts.confidence);
23619
- const margin = z112 * standardError;
23622
+ const z111 = getZScore(opts.confidence);
23623
+ const margin = z111 * standardError;
23620
23624
  return {
23621
23625
  lower: mean - margin,
23622
23626
  upper: mean + margin,
@@ -25366,9 +25370,9 @@ function generateTopicsTable(index) {
25366
25370
  "multi-agent-worker-dispatch": "Worker dispatch and wave execution"
25367
25371
  };
25368
25372
  const rows = topicStats.map((stat5) => {
25369
- const description2 = topicDescriptions[stat5.topic];
25373
+ const description = topicDescriptions[stat5.topic];
25370
25374
  const topicLink = `[${capitalizeWords(stat5.topic.replaceAll("-", " "))}](topics/${stat5.topic}/README.md)`;
25371
- return `| ${topicLink} | ${String(stat5.paperCount)} | ${String(stat5.techniqueCount)} | ${description2 ?? ""} |`;
25375
+ return `| ${topicLink} | ${String(stat5.paperCount)} | ${String(stat5.techniqueCount)} | ${description ?? ""} |`;
25372
25376
  });
25373
25377
  return `---
25374
25378
 
@@ -26037,7 +26041,7 @@ function registerCreateExpertTool(server, deps) {
26037
26041
  ]).describe("Expert role to create"),
26038
26042
  modelPreference: z44.string().max(100).optional().describe("Preferred model (e.g., claude-sonnet-4)")
26039
26043
  };
26040
- const description2 = "Create a specialized expert agent for code, architecture, security, documentation, testing, devops, research, product management, UX, or infrastructure tasks";
26044
+ const description = "Create a specialized expert agent for code, architecture, security, documentation, testing, devops, research, product management, UX, or infrastructure tasks";
26041
26045
  const secureHandler = createSecureHandler(createCreateExpertHandler(deps), {
26042
26046
  toolName: "create_expert",
26043
26047
  rateLimiter: deps.rateLimiter,
@@ -26047,7 +26051,7 @@ function registerCreateExpertTool(server, deps) {
26047
26051
  const wrappedHandler = wrapToolWithTimeout("create_expert", secureHandler, { timeoutMs, logger: logger55 });
26048
26052
  server.registerTool(
26049
26053
  "create_expert",
26050
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("create_expert") },
26054
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("create_expert") },
26051
26055
  toSdkCallback(wrappedHandler)
26052
26056
  );
26053
26057
  logger55.info("Registered create_expert tool with secure handler and timeout protection");
@@ -27001,7 +27005,7 @@ async function populateUnifiedContextOnState(state) {
27001
27005
  try {
27002
27006
  const taskCandidate = state["task"];
27003
27007
  if (typeof taskCandidate !== "string" || taskCandidate === "") return;
27004
- const { getContextForTask: getContextForTask2, inferTaskCategory: inferTaskCategory2 } = await import("./context-retriever-6O6TREXH.js");
27008
+ const { getContextForTask: getContextForTask2, inferTaskCategory: inferTaskCategory2 } = await import("./context-retriever-H22L3WFV.js");
27005
27009
  const ctx = await getContextForTask2({
27006
27010
  task: taskCandidate,
27007
27011
  category: inferTaskCategory2(taskCandidate),
@@ -28030,12 +28034,12 @@ var logger18 = createLogger({ component: "CorePlugins" });
28030
28034
  function noopStageResult() {
28031
28035
  return { success: true, outputArtifacts: [], metadata: { stub: true } };
28032
28036
  }
28033
- function createCorePlugin(id, description2, stages) {
28037
+ function createCorePlugin(id, description, stages) {
28034
28038
  return {
28035
28039
  manifest: {
28036
28040
  id,
28037
28041
  version: "1.0.0",
28038
- description: description2,
28042
+ description,
28039
28043
  stages,
28040
28044
  requiredCapabilities: [],
28041
28045
  trustLevel: "core",
@@ -34288,7 +34292,7 @@ function registerOrchestrateTool(server, deps) {
34288
34292
  const logger55 = deps.logger ?? createLogger({ tool: "orchestrate" });
34289
34293
  const notifier = deps.notifier ?? createMcpNotifier(server);
34290
34294
  const depsWithNotifier = { ...deps, notifier };
34291
- const description2 = "Orchestrate a task by analyzing it, breaking it into subtasks if needed, and coordinating expert agents";
34295
+ const description = "Orchestrate a task by analyzing it, breaking it into subtasks if needed, and coordinating expert agents";
34292
34296
  const secureHandler = createSecureHandler(createOrchestrateHandler(depsWithNotifier), {
34293
34297
  toolName: "orchestrate",
34294
34298
  securityTier: "user-facing",
@@ -34303,7 +34307,7 @@ function registerOrchestrateTool(server, deps) {
34303
34307
  server.registerTool(
34304
34308
  "orchestrate",
34305
34309
  {
34306
- description: description2,
34310
+ description,
34307
34311
  inputSchema: ORCHESTRATE_TOOL_SCHEMA,
34308
34312
  annotations: getToolAnnotations("orchestrate")
34309
34313
  },
@@ -35865,7 +35869,7 @@ function registerListExpertsTool(server, deps) {
35865
35869
  const toolSchema = {
35866
35870
  format: z57.enum(["full", "names"]).optional().describe("Output format: full (with details) or names (just role names)")
35867
35871
  };
35868
- const description2 = "Inventory of expert ROLES available to `create_expert` (architect, security, devex, etc.). Use this BEFORE create_expert to pick a role; returns role name, capability summary, default model.";
35872
+ const description = "Inventory of expert ROLES available to `create_expert` (architect, security, devex, etc.). Use this BEFORE create_expert to pick a role; returns role name, capability summary, default model.";
35869
35873
  const secureHandler = createSecureHandler(listExpertsHandler, {
35870
35874
  toolName: "list_experts",
35871
35875
  rateLimiter: deps.rateLimiter,
@@ -35887,7 +35891,7 @@ function registerListExpertsTool(server, deps) {
35887
35891
  server.registerTool(
35888
35892
  "list_experts",
35889
35893
  {
35890
- description: description2,
35894
+ description,
35891
35895
  inputSchema: toolSchema,
35892
35896
  outputSchema,
35893
35897
  annotations: getToolAnnotations("list_experts")
@@ -35958,7 +35962,7 @@ function registerListWorkflowsTool(server, deps) {
35958
35962
  category: z58.string().optional().describe("Filter by category (e.g., development, security)"),
35959
35963
  format: z58.enum(["full", "names"]).optional().describe("Output format: full (with details) or names (just template names)")
35960
35964
  };
35961
- const description2 = "Inventory of multi-step TEMPLATES available to `run_workflow` (code-review, security-audit, etc.). Use this BEFORE run_workflow to pick a template; returns template name, version, description, category, and required inputs.";
35965
+ const description = "Inventory of multi-step TEMPLATES available to `run_workflow` (code-review, security-audit, etc.). Use this BEFORE run_workflow to pick a template; returns template name, version, description, category, and required inputs.";
35962
35966
  const secureHandler = createSecureHandler(createListWorkflowsHandler(deps.workflowEngine), {
35963
35967
  toolName: "list_workflows",
35964
35968
  rateLimiter: deps.rateLimiter,
@@ -35985,7 +35989,7 @@ function registerListWorkflowsTool(server, deps) {
35985
35989
  server.registerTool(
35986
35990
  "list_workflows",
35987
35991
  {
35988
- description: description2,
35992
+ description,
35989
35993
  inputSchema: toolSchema,
35990
35994
  outputSchema,
35991
35995
  annotations: getToolAnnotations("list_workflows")
@@ -36200,10 +36204,10 @@ function sanitizeExpertSummary(summary) {
36200
36204
  function buildTask(input) {
36201
36205
  const autoTimeout = getExpertTaskTimeout(input.task);
36202
36206
  const timeoutMs = input.timeoutMs ?? autoTimeout;
36203
- let description2 = input.task;
36207
+ let description = input.task;
36204
36208
  if (input.previousExpertSummary !== void 0) {
36205
36209
  const sanitized = sanitizeExpertSummary(input.previousExpertSummary);
36206
- description2 = `[Previous expert context]
36210
+ description = `[Previous expert context]
36207
36211
  ${sanitized}
36208
36212
 
36209
36213
  [Your task]
@@ -36211,7 +36215,7 @@ ${input.task}`;
36211
36215
  }
36212
36216
  return {
36213
36217
  id: `exec-${String(getTimeProvider().now())}-${getRandomProvider().random().toString(36).slice(2, 9)}`,
36214
- description: description2,
36218
+ description,
36215
36219
  context: {
36216
36220
  metadata: input.context ?? {}
36217
36221
  },
@@ -36564,11 +36568,11 @@ function registerExecuteExpertTool(server, deps) {
36564
36568
  const logger55 = deps.logger ?? createLogger({ tool: "execute_expert" });
36565
36569
  const notifier = deps.notifier ?? createMcpNotifier(server);
36566
36570
  const depsWithNotifier = { ...deps, notifier };
36567
- const description2 = "Run a task through an expert YOU PREVIOUSLY CREATED via `create_expert`. Requires the expertId returned by create_expert; not for ad-hoc execution. Returns the expert analysis including output, confidence, and token usage.";
36571
+ const description = "Run a task through an expert YOU PREVIOUSLY CREATED via `create_expert`. Requires the expertId returned by create_expert; not for ad-hoc execution. Returns the expert analysis including output, confidence, and token usage.";
36568
36572
  server.experimental.tasks.registerToolTask(
36569
36573
  "execute_expert",
36570
36574
  {
36571
- description: description2,
36575
+ description,
36572
36576
  inputSchema: EXECUTE_EXPERT_TOOL_SCHEMA,
36573
36577
  execution: { taskSupport: "optional" },
36574
36578
  annotations: getToolAnnotations("execute_expert")
@@ -37990,7 +37994,7 @@ function registerResearchQueryTool(server, deps) {
37990
37994
  status: z62.enum(["implemented", "planned", "not-started", "rejected", "all"]).optional().describe("Filter by technique status"),
37991
37995
  threshold: z62.number().min(0).max(1).optional().describe("Overlap threshold (0-1) for overlap action")
37992
37996
  };
37993
- const description2 = "Query the research registry for technique status, overlaps, statistics, or text search. Provides read-only access to the research tracking system.";
37997
+ const description = "Query the research registry for technique status, overlaps, statistics, or text search. Provides read-only access to the research tracking system.";
37994
37998
  const secureHandler = createSecureHandler(createResearchQueryHandler(deps), {
37995
37999
  toolName: "research_query",
37996
38000
  rateLimiter: deps.rateLimiter,
@@ -38009,7 +38013,7 @@ function registerResearchQueryTool(server, deps) {
38009
38013
  server.registerTool(
38010
38014
  "research_query",
38011
38015
  {
38012
- description: description2,
38016
+ description,
38013
38017
  inputSchema: toolSchema,
38014
38018
  outputSchema,
38015
38019
  annotations: getToolAnnotations("research_query")
@@ -38098,7 +38102,7 @@ function registerResearchAddTool(server, deps) {
38098
38102
  priority: z63.enum(["P1", "P2", "P3", "P4"]).optional().describe("Priority level"),
38099
38103
  dryRun: z63.boolean().optional().default(false).describe("Preview without persisting")
38100
38104
  };
38101
- const description2 = "PAPER-only: add an arXiv preprint to the research registry by arXiv ID. Fetches metadata from arxiv.org and persists to the registry. For non-paper sources (GitHub repos, tools, blogs) use `research_add_source` instead. Use dryRun=true to preview without saving.";
38105
+ const description = "PAPER-only: add an arXiv preprint to the research registry by arXiv ID. Fetches metadata from arxiv.org and persists to the registry. For non-paper sources (GitHub repos, tools, blogs) use `research_add_source` instead. Use dryRun=true to preview without saving.";
38102
38106
  const secureHandler = createSecureHandler(createResearchAddHandler(deps), {
38103
38107
  toolName: "research_add",
38104
38108
  rateLimiter: deps.rateLimiter,
@@ -38119,7 +38123,7 @@ function registerResearchAddTool(server, deps) {
38119
38123
  server.registerTool(
38120
38124
  "research_add",
38121
38125
  {
38122
- description: description2,
38126
+ description,
38123
38127
  inputSchema: toolSchema,
38124
38128
  outputSchema,
38125
38129
  annotations: getToolAnnotations("research_add")
@@ -38314,7 +38318,7 @@ function registerResearchAddSourceTool(server, deps) {
38314
38318
  verdict_notes: z64.string().max(500).optional().describe("Verdict notes"),
38315
38319
  dryRun: z64.boolean().optional().default(false).describe("Preview only")
38316
38320
  };
38317
- const description2 = "NON-PAPER source: add a GitHub repo / tool / blog URL to the research registry. Auto-computes quality_score from provided quality_signals. For arXiv papers use `research_add` instead. Use dryRun=true to preview without saving.";
38321
+ const description = "NON-PAPER source: add a GitHub repo / tool / blog URL to the research registry. Auto-computes quality_score from provided quality_signals. For arXiv papers use `research_add` instead. Use dryRun=true to preview without saving.";
38318
38322
  const secureHandler = createSecureHandler(createResearchAddSourceHandler(deps), {
38319
38323
  toolName: "research_add_source",
38320
38324
  securityTier: "external",
@@ -38329,7 +38333,7 @@ function registerResearchAddSourceTool(server, deps) {
38329
38333
  server.registerTool(
38330
38334
  "research_add_source",
38331
38335
  {
38332
- description: description2,
38336
+ description,
38333
38337
  inputSchema: toolSchema,
38334
38338
  outputSchema: RESEARCH_ADD_SOURCE_OUTPUT_SCHEMA,
38335
38339
  annotations: getToolAnnotations("research_add_source")
@@ -38649,7 +38653,7 @@ function registerResearchDiscoverTool(server, deps) {
38649
38653
  sinceDate: z65.string().optional().describe("Only results after this date (YYYY-MM-DD)"),
38650
38654
  relevanceThreshold: z65.number().min(0).max(1).optional().describe("Minimum relevance score (0-1) to include results. Higher = stricter filtering.")
38651
38655
  };
38652
- const description2 = "Discover new research papers and repositories from external sources. Searches arXiv, GitHub, and other sources. Filters out items already in the registry.";
38656
+ const description = "Discover new research papers and repositories from external sources. Searches arXiv, GitHub, and other sources. Filters out items already in the registry.";
38653
38657
  const secureHandler = createSecureHandler(createResearchDiscoverHandler(deps), {
38654
38658
  toolName: "research_discover",
38655
38659
  rateLimiter: deps.rateLimiter,
@@ -38663,7 +38667,7 @@ function registerResearchDiscoverTool(server, deps) {
38663
38667
  server.registerTool(
38664
38668
  "research_discover",
38665
38669
  {
38666
- description: description2,
38670
+ description,
38667
38671
  inputSchema: toolSchema,
38668
38672
  outputSchema: RESEARCH_DISCOVER_OUTPUT_SCHEMA,
38669
38673
  annotations: getToolAnnotations("research_discover")
@@ -38937,7 +38941,7 @@ function registerResearchAnalyzeTool(server, deps) {
38937
38941
  focus: z66.enum(["gaps", "trends", "priorities", "stale", "coverage"]).describe("Analysis focus area"),
38938
38942
  topic: z66.string().optional().describe("Optional topic filter")
38939
38943
  };
38940
- const description2 = "Analyze the research registry for gaps, trends, priorities, stale entries, or coverage. Returns structured analysis with recommendations.";
38944
+ const description = "Analyze the research registry for gaps, trends, priorities, stale entries, or coverage. Returns structured analysis with recommendations.";
38941
38945
  const secureHandler = createSecureHandler(createResearchAnalyzeHandler(deps), {
38942
38946
  toolName: "research_analyze",
38943
38947
  rateLimiter: deps.rateLimiter,
@@ -38957,7 +38961,7 @@ function registerResearchAnalyzeTool(server, deps) {
38957
38961
  server.registerTool(
38958
38962
  "research_analyze",
38959
38963
  {
38960
- description: description2,
38964
+ description,
38961
38965
  inputSchema: toolSchema,
38962
38966
  outputSchema,
38963
38967
  annotations: getToolAnnotations("research_analyze")
@@ -39112,7 +39116,7 @@ function registerResearchCatalogReviewTool(server, deps) {
39112
39116
  topic: z67.string().optional().describe("Topic for approved papers"),
39113
39117
  createIssue: z67.boolean().optional().describe("Create GitHub issue when approving")
39114
39118
  };
39115
- const description2 = "Review auto-cataloged research references found during tool execution. List pending references, approve them for registry addition, dismiss, or clear all.";
39119
+ const description = "Review auto-cataloged research references found during tool execution. List pending references, approve them for registry addition, dismiss, or clear all.";
39116
39120
  const secureHandler = createSecureHandler(createCatalogReviewHandler(deps), {
39117
39121
  toolName: "research_catalog_review",
39118
39122
  rateLimiter: deps.rateLimiter,
@@ -39132,7 +39136,7 @@ function registerResearchCatalogReviewTool(server, deps) {
39132
39136
  server.registerTool(
39133
39137
  "research_catalog_review",
39134
39138
  {
39135
- description: description2,
39139
+ description,
39136
39140
  inputSchema: toolSchema,
39137
39141
  outputSchema,
39138
39142
  annotations: getToolAnnotations("research_catalog_review")
@@ -39174,7 +39178,7 @@ function registerResearchSynthesizeTool(server, deps) {
39174
39178
  const toolSchema = {
39175
39179
  topic: z68.string().optional().describe("Optional topic filter for single-cluster synthesis")
39176
39180
  };
39177
- const description2 = "Synthesize the research registry by grouping papers into topic clusters. Returns structured summaries with common themes, key insights, techniques, implementation opportunities, and cross-cutting themes across clusters.";
39181
+ const description = "Synthesize the research registry by grouping papers into topic clusters. Returns structured summaries with common themes, key insights, techniques, implementation opportunities, and cross-cutting themes across clusters.";
39178
39182
  const secureHandler = createSecureHandler(createResearchSynthesizeHandler(deps), {
39179
39183
  toolName: "research_synthesize",
39180
39184
  rateLimiter: deps.rateLimiter,
@@ -39194,7 +39198,7 @@ function registerResearchSynthesizeTool(server, deps) {
39194
39198
  server.registerTool(
39195
39199
  "research_synthesize",
39196
39200
  {
39197
- description: description2,
39201
+ description,
39198
39202
  inputSchema: toolSchema,
39199
39203
  outputSchema,
39200
39204
  annotations: getToolAnnotations("research_synthesize")
@@ -39266,7 +39270,7 @@ function registerIssueTriageTool(server, deps) {
39266
39270
  issueUrl: z69.string().min(1).describe("GitHub issue URL (e.g., https://github.com/owner/repo/issues/123)"),
39267
39271
  dryRun: z69.boolean().optional().default(true).describe("Read-only mode (default: true)")
39268
39272
  };
39269
- const description2 = "Triage a GitHub issue using the full security pipeline. Classifies the issue, assesses author trust and reputation, proposes labels and actions, and validates all outputs through policy gate and corroboration checks. Read-only by default. Requires GITHUB_TOKEN or GH_TOKEN environment variable, or gh CLI auth.";
39273
+ const description = "Triage a GitHub issue using the full security pipeline. Classifies the issue, assesses author trust and reputation, proposes labels and actions, and validates all outputs through policy gate and corroboration checks. Read-only by default. Requires GITHUB_TOKEN or GH_TOKEN environment variable, or gh CLI auth.";
39270
39274
  const secureHandler = createSecureHandler(createIssueTriageHandler(deps), {
39271
39275
  toolName: "issue_triage",
39272
39276
  securityTier: "external",
@@ -39280,7 +39284,7 @@ function registerIssueTriageTool(server, deps) {
39280
39284
  });
39281
39285
  server.registerTool(
39282
39286
  "issue_triage",
39283
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("issue_triage") },
39287
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("issue_triage") },
39284
39288
  toSdkCallback(wrappedHandler)
39285
39289
  );
39286
39290
  logger55.info("Registered issue_triage tool with secure handler and timeout protection");
@@ -40106,10 +40110,10 @@ function registerExecuteSpecTool(server, deps) {
40106
40110
  ),
40107
40111
  dryRun: z71.boolean().optional().describe("Parse and decompose only (no execution)")
40108
40112
  };
40109
- const description2 = "Execute a markdown specification through the full pipeline: parse, decompose into task DAG, compile to graph, execute, validate against acceptance criteria, and analyze failures.";
40113
+ const description = "Execute a markdown specification through the full pipeline: parse, decompose into task DAG, compile to graph, execute, validate against acceptance criteria, and analyze failures.";
40110
40114
  server.registerTool(
40111
40115
  "execute_spec",
40112
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("execute_spec") },
40116
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("execute_spec") },
40113
40117
  toSdkCallback(wrapped)
40114
40118
  );
40115
40119
  logger55.info("Registered execute_spec tool");
@@ -40251,7 +40255,7 @@ function registerMemoryQueryTool(server, deps) {
40251
40255
  limit: z72.number().int().min(1).max(50).optional().describe("Maximum results to return (default: 10, max: 50)"),
40252
40256
  source: z72.enum(["session", "belief", "agentic", "typed", "adaptive", "all"]).optional().describe("Filter by memory source (default: all)")
40253
40257
  };
40254
- const description2 = "Query across all memory backends (session, belief, agentic, adaptive, typed) with unified results. Returns memories matching the query with source attribution and relevance scores.";
40258
+ const description = "Query across all memory backends (session, belief, agentic, adaptive, typed) with unified results. Returns memories matching the query with source attribution and relevance scores.";
40255
40259
  const secureHandler = createSecureHandler(memoryQueryHandler, {
40256
40260
  toolName: "memory_query",
40257
40261
  rateLimiter: deps.rateLimiter,
@@ -40269,7 +40273,7 @@ function registerMemoryQueryTool(server, deps) {
40269
40273
  server.registerTool(
40270
40274
  "memory_query",
40271
40275
  {
40272
- description: description2,
40276
+ description,
40273
40277
  inputSchema: toolSchema,
40274
40278
  outputSchema,
40275
40279
  annotations: getToolAnnotations("memory_query")
@@ -40369,7 +40373,7 @@ function registerMemoryStatsTool(server, deps) {
40369
40373
  const toolSchema = {
40370
40374
  includeDecay: z73.boolean().optional().describe("Include decay statistics (default: true)")
40371
40375
  };
40372
- const description2 = "Get memory system statistics dashboard. Shows backend availability, entry counts, and decay stats across all 7 memory backends.";
40376
+ const description = "Get memory system statistics dashboard. Shows backend availability, entry counts, and decay stats across all 7 memory backends.";
40373
40377
  const secureHandler = createSecureHandler(memoryStatsHandler, {
40374
40378
  toolName: "memory_stats",
40375
40379
  rateLimiter: deps.rateLimiter,
@@ -40390,7 +40394,7 @@ function registerMemoryStatsTool(server, deps) {
40390
40394
  server.registerTool(
40391
40395
  "memory_stats",
40392
40396
  {
40393
- description: description2,
40397
+ description,
40394
40398
  inputSchema: toolSchema,
40395
40399
  outputSchema,
40396
40400
  annotations: getToolAnnotations("memory_stats")
@@ -40402,87 +40406,6 @@ function registerMemoryStatsTool(server, deps) {
40402
40406
 
40403
40407
  // src/mcp/tools/memory-write.ts
40404
40408
  import { z as z74 } from "zod";
40405
-
40406
- // src/mcp/middleware/tool-prerequisites.ts
40407
- import { execFile as execFile2 } from "child_process";
40408
- import { access as access2, constants } from "fs/promises";
40409
- import { dirname as dirname5 } from "path";
40410
- import { promisify as promisify2 } from "util";
40411
- var execFileAsync2 = promisify2(execFile2);
40412
- async function ghCliAvailable() {
40413
- try {
40414
- await execFileAsync2("gh", ["--version"], { timeout: 5e3 });
40415
- return { ok: true };
40416
- } catch (err2) {
40417
- return {
40418
- ok: false,
40419
- remediation: `the 'gh' CLI is not available (${getErrorMessage(err2)}) \u2014 install GitHub CLI and authenticate (\`gh auth login\`)`
40420
- };
40421
- }
40422
- }
40423
- async function dataDirWritable() {
40424
- const dir = getNexusDataDir();
40425
- try {
40426
- await access2(dir, constants.W_OK);
40427
- return { ok: true };
40428
- } catch {
40429
- try {
40430
- await access2(dirname5(dir), constants.W_OK);
40431
- return { ok: true };
40432
- } catch (err2) {
40433
- return {
40434
- ok: false,
40435
- remediation: `NEXUS_DATA_DIR (${dir}) is not writable or creatable (${getErrorMessage(err2)}) \u2014 fix its permissions; run \`nexus-agents doctor\` to diagnose`
40436
- };
40437
- }
40438
- }
40439
- }
40440
- var TOOL_PREREQUISITES = {
40441
- improvement_review: {
40442
- name: "gh-cli-available",
40443
- rationale: "improvement_review's fileIssues mode shells out to `gh` to file candidate issues; without it the write path fails mid-operation",
40444
- check: ghCliAvailable
40445
- },
40446
- memory_write: {
40447
- name: "data-dir-writable",
40448
- rationale: "memory_write persists entries under NEXUS_DATA_DIR \u2014 an unwritable data dir fails the write confusingly mid-operation",
40449
- check: dataDirWritable
40450
- },
40451
- registry_import: {
40452
- name: "data-dir-writable",
40453
- rationale: "registry_import persists a draft registry entry under NEXUS_DATA_DIR when not in dryRun mode",
40454
- check: dataDirWritable
40455
- }
40456
- };
40457
- function applyPrerequisite(toolName, prereq, handler3) {
40458
- return async (args, ctx) => {
40459
- let result;
40460
- try {
40461
- result = await prereq.check();
40462
- } catch (err2) {
40463
- result = { ok: false, remediation: `prerequisite check threw: ${getErrorMessage(err2)}` };
40464
- }
40465
- if (!result.ok) {
40466
- return toolStructuredError({
40467
- errorCategory: "permission",
40468
- message: `${toolName} blocked: prerequisite '${prereq.name}' not satisfied`,
40469
- detail: {
40470
- failedPrerequisite: prereq.name,
40471
- rationale: prereq.rationale,
40472
- remediation: result.remediation ?? "see .rules/tool-prerequisites.md"
40473
- }
40474
- });
40475
- }
40476
- return handler3(args, ctx);
40477
- };
40478
- }
40479
- function withPrerequisite(toolName, handler3) {
40480
- const prereq = TOOL_PREREQUISITES[toolName];
40481
- if (prereq === void 0) return handler3;
40482
- return applyPrerequisite(toolName, prereq, handler3);
40483
- }
40484
-
40485
- // src/mcp/tools/memory-write.ts
40486
40409
  var MemoryWriteInputSchema = z74.object({
40487
40410
  key: z74.string().min(1).max(200).describe("Memory identifier or subject"),
40488
40411
  content: z74.string().min(1).max(5e3).describe("Memory content to store"),
@@ -40620,7 +40543,7 @@ function registerMemoryWriteTool(server, deps) {
40620
40543
  confidence: z74.enum(["high", "medium", "low"]).optional().describe("Confidence level (default: medium)"),
40621
40544
  metadata: z74.record(z74.string().max(100), z74.string().max(500)).optional().describe("Optional key-value metadata tags")
40622
40545
  };
40623
- const description2 = "Write a memory entry to a specific backend. Supports session (learnings), belief (subject-predicate-object triples), agentic (knowledge with attributes), adaptive (priority-scored), and typed (MIRIX-style semantic) backends.";
40546
+ const description = "Write a memory entry to a specific backend. Supports session (learnings), belief (subject-predicate-object triples), agentic (knowledge with attributes), adaptive (priority-scored), and typed (MIRIX-style semantic) backends.";
40624
40547
  const secureHandler = createSecureHandler(memoryWriteHandler, {
40625
40548
  toolName: "memory_write",
40626
40549
  rateLimiter: deps.rateLimiter,
@@ -40639,7 +40562,7 @@ function registerMemoryWriteTool(server, deps) {
40639
40562
  server.registerTool(
40640
40563
  "memory_write",
40641
40564
  {
40642
- description: description2,
40565
+ description,
40643
40566
  inputSchema: toolSchema,
40644
40567
  outputSchema,
40645
40568
  annotations: getToolAnnotations("memory_write")
@@ -40713,7 +40636,7 @@ function registerWeatherReportTool(server, deps) {
40713
40636
  ]).optional().describe("Filter by task category"),
40714
40637
  includeAdaptive: z75.boolean().optional().describe("Include adaptive routing bonuses (default: true)")
40715
40638
  };
40716
- const description2 = "Get multi-CLI performance weather report. Shows per-CLI success rates, per-category breakdowns, and adaptive routing bonus recommendations based on observed task outcomes.";
40639
+ const description = "Get multi-CLI performance weather report. Shows per-CLI success rates, per-category breakdowns, and adaptive routing bonus recommendations based on observed task outcomes.";
40717
40640
  const secureHandler = createSecureHandler(weatherReportHandler, {
40718
40641
  toolName: "weather_report",
40719
40642
  rateLimiter: deps.rateLimiter,
@@ -40726,7 +40649,7 @@ function registerWeatherReportTool(server, deps) {
40726
40649
  });
40727
40650
  server.registerTool(
40728
40651
  "weather_report",
40729
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("weather_report") },
40652
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("weather_report") },
40730
40653
  toSdkCallback(wrappedHandler)
40731
40654
  );
40732
40655
  logger55.info("Registered weather_report tool");
@@ -40858,7 +40781,7 @@ function registerRegistryImportTool(server, deps) {
40858
40781
  modelId: z77.string().min(1).describe("Provider model identifier"),
40859
40782
  dryRun: z77.boolean().optional().describe("Preview without persisting (default: true)")
40860
40783
  };
40861
- const description2 = "Draft a registry ENTRY for a NEW model so routing can consider it later. Generates a ModelCapability YAML with conservative quality scores (5/10) for human review. For picking among ALREADY-registered models, use `delegate_to_model`. Use dryRun=true (default) to preview the entry without saving.";
40784
+ const description = "Draft a registry ENTRY for a NEW model so routing can consider it later. Generates a ModelCapability YAML with conservative quality scores (5/10) for human review. For picking among ALREADY-registered models, use `delegate_to_model`. Use dryRun=true (default) to preview the entry without saving.";
40862
40785
  const secureHandler = createSecureHandler(registryImportHandler, {
40863
40786
  toolName: "registry_import",
40864
40787
  rateLimiter: deps.rateLimiter,
@@ -40872,7 +40795,7 @@ function registerRegistryImportTool(server, deps) {
40872
40795
  });
40873
40796
  server.registerTool(
40874
40797
  "registry_import",
40875
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("registry_import") },
40798
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("registry_import") },
40876
40799
  toSdkCallback(wrappedHandler)
40877
40800
  );
40878
40801
  logger55.info("Registered registry_import tool");
@@ -40913,7 +40836,7 @@ function registerRepoAnalyzeTool(server, deps) {
40913
40836
  repo: z79.string().min(1).describe('GitHub repository in "owner/name" format or full URL'),
40914
40837
  depth: z79.enum(["shallow", "deep"]).optional().describe("Analysis depth: shallow (tree + README) or deep")
40915
40838
  };
40916
- const description2 = "Analyze a GitHub repository structure. Returns language, framework, package manager, CI provider, security tooling, Dockerfile/Helm/Makefile detection, and gap identification. Replaces multi-step manual inspection with a single structured query.";
40839
+ const description = "Analyze a GitHub repository structure. Returns language, framework, package manager, CI provider, security tooling, Dockerfile/Helm/Makefile detection, and gap identification. Replaces multi-step manual inspection with a single structured query.";
40917
40840
  const secureHandler = createSecureHandler(repoAnalyzeHandler, {
40918
40841
  toolName: "repo_analyze",
40919
40842
  rateLimiter: deps.rateLimiter,
@@ -40926,7 +40849,7 @@ function registerRepoAnalyzeTool(server, deps) {
40926
40849
  });
40927
40850
  server.registerTool(
40928
40851
  "repo_analyze",
40929
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("repo_analyze") },
40852
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("repo_analyze") },
40930
40853
  toSdkCallback(wrappedHandler)
40931
40854
  );
40932
40855
  logger55.info("Registered repo_analyze tool");
@@ -40967,7 +40890,7 @@ function registerRepoSecurityPlanTool(server, deps) {
40967
40890
  categories: z81.array(z81.string().max(50)).max(10).optional().describe('Filter to specific categories (e.g., ["sast", "sca", "secrets"])'),
40968
40891
  maxScanners: z81.number().min(1).max(20).optional().describe("Maximum scanners to recommend (default: 10)")
40969
40892
  };
40970
- const description2 = "Generate a security scanning pipeline recommendation for a GitHub repository. Analyzes repo structure, detects languages/frameworks, and recommends specific vulnerability scanners with CI config snippets. Powered by the vulnerability scanner registry with provenance-tracked metrics.";
40893
+ const description = "Generate a security scanning pipeline recommendation for a GitHub repository. Analyzes repo structure, detects languages/frameworks, and recommends specific vulnerability scanners with CI config snippets. Powered by the vulnerability scanner registry with provenance-tracked metrics.";
40971
40894
  const secureHandler = createSecureHandler(handler, {
40972
40895
  toolName: "repo_security_plan",
40973
40896
  rateLimiter: deps.rateLimiter,
@@ -40980,7 +40903,7 @@ function registerRepoSecurityPlanTool(server, deps) {
40980
40903
  });
40981
40904
  server.registerTool(
40982
40905
  "repo_security_plan",
40983
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("repo_security_plan") },
40906
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("repo_security_plan") },
40984
40907
  toSdkCallback(wrappedHandler)
40985
40908
  );
40986
40909
  logger55.info("Registered repo_security_plan tool");
@@ -41106,7 +41029,7 @@ function registerSearchCodebaseTool(server, deps) {
41106
41029
  limit: z82.number().min(1).max(50).optional().describe("Max results"),
41107
41030
  mode: z82.enum(["search", "summary", "list"]).optional().describe("search/summary/list")
41108
41031
  };
41109
- const description2 = "Cross-file ripgrep-style search across the working directory. Builds an in-memory symbol index and ranks matches with relevance scoring. Use when you need usages of a symbol or pattern across MANY files. For the AST of a single file, use `extract_symbols` instead. Modes: search (find by keyword), summary (per-file overview), list (all indexed files).";
41032
+ const description = "Cross-file ripgrep-style search across the working directory. Builds an in-memory symbol index and ranks matches with relevance scoring. Use when you need usages of a symbol or pattern across MANY files. For the AST of a single file, use `extract_symbols` instead. Modes: search (find by keyword), summary (per-file overview), list (all indexed files).";
41110
41033
  const secureHandler = createSecureHandler(searchCodebaseHandler, {
41111
41034
  toolName: "search_codebase",
41112
41035
  rateLimiter: deps.rateLimiter,
@@ -41116,7 +41039,7 @@ function registerSearchCodebaseTool(server, deps) {
41116
41039
  const wrapped = wrapToolWithTimeout("search_codebase", secureHandler, { timeoutMs, logger: logger55 });
41117
41040
  server.registerTool(
41118
41041
  "search_codebase",
41119
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("search_codebase") },
41042
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("search_codebase") },
41120
41043
  toSdkCallback(wrapped)
41121
41044
  );
41122
41045
  logger55.info("Registered search_codebase tool");
@@ -41191,7 +41114,7 @@ function registerExtractSymbolsTool(server, deps) {
41191
41114
  filePath: z83.string().min(1).max(500).describe("Path to TypeScript/JavaScript file"),
41192
41115
  mode: z83.enum(["index", "full"]).optional().describe("index (default): names+lines. full: includes source text")
41193
41116
  };
41194
- const description2 = "Parse a SINGLE TypeScript/JavaScript file with tree-sitter and return its structural AST symbols. Use when you need the structure of one file \u2014 function/class/method/interface/type definitions. Not a cross-file search; for that use `search_codebase`. Output is 80%+ smaller than reading the full file.";
41117
+ const description = "Parse a SINGLE TypeScript/JavaScript file with tree-sitter and return its structural AST symbols. Use when you need the structure of one file \u2014 function/class/method/interface/type definitions. Not a cross-file search; for that use `search_codebase`. Output is 80%+ smaller than reading the full file.";
41195
41118
  const secureHandler = createSecureHandler(extractSymbolsHandler, {
41196
41119
  toolName: "extract_symbols",
41197
41120
  rateLimiter: deps.rateLimiter,
@@ -41204,7 +41127,7 @@ function registerExtractSymbolsTool(server, deps) {
41204
41127
  });
41205
41128
  server.registerTool(
41206
41129
  "extract_symbols",
41207
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("extract_symbols") },
41130
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("extract_symbols") },
41208
41131
  toSdkCallback(wrapped)
41209
41132
  );
41210
41133
  logger55.info("Registered extract_symbols tool");
@@ -41326,7 +41249,7 @@ function registerQueryTraceTool(server, deps) {
41326
41249
  eventType: z84.string().max(100).regex(/^[a-zA-Z0-9._-]+$/).optional().describe("Filter by event type (e.g., model.called)"),
41327
41250
  limit: z84.number().min(1).max(500).optional().describe("Max events to return (default: 100)")
41328
41251
  };
41329
- const description2 = "Query execution traces by run ID. Returns agent and model attribution for pipeline runs including decision paths, error taxonomy, and timing data.";
41252
+ const description = "Query execution traces by run ID. Returns agent and model attribution for pipeline runs including decision paths, error taxonomy, and timing data.";
41330
41253
  const secureHandler = createSecureHandler(queryTraceHandler, {
41331
41254
  toolName: "query_trace",
41332
41255
  rateLimiter: deps.rateLimiter,
@@ -41336,7 +41259,7 @@ function registerQueryTraceTool(server, deps) {
41336
41259
  const wrappedHandler = wrapToolWithTimeout("query_trace", secureHandler, { timeoutMs, logger: logger55 });
41337
41260
  server.registerTool(
41338
41261
  "query_trace",
41339
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("query_trace") },
41262
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("query_trace") },
41340
41263
  toSdkCallback(wrappedHandler)
41341
41264
  );
41342
41265
  logger55.info("Registered query_trace tool");
@@ -42485,7 +42408,7 @@ async function tryIssueTriage(task) {
42485
42408
  try {
42486
42409
  const issueMatch = task.match(/github\.com\/([^/]+\/[^/]+)\/issues\/(\d+)/);
42487
42410
  if (issueMatch === null) return null;
42488
- const { createIssueTriage } = await import("./issue-triage-KZTENUDH.js");
42411
+ const { createIssueTriage } = await import("./issue-triage-VVNQIQW5.js");
42489
42412
  const triage = createIssueTriage();
42490
42413
  const owner = issueMatch[1] ?? "";
42491
42414
  const num = issueMatch[2] ?? "";
@@ -42513,7 +42436,7 @@ var VALID_TEMPLATES = /* @__PURE__ */ new Set([
42513
42436
  ]);
42514
42437
  async function classifyWithLLM(task) {
42515
42438
  try {
42516
- const { executeExpert: executeExpert2 } = await import("./expert-bridge-Q3OWPD4L.js");
42439
+ const { executeExpert: executeExpert2 } = await import("./expert-bridge-IAQPOJAQ.js");
42517
42440
  const prompt = [
42518
42441
  "Classify this task into exactly one pipeline template.",
42519
42442
  "Templates: dev (implementation/bug fix/refactor), research (investigate/evaluate/compare),",
@@ -42777,9 +42700,9 @@ var logger34 = createLogger({ component: "security-scan" });
42777
42700
  var SCAN_TIMEOUT_MS = 3e5;
42778
42701
  async function isSemgrepAvailable() {
42779
42702
  try {
42780
- const { execFile: execFile5 } = await import("child_process");
42781
- const { promisify: promisify5 } = await import("util");
42782
- const exec2 = promisify5(execFile5);
42703
+ const { execFile: execFile3 } = await import("child_process");
42704
+ const { promisify: promisify3 } = await import("util");
42705
+ const exec2 = promisify3(execFile3);
42783
42706
  await exec2("semgrep", ["--version"], { timeout: 1e4 });
42784
42707
  return true;
42785
42708
  } catch {
@@ -42787,9 +42710,9 @@ async function isSemgrepAvailable() {
42787
42710
  }
42788
42711
  }
42789
42712
  async function runSemgrep(targetDir, rulesets) {
42790
- const { execFile: execFile5 } = await import("child_process");
42791
- const { promisify: promisify5 } = await import("util");
42792
- const exec2 = promisify5(execFile5);
42713
+ const { execFile: execFile3 } = await import("child_process");
42714
+ const { promisify: promisify3 } = await import("util");
42715
+ const exec2 = promisify3(execFile3);
42793
42716
  const args = ["--sarif", "--quiet", ...rulesets.flatMap((r) => ["--config", r]), targetDir];
42794
42717
  const { stdout } = await exec2("semgrep", args, {
42795
42718
  timeout: SCAN_TIMEOUT_MS,
@@ -43295,7 +43218,7 @@ var memoryInitPromise = null;
43295
43218
  async function initPipelineMemory() {
43296
43219
  if (cachedMemory !== null) return cachedMemory;
43297
43220
  try {
43298
- const { createSessionMemory: createSessionMemory2 } = await import("./session-memory-SXQAA2EN.js");
43221
+ const { createSessionMemory: createSessionMemory2 } = await import("./session-memory-X7CJ6X4A.js");
43299
43222
  const { getLearningDir } = await import("./learning-persistence-UKPO7RYK.js");
43300
43223
  const mem = createSessionMemory2(getLearningDir());
43301
43224
  mem.startSession(`pipeline-${String(getTimeProvider().now())}`);
@@ -43352,7 +43275,7 @@ function recordRoutingExperience(category, success, durationMs) {
43352
43275
  callRecord(routingMemoryCache);
43353
43276
  return;
43354
43277
  }
43355
- routingMemoryInitPromise ??= import("./routing-memory-YZRYGXQC.js").then(({ createRoutingMemory }) => {
43278
+ routingMemoryInitPromise ??= import("./routing-memory-5T5QJF47.js").then(({ createRoutingMemory }) => {
43356
43279
  routingMemoryCache ??= createRoutingMemory();
43357
43280
  return routingMemoryCache;
43358
43281
  }).catch((error) => {
@@ -43386,7 +43309,7 @@ ${text}` : "";
43386
43309
  }
43387
43310
  async function getWeatherContext() {
43388
43311
  try {
43389
- const { generateWeatherReport: generateWeatherReport2 } = await import("./weather-report-D6HFOK7S.js");
43312
+ const { generateWeatherReport: generateWeatherReport2 } = await import("./weather-report-SUVIXWKI.js");
43390
43313
  const report = generateWeatherReport2({ includeAdaptive: true });
43391
43314
  const mappings = "recommendedMappings" in report ? report.recommendedMappings : [];
43392
43315
  if (!Array.isArray(mappings) || mappings.length === 0) return "";
@@ -43404,7 +43327,7 @@ ${lines}
43404
43327
  }
43405
43328
  async function getMemoryContext(task) {
43406
43329
  try {
43407
- const { createSessionMemory: createSessionMemory2 } = await import("./session-memory-SXQAA2EN.js");
43330
+ const { createSessionMemory: createSessionMemory2 } = await import("./session-memory-X7CJ6X4A.js");
43408
43331
  const { getLearningDir } = await import("./learning-persistence-UKPO7RYK.js");
43409
43332
  const memory = createSessionMemory2(getLearningDir(), { maxLearningsInContext: 10 });
43410
43333
  const learnings = memory.searchLearnings(task.slice(0, 200));
@@ -43510,7 +43433,7 @@ ${contextBlock}`;
43510
43433
  const strategy = config.votingStrategy ?? "higher_order";
43511
43434
  await postProgress(config, "Vote", `Running consensus with ${strategy} strategy...`);
43512
43435
  try {
43513
- const { executeVoting } = await import("./consensus-vote-XLEQFVE7.js");
43436
+ const { executeVoting } = await import("./consensus-vote-EQAYX53Z.js");
43514
43437
  const votingResult = await executeVoting(
43515
43438
  {
43516
43439
  proposal: plan.slice(0, 4e3),
@@ -44437,7 +44360,7 @@ async function searchCodebaseForTask(task) {
44437
44360
  }
44438
44361
  async function queryResearchRegistry(task) {
44439
44362
  try {
44440
- const { synthesizeResearch: synthesizeResearch2 } = await import("./research-helpers-synthesize-CGVR6M4S.js");
44363
+ const { synthesizeResearch: synthesizeResearch2 } = await import("./research-helpers-synthesize-OSP6FGNV.js");
44441
44364
  const topic = task.split(/[.!?\n]/).filter((s) => s.trim().length > 10)[0]?.trim();
44442
44365
  if (topic === void 0) return null;
44443
44366
  const result = await synthesizeResearch2(topic.slice(0, 50));
@@ -44508,7 +44431,7 @@ function createScanStageWrapper() {
44508
44431
  try {
44509
44432
  const slug = ctx.task.match(/([a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+)/)?.[1];
44510
44433
  if (slug !== void 0) {
44511
- const { generateSecurityPlan: generateSecurityPlan2 } = await import("./repo-security-plan-XCX7EFJR.js");
44434
+ const { generateSecurityPlan: generateSecurityPlan2 } = await import("./repo-security-plan-X74TBYOV.js");
44512
44435
  const plan = await generateSecurityPlan2({ repo: slug, maxScanners: 10 });
44513
44436
  const recs = plan.recommendations.slice(0, 5).map((r) => `${r.priority}: ${r.displayName} (${r.category})`).join("; ");
44514
44437
  return output(PIPELINE_STATE_KEYS.FINDINGS, recs, getTimeProvider().now() - start, true);
@@ -44792,7 +44715,7 @@ async function prReviewHandler(args, ctx) {
44792
44715
  }
44793
44716
  function registerPrReviewTool(server, deps) {
44794
44717
  const logger55 = deps.logger ?? createLogger({ tool: "pr_review" });
44795
- const description2 = "Run multi-voter consensus review on a PR diff (#2233). 5 voters (architect, security, devex, catfish, scope_steward) each emit approve/request_changes/abstain with reasoning and citations. Reuses consensus_vote infra; experimental.";
44718
+ const description = "Run multi-voter consensus review on a PR diff (#2233). 5 voters (architect, security, devex, catfish, scope_steward) each emit approve/request_changes/abstain with reasoning and citations. Reuses consensus_vote infra; experimental.";
44796
44719
  const secureHandler = createSecureHandler(prReviewHandler, {
44797
44720
  toolName: "pr_review",
44798
44721
  rateLimiter: deps.rateLimiter,
@@ -44803,7 +44726,7 @@ function registerPrReviewTool(server, deps) {
44803
44726
  server.registerTool(
44804
44727
  "pr_review",
44805
44728
  {
44806
- description: description2,
44729
+ description,
44807
44730
  inputSchema: PrReviewInputSchema.shape,
44808
44731
  annotations: getToolAnnotations("pr_review")
44809
44732
  },
@@ -45380,923 +45303,10 @@ function registerCompareDataFeedsTool(server, deps) {
45380
45303
  logger55.info("Registered compare_data_feeds tool");
45381
45304
  }
45382
45305
 
45383
- // src/mcp/tools/improvement-review.ts
45384
- import { execFile as execFile3 } from "child_process";
45385
- import { promisify as promisify3 } from "util";
45386
- import { z as z95 } from "zod";
45387
-
45388
- // src/governance/fitness-score.ts
45389
- import { existsSync as existsSync11, readFileSync as readFileSync9, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
45390
- import { join as join11 } from "path";
45391
- function findPkgRoot() {
45392
- let dir = import.meta.dirname;
45393
- for (let i = 0; i < 10; i++) {
45394
- const pkgPath = join11(dir, "package.json");
45395
- if (existsSync11(pkgPath)) {
45396
- const content = readFileSync9(pkgPath, "utf-8");
45397
- if (content.includes('"nexus-agents"')) return dir;
45398
- }
45399
- dir = join11(dir, "..");
45400
- }
45401
- return join11(import.meta.dirname, "../..");
45402
- }
45403
- var PKG_ROOT = findPkgRoot();
45404
- var SRC_ROOT = join11(PKG_ROOT, "src");
45405
- var REPO_ROOT = join11(PKG_ROOT, "../..");
45406
- var DOCS_ROOT = join11(REPO_ROOT, "docs");
45407
- var DETERMINISM_EXCLUDES = [
45408
- /\.test\.ts$/,
45409
- /\.spec\.ts$/,
45410
- /random-provider\.ts$/,
45411
- /time-provider\.ts$/
45412
- ];
45413
- function countFiles(dir, pattern) {
45414
- if (!existsSync11(dir)) return 0;
45415
- let count = 0;
45416
- for (const entry of readdirSync2(dir)) {
45417
- const fullPath = join11(dir, entry);
45418
- const stat5 = statSync2(fullPath);
45419
- if (stat5.isDirectory() && !entry.startsWith(".")) {
45420
- count += countFiles(fullPath, pattern);
45421
- } else if (pattern.test(entry)) {
45422
- count++;
45423
- }
45424
- }
45425
- return count;
45426
- }
45427
- function fileContains(filePath, pattern) {
45428
- if (!existsSync11(filePath)) return false;
45429
- return pattern.test(readFileSync9(filePath, "utf-8"));
45430
- }
45431
- function isExcluded(entry, excludePatterns) {
45432
- return excludePatterns?.some((p) => p.test(entry)) ?? false;
45433
- }
45434
- function countMatchesInFile(fullPath, contentPattern) {
45435
- const matches = readFileSync9(fullPath, "utf-8").match(contentPattern);
45436
- return matches?.length ?? 0;
45437
- }
45438
- function countPatternInDir(dir, filePattern, contentPattern, excludePatterns) {
45439
- if (!existsSync11(dir)) return 0;
45440
- let count = 0;
45441
- for (const entry of readdirSync2(dir)) {
45442
- const fullPath = join11(dir, entry);
45443
- const stat5 = statSync2(fullPath);
45444
- if (stat5.isDirectory() && !entry.startsWith(".") && entry !== "node_modules") {
45445
- count += countPatternInDir(fullPath, filePattern, contentPattern, excludePatterns);
45446
- } else if (filePattern.test(entry) && !isExcluded(entry, excludePatterns)) {
45447
- count += countMatchesInFile(fullPath, contentPattern);
45448
- }
45449
- }
45450
- return count;
45451
- }
45452
- function clamp2(score, max) {
45453
- return Math.max(0, Math.min(max, score));
45454
- }
45455
- var FitnessScoreCalculator = class {
45456
- logger;
45457
- checks = [];
45458
- constructor(logger55) {
45459
- this.logger = logger55 ?? createLogger({ component: "FitnessScoreCalculator" });
45460
- this.registerDefaultChecks();
45461
- }
45462
- /** Register default fitness checks. */
45463
- registerDefaultChecks() {
45464
- const reg = (dimension, maxPoints, name, check) => {
45465
- this.checks.push({ dimension, maxPoints, name, check });
45466
- };
45467
- reg("canonicalPaths", 20, "Canonical Paths", () => this.checkCanonicalPaths());
45468
- reg("explicitBehavior", 15, "Explicit Behavior", () => this.checkExplicitBehavior());
45469
- reg("determinism", 15, "Determinism", () => this.checkDeterminism());
45470
- reg("observability", 15, "Observability", () => this.checkObservability());
45471
- reg("configSimplicity", 10, "Config Simplicity", () => this.checkConfigSimplicity());
45472
- reg("layerSeparation", 10, "Layer Separation", () => this.checkLayerSeparation());
45473
- reg("operatorErgonomics", 10, "Operator Ergonomics", () => this.checkOperatorErgonomics());
45474
- reg(
45475
- "governanceIntegration",
45476
- 5,
45477
- "Governance Integration",
45478
- () => this.checkGovernanceIntegration()
45479
- );
45480
- }
45481
- /** Run full fitness audit. */
45482
- audit(version) {
45483
- const findings = [];
45484
- const dimensions = {};
45485
- const cliAdaptersDir = join11(SRC_ROOT, "cli-adapters");
45486
- if (!existsSync11(cliAdaptersDir)) {
45487
- return this.notSourceRepoResult(version);
45488
- }
45489
- for (const check of this.checks) {
45490
- this.logger.debug(`Running fitness check: ${check.name}`);
45491
- const result = check.check();
45492
- dimensions[check.dimension] = result.score;
45493
- findings.push(...result.findings);
45494
- }
45495
- const score = Object.values(dimensions).reduce((sum, val) => sum + val, 0);
45496
- this.logger.info("Fitness audit complete", { score, version });
45497
- const safeDim = (k) => dimensions[k] ?? 0;
45498
- const typedDimensions = {
45499
- canonicalPaths: safeDim("canonicalPaths"),
45500
- explicitBehavior: safeDim("explicitBehavior"),
45501
- determinism: safeDim("determinism"),
45502
- observability: safeDim("observability"),
45503
- configSimplicity: safeDim("configSimplicity"),
45504
- layerSeparation: safeDim("layerSeparation"),
45505
- operatorErgonomics: safeDim("operatorErgonomics"),
45506
- governanceIntegration: safeDim("governanceIntegration")
45507
- };
45508
- return {
45509
- score,
45510
- dimensions: typedDimensions,
45511
- findings,
45512
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
45513
- version
45514
- };
45515
- }
45516
- /**
45517
- * Return when the runtime SRC_ROOT doesn't look like the nexus-agents
45518
- * source tree (#2716). One finding, score 0 — distinct from "the source
45519
- * tree is broken" because every existsSync would falsely report missing.
45520
- */
45521
- notSourceRepoResult(version) {
45522
- const finding = {
45523
- dimension: "governanceIntegration",
45524
- severity: "info",
45525
- description: `fitness-audit must run against the nexus-agents source repo, but ${SRC_ROOT}/cli-adapters does not exist. You are likely running the installed npm package via \`npx nexus-agents\`, which ships only the bundled dist/. Clone the source repo and run \`node packages/nexus-agents/dist/cli.js fitness-audit\` (or invoke \`pnpm fitness-audit\` from the workspace root).`,
45526
- pointsDeducted: 0
45527
- };
45528
- return {
45529
- score: 0,
45530
- dimensions: {
45531
- canonicalPaths: 0,
45532
- explicitBehavior: 0,
45533
- determinism: 0,
45534
- observability: 0,
45535
- configSimplicity: 0,
45536
- layerSeparation: 0,
45537
- operatorErgonomics: 0,
45538
- governanceIntegration: 0
45539
- },
45540
- findings: [finding],
45541
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
45542
- version
45543
- };
45544
- }
45545
- // =========================================================================
45546
- // Individual Checks — real filesystem analysis
45547
- // =========================================================================
45548
- /**
45549
- * Check canonical paths: penalize duplicate router implementations.
45550
- *
45551
- * The current minimum is 6 (raised from 5 in #2063 after an audit):
45552
- * 1. composite-router — pipeline orchestrator
45553
- * 2. budget-router — budget/cost filtering
45554
- * 3. zero-router — hard-constraint exclusion
45555
- * 4. preference-router — user/task preference application
45556
- * 5. topsis-router — TOPSIS multi-criteria scoring
45557
- * 6. agreement-cascade-router — agreement-based cascade retry
45558
- *
45559
- * Each stage is distinct per CLAUDE.md's documented pipeline:
45560
- * Task → BudgetRouter → ZeroRouter → PreferenceRouter → TopsisRouter → Agreement → Model
45561
- */
45562
- checkCanonicalPaths() {
45563
- const findings = [];
45564
- let score = 20;
45565
- const routerCount = countFiles(join11(SRC_ROOT, "cli-adapters"), /router\.ts$/);
45566
- const ROUTER_COUNT_THRESHOLD = 6;
45567
- if (routerCount > ROUTER_COUNT_THRESHOLD) {
45568
- const excess = routerCount - ROUTER_COUNT_THRESHOLD;
45569
- const deduction = Math.min(5, excess);
45570
- score -= deduction;
45571
- findings.push(
45572
- this.finding(
45573
- "canonicalPaths",
45574
- "warning",
45575
- `${String(routerCount)} router implementations found (target: <=${String(ROUTER_COUNT_THRESHOLD)})`,
45576
- deduction,
45577
- "Consolidate duplicate routers into CompositeRouter"
45578
- )
45579
- );
45580
- }
45581
- if (existsSync11(join11(SRC_ROOT, "cli-adapters/composite-router.ts"))) {
45582
- score += 2;
45583
- } else {
45584
- score -= 3;
45585
- findings.push(
45586
- this.finding(
45587
- "canonicalPaths",
45588
- "critical",
45589
- "CompositeRouter missing \u2014 no unified routing entry point",
45590
- 3
45591
- )
45592
- );
45593
- }
45594
- score = this.checkOrchestratorInterface(score, findings);
45595
- return { score: clamp2(score, 20), findings };
45596
- }
45597
- /** Sub-check for IOrchestrator interface and adapter wiring. */
45598
- checkOrchestratorInterface(score, findings) {
45599
- const orchPath = join11(SRC_ROOT, "core/types/orchestrator.ts");
45600
- if (existsSync11(orchPath) && fileContains(orchPath, /interface IOrchestrator/)) {
45601
- score += 3;
45602
- } else {
45603
- score -= 2;
45604
- findings.push(
45605
- this.finding("canonicalPaths", "warning", "No IOrchestrator interface in core/types", 2)
45606
- );
45607
- }
45608
- const adapterPath = join11(SRC_ROOT, "orchestration/orchestrator-adapters.ts");
45609
- if (existsSync11(adapterPath) && fileContains(adapterPath, /TechLeadAdapter|PuppeteerAdapter/)) {
45610
- score += 2;
45611
- }
45612
- return score;
45613
- }
45614
- /**
45615
- * Check explicit behavior: penalize hidden/magic behavior.
45616
- *
45617
- * Implementation is intentionally filesystem-signal-based (no AST parse).
45618
- * The `NEXUS_ALLOW_MOCK_ORCHESTRATION` guard and magic-routing pattern
45619
- * grep capture the observable failure modes that historically slipped
45620
- * past review. AST-based detection of implicit fallbacks was considered
45621
- * but not pursued — it would significantly widen this function's
45622
- * footprint and the filesystem signals already catch the recurring
45623
- * regressions. Revisit only if a new class of hidden-behavior bug
45624
- * surfaces that this grep-over-source approach can't catch.
45625
- */
45626
- checkExplicitBehavior() {
45627
- const findings = [];
45628
- let score = 15;
45629
- const mockGuardCount = countPatternInDir(
45630
- SRC_ROOT,
45631
- /\.ts$/,
45632
- /NEXUS_ALLOW_MOCK_ORCHESTRATION/g,
45633
- DETERMINISM_EXCLUDES
45634
- );
45635
- if (mockGuardCount === 0) {
45636
- score -= 3;
45637
- findings.push(
45638
- this.finding(
45639
- "explicitBehavior",
45640
- "warning",
45641
- "No NEXUS_ALLOW_MOCK_ORCHESTRATION guard found \u2014 mock fallback may be implicit",
45642
- 3,
45643
- "Require explicit env var for mock orchestration"
45644
- )
45645
- );
45646
- }
45647
- const magicRouting = countPatternInDir(
45648
- SRC_ROOT,
45649
- /\.ts$/,
45650
- /fallback.*=.*true|implicitRoute/g,
45651
- DETERMINISM_EXCLUDES
45652
- );
45653
- if (magicRouting > 5) {
45654
- const deduction = Math.min(3, Math.floor(magicRouting / 3));
45655
- score -= deduction;
45656
- findings.push(
45657
- this.finding(
45658
- "explicitBehavior",
45659
- "info",
45660
- `${String(magicRouting)} implicit fallback/routing patterns detected`,
45661
- deduction
45662
- )
45663
- );
45664
- }
45665
- return { score: clamp2(score, 15), findings };
45666
- }
45667
- /** Check determinism: penalize unseeded random and raw Date.now(). */
45668
- checkDeterminism() {
45669
- const findings = [];
45670
- let score = 15;
45671
- score = this.checkRandomDeterminism(score, findings);
45672
- score = this.checkTimeDeterminism(score, findings);
45673
- return { score: clamp2(score, 15), findings };
45674
- }
45675
- /** Sub-check for Math.random() and injectable random provider. */
45676
- checkRandomDeterminism(score, findings) {
45677
- const randomCount = countPatternInDir(
45678
- SRC_ROOT,
45679
- /\.ts$/,
45680
- /Math\.random\(\)/g,
45681
- DETERMINISM_EXCLUDES
45682
- );
45683
- if (randomCount > 10) {
45684
- const deduction = Math.min(5, Math.floor(randomCount / 5));
45685
- score -= deduction;
45686
- findings.push(
45687
- this.finding(
45688
- "determinism",
45689
- "warning",
45690
- `${String(randomCount)} unseeded Math.random() calls in production code`,
45691
- deduction,
45692
- "Use getRandomProvider() for injectable randomness"
45693
- )
45694
- );
45695
- } else if (randomCount === 0) {
45696
- score += 2;
45697
- }
45698
- if (existsSync11(join11(SRC_ROOT, "core/random-provider.ts"))) {
45699
- score += 1;
45700
- }
45701
- const randomUsage = countPatternInDir(
45702
- SRC_ROOT,
45703
- /\.ts$/,
45704
- /getRandomProvider\(\)/g,
45705
- DETERMINISM_EXCLUDES
45706
- );
45707
- if (randomUsage > 5) {
45708
- score += 1;
45709
- }
45710
- return score;
45711
- }
45712
- /** Sub-check for Date.now() and injectable time provider. */
45713
- checkTimeDeterminism(score, findings) {
45714
- const dateNowCount = countPatternInDir(
45715
- SRC_ROOT,
45716
- /\.ts$/,
45717
- /Date\.now\(\)/g,
45718
- DETERMINISM_EXCLUDES
45719
- );
45720
- if (dateNowCount > 50) {
45721
- score -= 2;
45722
- findings.push(
45723
- this.finding(
45724
- "determinism",
45725
- "info",
45726
- `${String(dateNowCount)} Date.now() calls in production code`,
45727
- 2,
45728
- "Use getTimeProvider() for injectable time"
45729
- )
45730
- );
45731
- }
45732
- if (existsSync11(join11(SRC_ROOT, "core/time-provider.ts"))) {
45733
- score += 1;
45734
- }
45735
- const timeUsage = countPatternInDir(
45736
- SRC_ROOT,
45737
- /\.ts$/,
45738
- /getTimeProvider\(\)/g,
45739
- DETERMINISM_EXCLUDES
45740
- );
45741
- if (timeUsage > 10) {
45742
- score += 1;
45743
- }
45744
- return score;
45745
- }
45746
- /** Check observability: reward tracing, logging, and audit coverage. */
45747
- checkObservability() {
45748
- const findings = [];
45749
- let score = 15;
45750
- if (existsSync11(join11(SRC_ROOT, "observability/swarm-observer.ts"))) {
45751
- score += 3;
45752
- } else {
45753
- score -= 3;
45754
- findings.push(
45755
- this.finding(
45756
- "observability",
45757
- "warning",
45758
- "No SwarmObserver found",
45759
- 3,
45760
- "Add observability/swarm-observer.ts"
45761
- )
45762
- );
45763
- }
45764
- if (existsSync11(join11(SRC_ROOT, "core/trace.ts"))) {
45765
- score += 2;
45766
- }
45767
- const loggerCount = countPatternInDir(SRC_ROOT, /\.ts$/, /createLogger\(/g);
45768
- if (loggerCount > 50) {
45769
- score += 2;
45770
- } else {
45771
- findings.push(
45772
- this.finding(
45773
- "observability",
45774
- "info",
45775
- `Only ${String(loggerCount)} createLogger() calls (target: >50)`,
45776
- 0
45777
- )
45778
- );
45779
- }
45780
- if (existsSync11(join11(SRC_ROOT, "audit"))) {
45781
- score += 2;
45782
- }
45783
- return { score: clamp2(score, 15), findings };
45784
- }
45785
- /** Check config simplicity: penalize excessive schema sprawl. */
45786
- checkConfigSimplicity() {
45787
- const findings = [];
45788
- let score = 10;
45789
- const schemaCount = countFiles(join11(SRC_ROOT, "config"), /schema.*\.ts$/);
45790
- if (schemaCount > 10) {
45791
- score -= 2;
45792
- findings.push(
45793
- this.finding(
45794
- "configSimplicity",
45795
- "info",
45796
- `${String(schemaCount)} config schemas (target: <=10)`,
45797
- 2,
45798
- "Consolidate related schemas"
45799
- )
45800
- );
45801
- } else {
45802
- score += 1;
45803
- }
45804
- if (existsSync11(join11(SRC_ROOT, "config/config-loader.ts"))) {
45805
- score += 2;
45806
- }
45807
- if (existsSync11(join11(SRC_ROOT, "config/config-manager.ts"))) {
45808
- score += 1;
45809
- }
45810
- return { score: clamp2(score, 10), findings };
45811
- }
45812
- /** Check layer separation: penalize cross-layer imports. */
45813
- checkLayerSeparation() {
45814
- const findings = [];
45815
- let score = 10;
45816
- const adapterAgentImports = countPatternInDir(
45817
- join11(SRC_ROOT, "adapters"),
45818
- /\.ts$/,
45819
- /from ['"]\.\.\/agents\//g
45820
- );
45821
- if (adapterAgentImports > 0) {
45822
- const deduction = Math.min(5, adapterAgentImports);
45823
- score -= deduction;
45824
- findings.push(
45825
- this.finding(
45826
- "layerSeparation",
45827
- "warning",
45828
- `${String(adapterAgentImports)} adapter->agent import violations`,
45829
- deduction,
45830
- "Adapters should not import from agents layer"
45831
- )
45832
- );
45833
- } else {
45834
- score += 2;
45835
- }
45836
- const coreMcpImports = countPatternInDir(
45837
- join11(SRC_ROOT, "core"),
45838
- /\.ts$/,
45839
- /from ['"]\.\.\/mcp\//g
45840
- );
45841
- if (coreMcpImports > 0) {
45842
- const deduction = Math.min(3, coreMcpImports);
45843
- score -= deduction;
45844
- findings.push(
45845
- this.finding(
45846
- "layerSeparation",
45847
- "critical",
45848
- `${String(coreMcpImports)} core->MCP import violations`,
45849
- deduction,
45850
- "Core must not depend on MCP layer"
45851
- )
45852
- );
45853
- } else {
45854
- score += 1;
45855
- }
45856
- return { score: clamp2(score, 10), findings };
45857
- }
45858
- /** Check operator ergonomics: reward rich CLI commands. */
45859
- checkOperatorErgonomics() {
45860
- const findings = [];
45861
- let score = 10;
45862
- const commandCount = countFiles(join11(SRC_ROOT, "cli"), /\.ts$/);
45863
- if (commandCount >= 20) {
45864
- score += 3;
45865
- } else {
45866
- findings.push(
45867
- this.finding(
45868
- "operatorErgonomics",
45869
- "info",
45870
- `${String(commandCount)} CLI commands (target: >=20)`,
45871
- 0
45872
- )
45873
- );
45874
- }
45875
- score = this.checkCliCommands(score, findings);
45876
- return { score: clamp2(score, 10), findings };
45877
- }
45878
- /** Sub-check for essential CLI commands (doctor, setup, demo, config). */
45879
- checkCliCommands(score, findings) {
45880
- const commands = [
45881
- ["cli/doctor.ts", "Doctor command", 2],
45882
- ["cli/setup-command.ts", "Setup wizard", 2],
45883
- ["cli/demo-command.ts", "Demo command", 1],
45884
- ["cli/config-command.ts", "Config command", 1]
45885
- ];
45886
- for (const [path14, name, bonus] of commands) {
45887
- if (existsSync11(join11(SRC_ROOT, path14))) {
45888
- score += bonus;
45889
- } else {
45890
- findings.push(this.finding("operatorErgonomics", "info", `Missing ${name} (${path14})`, 0));
45891
- }
45892
- }
45893
- return score;
45894
- }
45895
- /** Check governance integration: policy firewall, rate limiter, docs. */
45896
- checkGovernanceIntegration() {
45897
- const findings = [];
45898
- let score = 5;
45899
- score = this.checkGovernanceDocs(score, findings);
45900
- score = this.checkGovernanceInfra(score, findings);
45901
- return { score: clamp2(score, 5), findings };
45902
- }
45903
- /** Sub-check for governance documentation artifacts. */
45904
- checkGovernanceDocs(score, findings) {
45905
- if (!existsSync11(join11(REPO_ROOT, "CLAUDE.md"))) {
45906
- score -= 3;
45907
- findings.push(
45908
- this.finding("governanceIntegration", "critical", "No CLAUDE.md governance document", 3)
45909
- );
45910
- } else {
45911
- score += 1;
45912
- }
45913
- if (existsSync11(join11(DOCS_ROOT, "architecture/wiring-graph.json"))) {
45914
- score += 1;
45915
- }
45916
- if (existsSync11(join11(DOCS_ROOT, "adr"))) {
45917
- score += 1;
45918
- } else {
45919
- findings.push(this.finding("governanceIntegration", "info", "No ADR directory", 0));
45920
- }
45921
- return score;
45922
- }
45923
- /** Sub-check for governance runtime infrastructure. */
45924
- checkGovernanceInfra(score, findings) {
45925
- const hasPolicyFirewall = countPatternInDir(join11(SRC_ROOT, "security"), /\.ts$/, /PolicyGate|policyFirewall/g) > 0;
45926
- if (hasPolicyFirewall) {
45927
- score += 1;
45928
- } else {
45929
- findings.push(
45930
- this.finding(
45931
- "governanceIntegration",
45932
- "warning",
45933
- "No policy firewall detected in security layer",
45934
- 0
45935
- )
45936
- );
45937
- }
45938
- const hasRateLimiter = countPatternInDir(SRC_ROOT, /\.ts$/, /RateLimiter|rateLimiter/g) > 0;
45939
- if (hasRateLimiter) {
45940
- score += 1;
45941
- }
45942
- return score;
45943
- }
45944
- /** Helper to create a FitnessFinding with defaults. */
45945
- finding(dimension, severity, description2, pointsDeducted, suggestion) {
45946
- const base = { dimension, severity, description: description2, pointsDeducted };
45947
- if (suggestion !== void 0) {
45948
- return { ...base, suggestion };
45949
- }
45950
- return base;
45951
- }
45952
- };
45953
- function createFitnessScoreCalculator(logger55) {
45954
- return new FitnessScoreCalculator(logger55);
45955
- }
45956
- function calculateFitnessScore(version) {
45957
- const calculator = createFitnessScoreCalculator();
45958
- return calculator.audit(version);
45959
- }
45960
-
45961
- // src/mcp/tools/improvement-review-signals.ts
45962
- function worstDimension(audit) {
45963
- let worst;
45964
- for (const finding of audit.findings) {
45965
- if (worst === void 0 || finding.pointsDeducted > worst.pointsDeducted) {
45966
- worst = { dimension: finding.dimension, pointsDeducted: finding.pointsDeducted };
45967
- }
45968
- }
45969
- return worst?.dimension;
45970
- }
45971
- function emitFitnessDeclinedSignal(audit, fitnessFloor, bus, logger55) {
45972
- if (audit.score >= fitnessFloor) return;
45973
- try {
45974
- const dimension = worstDimension(audit);
45975
- bus.emit({
45976
- type: "signal.fitness_declined",
45977
- timestamp: getTimeProvider().now(),
45978
- score: audit.score,
45979
- floor: fitnessFloor,
45980
- ...dimension !== void 0 ? { dimension } : {}
45981
- });
45982
- } catch (error) {
45983
- logger55.warn("Failed to emit signal.fitness_declined", { error: getErrorMessage(error) });
45984
- }
45985
- }
45986
-
45987
- // src/mcp/tools/improvement-review.ts
45988
- var execFileAsync3 = promisify3(execFile3);
45989
- var ImprovementReviewInputSchema = z95.object({
45990
- lookbackDays: z95.number().int().min(1).max(90).optional().default(7).describe("Lookback window for outcome data, in days. Default 7."),
45991
- fileIssues: z95.boolean().optional().default(false).describe(
45992
- "When true, file candidate issues via `gh issue create` for crossed thresholds (rate-limited to 5 per run, deduped against open issues). When false (default), return signals only."
45993
- ),
45994
- minSampleSize: z95.number().int().min(1).max(1e3).optional().default(5).describe("Minimum sample size before a CLI/category signal can fire."),
45995
- fitnessFloor: z95.number().int().min(0).max(100).optional().default(90).describe("Fitness score below this threshold triggers a tech-debt signal.")
45996
- });
45997
- var MAX_ISSUES_PER_RUN = 5;
45998
- var HOUR_MS = 60 * 60 * 1e3;
45999
- var DAY_MS = 24 * HOUR_MS;
46000
- function filterByLookback(outcomes, lookbackDays, now) {
46001
- const cutoff = now - lookbackDays * DAY_MS;
46002
- return outcomes.filter((o) => {
46003
- const t = Date.parse(o.timestamp);
46004
- return Number.isFinite(t) && t >= cutoff;
46005
- });
46006
- }
46007
- function detectCliPerformanceFloor(outcomes, minSamples, windowLabel) {
46008
- const buckets = /* @__PURE__ */ new Map();
46009
- for (const o of outcomes) {
46010
- const key = `${o.cli}::${o.category}`;
46011
- const bucket = buckets.get(key) ?? { cli: o.cli, category: o.category, ok: 0, total: 0 };
46012
- bucket.total += 1;
46013
- if (o.success) bucket.ok += 1;
46014
- buckets.set(key, bucket);
46015
- }
46016
- const signals = [];
46017
- for (const b of buckets.values()) {
46018
- if (b.total < minSamples) continue;
46019
- const rate = b.ok / b.total;
46020
- if (rate >= 0.6) continue;
46021
- const ratePct = Math.round(rate * 100);
46022
- signals.push({
46023
- category: "routing",
46024
- signalKey: `routing:cli-floor:${b.cli}:${b.category}`,
46025
- severity: rate < 0.4 ? "critical" : "warning",
46026
- title: `routing: ${b.cli} success rate ${String(ratePct)}% on ${b.category} (${windowLabel})`,
46027
- body: [
46028
- `Observed performance floor breach in the ${windowLabel} window.`,
46029
- "",
46030
- `- CLI: \`${b.cli}\``,
46031
- `- Category: \`${b.category}\``,
46032
- `- Success rate: ${String(ratePct)}% (${String(b.ok)}/${String(b.total)})`,
46033
- `- Threshold: 60% with \u2265${String(minSamples)} samples`,
46034
- "",
46035
- "Consider routing this category away from this CLI, or investigating the failure pattern via `weather_report` and the OutcomeStore."
46036
- ].join("\n"),
46037
- evidence: {
46038
- samples: b.total,
46039
- window: windowLabel,
46040
- observedValue: rate,
46041
- threshold: 0.6
46042
- }
46043
- });
46044
- }
46045
- return signals;
46046
- }
46047
- function detectFailureCategoryConcentration(outcomes, windowLabel) {
46048
- const failures = outcomes.filter((o) => !o.success);
46049
- if (failures.length < 10) return [];
46050
- const byCategory = /* @__PURE__ */ new Map();
46051
- for (const f of failures) {
46052
- const cat = f.failureCategory ?? "unknown";
46053
- byCategory.set(cat, (byCategory.get(cat) ?? 0) + 1);
46054
- }
46055
- const signals = [];
46056
- for (const [cat, count] of byCategory) {
46057
- const share = count / failures.length;
46058
- if (share <= 0.5) continue;
46059
- const sharePct = Math.round(share * 100);
46060
- signals.push({
46061
- category: "bug",
46062
- signalKey: `bug:failure-concentration:${cat}`,
46063
- severity: "warning",
46064
- title: `bug: ${String(sharePct)}% of failures in ${windowLabel} share category \`${cat}\``,
46065
- body: [
46066
- `Failure-category concentration breach in the ${windowLabel} window.`,
46067
- "",
46068
- `- Category: \`${cat}\``,
46069
- `- Share: ${String(sharePct)}% (${String(count)}/${String(failures.length)} failures)`,
46070
- `- Threshold: > 50% with \u226510 failures`,
46071
- "",
46072
- "A single failure mode dominating the error budget usually means a systemic bug or routing miss. Investigate via `query_trace` and the OutcomeStore."
46073
- ].join("\n"),
46074
- evidence: {
46075
- samples: failures.length,
46076
- window: windowLabel,
46077
- observedValue: share,
46078
- threshold: 0.5
46079
- }
46080
- });
46081
- }
46082
- return signals;
46083
- }
46084
- function buildFloorSignal(audit, fitnessFloor) {
46085
- return {
46086
- category: "tech-debt",
46087
- signalKey: `tech-debt:fitness-below-floor`,
46088
- severity: audit.score < 70 ? "critical" : "warning",
46089
- title: `tech-debt: fitness score ${String(audit.score)}/100 below floor ${String(fitnessFloor)}`,
46090
- body: [
46091
- `Code fitness score has dropped below the governance floor.`,
46092
- "",
46093
- `- Score: ${String(audit.score)} / 100`,
46094
- `- Floor: ${String(fitnessFloor)} (governance threshold per CLAUDE.md)`,
46095
- `- Findings: ${String(audit.findings.length)} total`,
46096
- "",
46097
- "Run `nexus-agents fitness-audit` for the full breakdown. Critical findings:",
46098
- ...audit.findings.filter((f) => f.severity === "critical").slice(0, 5).map((f) => `- ${f.dimension}: ${f.description}`)
46099
- ].join("\n"),
46100
- evidence: { observedValue: audit.score, threshold: fitnessFloor }
46101
- };
46102
- }
46103
- function buildCriticalFindingSignal(finding) {
46104
- return {
46105
- category: "tech-debt",
46106
- signalKey: `tech-debt:fitness-critical:${finding.dimension}`,
46107
- severity: "critical",
46108
- title: `tech-debt: critical fitness finding in ${finding.dimension}`,
46109
- body: [
46110
- `Fitness audit returned a CRITICAL finding.`,
46111
- "",
46112
- `- Dimension: \`${finding.dimension}\``,
46113
- `- Description: ${finding.description}`,
46114
- `- Points deducted: ${String(finding.pointsDeducted)}`,
46115
- finding.location !== void 0 ? `- Location: ${finding.location}` : "",
46116
- finding.suggestion !== void 0 ? `- Suggestion: ${finding.suggestion}` : ""
46117
- ].filter((line) => line.length > 0).join("\n"),
46118
- evidence: { observedValue: -finding.pointsDeducted }
46119
- };
46120
- }
46121
- function detectFitnessSignals(audit, fitnessFloor) {
46122
- const signals = [];
46123
- if (audit.score < fitnessFloor) signals.push(buildFloorSignal(audit, fitnessFloor));
46124
- for (const finding of audit.findings) {
46125
- if (finding.severity === "critical") signals.push(buildCriticalFindingSignal(finding));
46126
- }
46127
- return signals;
46128
- }
46129
- async function existingIssueForSignal(signalKey) {
46130
- try {
46131
- const { stdout } = await execFileAsync3("gh", [
46132
- "issue",
46133
- "list",
46134
- "--state",
46135
- "open",
46136
- "--search",
46137
- `"${signalKey}" in:body`,
46138
- "--json",
46139
- "number,url",
46140
- "--limit",
46141
- "5"
46142
- ]);
46143
- const parsed = JSON.parse(stdout);
46144
- if (parsed.length > 0 && typeof parsed[0]?.url === "string") {
46145
- return parsed[0].url;
46146
- }
46147
- return null;
46148
- } catch {
46149
- return null;
46150
- }
46151
- }
46152
- async function fileIssueForSignal(signal) {
46153
- const body = `${signal.body}
46154
-
46155
- ---
46156
-
46157
- _Signal key (do not edit): \`${signal.signalKey}\` \xB7 Generated by \`improvement_review\` (#2402) \xB7 Severity: ${signal.severity}_`;
46158
- const labels = signal.category === "security" ? "security" : signal.category;
46159
- try {
46160
- const { stdout } = await execFileAsync3("gh", [
46161
- "issue",
46162
- "create",
46163
- "--title",
46164
- signal.title,
46165
- "--body",
46166
- body,
46167
- "--label",
46168
- labels
46169
- ]);
46170
- const url = stdout.trim();
46171
- if (!url.startsWith("https://")) {
46172
- return { ok: false, error: `gh returned unexpected output: ${stdout.slice(0, 200)}` };
46173
- }
46174
- return { ok: true, url };
46175
- } catch (caught) {
46176
- const message = caught instanceof Error ? caught.message : String(caught);
46177
- return { ok: false, error: message };
46178
- }
46179
- }
46180
- function safeFitnessAudit(now, ctx) {
46181
- try {
46182
- return calculateFitnessScore("improvement-review");
46183
- } catch (caught) {
46184
- ctx.logger.warn("fitness audit failed; skipping fitness signals", {
46185
- error: caught instanceof Error ? caught.message : String(caught)
46186
- });
46187
- return {
46188
- score: 100,
46189
- dimensions: {},
46190
- findings: [],
46191
- timestamp: new Date(now).toISOString(),
46192
- version: "improvement-review-fallback"
46193
- };
46194
- }
46195
- }
46196
- var SEVERITY_ORDER3 = {
46197
- critical: 0,
46198
- warning: 1,
46199
- info: 2
46200
- };
46201
- async function fileSignalsAsIssues(signals, ctx) {
46202
- const issuesFiled = [];
46203
- const issuesSkipped = [];
46204
- for (const signal of signals) {
46205
- if (issuesFiled.length >= MAX_ISSUES_PER_RUN) {
46206
- issuesSkipped.push({ signalKey: signal.signalKey, reason: "rate-limit" });
46207
- continue;
46208
- }
46209
- const existing = await existingIssueForSignal(signal.signalKey);
46210
- if (existing !== null) {
46211
- issuesSkipped.push({ signalKey: signal.signalKey, reason: `dup:${existing}` });
46212
- continue;
46213
- }
46214
- const result = await fileIssueForSignal(signal);
46215
- if (result.ok) {
46216
- issuesFiled.push({ signalKey: signal.signalKey, issueUrl: result.url });
46217
- ctx.logger.info("improvement signal filed", {
46218
- signalKey: signal.signalKey,
46219
- url: result.url
46220
- });
46221
- } else {
46222
- issuesSkipped.push({ signalKey: signal.signalKey, reason: `error:${result.error}` });
46223
- }
46224
- }
46225
- return { issuesFiled, issuesSkipped };
46226
- }
46227
- async function runImprovementReview(input, deps = {}) {
46228
- const logger55 = deps.logger ?? createLogger({ component: "improvement_review" });
46229
- const { lookbackDays, fileIssues, minSampleSize, fitnessFloor } = input;
46230
- const now = Date.now();
46231
- const windowLabel = `${String(lookbackDays)}d`;
46232
- const allOutcomes = getOutcomeStore().query();
46233
- const windowed = filterByLookback(allOutcomes, lookbackDays, now);
46234
- const audit = safeFitnessAudit(now, { logger: logger55 });
46235
- const signals = [
46236
- ...detectCliPerformanceFloor(windowed, minSampleSize, windowLabel),
46237
- ...detectFailureCategoryConcentration(windowed, windowLabel),
46238
- ...detectFitnessSignals(audit, fitnessFloor)
46239
- ];
46240
- signals.sort((a, b) => SEVERITY_ORDER3[a.severity] - SEVERITY_ORDER3[b.severity]);
46241
- emitFitnessDeclinedSignal(audit, fitnessFloor, getPipelineEventBus(), logger55);
46242
- const { issuesFiled, issuesSkipped } = fileIssues ? await fileSignalsAsIssues(signals, { logger: logger55 }) : { issuesFiled: [], issuesSkipped: [] };
46243
- return {
46244
- window: windowLabel,
46245
- totalOutcomes: windowed.length,
46246
- signals,
46247
- issuesFiled,
46248
- issuesSkipped
46249
- };
46250
- }
46251
- async function reviewHandler(args, ctx) {
46252
- const parsed = ImprovementReviewInputSchema.safeParse(args);
46253
- if (!parsed.success) {
46254
- return toolStructuredError({
46255
- errorCategory: "validation",
46256
- message: `Validation error: ${formatZodError(parsed.error)}`
46257
- });
46258
- }
46259
- const response = await runImprovementReview(parsed.data, { logger: ctx.logger });
46260
- return toolSuccessStructured(response);
46261
- }
46262
- var description = "Periodic threshold-gated observability-driven improvement loop. Reads OutcomeStore + fitness audit, surfaces patterns crossing documented thresholds as candidate findings. When fileIssues=true, files candidate GitHub issues via `gh issue create` (rate-limited to 5 per run, deduped against open issues). Never auto-merges. Replaces the deleted self-development engine (#2402).";
46263
- var TOOL_INPUT_SCHEMA = {
46264
- lookbackDays: z95.number().int().min(1).max(90).optional().describe("Lookback window for outcome data, in days. Default 7."),
46265
- fileIssues: z95.boolean().optional().describe(
46266
- "When true, file candidate issues for crossed thresholds (default false \u2014 return signals only)"
46267
- ),
46268
- minSampleSize: z95.number().int().min(1).max(1e3).optional().describe("Minimum sample size before a CLI/category signal fires (default 5)."),
46269
- fitnessFloor: z95.number().int().min(0).max(100).optional().describe("Fitness score below this threshold triggers a tech-debt signal (default 90).")
46270
- };
46271
- function registerImprovementReviewTool(server, deps) {
46272
- const logger55 = deps.logger ?? createLogger({ tool: "improvement_review" });
46273
- const secureHandler = createSecureHandler(reviewHandler, {
46274
- toolName: "improvement_review",
46275
- rateLimiter: deps.rateLimiter,
46276
- logger: logger55
46277
- });
46278
- const guardedHandler = withPrerequisite("improvement_review", secureHandler);
46279
- const timeoutMs = getToolTimeout("improvement_review", deps.security);
46280
- const wrappedHandler = wrapToolWithTimeout("improvement_review", guardedHandler, {
46281
- timeoutMs,
46282
- logger: logger55
46283
- });
46284
- server.registerTool(
46285
- "improvement_review",
46286
- {
46287
- description,
46288
- inputSchema: TOOL_INPUT_SCHEMA,
46289
- annotations: getToolAnnotations("improvement_review")
46290
- },
46291
- toSdkCallback(wrappedHandler)
46292
- );
46293
- logger55.info("Registered improvement_review tool");
46294
- }
46295
-
46296
45306
  // src/mcp/tools/query-task-state-tool.ts
46297
- import { z as z96 } from "zod";
46298
- var QueryTaskStateInputSchema = z96.object({
46299
- taskId: z96.string().min(1).max(128).describe("Task ID whose structured state log should be read")
45307
+ import { z as z95 } from "zod";
45308
+ var QueryTaskStateInputSchema = z95.object({
45309
+ taskId: z95.string().min(1).max(128).describe("Task ID whose structured state log should be read")
46300
45310
  });
46301
45311
  function queryTaskStateHandler(args, ctx) {
46302
45312
  const parsed = QueryTaskStateInputSchema.safeParse(args);
@@ -46331,9 +45341,9 @@ function queryTaskStateHandler(args, ctx) {
46331
45341
  function registerQueryTaskStateTool(server, deps) {
46332
45342
  const logger55 = deps.logger ?? createLogger({ tool: "query_task_state" });
46333
45343
  const toolSchema = {
46334
- taskId: z96.string().min(1).max(128).describe("Task ID whose structured state log should be read")
45344
+ taskId: z95.string().min(1).max(128).describe("Task ID whose structured state log should be read")
46335
45345
  };
46336
- const description2 = "Read the structured state log for a task ID and return the current snapshot. Includes Magentic-One Task Ledger (facts/guesses/openQuestions) and Progress Ledger (per-step reflections with suggestedAction) when orchestrators have written them. Structured state is only written when NEXUS_TASK_STATE_ENABLED=1 was set during the orchestrate invocation.";
45346
+ const description = "Read the structured state log for a task ID and return the current snapshot. Includes Magentic-One Task Ledger (facts/guesses/openQuestions) and Progress Ledger (per-step reflections with suggestedAction) when orchestrators have written them. Structured state is only written when NEXUS_TASK_STATE_ENABLED=1 was set during the orchestrate invocation.";
46337
45347
  const secureHandler = createSecureHandler(queryTaskStateHandler, {
46338
45348
  toolName: "query_task_state",
46339
45349
  rateLimiter: deps.rateLimiter,
@@ -46346,14 +45356,14 @@ function registerQueryTaskStateTool(server, deps) {
46346
45356
  });
46347
45357
  server.registerTool(
46348
45358
  "query_task_state",
46349
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("query_task_state") },
45359
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("query_task_state") },
46350
45360
  toSdkCallback(wrappedHandler)
46351
45361
  );
46352
45362
  logger55.info("Registered query_task_state tool");
46353
45363
  }
46354
45364
 
46355
45365
  // src/mcp/tools/get-job-result-tool.ts
46356
- import { z as z97 } from "zod";
45366
+ import { z as z96 } from "zod";
46357
45367
 
46358
45368
  // src/mcp/jobs/task-state-source.ts
46359
45369
  var logger42 = createLogger({ component: "task-state-source" });
@@ -46422,8 +45432,8 @@ function resolveJobResult(jobId, customDir) {
46422
45432
  }
46423
45433
 
46424
45434
  // src/mcp/tools/get-job-result-tool.ts
46425
- var GetJobResultInputSchema = z97.object({
46426
- jobId: z97.string().min(1).max(128).describe('Job ID returned by orchestrate({ mode: "async" })')
45435
+ var GetJobResultInputSchema = z96.object({
45436
+ jobId: z96.string().min(1).max(128).describe('Job ID returned by orchestrate({ mode: "async" })')
46427
45437
  });
46428
45438
  function getJobResultHandler(args) {
46429
45439
  const parsed = GetJobResultInputSchema.safeParse(args);
@@ -46454,9 +45464,9 @@ function getJobResultHandler(args) {
46454
45464
  function registerGetJobResultTool(server, deps) {
46455
45465
  const logger55 = deps.logger ?? createLogger({ tool: "get_job_result" });
46456
45466
  const toolSchema = {
46457
- jobId: z97.string().min(1).max(128).describe('Job ID returned by orchestrate({ mode: "async" })')
45467
+ jobId: z96.string().min(1).max(128).describe('Job ID returned by orchestrate({ mode: "async" })')
46458
45468
  };
46459
- const description2 = 'Read the result of an async-mode tool invocation by jobId. Returns the structured record (status, result | error, timestamps). Poll until status !== "pending". Stage-1 of epic #2631 \u2014 Stage 2 will fold this into query_task_state once StructuredTaskState gains the result field.';
45469
+ const description = 'Read the result of an async-mode tool invocation by jobId. Returns the structured record (status, result | error, timestamps). Poll until status !== "pending". Stage-1 of epic #2631 \u2014 Stage 2 will fold this into query_task_state once StructuredTaskState gains the result field.';
46460
45470
  const secureHandler = createSecureHandler(getJobResultHandler, {
46461
45471
  toolName: "get_job_result",
46462
45472
  rateLimiter: deps.rateLimiter,
@@ -46469,21 +45479,21 @@ function registerGetJobResultTool(server, deps) {
46469
45479
  });
46470
45480
  server.registerTool(
46471
45481
  "get_job_result",
46472
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("get_job_result") },
45482
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("get_job_result") },
46473
45483
  toSdkCallback(wrappedHandler)
46474
45484
  );
46475
45485
  logger55.info("Registered get_job_result tool");
46476
45486
  }
46477
45487
 
46478
45488
  // src/mcp/tools/list-jobs-tool.ts
46479
- import { z as z98 } from "zod";
45489
+ import { z as z97 } from "zod";
46480
45490
  var MAX_LIST_JOBS_RESULTS = 200;
46481
- var ListJobsInputSchema = z98.object({
45491
+ var ListJobsInputSchema = z97.object({
46482
45492
  /**
46483
45493
  * Filter to jobs from a specific tool (exact match — e.g. `'orchestrate'`).
46484
45494
  * Omit to list every tool's jobs.
46485
45495
  */
46486
- toolName: z98.string().min(1).max(128).optional().describe("Filter to one tool (exact match)."),
45496
+ toolName: z97.string().min(1).max(128).optional().describe("Filter to one tool (exact match)."),
46487
45497
  /**
46488
45498
  * Filter to jobs in a specific lifecycle state.
46489
45499
  * Omit to list every state.
@@ -46496,7 +45506,7 @@ var ListJobsInputSchema = z98.object({
46496
45506
  * Newest jobs are returned first, so a smaller limit shows the most
46497
45507
  * recent activity.
46498
45508
  */
46499
- limit: z98.number().int().min(1).max(MAX_LIST_JOBS_RESULTS).optional().describe(`Max summaries to return (1-${String(MAX_LIST_JOBS_RESULTS)}, newest first).`)
45509
+ limit: z97.number().int().min(1).max(MAX_LIST_JOBS_RESULTS).optional().describe(`Max summaries to return (1-${String(MAX_LIST_JOBS_RESULTS)}, newest first).`)
46500
45510
  });
46501
45511
  function listJobsHandler(args) {
46502
45512
  const parsed = ListJobsInputSchema.safeParse(args);
@@ -46527,13 +45537,13 @@ function listJobsHandler(args) {
46527
45537
  function registerListJobsTool(server, deps) {
46528
45538
  const logger55 = deps.logger ?? createLogger({ tool: "list_jobs" });
46529
45539
  const toolSchema = {
46530
- toolName: z98.string().min(1).max(128).optional().describe("Filter to one tool (exact match)."),
45540
+ toolName: z97.string().min(1).max(128).optional().describe("Filter to one tool (exact match)."),
46531
45541
  status: JobStatusSchema.optional().describe(
46532
45542
  "Filter to pending | complete | failed | cancelled. Omit for all."
46533
45543
  ),
46534
- limit: z98.number().int().min(1).max(MAX_LIST_JOBS_RESULTS).optional().describe(`Max summaries to return (1-${String(MAX_LIST_JOBS_RESULTS)}, newest first).`)
45544
+ limit: z97.number().int().min(1).max(MAX_LIST_JOBS_RESULTS).optional().describe(`Max summaries to return (1-${String(MAX_LIST_JOBS_RESULTS)}, newest first).`)
46535
45545
  };
46536
- const description2 = "List async-mode jobs (cross-session discovery). Returns summaries \u2014 jobId, toolName, status, timestamps \u2014 newest first. Filter by toolName / status / limit. Result payloads excluded; fetch via get_job_result(jobId). Stage 5 of epic #2631.";
45546
+ const description = "List async-mode jobs (cross-session discovery). Returns summaries \u2014 jobId, toolName, status, timestamps \u2014 newest first. Filter by toolName / status / limit. Result payloads excluded; fetch via get_job_result(jobId). Stage 5 of epic #2631.";
46537
45547
  const secureHandler = createSecureHandler(listJobsHandler, {
46538
45548
  toolName: "list_jobs",
46539
45549
  rateLimiter: deps.rateLimiter,
@@ -46546,17 +45556,17 @@ function registerListJobsTool(server, deps) {
46546
45556
  });
46547
45557
  server.registerTool(
46548
45558
  "list_jobs",
46549
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("list_jobs") },
45559
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("list_jobs") },
46550
45560
  toSdkCallback(wrappedHandler)
46551
45561
  );
46552
45562
  logger55.info("Registered list_jobs tool");
46553
45563
  }
46554
45564
 
46555
45565
  // src/mcp/tools/cancel-job-tool.ts
46556
- import { z as z99 } from "zod";
46557
- var CancelJobInputSchema = z99.object({
46558
- jobId: z99.string().min(1).max(128).describe("Job ID returned by orchestrate / run_workflow / consensus_vote in async mode"),
46559
- reason: z99.string().max(1e3).optional().describe('Optional human-readable note (e.g. "user clicked cancel").')
45566
+ import { z as z98 } from "zod";
45567
+ var CancelJobInputSchema = z98.object({
45568
+ jobId: z98.string().min(1).max(128).describe("Job ID returned by orchestrate / run_workflow / consensus_vote in async mode"),
45569
+ reason: z98.string().max(1e3).optional().describe('Optional human-readable note (e.g. "user clicked cancel").')
46560
45570
  });
46561
45571
  function cancelJobHandler(args) {
46562
45572
  const parsed = CancelJobInputSchema.safeParse(args);
@@ -46608,10 +45618,10 @@ function cancelJobHandler(args) {
46608
45618
  function registerCancelJobTool(server, deps) {
46609
45619
  const logger55 = deps.logger ?? createLogger({ tool: "cancel_job" });
46610
45620
  const toolSchema = {
46611
- jobId: z99.string().min(1).max(128).describe("Job ID returned by orchestrate / run_workflow / consensus_vote in async mode"),
46612
- reason: z99.string().max(1e3).optional().describe('Optional human-readable note (e.g. "user clicked cancel").')
45621
+ jobId: z98.string().min(1).max(128).describe("Job ID returned by orchestrate / run_workflow / consensus_vote in async mode"),
45622
+ reason: z98.string().max(1e3).optional().describe('Optional human-readable note (e.g. "user clicked cancel").')
46613
45623
  };
46614
- const description2 = "Mark an async-mode job as cancelled (#3042 Stage 1b / epic #2631). Same-process dispatcher unwinds via AbortSignal (#3035/#3038); cross-process workers observe via get_job_result. Idempotent \u2014 cancel-after-complete is a no-op (preserves the terminal record); second cancel returns already_cancelled.";
45624
+ const description = "Mark an async-mode job as cancelled (#3042 Stage 1b / epic #2631). Same-process dispatcher unwinds via AbortSignal (#3035/#3038); cross-process workers observe via get_job_result. Idempotent \u2014 cancel-after-complete is a no-op (preserves the terminal record); second cancel returns already_cancelled.";
46615
45625
  const secureHandler = createSecureHandler(cancelJobHandler, {
46616
45626
  toolName: "cancel_job",
46617
45627
  rateLimiter: deps.rateLimiter,
@@ -46624,29 +45634,29 @@ function registerCancelJobTool(server, deps) {
46624
45634
  });
46625
45635
  server.registerTool(
46626
45636
  "cancel_job",
46627
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("cancel_job") },
45637
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("cancel_job") },
46628
45638
  toSdkCallback(wrappedHandler)
46629
45639
  );
46630
45640
  logger55.info("Registered cancel_job tool");
46631
45641
  }
46632
45642
 
46633
45643
  // src/mcp/tools/ci-health-check-tool.ts
46634
- import { z as z101 } from "zod";
45644
+ import { z as z100 } from "zod";
46635
45645
 
46636
45646
  // src/mcp/tools/ci-health-log.ts
46637
- import { appendFileSync as appendFileSync4, existsSync as existsSync12, readFileSync as readFileSync10, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
46638
- import { z as z100 } from "zod";
45647
+ import { appendFileSync as appendFileSync4, existsSync as existsSync11, readFileSync as readFileSync9, statSync as statSync2, writeFileSync as writeFileSync3 } from "fs";
45648
+ import { z as z99 } from "zod";
46639
45649
  var logger43 = createLogger({ component: "ci-health-log" });
46640
- var CiHealthEventSchema = z100.object({
46641
- v: z100.literal(1),
46642
- ts: z100.iso.datetime(),
45650
+ var CiHealthEventSchema = z99.object({
45651
+ v: z99.literal(1),
45652
+ ts: z99.iso.datetime(),
46643
45653
  status: CiHealthStatusSchema,
46644
- repo: z100.string().optional(),
46645
- signals: z100.array(
46646
- z100.object({
46647
- source: z100.enum(["github-status", "repo-activity-window"]),
45654
+ repo: z99.string().optional(),
45655
+ signals: z99.array(
45656
+ z99.object({
45657
+ source: z99.enum(["github-status", "repo-activity-window"]),
46648
45658
  status: CiHealthStatusSchema,
46649
- evidence: z100.string()
45659
+ evidence: z99.string()
46650
45660
  })
46651
45661
  )
46652
45662
  });
@@ -46664,13 +45674,13 @@ function capLogSize(path14) {
46664
45674
  const max = maxLogBytes();
46665
45675
  let size;
46666
45676
  try {
46667
- size = statSync3(path14).size;
45677
+ size = statSync2(path14).size;
46668
45678
  } catch {
46669
45679
  return;
46670
45680
  }
46671
45681
  if (size <= max) return;
46672
45682
  try {
46673
- const lines = readFileSync10(path14, "utf-8").split("\n").filter((l) => l !== "");
45683
+ const lines = readFileSync9(path14, "utf-8").split("\n").filter((l) => l !== "");
46674
45684
  const kept = [];
46675
45685
  let bytes = 0;
46676
45686
  for (let i = lines.length - 1; i >= 0; i--) {
@@ -46726,18 +45736,18 @@ function eventFromCheck(params) {
46726
45736
  }
46727
45737
 
46728
45738
  // src/mcp/tools/ci-health-check-tool.ts
46729
- var CiHealthStatusSchema = z101.enum(["healthy", "degraded", "outage", "unknown"]);
46730
- var CiHealthCheckInputSchema = z101.object({
45739
+ var CiHealthStatusSchema = z100.enum(["healthy", "degraded", "outage", "unknown"]);
45740
+ var CiHealthCheckInputSchema = z100.object({
46731
45741
  /**
46732
45742
  * Repo to check for the recent-runs activity signal (in `owner/repo` form).
46733
45743
  * Optional — when omitted, only the status-page signal is consulted.
46734
45744
  */
46735
- repo: z101.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/, "Must be owner/repo form").optional().describe("GitHub repo (owner/repo) to check for recent CI activity. Optional."),
45745
+ repo: z100.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/, "Must be owner/repo form").optional().describe("GitHub repo (owner/repo) to check for recent CI activity. Optional."),
46736
45746
  /**
46737
45747
  * How far back to look for recent-runs activity (minutes). Default 30 —
46738
45748
  * matches the typical wedge-detection window from the #3070 / #3076 outages.
46739
45749
  */
46740
- activityWindowMinutes: z101.number().int().min(5).max(180).default(30).describe("Recent-runs lookback window in minutes (5-180; default 30).")
45750
+ activityWindowMinutes: z100.number().int().min(5).max(180).default(30).describe("Recent-runs lookback window in minutes (5-180; default 30).")
46741
45751
  });
46742
45752
  var STATUS_PAGE_URL = "https://www.githubstatus.com/api/v2/components.json";
46743
45753
  function mapStatusPageStatus(raw) {
@@ -46870,8 +45880,8 @@ var DESCRIPTION = "Check CI infrastructure health before triggering / polling ru
46870
45880
  function registerCiHealthCheckTool(server, deps) {
46871
45881
  const logger55 = deps.logger ?? createLogger({ tool: "ci_health_check" });
46872
45882
  const toolSchema = {
46873
- repo: z101.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/, "Must be owner/repo form").optional().describe("GitHub repo (owner/repo) to check for recent CI activity. Optional."),
46874
- activityWindowMinutes: z101.number().int().min(5).max(180).optional().describe("Recent-runs lookback window in minutes (5-180; default 30).")
45883
+ repo: z100.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/, "Must be owner/repo form").optional().describe("GitHub repo (owner/repo) to check for recent CI activity. Optional."),
45884
+ activityWindowMinutes: z100.number().int().min(5).max(180).optional().describe("Recent-runs lookback window in minutes (5-180; default 30).")
46875
45885
  };
46876
45886
  const secureHandler = createSecureHandler((args) => ciHealthCheckHandler(args, logger55), {
46877
45887
  toolName: "ci_health_check",
@@ -46898,9 +45908,9 @@ function registerCiHealthCheckTool(server, deps) {
46898
45908
  // src/mcp/tools/verify-audit-chain-tool.ts
46899
45909
  import * as fs12 from "fs/promises";
46900
45910
  import * as path11 from "path";
46901
- import { z as z102 } from "zod";
46902
- var VerifyAuditChainInputSchema = z102.object({
46903
- logDir: z102.string().min(1).max(512).describe(
45911
+ import { z as z101 } from "zod";
45912
+ var VerifyAuditChainInputSchema = z101.object({
45913
+ logDir: z101.string().min(1).max(512).describe(
46904
45914
  "Filesystem path to the FileAuditStorage log directory. Tool reads all `audit-*.jsonl` files in lexicographic order and verifies the combined chain."
46905
45915
  )
46906
45916
  });
@@ -46977,11 +45987,11 @@ async function handler2(args, ctx) {
46977
45987
  function registerVerifyAuditChainTool(server, deps) {
46978
45988
  const logger55 = deps.logger ?? createLogger({ tool: "verify_audit_chain" });
46979
45989
  const toolSchema = {
46980
- logDir: z102.string().min(1).max(512).describe(
45990
+ logDir: z101.string().min(1).max(512).describe(
46981
45991
  "Filesystem path to the FileAuditStorage log directory. Tool reads all `audit-*.jsonl` files and verifies the combined hash chain."
46982
45992
  )
46983
45993
  };
46984
- const description2 = "Verify the hash chain of a persisted FileAuditStorage audit log. Reads all `audit-*.jsonl` files in the given directory, parses events, and runs `verifyChain()` to detect tampering. Returns a structured result with eventCount, fileCount, and one of three tamper signals if detected (hash_mismatch, previous_hash_mismatch, missing_hash). Read-only \u2014 never writes or deletes events.";
45994
+ const description = "Verify the hash chain of a persisted FileAuditStorage audit log. Reads all `audit-*.jsonl` files in the given directory, parses events, and runs `verifyChain()` to detect tampering. Returns a structured result with eventCount, fileCount, and one of three tamper signals if detected (hash_mismatch, previous_hash_mismatch, missing_hash). Read-only \u2014 never writes or deletes events.";
46985
45995
  const secureHandler = createSecureHandler(handler2, {
46986
45996
  toolName: "verify_audit_chain",
46987
45997
  rateLimiter: deps.rateLimiter,
@@ -46994,25 +46004,25 @@ function registerVerifyAuditChainTool(server, deps) {
46994
46004
  });
46995
46005
  server.registerTool(
46996
46006
  "verify_audit_chain",
46997
- { description: description2, inputSchema: toolSchema, annotations: getToolAnnotations("verify_audit_chain") },
46007
+ { description, inputSchema: toolSchema, annotations: getToolAnnotations("verify_audit_chain") },
46998
46008
  toSdkCallback(wrappedHandler)
46999
46009
  );
47000
46010
  logger55.info("Registered verify_audit_chain tool");
47001
46011
  }
47002
46012
 
47003
46013
  // src/mcp/tools/pipeline-tool.ts
47004
- import { z as z103 } from "zod";
46014
+ import { z as z102 } from "zod";
47005
46015
  import * as fs13 from "fs";
47006
46016
  import * as path12 from "path";
47007
- var PipelineInputSchema = z103.object({
46017
+ var PipelineInputSchema = z102.object({
47008
46018
  /** The task to execute. */
47009
- task: z103.string().min(5).max(1e4).describe("Task description \u2014 pipeline template auto-selected based on content"),
46019
+ task: z102.string().min(5).max(1e4).describe("Task description \u2014 pipeline template auto-selected based on content"),
47010
46020
  /** Path to a spec file (.md, .yaml) to use as task input. */
47011
- specFile: z103.string().max(500).optional().describe("Path to a spec file \u2014 content prepended to task for greenfield projects"),
46021
+ specFile: z102.string().max(500).optional().describe("Path to a spec file \u2014 content prepended to task for greenfield projects"),
47012
46022
  /** Override template — see `listTemplateIds()` for the canonical list (#2728). Auto-detected if omitted. */
47013
- template: z103.string().max(50).optional().describe(`Pipeline template override. Available: ${listTemplateIds().join(", ")}`),
46023
+ template: z102.string().max(50).optional().describe(`Pipeline template override. Available: ${listTemplateIds().join(", ")}`),
47014
46024
  /** Voting strategy for consensus stages. */
47015
- votingStrategy: z103.enum([
46025
+ votingStrategy: z102.enum([
47016
46026
  "simple_majority",
47017
46027
  "supermajority",
47018
46028
  "unanimous",
@@ -47023,13 +46033,13 @@ var PipelineInputSchema = z103.object({
47023
46033
  "Voting strategy for plan approval. simple_majority (default), supermajority (67%), unanimous, higher_order (Bayesian), proof_of_learning, opinion_wise"
47024
46034
  ),
47025
46035
  /** Use 3 agents instead of 6 for faster voting. */
47026
- quickMode: z103.boolean().default(false).describe("Use 3 agents instead of 6 for faster consensus voting"),
46036
+ quickMode: z102.boolean().default(false).describe("Use 3 agents instead of 6 for faster consensus voting"),
47027
46037
  /** Maximum execution time per stage in milliseconds (min 30s, max 600s). */
47028
- timeoutMs: z103.number().int().min(3e4).max(6e5).optional().describe("Max time per stage in ms (30000-600000). Default: varies by stage complexity"),
46038
+ timeoutMs: z102.number().int().min(3e4).max(6e5).optional().describe("Max time per stage in ms (30000-600000). Default: varies by stage complexity"),
47029
46039
  /** Stop after planning/voting (no implementation). */
47030
- dryRun: z103.boolean().default(false).describe("Stop after vote stage (no implementation)"),
46040
+ dryRun: z102.boolean().default(false).describe("Stop after vote stage (no implementation)"),
47031
46041
  /** TESTS ONLY — random output, must not be used for real decisions. (#2319) */
47032
- simulateVotes: z103.boolean().default(false).describe("TESTS ONLY \u2014 random output, must not be used for real decisions (#2319)")
46042
+ simulateVotes: z102.boolean().default(false).describe("TESTS ONLY \u2014 random output, must not be used for real decisions (#2319)")
47033
46043
  });
47034
46044
  function buildOutput2(result) {
47035
46045
  return {
@@ -47131,7 +46141,7 @@ function registerPipelineTool(server, deps) {
47131
46141
  }
47132
46142
 
47133
46143
  // src/mcp/tools/supply-chain-tradeoff-panel.ts
47134
- import { z as z104 } from "zod";
46144
+ import { z as z103 } from "zod";
47135
46145
  var DEFAULT_AXES = [
47136
46146
  "build_time_determinism",
47137
46147
  "supply_chain_risk",
@@ -47151,16 +46161,16 @@ var FULL_PANEL = [
47151
46161
  "scope_steward"
47152
46162
  ];
47153
46163
  var QUICK_PANEL = ["architect", "security", "scope_steward"];
47154
- var SupplyChainTradeoffPanelInputSchema = z104.object({
47155
- proposal: z104.string().min(1).max(MAX_PROPOSAL_LENGTH).describe('The proposal under tradeoff review (e.g. "Should aegis-boot adopt cargo-nextest?")'),
47156
- axes: z104.array(z104.string().min(1).max(MAX_AXIS_NAME_LENGTH)).min(1).max(MAX_AXES).optional().describe(
46164
+ var SupplyChainTradeoffPanelInputSchema = z103.object({
46165
+ proposal: z103.string().min(1).max(MAX_PROPOSAL_LENGTH).describe('The proposal under tradeoff review (e.g. "Should aegis-boot adopt cargo-nextest?")'),
46166
+ axes: z103.array(z103.string().min(1).max(MAX_AXIS_NAME_LENGTH)).min(1).max(MAX_AXES).optional().describe(
47157
46167
  `Tradeoff axes to evaluate. Default: ${DEFAULT_AXES.join(", ")}. Custom axes accepted; max ${String(MAX_AXES)}.`
47158
46168
  ),
47159
- context: z104.string().max(MAX_CONTEXT_LENGTH).optional().describe(
46169
+ context: z103.string().max(MAX_CONTEXT_LENGTH).optional().describe(
47160
46170
  "Optional context: relevant repo state, dependency tree, vendor publishing patterns, etc."
47161
46171
  ),
47162
- quickMode: z104.boolean().optional().default(false).describe("Use 3 voters (architect, security, scope_steward) instead of 7"),
47163
- simulate: z104.boolean().optional().default(false).describe("Use simulated voters (testing only)")
46172
+ quickMode: z103.boolean().optional().default(false).describe("Use 3 voters (architect, security, scope_steward) instead of 7"),
46173
+ simulate: z103.boolean().optional().default(false).describe("Use simulated voters (testing only)")
47164
46174
  });
47165
46175
  function buildTradeoffProposal(input) {
47166
46176
  const axes = input.axes ?? DEFAULT_AXES;
@@ -47383,7 +46393,7 @@ async function tradeoffPanelHandler(args, ctx) {
47383
46393
  }
47384
46394
  function registerSupplyChainTradeoffPanelTool(server, deps) {
47385
46395
  const logger55 = deps.logger ?? createLogger({ tool: "supply_chain_tradeoff_panel" });
47386
- const description2 = "Run a structured per-axis tradeoff vote on an engineering proposal (#2294). Default axes: build_time_determinism / supply_chain_risk / update_cadence. Voters answer EACH axis independently; aggregator surfaces per-axis verdicts so legitimate tradeoffs are not masked by a single approve/reject.";
46396
+ const description = "Run a structured per-axis tradeoff vote on an engineering proposal (#2294). Default axes: build_time_determinism / supply_chain_risk / update_cadence. Voters answer EACH axis independently; aggregator surfaces per-axis verdicts so legitimate tradeoffs are not masked by a single approve/reject.";
47387
46397
  const secureHandler = createSecureHandler(tradeoffPanelHandler, {
47388
46398
  toolName: "supply_chain_tradeoff_panel",
47389
46399
  rateLimiter: deps.rateLimiter,
@@ -47397,7 +46407,7 @@ function registerSupplyChainTradeoffPanelTool(server, deps) {
47397
46407
  server.registerTool(
47398
46408
  "supply_chain_tradeoff_panel",
47399
46409
  {
47400
- description: description2,
46410
+ description,
47401
46411
  inputSchema: SupplyChainTradeoffPanelInputSchema.shape,
47402
46412
  annotations: getToolAnnotations("supply_chain_tradeoff_panel")
47403
46413
  },
@@ -48225,40 +47235,40 @@ var RiskLevel = /* @__PURE__ */ ((RiskLevel2) => {
48225
47235
  })(RiskLevel || {});
48226
47236
 
48227
47237
  // src/mcp/safety/stpa-schemas.ts
48228
- import { z as z105 } from "zod";
48229
- var HazardCategorySchema = z105.enum(HazardCategory);
48230
- var HazardSeveritySchema = z105.enum(HazardSeverity);
48231
- var ConstraintPrioritySchema = z105.enum(ConstraintPriority);
48232
- var RiskLevelSchema = z105.enum(RiskLevel);
48233
- var TriggerPatternSchema = z105.object({
48234
- parameter: z105.string().min(1),
48235
- matchType: z105.enum(["contains", "regex", "equals", "startsWith", "endsWith"]),
48236
- pattern: z105.string(),
48237
- reason: z105.string()
47238
+ import { z as z104 } from "zod";
47239
+ var HazardCategorySchema = z104.enum(HazardCategory);
47240
+ var HazardSeveritySchema = z104.enum(HazardSeverity);
47241
+ var ConstraintPrioritySchema = z104.enum(ConstraintPriority);
47242
+ var RiskLevelSchema = z104.enum(RiskLevel);
47243
+ var TriggerPatternSchema = z104.object({
47244
+ parameter: z104.string().min(1),
47245
+ matchType: z104.enum(["contains", "regex", "equals", "startsWith", "endsWith"]),
47246
+ pattern: z104.string(),
47247
+ reason: z104.string()
48238
47248
  });
48239
- var HazardSchema = z105.object({
48240
- id: z105.string().min(1),
48241
- description: z105.string(),
47249
+ var HazardSchema = z104.object({
47250
+ id: z104.string().min(1),
47251
+ description: z104.string(),
48242
47252
  category: HazardCategorySchema,
48243
47253
  severity: HazardSeveritySchema,
48244
- likelihood: z105.enum(["almost_certain", "likely", "possible", "unlikely", "rare"]),
48245
- triggerConditions: z105.array(z105.string()),
48246
- consequences: z105.array(z105.string())
47254
+ likelihood: z104.enum(["almost_certain", "likely", "possible", "unlikely", "rare"]),
47255
+ triggerConditions: z104.array(z104.string()),
47256
+ consequences: z104.array(z104.string())
48247
47257
  });
48248
- var UnsafeControlActionSchema = z105.object({
48249
- id: z105.string().min(1),
48250
- toolName: z105.string().min(1),
48251
- type: z105.enum(["not_provided", "provided_causes_hazard", "wrong_timing", "wrong_duration"]),
48252
- description: z105.string(),
48253
- unsafeContext: z105.string(),
48254
- relatedHazards: z105.array(z105.string()),
48255
- triggerPatterns: z105.array(TriggerPatternSchema).optional()
47258
+ var UnsafeControlActionSchema = z104.object({
47259
+ id: z104.string().min(1),
47260
+ toolName: z104.string().min(1),
47261
+ type: z104.enum(["not_provided", "provided_causes_hazard", "wrong_timing", "wrong_duration"]),
47262
+ description: z104.string(),
47263
+ unsafeContext: z104.string(),
47264
+ relatedHazards: z104.array(z104.string()),
47265
+ triggerPatterns: z104.array(TriggerPatternSchema).optional()
48256
47266
  });
48257
- var SafetyConstraintSchema = z105.object({
48258
- id: z105.string().min(1),
48259
- description: z105.string(),
48260
- mitigates: z105.array(z105.string()),
48261
- enforcement: z105.enum([
47267
+ var SafetyConstraintSchema = z104.object({
47268
+ id: z104.string().min(1),
47269
+ description: z104.string(),
47270
+ mitigates: z104.array(z104.string()),
47271
+ enforcement: z104.enum([
48262
47272
  "prevent",
48263
47273
  "require_confirmation",
48264
47274
  "alert",
@@ -48266,54 +47276,54 @@ var SafetyConstraintSchema = z105.object({
48266
47276
  "rate_limit",
48267
47277
  "require_privilege"
48268
47278
  ]),
48269
- validationFunction: z105.string().optional(),
47279
+ validationFunction: z104.string().optional(),
48270
47280
  priority: ConstraintPrioritySchema
48271
47281
  });
48272
- var PropertySchemaSchema = z105.object({
48273
- type: z105.string(),
48274
- description: z105.string().optional(),
48275
- enum: z105.array(z105.unknown()).optional(),
48276
- pattern: z105.string().optional(),
48277
- minimum: z105.number().optional(),
48278
- maximum: z105.number().optional()
47282
+ var PropertySchemaSchema = z104.object({
47283
+ type: z104.string(),
47284
+ description: z104.string().optional(),
47285
+ enum: z104.array(z104.unknown()).optional(),
47286
+ pattern: z104.string().optional(),
47287
+ minimum: z104.number().optional(),
47288
+ maximum: z104.number().optional()
48279
47289
  });
48280
- var ToolInputSchemaSchema = z105.object({
48281
- type: z105.string(),
48282
- properties: z105.record(z105.string(), PropertySchemaSchema).optional(),
48283
- required: z105.array(z105.string()).optional(),
48284
- additionalProperties: z105.boolean().optional()
47290
+ var ToolInputSchemaSchema = z104.object({
47291
+ type: z104.string(),
47292
+ properties: z104.record(z104.string(), PropertySchemaSchema).optional(),
47293
+ required: z104.array(z104.string()).optional(),
47294
+ additionalProperties: z104.boolean().optional()
48285
47295
  });
48286
- var ToolDefinitionSchema = z105.object({
48287
- name: z105.string().min(1),
48288
- description: z105.string(),
47296
+ var ToolDefinitionSchema = z104.object({
47297
+ name: z104.string().min(1),
47298
+ description: z104.string(),
48289
47299
  inputSchema: ToolInputSchemaSchema
48290
47300
  });
48291
- var AnalysisConfigurationSchema = z105.object({
48292
- includeLowSeverity: z105.boolean().default(true),
48293
- generateAllConstraints: z105.boolean().default(true),
48294
- checkInteractions: z105.boolean().default(true),
48295
- maxHazardsPerTool: z105.number().int().min(1).max(100).default(50),
48296
- categories: z105.array(HazardCategorySchema).default([])
47301
+ var AnalysisConfigurationSchema = z104.object({
47302
+ includeLowSeverity: z104.boolean().default(true),
47303
+ generateAllConstraints: z104.boolean().default(true),
47304
+ checkInteractions: z104.boolean().default(true),
47305
+ maxHazardsPerTool: z104.number().int().min(1).max(100).default(50),
47306
+ categories: z104.array(HazardCategorySchema).default([])
48297
47307
  });
48298
- var ConstraintViolationSchema = z105.object({
48299
- constraintId: z105.string().min(1),
48300
- constraintDescription: z105.string(),
47308
+ var ConstraintViolationSchema = z104.object({
47309
+ constraintId: z104.string().min(1),
47310
+ constraintDescription: z104.string(),
48301
47311
  severity: HazardSeveritySchema,
48302
- details: z105.string(),
48303
- remediation: z105.string()
47312
+ details: z104.string(),
47313
+ remediation: z104.string()
48304
47314
  });
48305
- var ValidationWarningSchema = z105.object({
48306
- code: z105.string().min(1),
48307
- message: z105.string(),
48308
- affected: z105.string()
47315
+ var ValidationWarningSchema = z104.object({
47316
+ code: z104.string().min(1),
47317
+ message: z104.string(),
47318
+ affected: z104.string()
48309
47319
  });
48310
- var ValidationResultSchema = z105.object({
48311
- valid: z105.boolean(),
48312
- toolName: z105.string().min(1),
48313
- violations: z105.array(ConstraintViolationSchema),
48314
- passed: z105.array(z105.string()),
48315
- warnings: z105.array(ValidationWarningSchema),
48316
- validatedAt: z105.date()
47320
+ var ValidationResultSchema = z104.object({
47321
+ valid: z104.boolean(),
47322
+ toolName: z104.string().min(1),
47323
+ violations: z104.array(ConstraintViolationSchema),
47324
+ passed: z104.array(z104.string()),
47325
+ warnings: z104.array(ValidationWarningSchema),
47326
+ validatedAt: z104.date()
48317
47327
  });
48318
47328
 
48319
47329
  // src/mcp/safety/stpa-types.ts
@@ -49398,43 +48408,43 @@ var GeminiResponseParser = class {
49398
48408
  };
49399
48409
 
49400
48410
  // src/cli-adapters/router-types.ts
49401
- import { z as z106 } from "zod";
49402
- var RouterConfigSchema = z106.object({
49403
- minCapacityThreshold: z106.number().min(0).max(1).default(0.1),
49404
- preferCostEfficient: z106.boolean().default(false),
49405
- maxDecisionTimeMs: z106.number().min(1).max(1e3).default(100)
48411
+ import { z as z105 } from "zod";
48412
+ var RouterConfigSchema = z105.object({
48413
+ minCapacityThreshold: z105.number().min(0).max(1).default(0.1),
48414
+ preferCostEfficient: z105.boolean().default(false),
48415
+ maxDecisionTimeMs: z105.number().min(1).max(1e3).default(100)
49406
48416
  });
49407
48417
 
49408
48418
  // src/cli-adapters/agreement-cascade-types.ts
49409
- import { z as z107 } from "zod";
49410
- var AgreementCascadeConfigSchema = z107.object({
49411
- agreementThreshold: z107.number().min(0.5).max(1).default(0.7),
49412
- maxStages: z107.number().int().min(1).max(5).default(3),
49413
- modelTimeoutMs: z107.number().int().min(1e3).max(3e5).default(6e4)
48419
+ import { z as z106 } from "zod";
48420
+ var AgreementCascadeConfigSchema = z106.object({
48421
+ agreementThreshold: z106.number().min(0.5).max(1).default(0.7),
48422
+ maxStages: z106.number().int().min(1).max(5).default(3),
48423
+ modelTimeoutMs: z106.number().int().min(1e3).max(3e5).default(6e4)
49414
48424
  });
49415
48425
 
49416
48426
  // src/cli-adapters/agreement-cascade-router.ts
49417
48427
  var logger45 = createLogger({ component: "agreement-cascade-router" });
49418
48428
 
49419
48429
  // src/cli-adapters/task-classifier.ts
49420
- import { z as z108 } from "zod";
49421
- var ClassificationPatternsSchema = z108.object({
49422
- code: z108.array(z108.string()).readonly(),
49423
- research: z108.array(z108.string()).readonly(),
49424
- documentation: z108.array(z108.string()).readonly(),
49425
- analysis: z108.array(z108.string()).readonly()
48430
+ import { z as z107 } from "zod";
48431
+ var ClassificationPatternsSchema = z107.object({
48432
+ code: z107.array(z107.string()).readonly(),
48433
+ research: z107.array(z107.string()).readonly(),
48434
+ documentation: z107.array(z107.string()).readonly(),
48435
+ analysis: z107.array(z107.string()).readonly()
49426
48436
  });
49427
48437
 
49428
48438
  // src/cli-adapters/response-cache-types.ts
49429
- import { z as z109 } from "zod";
49430
- var ResponseCacheConfigSchema = z109.object({
49431
- defaultTTL: z109.number().min(1e3).max(36e5).default(3e5),
48439
+ import { z as z108 } from "zod";
48440
+ var ResponseCacheConfigSchema = z108.object({
48441
+ defaultTTL: z108.number().min(1e3).max(36e5).default(3e5),
49432
48442
  // 5 minutes
49433
- maxEntries: z109.number().min(10).max(1e5).default(1e3),
49434
- maxMemoryMB: z109.number().min(1).max(1e3).default(50),
49435
- cleanupInterval: z109.number().min(1e3).max(6e5).default(6e4),
48443
+ maxEntries: z108.number().min(10).max(1e5).default(1e3),
48444
+ maxMemoryMB: z108.number().min(1).max(1e3).default(50),
48445
+ cleanupInterval: z108.number().min(1e3).max(6e5).default(6e4),
49436
48446
  // 1 minute
49437
- enableLogging: z109.boolean().default(false)
48447
+ enableLogging: z108.boolean().default(false)
49438
48448
  });
49439
48449
 
49440
48450
  // src/cli-adapters/response-cache-utils.ts
@@ -49442,12 +48452,12 @@ import { createHash as createHash4 } from "crypto";
49442
48452
  var logger46 = createLogger({ component: "ResponseCacheUtils" });
49443
48453
 
49444
48454
  // src/cli-adapters/unified-routing-types.ts
49445
- import { z as z110 } from "zod";
49446
- var UnifiedRoutingDecisionSchema = z110.object({
49447
- selectedCli: z110.string(),
49448
- confidence: z110.number().min(0).max(1),
49449
- reason: z110.string(),
49450
- strategy: z110.enum([
48455
+ import { z as z109 } from "zod";
48456
+ var UnifiedRoutingDecisionSchema = z109.object({
48457
+ selectedCli: z109.string(),
48458
+ confidence: z109.number().min(0).max(1),
48459
+ reason: z109.string(),
48460
+ strategy: z109.enum([
49451
48461
  "composite",
49452
48462
  "quality",
49453
48463
  "budget",
@@ -49459,57 +48469,57 @@ var UnifiedRoutingDecisionSchema = z110.object({
49459
48469
  "linucb",
49460
48470
  "direct"
49461
48471
  ]),
49462
- decisionTimeMs: z110.number().nonnegative(),
49463
- alternatives: z110.array(z110.string()).readonly(),
49464
- stagesExecuted: z110.array(z110.string()).readonly(),
49465
- withinBudget: z110.boolean().optional(),
49466
- estimatedComplexity: z110.enum(["simple", "moderate", "complex", "expert"]).optional(),
49467
- estimatedTokens: z110.number().int().positive().optional(),
49468
- topsisScore: z110.number().optional(),
49469
- ucbScore: z110.number().optional(),
49470
- resolvedAtStage: z110.number().int().nonnegative().optional(),
49471
- consensusReached: z110.boolean().optional(),
49472
- agreementScore: z110.number().min(0).max(1).optional(),
49473
- metadata: z110.record(z110.string(), z110.unknown()).optional()
48472
+ decisionTimeMs: z109.number().nonnegative(),
48473
+ alternatives: z109.array(z109.string()).readonly(),
48474
+ stagesExecuted: z109.array(z109.string()).readonly(),
48475
+ withinBudget: z109.boolean().optional(),
48476
+ estimatedComplexity: z109.enum(["simple", "moderate", "complex", "expert"]).optional(),
48477
+ estimatedTokens: z109.number().int().positive().optional(),
48478
+ topsisScore: z109.number().optional(),
48479
+ ucbScore: z109.number().optional(),
48480
+ resolvedAtStage: z109.number().int().nonnegative().optional(),
48481
+ consensusReached: z109.boolean().optional(),
48482
+ agreementScore: z109.number().min(0).max(1).optional(),
48483
+ metadata: z109.record(z109.string(), z109.unknown()).optional()
49474
48484
  });
49475
48485
 
49476
48486
  // src/learning/outcome-feedback-types.ts
49477
- import { z as z111 } from "zod";
49478
- var QualitySignalsSchema = z111.object({
49479
- testsPass: z111.boolean().optional(),
49480
- lintErrors: z111.number().int().min(0).optional(),
49481
- userApproved: z111.boolean().optional(),
49482
- retryCount: z111.number().int().min(0).default(0),
49483
- completionRatio: z111.number().min(0).max(1).default(1),
49484
- validStructure: z111.boolean().optional(),
49485
- coherenceScore: z111.number().min(0).max(1).optional()
48487
+ import { z as z110 } from "zod";
48488
+ var QualitySignalsSchema = z110.object({
48489
+ testsPass: z110.boolean().optional(),
48490
+ lintErrors: z110.number().int().min(0).optional(),
48491
+ userApproved: z110.boolean().optional(),
48492
+ retryCount: z110.number().int().min(0).default(0),
48493
+ completionRatio: z110.number().min(0).max(1).default(1),
48494
+ validStructure: z110.boolean().optional(),
48495
+ coherenceScore: z110.number().min(0).max(1).optional()
49486
48496
  });
49487
- var RoutingDecisionSchema = z111.object({
49488
- id: z111.uuid(),
49489
- timestamp: z111.iso.datetime(),
49490
- query: z111.string(),
49491
- routerType: z111.enum(["linucb", "preference", "quality", "cascade", "topsis"]),
49492
- selectedModel: z111.string(),
49493
- selectedTier: z111.enum(["strong", "weak"]).optional(),
49494
- armIndex: z111.number().int().min(0).optional(),
49495
- banditContext: z111.record(z111.string(), z111.unknown()).optional(),
49496
- queryFeatures: z111.record(z111.string(), z111.unknown()).optional(),
49497
- ucbScore: z111.number().optional(),
49498
- confidence: z111.number().min(0).max(1).optional(),
49499
- traceId: z111.string(),
49500
- domain: z111.string().optional()
48497
+ var RoutingDecisionSchema = z110.object({
48498
+ id: z110.uuid(),
48499
+ timestamp: z110.iso.datetime(),
48500
+ query: z110.string(),
48501
+ routerType: z110.enum(["linucb", "preference", "quality", "cascade", "topsis"]),
48502
+ selectedModel: z110.string(),
48503
+ selectedTier: z110.enum(["strong", "weak"]).optional(),
48504
+ armIndex: z110.number().int().min(0).optional(),
48505
+ banditContext: z110.record(z110.string(), z110.unknown()).optional(),
48506
+ queryFeatures: z110.record(z110.string(), z110.unknown()).optional(),
48507
+ ucbScore: z110.number().optional(),
48508
+ confidence: z110.number().min(0).max(1).optional(),
48509
+ traceId: z110.string(),
48510
+ domain: z110.string().optional()
49501
48511
  });
49502
- var TaskOutcomeSchema = z111.object({
49503
- routingDecisionId: z111.uuid(),
49504
- timestamp: z111.iso.datetime(),
49505
- outcomeClass: z111.enum(["success", "partial", "failure", "timeout", "error"]),
49506
- success: z111.boolean(),
49507
- qualityScore: z111.number().min(0).max(1),
49508
- durationMs: z111.number().min(0),
49509
- tokenUsage: z111.number().int().min(0),
49510
- errorMessage: z111.string().optional(),
48512
+ var TaskOutcomeSchema = z110.object({
48513
+ routingDecisionId: z110.uuid(),
48514
+ timestamp: z110.iso.datetime(),
48515
+ outcomeClass: z110.enum(["success", "partial", "failure", "timeout", "error"]),
48516
+ success: z110.boolean(),
48517
+ qualityScore: z110.number().min(0).max(1),
48518
+ durationMs: z110.number().min(0),
48519
+ tokenUsage: z110.number().int().min(0),
48520
+ errorMessage: z110.string().optional(),
49511
48521
  qualitySignals: QualitySignalsSchema,
49512
- traceId: z111.string()
48522
+ traceId: z110.string()
49513
48523
  });
49514
48524
  var DEFAULT_FEEDBACK_COLLECTOR_CONFIG = {
49515
48525
  maxPendingDecisions: 1e3,
@@ -49524,17 +48534,17 @@ var DEFAULT_FEEDBACK_COLLECTOR_CONFIG = {
49524
48534
  targetTokenUsage: 2e3,
49525
48535
  maxHistorySize: 1e4
49526
48536
  };
49527
- var FeedbackCollectorConfigSchema = z111.object({
49528
- maxPendingDecisions: z111.number().int().positive().default(1e3),
49529
- pendingTimeoutMs: z111.number().positive().default(3e5),
49530
- enableAutoReward: z111.boolean().default(true),
49531
- qualityWeight: z111.number().min(0).max(1).default(0.5),
49532
- speedWeight: z111.number().min(0).max(1).default(0.2),
49533
- efficiencyWeight: z111.number().min(0).max(1).default(0.2),
49534
- retryPenalty: z111.number().min(0).max(1).default(0.1),
49535
- targetDurationMs: z111.number().positive().default(5e3),
49536
- targetTokenUsage: z111.number().positive().default(2e3),
49537
- maxHistorySize: z111.number().int().positive().default(1e4)
48537
+ var FeedbackCollectorConfigSchema = z110.object({
48538
+ maxPendingDecisions: z110.number().int().positive().default(1e3),
48539
+ pendingTimeoutMs: z110.number().positive().default(3e5),
48540
+ enableAutoReward: z110.boolean().default(true),
48541
+ qualityWeight: z110.number().min(0).max(1).default(0.5),
48542
+ speedWeight: z110.number().min(0).max(1).default(0.2),
48543
+ efficiencyWeight: z110.number().min(0).max(1).default(0.2),
48544
+ retryPenalty: z110.number().min(0).max(1).default(0.1),
48545
+ targetDurationMs: z110.number().positive().default(5e3),
48546
+ targetTokenUsage: z110.number().positive().default(2e3),
48547
+ maxHistorySize: z110.number().int().positive().default(1e4)
49538
48548
  });
49539
48549
 
49540
48550
  // src/learning/outcome-feedback-helpers.ts
@@ -50596,10 +49606,10 @@ function getPolicy(id) {
50596
49606
  }
50597
49607
 
50598
49608
  // src/security/sandbox/sandbox-executor.ts
50599
- import { execFile as execFile4 } from "child_process";
50600
- import { promisify as promisify4 } from "util";
49609
+ import { execFile as execFile2 } from "child_process";
49610
+ import { promisify as promisify2 } from "util";
50601
49611
  import { resolve as resolve17, normalize as normalize2, sep as sep10 } from "path";
50602
- var execFileAsync4 = promisify4(execFile4);
49612
+ var execFileAsync2 = promisify2(execFile2);
50603
49613
  var logger48 = createLogger({ component: "sandbox-executor" });
50604
49614
  function parseExecError(error) {
50605
49615
  const execError = error;
@@ -50708,7 +49718,7 @@ var PolicySandboxExecutor = class {
50708
49718
  * Executes command with resource limits.
50709
49719
  */
50710
49720
  async executeWithLimits(command, args, cwd, env, limits) {
50711
- const { stdout, stderr } = await execFileAsync4(command, [...args], {
49721
+ const { stdout, stderr } = await execFileAsync2(command, [...args], {
50712
49722
  cwd: cwd ?? process.cwd(),
50713
49723
  timeout: limits.maxWallTimeMs,
50714
49724
  maxBuffer: limits.maxOutputBytes,
@@ -51138,9 +50148,9 @@ import * as fs14 from "fs";
51138
50148
  import * as path13 from "path";
51139
50149
  var logger54 = createLogger({ component: "task-tracker" });
51140
50150
  async function exec(cmd, args, timeout = 15e3) {
51141
- const { execFile: execFile5 } = await import("child_process");
51142
- const { promisify: promisify5 } = await import("util");
51143
- const run = promisify5(execFile5);
50151
+ const { execFile: execFile3 } = await import("child_process");
50152
+ const { promisify: promisify3 } = await import("util");
50153
+ const run = promisify3(execFile3);
51144
50154
  const { stdout } = await run(cmd, [...args], { timeout });
51145
50155
  return stdout.trim();
51146
50156
  }
@@ -51151,7 +50161,7 @@ var GitHubTaskTracker = class {
51151
50161
  cachedProvider = null;
51152
50162
  async getProvider() {
51153
50163
  if (this.cachedProvider !== null) return this.cachedProvider;
51154
- const { createScmProvider } = await import("./factory-PSMTMC7V.js");
50164
+ const { createScmProvider } = await import("./factory-P2SQS7UM.js");
51155
50165
  const result = await createScmProvider({ repo: this.config.repo ?? "" });
51156
50166
  if (!result.ok) throw new Error(`SCM provider error: ${result.error.message}`);
51157
50167
  this.cachedProvider = result.value;
@@ -51753,11 +50763,6 @@ export {
51753
50763
  registerMemoryStatsTool,
51754
50764
  MemoryWriteInputSchema,
51755
50765
  registerMemoryWriteTool,
51756
- createFitnessScoreCalculator,
51757
- calculateFitnessScore,
51758
- ImprovementReviewInputSchema,
51759
- runImprovementReview,
51760
- registerImprovementReviewTool,
51761
50766
  registerWeatherReportTool,
51762
50767
  RegistryImportInputSchema,
51763
50768
  registerRegistryImportTool,
@@ -51859,4 +50864,4 @@ export {
51859
50864
  detectBackend,
51860
50865
  createTaskTracker
51861
50866
  };
51862
- //# sourceMappingURL=chunk-FYGZ4MEQ.js.map
50867
+ //# sourceMappingURL=chunk-76FTBRUS.js.map