0xray 2.0.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 (739) hide show
  1. package/.opencode/agents/api-design.yml +31 -0
  2. package/.opencode/agents/architect.yml +15 -0
  3. package/.opencode/agents/architecture-patterns.yml +14 -0
  4. package/.opencode/agents/auto-format.yml +14 -0
  5. package/.opencode/agents/backend-engineer.yml +12 -0
  6. package/.opencode/agents/boot-orchestrator.yml +14 -0
  7. package/.opencode/agents/bug-triage-specialist.yml +15 -0
  8. package/.opencode/agents/code-analyzer.yml +12 -0
  9. package/.opencode/agents/code-reviewer.yml +14 -0
  10. package/.opencode/agents/content-creator.yml +12 -0
  11. package/.opencode/agents/database-engineer.yml +12 -0
  12. package/.opencode/agents/devops-engineer.yml +12 -0
  13. package/.opencode/agents/framework-compliance-audit.yml +14 -0
  14. package/.opencode/agents/frontend-engineer.yml +12 -0
  15. package/.opencode/agents/frontend-ui-ux-engineer.yml +12 -0
  16. package/.opencode/agents/git-workflow.yml +15 -0
  17. package/.opencode/agents/growth-strategist.yml +12 -0
  18. package/.opencode/agents/hermes-agent.yml +12 -0
  19. package/.opencode/agents/inference-improve.yml +12 -0
  20. package/.opencode/agents/lint.yml +14 -0
  21. package/.opencode/agents/log-monitor.yml +12 -0
  22. package/.opencode/agents/mobile-developer.yml +12 -0
  23. package/.opencode/agents/model-health-check.yml +12 -0
  24. package/.opencode/agents/multimodal-looker.yml +12 -0
  25. package/.opencode/agents/performance-analysis.yml +12 -0
  26. package/.opencode/agents/performance-engineer.yml +12 -0
  27. package/.opencode/agents/performance-optimization.yml +12 -0
  28. package/.opencode/agents/processor-pipeline.yml +14 -0
  29. package/.opencode/agents/project-analysis.yml +12 -0
  30. package/.opencode/agents/refactorer.yml +12 -0
  31. package/.opencode/agents/researcher.yml +12 -0
  32. package/.opencode/agents/security-auditor.yml +12 -0
  33. package/.opencode/agents/security-scan.yml +12 -0
  34. package/.opencode/agents/seo-consultant.yml +12 -0
  35. package/.opencode/agents/session-management.yml +12 -0
  36. package/.opencode/agents/state-manager.yml +12 -0
  37. package/.opencode/agents/storyteller.yml +12 -0
  38. package/.opencode/agents/strategist.yml +12 -0
  39. package/.opencode/agents/tech-writer.yml +12 -0
  40. package/.opencode/agents/testing-best-practices.yml +12 -0
  41. package/.opencode/agents/testing-lead.yml +12 -0
  42. package/.opencode/agents/ui-ux-design.yml +12 -0
  43. package/.opencode/codex.codex +8 -0
  44. package/.opencode/commands/auto-format.md +99 -0
  45. package/.opencode/commands/auto-summary-capture.md +90 -0
  46. package/.opencode/commands/dependency-audit.md +184 -0
  47. package/.opencode/commands/enforcer-daily-scan.md +137 -0
  48. package/.opencode/commands/framework-compliance-audit.md +205 -0
  49. package/.opencode/commands/interactive-validator.md +75 -0
  50. package/.opencode/commands/job-summary-logger.md +68 -0
  51. package/.opencode/commands/lint.md +11 -0
  52. package/.opencode/commands/mode-switch.md +95 -0
  53. package/.opencode/commands/model-health-check.md +186 -0
  54. package/.opencode/commands/performance-analysis.md +144 -0
  55. package/.opencode/commands/pre-commit-introspection.md +185 -0
  56. package/.opencode/commands/pre-commit-introspection.sh +133 -0
  57. package/.opencode/commands/security-scan.md +157 -0
  58. package/.opencode/commands/sisyphus-validation.md +128 -0
  59. package/.opencode/commands/summary-logger.md +83 -0
  60. package/.opencode/enforcer-config.json +285 -0
  61. package/.opencode/hooks/hook-metrics.json +380 -0
  62. package/.opencode/hooks/post-commit +114 -0
  63. package/.opencode/hooks/post-push +34 -0
  64. package/.opencode/init.sh +151 -0
  65. package/.opencode/skills/api-design/SKILL.md +37 -0
  66. package/.opencode/skills/architect-tools/SKILL.md +37 -0
  67. package/.opencode/skills/architecture-patterns/SKILL.md +37 -0
  68. package/.opencode/skills/auto-format/SKILL.md +37 -0
  69. package/.opencode/skills/backend-engineer/SKILL.md +49 -0
  70. package/.opencode/skills/boot-orchestrator/SKILL.md +37 -0
  71. package/.opencode/skills/bug-triage/SKILL.md +43 -0
  72. package/.opencode/skills/code-analyzer/SKILL.md +45 -0
  73. package/.opencode/skills/code-review/SKILL.md +52 -0
  74. package/.opencode/skills/content-creator/SKILL.md +38 -0
  75. package/.opencode/skills/database-engineer/SKILL.md +46 -0
  76. package/.opencode/skills/devops-engineer/SKILL.md +49 -0
  77. package/.opencode/skills/enforcer/SKILL.md +37 -0
  78. package/.opencode/skills/framework-compliance-audit/SKILL.md +37 -0
  79. package/.opencode/skills/frontend-engineer/SKILL.md +49 -0
  80. package/.opencode/skills/frontend-ui-ux-engineer/SKILL.md +41 -0
  81. package/.opencode/skills/git-workflow/SKILL.md +37 -0
  82. package/.opencode/skills/growth-strategist/SKILL.md +48 -0
  83. package/.opencode/skills/hermes-agent/SKILL.md +212 -0
  84. package/.opencode/skills/inference-improve/SKILL.md +97 -0
  85. package/.opencode/skills/lint/SKILL.md +37 -0
  86. package/.opencode/skills/log-monitor/SKILL.md +44 -0
  87. package/.opencode/skills/mobile-developer/SKILL.md +42 -0
  88. package/.opencode/skills/model-health-check/SKILL.md +37 -0
  89. package/.opencode/skills/multimodal-looker/SKILL.md +45 -0
  90. package/.opencode/skills/orchestrator/SKILL.md +37 -0
  91. package/.opencode/skills/performance-analysis/SKILL.md +37 -0
  92. package/.opencode/skills/performance-engineer/SKILL.md +41 -0
  93. package/.opencode/skills/performance-optimization/SKILL.md +37 -0
  94. package/.opencode/skills/processor-pipeline/SKILL.md +37 -0
  95. package/.opencode/skills/project-analysis/SKILL.md +42 -0
  96. package/.opencode/skills/refactoring-strategies/SKILL.md +37 -0
  97. package/.opencode/skills/registry.json +66 -0
  98. package/.opencode/skills/researcher/SKILL.md +37 -0
  99. package/.opencode/skills/security-audit/SKILL.md +47 -0
  100. package/.opencode/skills/security-scan/SKILL.md +37 -0
  101. package/.opencode/skills/seo-consultant/SKILL.md +43 -0
  102. package/.opencode/skills/session-management/SKILL.md +36 -0
  103. package/.opencode/skills/state-manager/SKILL.md +37 -0
  104. package/.opencode/skills/storyteller/SKILL.md +130 -0
  105. package/.opencode/skills/strategist/SKILL.md +32 -0
  106. package/.opencode/skills/tech-writer/SKILL.md +37 -0
  107. package/.opencode/skills/testing-best-practices/SKILL.md +37 -0
  108. package/.opencode/skills/testing-strategy/SKILL.md +43 -0
  109. package/.opencode/skills/ui-ux-design/SKILL.md +603 -0
  110. package/.opencode/workflows/post-deployment-audit.yml +123 -0
  111. package/AGENTS.md +110 -0
  112. package/LICENSE +21 -0
  113. package/README.md +131 -0
  114. package/dist/AGENTS.md +110 -0
  115. package/dist/CHANGELOG.md +2182 -0
  116. package/dist/LICENSE +21 -0
  117. package/dist/README.md +131 -0
  118. package/dist/agents/architect.js +56 -0
  119. package/dist/agents/backend-engineer.js +81 -0
  120. package/dist/agents/bug-triage-specialist.js +74 -0
  121. package/dist/agents/code-analyzer.js +150 -0
  122. package/dist/agents/code-reviewer.js +69 -0
  123. package/dist/agents/content-creator.js +72 -0
  124. package/dist/agents/database-engineer.js +76 -0
  125. package/dist/agents/devops-engineer.js +84 -0
  126. package/dist/agents/frontend-engineer.js +78 -0
  127. package/dist/agents/frontend-ui-ux-engineer.js +64 -0
  128. package/dist/agents/growth-strategist.js +111 -0
  129. package/dist/agents/index.js +45 -0
  130. package/dist/agents/librarian-agents-updater.js +333 -0
  131. package/dist/agents/log-monitor.js +109 -0
  132. package/dist/agents/mobile-developer.js +102 -0
  133. package/dist/agents/multimodal-looker.js +93 -0
  134. package/dist/agents/performance-engineer.js +86 -0
  135. package/dist/agents/refactorer.js +80 -0
  136. package/dist/agents/registry.js +340 -0
  137. package/dist/agents/researcher.js +83 -0
  138. package/dist/agents/security-auditor.js +158 -0
  139. package/dist/agents/seo-consultant.js +53 -0
  140. package/dist/agents/strategist.js +47 -0
  141. package/dist/agents/tech-writer.js +84 -0
  142. package/dist/agents/testing-lead.js +95 -0
  143. package/dist/agents/types.js +1 -0
  144. package/dist/analytics/consent-manager.js +258 -0
  145. package/dist/analytics/emerging-pattern-detector.js +260 -0
  146. package/dist/analytics/pattern-learning-engine.js +278 -0
  147. package/dist/analytics/pattern-performance-tracker.js +336 -0
  148. package/dist/analytics/predictive-analytics.js +248 -0
  149. package/dist/analytics/prompt-pattern-analyzer.js +371 -0
  150. package/dist/analytics/routing-performance-analyzer.js +356 -0
  151. package/dist/analytics/routing-refiner.js +380 -0
  152. package/dist/analytics/simple-pattern-analyzer.js +297 -0
  153. package/dist/architect/architect-tools.js +437 -0
  154. package/dist/architect/architectural-integrity.js +78 -0
  155. package/dist/benchmark/performance-benchmark.js +372 -0
  156. package/dist/cli/commands/analytics-disable.js +72 -0
  157. package/dist/cli/commands/analytics-enable-action.js +82 -0
  158. package/dist/cli/commands/analytics-preview.js +106 -0
  159. package/dist/cli/commands/analytics-status.js +68 -0
  160. package/dist/cli/commands/antigravity-status.js +106 -0
  161. package/dist/cli/commands/archive-logs.js +161 -0
  162. package/dist/cli/commands/credible-init.js +82 -0
  163. package/dist/cli/commands/grok-install.js +16 -0
  164. package/dist/cli/commands/hermes-install.js +66 -0
  165. package/dist/cli/commands/mcp-install.js +253 -0
  166. package/dist/cli/commands/openclaw-install.js +44 -0
  167. package/dist/cli/commands/opencode-install.js +99 -0
  168. package/dist/cli/commands/plugin-commands.js +246 -0
  169. package/dist/cli/commands/publish-agent.js +184 -0
  170. package/dist/cli/commands/security-audit.js +219 -0
  171. package/dist/cli/commands/skill-install.js +481 -0
  172. package/dist/cli/commands/status.js +196 -0
  173. package/dist/cli/commands/storyteller.js +230 -0
  174. package/dist/cli/index.js +986 -0
  175. package/dist/cli/server.js +147 -0
  176. package/dist/config/default-agents.js +16 -0
  177. package/dist/core/activity-logger.js +260 -0
  178. package/dist/core/adaptive-kernel.js +192 -0
  179. package/dist/core/agent-spawn-gate.js +120 -0
  180. package/dist/core/boot-orchestrator.js +812 -0
  181. package/dist/core/bridge.mjs +945 -0
  182. package/dist/core/codex-formatter.js +220 -0
  183. package/dist/core/codex-injector.js +424 -0
  184. package/dist/core/config-loader.js +148 -0
  185. package/dist/core/config-paths.js +162 -0
  186. package/dist/core/context-loader.js +269 -0
  187. package/dist/core/context-validator.js +212 -0
  188. package/dist/core/features-config.js +457 -0
  189. package/dist/core/framework-logger.js +275 -0
  190. package/dist/core/index.js +6 -0
  191. package/dist/core/kernel-patterns.js +302 -0
  192. package/dist/core/logging-config.js +43 -0
  193. package/dist/core/model-router.js +175 -0
  194. package/dist/core/orchestrator.js +408 -0
  195. package/dist/core/system-prompt-generator.js +265 -0
  196. package/dist/core/trace-context.js +33 -0
  197. package/dist/core/xray-activation.js +134 -0
  198. package/dist/delegation/agent-delegator.js +769 -0
  199. package/dist/delegation/agent-expertise.js +156 -0
  200. package/dist/delegation/analytics/index.js +12 -0
  201. package/dist/delegation/analytics/learning-engine.js +277 -0
  202. package/dist/delegation/analytics/outcome-tracker.js +279 -0
  203. package/dist/delegation/analytics/routing-analytics.js +193 -0
  204. package/dist/delegation/ast-code-parser.js +878 -0
  205. package/dist/delegation/codebase-context-analyzer.js +1040 -0
  206. package/dist/delegation/complexity-analyzer.js +282 -0
  207. package/dist/delegation/complexity-core.js +219 -0
  208. package/dist/delegation/config/types.js +6 -0
  209. package/dist/delegation/dependency-graph-builder.js +409 -0
  210. package/dist/delegation/index.js +20 -0
  211. package/dist/delegation/metrics-aggregator.js +335 -0
  212. package/dist/delegation/session-coordinator.js +352 -0
  213. package/dist/delegation/strategy-selector.js +108 -0
  214. package/dist/delegation/voting-coordinator.js +375 -0
  215. package/dist/delegation/voting-types.js +10 -0
  216. package/dist/delegation/weighted-voting-aggregator.js +194 -0
  217. package/dist/enforcement/core/index.js +19 -0
  218. package/dist/enforcement/core/rule-executor.js +365 -0
  219. package/dist/enforcement/core/rule-hierarchy.js +259 -0
  220. package/dist/enforcement/core/rule-registry.js +240 -0
  221. package/dist/enforcement/core/violation-fixer.js +651 -0
  222. package/dist/enforcement/enforcer-tools.js +909 -0
  223. package/dist/enforcement/index.js +41 -0
  224. package/dist/enforcement/loaders/agent-triage-loader.js +222 -0
  225. package/dist/enforcement/loaders/agents-md-validation-loader.js +252 -0
  226. package/dist/enforcement/loaders/base-loader.js +86 -0
  227. package/dist/enforcement/loaders/codex-loader.js +396 -0
  228. package/dist/enforcement/loaders/index.js +40 -0
  229. package/dist/enforcement/loaders/loader-orchestrator.js +168 -0
  230. package/dist/enforcement/loaders/processor-loader.js +113 -0
  231. package/dist/enforcement/rule-enforcer.js +298 -0
  232. package/dist/enforcement/test-auto-healing.js +325 -0
  233. package/dist/enforcement/types.js +30 -0
  234. package/dist/enforcement/validators/architecture-validators.js +600 -0
  235. package/dist/enforcement/validators/base-validator.js +108 -0
  236. package/dist/enforcement/validators/code-quality-validators.js +336 -0
  237. package/dist/enforcement/validators/index.js +21 -0
  238. package/dist/enforcement/validators/security-validators.js +220 -0
  239. package/dist/enforcement/validators/testing-validators.js +253 -0
  240. package/dist/enforcement/validators/validator-registry.js +150 -0
  241. package/dist/execution/opencode-cli-invoker.js +173 -0
  242. package/dist/execution/proposal-applier.js +254 -0
  243. package/dist/governance/codex-policy.service.js +167 -0
  244. package/dist/governance/governance-core.js +152 -0
  245. package/dist/governance/governance-service.js +274 -0
  246. package/dist/governance/governance-types.js +6 -0
  247. package/dist/index.js +24 -0
  248. package/dist/inference/deploy-verifier.js +161 -0
  249. package/dist/inference/index.js +5 -0
  250. package/dist/inference/inference-accumulator.js +126 -0
  251. package/dist/inference/inference-cycle.js +1168 -0
  252. package/dist/inference/semantic-patterns.js +310 -0
  253. package/dist/inference/session-capture.js +308 -0
  254. package/dist/integrations/base/ExampleIntegration.js +181 -0
  255. package/dist/integrations/base/Integration.js +395 -0
  256. package/dist/integrations/base/README.md +446 -0
  257. package/dist/integrations/base/index.js +16 -0
  258. package/dist/integrations/base/registry.js +606 -0
  259. package/dist/integrations/base/types.js +118 -0
  260. package/dist/integrations/governance/governance-client.js +316 -0
  261. package/dist/integrations/governance/index.js +373 -0
  262. package/dist/integrations/governance/types.js +97 -0
  263. package/dist/integrations/grok/grok-cli.js +83 -0
  264. package/dist/integrations/grok/hooks/pre-tool-use.js +134 -0
  265. package/dist/integrations/grok/plugin/0xray/.mcp.json +15 -0
  266. package/dist/integrations/grok/plugin/0xray/hooks/hooks.json +30 -0
  267. package/dist/integrations/hermes-agent/__init__.py +718 -0
  268. package/dist/integrations/hermes-agent/after-install.md +71 -0
  269. package/dist/integrations/hermes-agent/bridge.mjs +861 -0
  270. package/dist/integrations/hermes-agent/conftest.py +14 -0
  271. package/dist/integrations/hermes-agent/plugin.yaml +12 -0
  272. package/dist/integrations/hermes-agent/schemas.py +100 -0
  273. package/dist/integrations/hermes-agent/test_plugin.py +1100 -0
  274. package/dist/integrations/hermes-agent/tools.py +253 -0
  275. package/dist/integrations/openclaw/README.md +134 -0
  276. package/dist/integrations/openclaw/api-server.js +389 -0
  277. package/dist/integrations/openclaw/client.js +492 -0
  278. package/dist/integrations/openclaw/config.js +374 -0
  279. package/dist/integrations/openclaw/hooks/strray-hooks.js +280 -0
  280. package/dist/integrations/openclaw/index.js +351 -0
  281. package/dist/integrations/openclaw/types.js +153 -0
  282. package/dist/integrations/plugins/index.js +10 -0
  283. package/dist/integrations/plugins/plugin-integration.js +606 -0
  284. package/dist/integrations/plugins/plugin-registry.js +580 -0
  285. package/dist/mcps/agent-resolver.js +106 -0
  286. package/dist/mcps/architect-tools.server.js +277 -0
  287. package/dist/mcps/auto-format.server.js +413 -0
  288. package/dist/mcps/boot-orchestrator.server.js +853 -0
  289. package/dist/mcps/config/config-loader.js +103 -0
  290. package/dist/mcps/config/config-validator.js +101 -0
  291. package/dist/mcps/config/index.js +30 -0
  292. package/dist/mcps/config/plugin-server-registry.js +223 -0
  293. package/dist/mcps/config/server-config-registry.js +348 -0
  294. package/dist/mcps/connection/connection-manager.js +79 -0
  295. package/dist/mcps/connection/connection-pool.js +164 -0
  296. package/dist/mcps/connection/mcp-connection.js +233 -0
  297. package/dist/mcps/connection/process-spawner.js +34 -0
  298. package/dist/mcps/enforcer-tools.server.js +778 -0
  299. package/dist/mcps/estimation.server.js +192 -0
  300. package/dist/mcps/framework-compliance-audit.server.js +500 -0
  301. package/dist/mcps/framework-help.server.js +400 -0
  302. package/dist/mcps/governance.server.js +464 -0
  303. package/dist/mcps/in-process-skill-registry.js +48 -0
  304. package/dist/mcps/knowledge-skills/api-design.server.js +123 -0
  305. package/dist/mcps/knowledge-skills/architecture-patterns.server.js +113 -0
  306. package/dist/mcps/knowledge-skills/bug-triage-specialist.server.js +474 -0
  307. package/dist/mcps/knowledge-skills/code-analyzer.server.js +605 -0
  308. package/dist/mcps/knowledge-skills/code-review.server.js +847 -0
  309. package/dist/mcps/knowledge-skills/content-creator.server.js +256 -0
  310. package/dist/mcps/knowledge-skills/database-design.server.js +822 -0
  311. package/dist/mcps/knowledge-skills/devops-deployment.server.js +1180 -0
  312. package/dist/mcps/knowledge-skills/git-workflow.server.js +115 -0
  313. package/dist/mcps/knowledge-skills/growth-strategist.server.js +361 -0
  314. package/dist/mcps/knowledge-skills/log-monitor.server.js +451 -0
  315. package/dist/mcps/knowledge-skills/mobile-development.server.js +525 -0
  316. package/dist/mcps/knowledge-skills/multimodal-looker.server.js +1063 -0
  317. package/dist/mcps/knowledge-skills/performance-optimization.server.js +1587 -0
  318. package/dist/mcps/knowledge-skills/project-analysis.server.js +811 -0
  319. package/dist/mcps/knowledge-skills/refactoring-strategies.server.js +796 -0
  320. package/dist/mcps/knowledge-skills/security-audit.server.js +846 -0
  321. package/dist/mcps/knowledge-skills/seo-consultant.server.js +937 -0
  322. package/dist/mcps/knowledge-skills/session-management.server.js +470 -0
  323. package/dist/mcps/knowledge-skills/skill-invocation.server.js +729 -0
  324. package/dist/mcps/knowledge-skills/strategist.server.js +217 -0
  325. package/dist/mcps/knowledge-skills/tech-writer.server.js +1191 -0
  326. package/dist/mcps/knowledge-skills/testing-best-practices.server.js +866 -0
  327. package/dist/mcps/knowledge-skills/testing-strategy.server.js +827 -0
  328. package/dist/mcps/knowledge-skills/ui-ux-design.server.js +1538 -0
  329. package/dist/mcps/lint.server.js +381 -0
  330. package/dist/mcps/mcp-client.js +574 -0
  331. package/dist/mcps/model-health-check.server.js +228 -0
  332. package/dist/mcps/orchestrator/config/agent-capabilities.js +87 -0
  333. package/dist/mcps/orchestrator/execution/execution-planner.js +279 -0
  334. package/dist/mcps/orchestrator/handlers/complexity-handler.js +94 -0
  335. package/dist/mcps/orchestrator/handlers/status-handler.js +232 -0
  336. package/dist/mcps/orchestrator/handlers/task-handler.js +197 -0
  337. package/dist/mcps/orchestrator/server.js +305 -0
  338. package/dist/mcps/orchestrator/types.js +6 -0
  339. package/dist/mcps/orchestrator.server.js +19 -0
  340. package/dist/mcps/performance-analysis.server.js +519 -0
  341. package/dist/mcps/processor-pipeline.server.js +561 -0
  342. package/dist/mcps/protocol/protocol-constants.js +46 -0
  343. package/dist/mcps/registry.json +110 -0
  344. package/dist/mcps/researcher.server.js +504 -0
  345. package/dist/mcps/security-scan.server.js +531 -0
  346. package/dist/mcps/simulation/index.js +12 -0
  347. package/dist/mcps/simulation/server-simulations.js +219 -0
  348. package/dist/mcps/simulation/simulation-engine.js +96 -0
  349. package/dist/mcps/state-manager.server.js +637 -0
  350. package/dist/mcps/tools/index.js +14 -0
  351. package/dist/mcps/tools/tool-cache.js +112 -0
  352. package/dist/mcps/tools/tool-discovery.js +65 -0
  353. package/dist/mcps/tools/tool-executor.js +75 -0
  354. package/dist/mcps/tools/tool-registry.js +67 -0
  355. package/dist/mcps/types/index.js +15 -0
  356. package/dist/mcps/types/json-rpc.types.js +7 -0
  357. package/dist/mcps/types/mcp.types.js +7 -0
  358. package/dist/metrics/agent-metrics.js +574 -0
  359. package/dist/metrics/index.js +6 -0
  360. package/dist/monitoring/advanced-profiler.js +232 -0
  361. package/dist/monitoring/memory-monitor.js +315 -0
  362. package/dist/monitoring/nudge-watchdog.js +356 -0
  363. package/dist/monitoring/test-auto-generation-monitor.js +157 -0
  364. package/dist/orchestrator/agent-spawn-governor.js +559 -0
  365. package/dist/orchestrator/enhanced-multi-agent-orchestrator.js +399 -0
  366. package/dist/orchestrator/intelligent-commit-batcher.js +353 -0
  367. package/dist/orchestrator/multi-agent-orchestration-coordinator.js +456 -0
  368. package/dist/orchestrator/orchestrator.js +657 -0
  369. package/dist/orchestrator/self-direction-activation.js +245 -0
  370. package/dist/orchestrator/universal-librarian-consultation.js +216 -0
  371. package/dist/orchestrator/universal-registry-bridge.js +247 -0
  372. package/dist/performance/performance-budget-enforcer.js +434 -0
  373. package/dist/performance/performance-regression-tester.js +342 -0
  374. package/dist/plugin/xray-codex-injection.js +857 -0
  375. package/dist/postprocessor/PostProcessor.js +1048 -0
  376. package/dist/postprocessor/analysis/FailureAnalysisEngine.js +245 -0
  377. package/dist/postprocessor/autofix/AutoFixEngine.js +254 -0
  378. package/dist/postprocessor/autofix/FixValidator.js +56 -0
  379. package/dist/postprocessor/config.js +65 -0
  380. package/dist/postprocessor/escalation/EscalationEngine.js +492 -0
  381. package/dist/postprocessor/monitoring/MonitoringEngine.js +125 -0
  382. package/dist/postprocessor/redeploy/RedeployCoordinator.js +342 -0
  383. package/dist/postprocessor/services/RegressionAnalysisService.js +131 -0
  384. package/dist/postprocessor/success/SuccessHandler.js +134 -0
  385. package/dist/postprocessor/triggers/APITrigger.js +115 -0
  386. package/dist/postprocessor/triggers/GitHookTrigger.js +551 -0
  387. package/dist/postprocessor/triggers/WebhookTrigger.js +211 -0
  388. package/dist/postprocessor/types.js +4 -0
  389. package/dist/processors/doc-write-guard.js +46 -0
  390. package/dist/processors/implementations/agents-md-validation-processor.js +286 -0
  391. package/dist/processors/implementations/async-pattern-processor.js +158 -0
  392. package/dist/processors/implementations/codex-compliance-processor.js +57 -0
  393. package/dist/processors/implementations/commit-batcher-processor.js +71 -0
  394. package/dist/processors/implementations/console-log-guard-processor.js +163 -0
  395. package/dist/processors/implementations/coverage-analysis-processor.js +138 -0
  396. package/dist/processors/implementations/error-boundary-processor.js +44 -0
  397. package/dist/processors/implementations/inference-improvement-processor.js +270 -0
  398. package/dist/processors/implementations/log-protection-processor.js +118 -0
  399. package/dist/processors/implementations/nudge-processor.js +130 -0
  400. package/dist/processors/implementations/performance-budget-processor.js +217 -0
  401. package/dist/processors/implementations/postprocessor-chain-validator.js +149 -0
  402. package/dist/processors/implementations/pre-validate-processor.js +18 -0
  403. package/dist/processors/implementations/publish-preflight-processor.js +249 -0
  404. package/dist/processors/implementations/refactoring-logging-processor-wrapper.js +33 -0
  405. package/dist/processors/implementations/refactoring-logging-processor.js +96 -0
  406. package/dist/processors/implementations/regression-testing-processor.js +59 -0
  407. package/dist/processors/implementations/session-capture-processor.js +37 -0
  408. package/dist/processors/implementations/session-summary-processor.js +130 -0
  409. package/dist/processors/implementations/spawn-governance-processor.js +219 -0
  410. package/dist/processors/implementations/state-validation-processor.js +15 -0
  411. package/dist/processors/implementations/storytelling-trigger-processor.js +589 -0
  412. package/dist/processors/implementations/test-auto-creation-processor.js +484 -0
  413. package/dist/processors/implementations/test-execution-processor.js +132 -0
  414. package/dist/processors/implementations/typescript-compilation-processor.js +87 -0
  415. package/dist/processors/implementations/version-compliance-processor.js +350 -0
  416. package/dist/processors/processor-interfaces.js +126 -0
  417. package/dist/processors/processor-manager.js +826 -0
  418. package/dist/processors/processor-types.js +12 -0
  419. package/dist/public/about.html +228 -0
  420. package/dist/public/enterprise.html +27 -0
  421. package/dist/public/features.html +102 -0
  422. package/dist/public/index.html +145 -0
  423. package/dist/reporting/framework-reporting-system.js +187 -0
  424. package/dist/reporting/log-parser.js +281 -0
  425. package/dist/reporting/metrics.js +202 -0
  426. package/dist/reporting/report-formatter.js +146 -0
  427. package/dist/reporting/types.js +1 -0
  428. package/dist/scripts/activate-kernel-pipeline.js +101 -0
  429. package/dist/scripts/integration.js +234 -0
  430. package/dist/scripts/pre-command +26 -0
  431. package/dist/scripts/pre-command.mjs +358 -0
  432. package/dist/security/comprehensive-security-audit.js +1005 -0
  433. package/dist/security/index.js +13 -0
  434. package/dist/security/prompt-security-validator.js +148 -0
  435. package/dist/security/security-agent-coordinator.js +204 -0
  436. package/dist/security/security-auditor.js +584 -0
  437. package/dist/security/security-hardener.js +170 -0
  438. package/dist/security/security-hardening-system.js +727 -0
  439. package/dist/security/security-headers.js +118 -0
  440. package/dist/security/security-orchestration-layer.js +496 -0
  441. package/dist/security/security-scanner.js +429 -0
  442. package/dist/services/inference-tuner.js +301 -0
  443. package/dist/session/index.js +3 -0
  444. package/dist/session/session-cleanup-manager.js +366 -0
  445. package/dist/session/session-monitor.js +503 -0
  446. package/dist/session/session-state-manager.js +522 -0
  447. package/dist/skills/api-design/SKILL.md +37 -0
  448. package/dist/skills/architect-tools/SKILL.md +37 -0
  449. package/dist/skills/architecture-patterns/SKILL.md +37 -0
  450. package/dist/skills/auto-format/SKILL.md +37 -0
  451. package/dist/skills/backend-engineer/SKILL.md +49 -0
  452. package/dist/skills/boot-orchestrator/SKILL.md +37 -0
  453. package/dist/skills/bug-triage/SKILL.md +43 -0
  454. package/dist/skills/code-analyzer/SKILL.md +45 -0
  455. package/dist/skills/code-review/SKILL.md +52 -0
  456. package/dist/skills/content-creator/SKILL.md +38 -0
  457. package/dist/skills/database-engineer/SKILL.md +46 -0
  458. package/dist/skills/devops-engineer/SKILL.md +49 -0
  459. package/dist/skills/enforcer/SKILL.md +37 -0
  460. package/dist/skills/framework-compliance-audit/SKILL.md +37 -0
  461. package/dist/skills/frontend-engineer/SKILL.md +49 -0
  462. package/dist/skills/frontend-ui-ux-engineer/SKILL.md +41 -0
  463. package/dist/skills/git-workflow/SKILL.md +37 -0
  464. package/dist/skills/growth-strategist/SKILL.md +48 -0
  465. package/dist/skills/hermes-agent/SKILL.md +212 -0
  466. package/dist/skills/inference-improve/SKILL.md +97 -0
  467. package/dist/skills/lint/SKILL.md +37 -0
  468. package/dist/skills/log-monitor/SKILL.md +44 -0
  469. package/dist/skills/mobile-developer/SKILL.md +42 -0
  470. package/dist/skills/model-health-check/SKILL.md +37 -0
  471. package/dist/skills/multimodal-looker/SKILL.md +45 -0
  472. package/dist/skills/orchestrator/SKILL.md +37 -0
  473. package/dist/skills/performance-analysis/SKILL.md +37 -0
  474. package/dist/skills/performance-engineer/SKILL.md +41 -0
  475. package/dist/skills/performance-optimization/SKILL.md +37 -0
  476. package/dist/skills/processor-pipeline/SKILL.md +37 -0
  477. package/dist/skills/project-analysis/SKILL.md +42 -0
  478. package/dist/skills/refactoring-strategies/SKILL.md +37 -0
  479. package/dist/skills/registry.json +66 -0
  480. package/dist/skills/researcher/SKILL.md +37 -0
  481. package/dist/skills/security-audit/SKILL.md +48 -0
  482. package/dist/skills/security-scan/SKILL.md +37 -0
  483. package/dist/skills/seo-consultant/SKILL.md +43 -0
  484. package/dist/skills/session-management/SKILL.md +36 -0
  485. package/dist/skills/state-manager/SKILL.md +37 -0
  486. package/dist/skills/storyteller/SKILL.md +130 -0
  487. package/dist/skills/strategist/SKILL.md +32 -0
  488. package/dist/skills/tech-writer/SKILL.md +37 -0
  489. package/dist/skills/testing-best-practices/SKILL.md +37 -0
  490. package/dist/skills/testing-strategy/SKILL.md +43 -0
  491. package/dist/skills/ui-ux-design/SKILL.md +603 -0
  492. package/dist/state/context-providers.js +1 -0
  493. package/dist/state/index.js +7 -0
  494. package/dist/state/state-manager.js +208 -0
  495. package/dist/state/state-types.js +1 -0
  496. package/dist/testing/memory-regression-suite.js +258 -0
  497. package/dist/utils/batch-operations.js +292 -0
  498. package/dist/utils/codex-parser.js +445 -0
  499. package/dist/utils/command-runner.js +96 -0
  500. package/dist/utils/import-resolver.js +189 -0
  501. package/dist/utils/language-detector.js +383 -0
  502. package/dist/utils/path-resolver.js +112 -0
  503. package/dist/utils/shutdown-handler.js +75 -0
  504. package/dist/utils/test-template-generator.js +178 -0
  505. package/dist/utils/token-manager.js +163 -0
  506. package/dist/validation/estimation-validator.js +241 -0
  507. package/dist/validation/report-content-validator.js +218 -0
  508. package/opencode.json +153 -0
  509. package/package.json +170 -0
  510. package/scripts/helpers/resolve-config-path.cjs +57 -0
  511. package/scripts/helpers/resolve-config-path.mjs +73 -0
  512. package/scripts/hooks/pre-command +26 -0
  513. package/scripts/hooks/pre-command.mjs +358 -0
  514. package/scripts/hooks/run-hook.js +570 -0
  515. package/scripts/mjs/test-consumer-readiness.mjs +273 -0
  516. package/scripts/mjs/test-mcp-functionality.mjs +507 -0
  517. package/scripts/mjs/validate-mcp-connectivity.cjs +75 -0
  518. package/scripts/mjs/validate-postinstall-config.mjs +308 -0
  519. package/scripts/node/auto-reflection-generator.mjs +496 -0
  520. package/scripts/node/basic-security-audit.cjs +338 -0
  521. package/scripts/node/ci-cd-auto-fix.cjs +263 -0
  522. package/scripts/node/ci-report-generator.mjs +227 -0
  523. package/scripts/node/enforce-agents-md.mjs +420 -0
  524. package/scripts/node/enforce-version-compliance.sh +22 -0
  525. package/scripts/node/enforce-version-compliance.ts +126 -0
  526. package/scripts/node/github-actions-monitor.cjs +23 -0
  527. package/scripts/node/govern-reflection.mjs +160 -0
  528. package/scripts/node/postinstall.cjs +78 -0
  529. package/scripts/node/pre-publish-guard.js +267 -0
  530. package/scripts/node/prepare-consumer.cjs +143 -0
  531. package/scripts/node/reflection-processor.cjs +213 -0
  532. package/scripts/node/reflection-validate.sh +194 -0
  533. package/scripts/node/release-tweet.mjs +39 -0
  534. package/scripts/node/release.js +159 -0
  535. package/scripts/node/release.mjs +213 -0
  536. package/scripts/node/setup-dev.cjs +83 -0
  537. package/scripts/node/setup.cjs +214 -0
  538. package/scripts/node/sync-versions.mjs +140 -0
  539. package/scripts/node/universal-version-manager.js +1025 -0
  540. package/scripts/node/validate-external-processes.js +265 -0
  541. package/scripts/node/validate-mcp-connectivity.js +258 -0
  542. package/scripts/node/version-manager.mjs +524 -0
  543. package/scripts/validate-stringray-comprehensive.js +636 -0
  544. package/src/integrations/grok/plugin/0xray/.mcp.json +15 -0
  545. package/src/integrations/grok/plugin/0xray/hooks/hooks.json +30 -0
  546. package/src/mcps/agent-resolver.ts +168 -0
  547. package/src/mcps/architect-tools.server.ts +343 -0
  548. package/src/mcps/auto-format.server.ts +529 -0
  549. package/src/mcps/boot-orchestrator.server.ts +1082 -0
  550. package/src/mcps/config/__tests__/config-loader.test.ts +338 -0
  551. package/src/mcps/config/__tests__/config-validator.test.ts +646 -0
  552. package/src/mcps/config/__tests__/server-config-registry.test.ts +257 -0
  553. package/src/mcps/config/config-loader.ts +127 -0
  554. package/src/mcps/config/config-validator.ts +127 -0
  555. package/src/mcps/config/index.ts +32 -0
  556. package/src/mcps/config/plugin-server-registry.ts +335 -0
  557. package/src/mcps/config/server-config-registry.ts +395 -0
  558. package/src/mcps/connection/connection-manager.ts +91 -0
  559. package/src/mcps/connection/connection-pool.ts +216 -0
  560. package/src/mcps/connection/mcp-connection.ts +327 -0
  561. package/src/mcps/connection/process-spawner.ts +47 -0
  562. package/src/mcps/enforcer-tools.server.ts +1106 -0
  563. package/src/mcps/estimation.server.ts +229 -0
  564. package/src/mcps/framework-compliance-audit.server.ts +635 -0
  565. package/src/mcps/framework-help.server.ts +467 -0
  566. package/src/mcps/governance.server.ts +551 -0
  567. package/src/mcps/in-process-skill-registry.ts +79 -0
  568. package/src/mcps/knowledge-skills/api-design.server.test.ts +41 -0
  569. package/src/mcps/knowledge-skills/api-design.server.ts +160 -0
  570. package/src/mcps/knowledge-skills/architecture-patterns.server.ts +152 -0
  571. package/src/mcps/knowledge-skills/bug-triage-specialist.server.ts +624 -0
  572. package/src/mcps/knowledge-skills/code-analyzer.server.test.ts +129 -0
  573. package/src/mcps/knowledge-skills/code-analyzer.server.ts +591 -0
  574. package/src/mcps/knowledge-skills/code-review.server.ts +1132 -0
  575. package/src/mcps/knowledge-skills/content-creator.server.ts +300 -0
  576. package/src/mcps/knowledge-skills/database-design.server.ts +1200 -0
  577. package/src/mcps/knowledge-skills/devops-deployment.server.ts +1622 -0
  578. package/src/mcps/knowledge-skills/git-workflow.server.ts +152 -0
  579. package/src/mcps/knowledge-skills/growth-strategist.server.ts +413 -0
  580. package/src/mcps/knowledge-skills/log-monitor.server.ts +619 -0
  581. package/src/mcps/knowledge-skills/mobile-development.server.ts +672 -0
  582. package/src/mcps/knowledge-skills/multimodal-looker.server.ts +1500 -0
  583. package/src/mcps/knowledge-skills/performance-optimization.server.ts +2065 -0
  584. package/src/mcps/knowledge-skills/project-analysis.server.ts +1111 -0
  585. package/src/mcps/knowledge-skills/refactoring-strategies.server.ts +1092 -0
  586. package/src/mcps/knowledge-skills/security-audit.server.test.ts +112 -0
  587. package/src/mcps/knowledge-skills/security-audit.server.ts +1193 -0
  588. package/src/mcps/knowledge-skills/seo-consultant.server.ts +1160 -0
  589. package/src/mcps/knowledge-skills/session-management.server.ts +576 -0
  590. package/src/mcps/knowledge-skills/skill-invocation.server.ts +941 -0
  591. package/src/mcps/knowledge-skills/strategist.server.ts +267 -0
  592. package/src/mcps/knowledge-skills/tech-writer.server.ts +1638 -0
  593. package/src/mcps/knowledge-skills/testing-best-practices.server.test.ts +136 -0
  594. package/src/mcps/knowledge-skills/testing-best-practices.server.ts +1232 -0
  595. package/src/mcps/knowledge-skills/testing-strategy.server.test.ts +100 -0
  596. package/src/mcps/knowledge-skills/testing-strategy.server.ts +1172 -0
  597. package/src/mcps/knowledge-skills/ui-ux-design.server.ts +2076 -0
  598. package/src/mcps/lint.server.ts +483 -0
  599. package/src/mcps/mcp-client.ts +706 -0
  600. package/src/mcps/model-health-check.server.ts +292 -0
  601. package/src/mcps/orchestrator/config/agent-capabilities.ts +108 -0
  602. package/src/mcps/orchestrator/execution/execution-planner.ts +353 -0
  603. package/src/mcps/orchestrator/handlers/complexity-handler.ts +125 -0
  604. package/src/mcps/orchestrator/handlers/status-handler.ts +295 -0
  605. package/src/mcps/orchestrator/handlers/task-handler.ts +268 -0
  606. package/src/mcps/orchestrator/server.ts +388 -0
  607. package/src/mcps/orchestrator/types.ts +81 -0
  608. package/src/mcps/orchestrator.server.ts +34 -0
  609. package/src/mcps/performance-analysis.server.ts +715 -0
  610. package/src/mcps/processor-pipeline.server.ts +778 -0
  611. package/src/mcps/protocol/protocol-constants.ts +51 -0
  612. package/src/mcps/registry.json +110 -0
  613. package/src/mcps/researcher.server.ts +595 -0
  614. package/src/mcps/security-scan.server.ts +651 -0
  615. package/src/mcps/simulation/__tests__/simulation-engine.test.ts +275 -0
  616. package/src/mcps/simulation/index.ts +23 -0
  617. package/src/mcps/simulation/server-simulations.ts +241 -0
  618. package/src/mcps/simulation/simulation-engine.ts +126 -0
  619. package/src/mcps/state-manager.server.ts +777 -0
  620. package/src/mcps/tools/__tests__/tool-cache.test.ts +205 -0
  621. package/src/mcps/tools/__tests__/tool-discovery.test.ts +189 -0
  622. package/src/mcps/tools/__tests__/tool-executor.test.ts +215 -0
  623. package/src/mcps/tools/__tests__/tool-registry.test.ts +230 -0
  624. package/src/mcps/tools/index.ts +15 -0
  625. package/src/mcps/tools/tool-cache.ts +145 -0
  626. package/src/mcps/tools/tool-discovery.ts +83 -0
  627. package/src/mcps/tools/tool-executor.ts +106 -0
  628. package/src/mcps/tools/tool-registry.ts +78 -0
  629. package/src/mcps/types/__tests__/types.test.ts +341 -0
  630. package/src/mcps/types/index.ts +17 -0
  631. package/src/mcps/types/json-rpc.types.ts +38 -0
  632. package/src/mcps/types/mcp.types.ts +115 -0
  633. package/src/opencode/agents/api-design.yml +31 -0
  634. package/src/opencode/agents/architect.yml +15 -0
  635. package/src/opencode/agents/architecture-patterns.yml +14 -0
  636. package/src/opencode/agents/auto-format.yml +14 -0
  637. package/src/opencode/agents/backend-engineer.yml +12 -0
  638. package/src/opencode/agents/boot-orchestrator.yml +14 -0
  639. package/src/opencode/agents/bug-triage-specialist.yml +15 -0
  640. package/src/opencode/agents/code-analyzer.yml +12 -0
  641. package/src/opencode/agents/code-reviewer.yml +14 -0
  642. package/src/opencode/agents/content-creator.yml +12 -0
  643. package/src/opencode/agents/database-engineer.yml +12 -0
  644. package/src/opencode/agents/devops-engineer.yml +12 -0
  645. package/src/opencode/agents/framework-compliance-audit.yml +14 -0
  646. package/src/opencode/agents/frontend-engineer.yml +12 -0
  647. package/src/opencode/agents/frontend-ui-ux-engineer.yml +12 -0
  648. package/src/opencode/agents/git-workflow.yml +15 -0
  649. package/src/opencode/agents/growth-strategist.yml +12 -0
  650. package/src/opencode/agents/hermes-agent.yml +12 -0
  651. package/src/opencode/agents/inference-improve.yml +12 -0
  652. package/src/opencode/agents/lint.yml +14 -0
  653. package/src/opencode/agents/log-monitor.yml +12 -0
  654. package/src/opencode/agents/mobile-developer.yml +12 -0
  655. package/src/opencode/agents/model-health-check.yml +12 -0
  656. package/src/opencode/agents/multimodal-looker.yml +12 -0
  657. package/src/opencode/agents/performance-analysis.yml +12 -0
  658. package/src/opencode/agents/performance-engineer.yml +12 -0
  659. package/src/opencode/agents/performance-optimization.yml +12 -0
  660. package/src/opencode/agents/processor-pipeline.yml +14 -0
  661. package/src/opencode/agents/project-analysis.yml +12 -0
  662. package/src/opencode/agents/refactorer.yml +12 -0
  663. package/src/opencode/agents/researcher.yml +12 -0
  664. package/src/opencode/agents/security-auditor.yml +12 -0
  665. package/src/opencode/agents/security-scan.yml +12 -0
  666. package/src/opencode/agents/seo-consultant.yml +12 -0
  667. package/src/opencode/agents/session-management.yml +12 -0
  668. package/src/opencode/agents/state-manager.yml +12 -0
  669. package/src/opencode/agents/storyteller.yml +12 -0
  670. package/src/opencode/agents/strategist.yml +12 -0
  671. package/src/opencode/agents/tech-writer.yml +12 -0
  672. package/src/opencode/agents/testing-best-practices.yml +12 -0
  673. package/src/opencode/agents/testing-lead.yml +12 -0
  674. package/src/opencode/agents/ui-ux-design.yml +12 -0
  675. package/src/opencode/codex.codex +8 -0
  676. package/src/opencode/commands/auto-format.md +99 -0
  677. package/src/opencode/commands/auto-summary-capture.md +90 -0
  678. package/src/opencode/commands/dependency-audit.md +184 -0
  679. package/src/opencode/commands/enforcer-daily-scan.md +137 -0
  680. package/src/opencode/commands/framework-compliance-audit.md +205 -0
  681. package/src/opencode/commands/interactive-validator.md +75 -0
  682. package/src/opencode/commands/job-summary-logger.md +68 -0
  683. package/src/opencode/commands/lint.md +11 -0
  684. package/src/opencode/commands/mode-switch.md +95 -0
  685. package/src/opencode/commands/model-health-check.md +186 -0
  686. package/src/opencode/commands/performance-analysis.md +144 -0
  687. package/src/opencode/commands/pre-commit-introspection.md +185 -0
  688. package/src/opencode/commands/pre-commit-introspection.sh +133 -0
  689. package/src/opencode/commands/security-scan.md +157 -0
  690. package/src/opencode/commands/sisyphus-validation.md +128 -0
  691. package/src/opencode/commands/summary-logger.md +83 -0
  692. package/src/opencode/enforcer-config.json +285 -0
  693. package/src/opencode/openclaw/config.json +25 -0
  694. package/src/opencode/workflows/post-deployment-audit.yml +123 -0
  695. package/src/skills/api-design/SKILL.md +37 -0
  696. package/src/skills/architect-tools/SKILL.md +37 -0
  697. package/src/skills/architecture-patterns/SKILL.md +37 -0
  698. package/src/skills/auto-format/SKILL.md +37 -0
  699. package/src/skills/backend-engineer/SKILL.md +49 -0
  700. package/src/skills/boot-orchestrator/SKILL.md +37 -0
  701. package/src/skills/bug-triage/SKILL.md +43 -0
  702. package/src/skills/code-analyzer/SKILL.md +45 -0
  703. package/src/skills/code-review/SKILL.md +52 -0
  704. package/src/skills/content-creator/SKILL.md +38 -0
  705. package/src/skills/database-engineer/SKILL.md +46 -0
  706. package/src/skills/devops-engineer/SKILL.md +49 -0
  707. package/src/skills/enforcer/SKILL.md +37 -0
  708. package/src/skills/framework-compliance-audit/SKILL.md +37 -0
  709. package/src/skills/frontend-engineer/SKILL.md +49 -0
  710. package/src/skills/frontend-ui-ux-engineer/SKILL.md +41 -0
  711. package/src/skills/git-workflow/SKILL.md +37 -0
  712. package/src/skills/growth-strategist/SKILL.md +48 -0
  713. package/src/skills/hermes-agent/SKILL.md +212 -0
  714. package/src/skills/inference-improve/SKILL.md +97 -0
  715. package/src/skills/lint/SKILL.md +37 -0
  716. package/src/skills/log-monitor/SKILL.md +44 -0
  717. package/src/skills/mobile-developer/SKILL.md +42 -0
  718. package/src/skills/model-health-check/SKILL.md +37 -0
  719. package/src/skills/multimodal-looker/SKILL.md +45 -0
  720. package/src/skills/orchestrator/SKILL.md +37 -0
  721. package/src/skills/performance-analysis/SKILL.md +37 -0
  722. package/src/skills/performance-engineer/SKILL.md +41 -0
  723. package/src/skills/performance-optimization/SKILL.md +37 -0
  724. package/src/skills/processor-pipeline/SKILL.md +37 -0
  725. package/src/skills/project-analysis/SKILL.md +42 -0
  726. package/src/skills/refactoring-strategies/SKILL.md +37 -0
  727. package/src/skills/registry.json +66 -0
  728. package/src/skills/researcher/SKILL.md +37 -0
  729. package/src/skills/security-audit/SKILL.md +48 -0
  730. package/src/skills/security-scan/SKILL.md +37 -0
  731. package/src/skills/seo-consultant/SKILL.md +43 -0
  732. package/src/skills/session-management/SKILL.md +36 -0
  733. package/src/skills/state-manager/SKILL.md +37 -0
  734. package/src/skills/storyteller/SKILL.md +130 -0
  735. package/src/skills/strategist/SKILL.md +32 -0
  736. package/src/skills/tech-writer/SKILL.md +37 -0
  737. package/src/skills/testing-best-practices/SKILL.md +37 -0
  738. package/src/skills/testing-strategy/SKILL.md +43 -0
  739. package/src/skills/ui-ux-design/SKILL.md +603 -0
@@ -0,0 +1,2065 @@
1
+ /**
2
+ * xray Performance Optimization MCP Server
3
+ *
4
+ * Knowledge skill for performance analysis, optimization recommendations,
5
+ * profiling, benchmarking, memory analysis, and Core Web Vitals measurement
6
+ */
7
+
8
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
9
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
10
+ import {
11
+ CallToolRequestSchema,
12
+ ListToolsRequestSchema,
13
+ } from "@modelcontextprotocol/sdk/types.js";
14
+ import { frameworkLogger, generateJobId } from "../../core/framework-logger.js";
15
+ import { createGracefulShutdown } from "../../utils/shutdown-handler.js";
16
+ import fs from "fs";
17
+ import path from "path";
18
+ import os from "os";
19
+ import { execSync } from "child_process";
20
+
21
+ interface ProfileApplicationArgs {
22
+ projectRoot: string;
23
+ scope?: "full" | "runtime" | "build" | "memory";
24
+ duration?: number;
25
+ includeHotPaths?: boolean;
26
+ }
27
+
28
+ interface AnalyzeMemoryArgs {
29
+ projectRoot: string;
30
+ heapSnapshot?: boolean;
31
+ gcAnalysis?: boolean;
32
+ leakDetection?: boolean;
33
+ }
34
+
35
+ interface BenchmarkCodeArgs {
36
+ projectRoot: string;
37
+ testFile?: string;
38
+ iterations?: number;
39
+ warmupRuns?: number;
40
+ compareBaseline?: boolean;
41
+ }
42
+
43
+ interface SuggestOptimizationsArgs {
44
+ projectRoot: string;
45
+ focus?: "cpu" | "memory" | "network" | "io" | "all";
46
+ threshold?: number;
47
+ }
48
+
49
+ interface MeasureCoreWebVitalsArgs {
50
+ projectRoot: string;
51
+ analyzeBundle?: boolean;
52
+ checkAccessibility?: boolean;
53
+ measureLCP?: boolean;
54
+ measureINP?: boolean;
55
+ measureCLS?: boolean;
56
+ }
57
+
58
+ interface ProfilingResult {
59
+ hotPaths: string[];
60
+ functionCallCounts: Record<string, number>;
61
+ memoryFootprint: number;
62
+ bottlenecks: string[];
63
+ recommendations: string[];
64
+ cpuProfile: Record<string, unknown>;
65
+ metrics: ProfilingMetrics;
66
+ }
67
+
68
+ interface ProfilingMetrics {
69
+ totalFunctions: number;
70
+ hotFunctions: number;
71
+ avgExecutionTime: number;
72
+ peakMemory: number;
73
+ gcPauses: number;
74
+ }
75
+
76
+ interface MemoryAnalysisResult {
77
+ heapUsed: number;
78
+ heapTotal: number;
79
+ external: number;
80
+ rss: number;
81
+ memoryLeaks: MemoryLeak[];
82
+ gcEvents: GCEvent[];
83
+ recommendations: string[];
84
+ heapBreakdown: HeapBreakdown;
85
+ allocationsByType: MemoryAllocationBreakdown;
86
+ }
87
+
88
+ interface MemoryLeak {
89
+ location: string;
90
+ severity: "low" | "medium" | "high" | "critical";
91
+ suspectedCause: string;
92
+ estimatedImpact: string;
93
+ fixSuggestion: string;
94
+ }
95
+
96
+ interface GCEvent {
97
+ type: "minor" | "major" | "full";
98
+ duration: number;
99
+ timestamp: number;
100
+ reclaimedBytes: number;
101
+ }
102
+
103
+ interface HeapBreakdown {
104
+ strings: number;
105
+ arrays: number;
106
+ objects: number;
107
+ functions: number;
108
+ closures: number;
109
+ domNodes: number;
110
+ }
111
+
112
+ interface BenchmarkResult {
113
+ benchmarks: Benchmark[];
114
+ comparison?: BenchmarkComparison;
115
+ statistics: BenchmarkStatistics;
116
+ recommendations: string[];
117
+ }
118
+
119
+ interface Benchmark {
120
+ name: string;
121
+ operations: number;
122
+ duration: number;
123
+ opsPerSecond: number;
124
+ meanMs: number;
125
+ medianMs: number;
126
+ stdDevMs: number;
127
+ minMs: number;
128
+ maxMs: number;
129
+ p95Ms: number;
130
+ p99Ms: number;
131
+ }
132
+
133
+ interface BenchmarkComparison {
134
+ baseline: Benchmark;
135
+ current: Benchmark;
136
+ improvement: number;
137
+ significant: boolean;
138
+ }
139
+
140
+ interface BenchmarkStatistics {
141
+ totalBenchmarks: number;
142
+ fastest: string;
143
+ slowest: string;
144
+ averageOpsPerSecond: number;
145
+ variance: number;
146
+ }
147
+
148
+ interface MemoryAllocationBreakdown {
149
+ strings: number;
150
+ arrays: number;
151
+ objects: number;
152
+ functions: number;
153
+ buffers: number;
154
+ closures: number;
155
+ promises: number;
156
+ eventListeners: number;
157
+ }
158
+
159
+ interface OptimizationSuggestion {
160
+ id: string;
161
+ category: "cpu" | "memory" | "network" | "io" | "rendering";
162
+ title: string;
163
+ description: string;
164
+ impact: "low" | "medium" | "high" | "critical";
165
+ effort: "low" | "medium" | "high";
166
+ files: string[];
167
+ codeSnippet?: string;
168
+ suggestedFix: string;
169
+ expectedImprovement: string;
170
+ }
171
+
172
+ interface CoreWebVitalsResult {
173
+ LCP?: LCPMetrics;
174
+ INP?: INPMetrics;
175
+ CLS?: CLSMetrics;
176
+ bundleAnalysis?: BundleAnalysis;
177
+ recommendations: string[];
178
+ score: number;
179
+ status: "good" | "needs-improvement" | "poor";
180
+ }
181
+
182
+ interface LCPMetrics {
183
+ value: number;
184
+ score: number;
185
+ element: string;
186
+ resourceLoadTime: number;
187
+ renderDelay: number;
188
+ }
189
+
190
+ interface INPMetrics {
191
+ value: number;
192
+ score: number;
193
+ interactionType: string;
194
+ processingTime: number;
195
+ presentationDelay: number;
196
+ }
197
+
198
+ interface CLSMetrics {
199
+ value: number;
200
+ score: number;
201
+ layoutShifts: number;
202
+ unexpectedShifts: number;
203
+ sources: string[];
204
+ }
205
+
206
+ interface BundleAnalysis {
207
+ totalSize: number;
208
+ gzippedSize: number;
209
+ byType: Record<string, number>;
210
+ largestModules: { name: string; size: number }[];
211
+ duplication: { name: string; count: number }[];
212
+ treeShakingOpportunities: string[];
213
+ }
214
+
215
+ interface McpToolResponse {
216
+ content: Array<{ type: string; text: string }>;
217
+ data?: Record<string, unknown>;
218
+ }
219
+
220
+ class StringRayPerformanceOptimizationServer {
221
+ private server: Server;
222
+ private startTime: number;
223
+
224
+ constructor() {
225
+ this.server = new Server(
226
+ {
227
+ name: "performance-optimization", version: "1.22.67",
228
+ },
229
+ {
230
+ capabilities: {
231
+ tools: {},
232
+ },
233
+ },
234
+ );
235
+
236
+ this.startTime = Date.now();
237
+ this.setupToolHandlers();
238
+ }
239
+
240
+ private setupToolHandlers() {
241
+ this.server.setRequestHandler(ListToolsRequestSchema, async () => {
242
+ return {
243
+ tools: [
244
+ {
245
+ name: "profile-application",
246
+ description: "Run comprehensive performance profiling on the codebase to identify bottlenecks and hot paths",
247
+ inputSchema: {
248
+ type: "object",
249
+ properties: {
250
+ projectRoot: { type: "string", description: "Path to the project root directory" },
251
+ scope: {
252
+ type: "string",
253
+ enum: ["full", "runtime", "build", "memory"],
254
+ default: "full",
255
+ description: "Scope of profiling analysis"
256
+ },
257
+ duration: { type: "number", default: 30, description: "Profiling duration in seconds" },
258
+ includeHotPaths: { type: "boolean", default: true, description: "Include hot path analysis" }
259
+ },
260
+ required: ["projectRoot"]
261
+ }
262
+ },
263
+ {
264
+ name: "analyze-memory",
265
+ description: "Perform memory leak detection and heap analysis to identify memory issues",
266
+ inputSchema: {
267
+ type: "object",
268
+ properties: {
269
+ projectRoot: { type: "string", description: "Path to the project root directory" },
270
+ heapSnapshot: { type: "boolean", default: true, description: "Generate heap snapshot analysis" },
271
+ gcAnalysis: { type: "boolean", default: true, description: "Analyze garbage collection patterns" },
272
+ leakDetection: { type: "boolean", default: true, description: "Detect potential memory leaks" }
273
+ },
274
+ required: ["projectRoot"]
275
+ }
276
+ },
277
+ {
278
+ name: "benchmark-code",
279
+ description: "Execute and compare benchmark results for code performance measurement",
280
+ inputSchema: {
281
+ type: "object",
282
+ properties: {
283
+ projectRoot: { type: "string", description: "Path to the project root directory" },
284
+ testFile: { type: "string", description: "Specific benchmark test file to run" },
285
+ iterations: { type: "number", default: 100, description: "Number of benchmark iterations" },
286
+ warmupRuns: { type: "number", default: 10, description: "Number of warmup runs" },
287
+ compareBaseline: { type: "boolean", default: false, description: "Compare results against baseline" }
288
+ },
289
+ required: ["projectRoot"]
290
+ }
291
+ },
292
+ {
293
+ name: "suggest-optimizations",
294
+ description: "Generate specific, actionable optimization suggestions based on code analysis",
295
+ inputSchema: {
296
+ type: "object",
297
+ properties: {
298
+ projectRoot: { type: "string", description: "Path to the project root directory" },
299
+ focus: {
300
+ type: "string",
301
+ enum: ["cpu", "memory", "network", "io", "all"],
302
+ default: "all",
303
+ description: "Focus area for optimizations"
304
+ },
305
+ threshold: { type: "number", default: 100, description: "Performance threshold in ms" }
306
+ },
307
+ required: ["projectRoot"]
308
+ }
309
+ },
310
+ {
311
+ name: "measure-core-web-vitals",
312
+ description: "Analyze Core Web Vitals metrics (LCP, INP, CLS) for web application performance",
313
+ inputSchema: {
314
+ type: "object",
315
+ properties: {
316
+ projectRoot: { type: "string", description: "Path to the project root directory" },
317
+ analyzeBundle: { type: "boolean", default: true, description: "Analyze JavaScript bundle" },
318
+ checkAccessibility: { type: "boolean", default: true, description: "Check accessibility factors affecting CLS" },
319
+ measureLCP: { type: "boolean", default: true, description: "Measure Largest Contentful Paint" },
320
+ measureINP: { type: "boolean", default: true, description: "Measure Interaction to Next Paint" },
321
+ measureCLS: { type: "boolean", default: true, description: "Measure Cumulative Layout Shift" }
322
+ },
323
+ required: ["projectRoot"]
324
+ }
325
+ }
326
+ ]
327
+ };
328
+ });
329
+
330
+ this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
331
+ const { name, arguments: args } = request.params;
332
+
333
+ try {
334
+ switch (name) {
335
+ case "profile-application":
336
+ return await this.handleProfileApplication(args as unknown as ProfileApplicationArgs) as never;
337
+ case "analyze-memory":
338
+ return await this.handleAnalyzeMemory(args as unknown as AnalyzeMemoryArgs) as never;
339
+ case "benchmark-code":
340
+ return await this.handleBenchmarkCode(args as unknown as BenchmarkCodeArgs) as never;
341
+ case "suggest-optimizations":
342
+ return await this.handleSuggestOptimizations(args as unknown as SuggestOptimizationsArgs) as never;
343
+ case "measure-core-web-vitals":
344
+ return await this.handleMeasureCoreWebVitals(args as unknown as MeasureCoreWebVitalsArgs) as never;
345
+ default:
346
+ throw new Error(`Unknown tool: ${name}`);
347
+ }
348
+ } catch (error) {
349
+ frameworkLogger.log("mcp/performance-optimization", "tool-handler", "error", { tool: name, error: String(error) });
350
+ return {
351
+ content: [{
352
+ type: "text",
353
+ text: `Error executing tool "${name}": ${error instanceof Error ? error.message : String(error)}`
354
+ }]
355
+ };
356
+ }
357
+ });
358
+ }
359
+
360
+ private async handleProfileApplication(args: ProfileApplicationArgs): Promise<McpToolResponse> {
361
+ const { projectRoot, scope = "full", duration = 30, includeHotPaths = true } = args;
362
+ const jobId = generateJobId("mcp-perf-profiling");
363
+
364
+ await frameworkLogger.log("mcp/performance-optimization", "profiling-started", "info", { projectRoot, scope }, undefined, jobId);
365
+
366
+ try {
367
+ const result = await this.performProfiling(projectRoot, scope, duration, includeHotPaths);
368
+
369
+ const responseText = this.formatProfilingResult(result);
370
+
371
+ return {
372
+ content: [{ type: "text", text: responseText }],
373
+ data: result as unknown as Record<string, unknown>
374
+ };
375
+ } catch (error) {
376
+ return {
377
+ content: [{
378
+ type: "text",
379
+ text: `Profiling failed: ${error instanceof Error ? error.message : String(error)}`
380
+ }]
381
+ };
382
+ }
383
+ }
384
+
385
+ private async performProfiling(
386
+ projectRoot: string,
387
+ scope: string,
388
+ duration: number,
389
+ includeHotPaths: boolean
390
+ ): Promise<ProfilingResult> {
391
+ const result: ProfilingResult = {
392
+ hotPaths: [],
393
+ functionCallCounts: {},
394
+ memoryFootprint: 0,
395
+ bottlenecks: [],
396
+ recommendations: [],
397
+ cpuProfile: {},
398
+ metrics: {
399
+ totalFunctions: 0,
400
+ hotFunctions: 0,
401
+ avgExecutionTime: 0,
402
+ peakMemory: 0,
403
+ gcPauses: 0
404
+ }
405
+ };
406
+
407
+ const memUsage = process.memoryUsage();
408
+ result.memoryFootprint = Math.round(memUsage.heapUsed / 1024 / 1024);
409
+
410
+ if (fs.existsSync(path.join(projectRoot, "src"))) {
411
+ const codeFiles = this.findCodeFiles(projectRoot);
412
+ const analysis = this.analyzeCodeForPerformance(codeFiles, scope);
413
+
414
+ result.hotPaths = analysis.hotPaths;
415
+ result.functionCallCounts = analysis.functionCounts;
416
+ result.bottlenecks = analysis.bottlenecks;
417
+ result.recommendations = analysis.recommendations;
418
+ result.metrics.totalFunctions = analysis.totalFunctions;
419
+ result.metrics.hotFunctions = analysis.hotFunctions;
420
+ result.metrics.avgExecutionTime = analysis.avgExecutionTime;
421
+ result.metrics.peakMemory = analysis.peakMemory;
422
+ result.metrics.gcPauses = analysis.gcPauses;
423
+
424
+ if (includeHotPaths) {
425
+ result.cpuProfile = {
426
+ topFunctions: this.getTopFunctions(analysis),
427
+ callGraph: this.generateCallGraph(analysis),
428
+ criticalPath: this.identifyCriticalPath(analysis)
429
+ };
430
+ }
431
+ }
432
+
433
+ return result;
434
+ }
435
+
436
+ private analyzeCodeForPerformance(files: string[], scope: string): {
437
+ hotPaths: string[];
438
+ functionCounts: Record<string, number>;
439
+ bottlenecks: string[];
440
+ recommendations: string[];
441
+ totalFunctions: number;
442
+ hotFunctions: number;
443
+ avgExecutionTime: number;
444
+ peakMemory: number;
445
+ gcPauses: number;
446
+ } {
447
+ const hotPaths: string[] = [];
448
+ const functionCounts: Record<string, number> = {};
449
+ const bottlenecks: string[] = [];
450
+ const recommendations: string[] = [];
451
+ let totalFunctions = 0;
452
+ let hotFunctions = 0;
453
+
454
+ for (const file of files) {
455
+ try {
456
+ const content = fs.readFileSync(file, "utf8");
457
+ const analysis = this.analyzeFilePerformance(content, file, scope);
458
+
459
+ if (analysis.functions.length > 0) {
460
+ totalFunctions += analysis.functions.length;
461
+ hotFunctions += analysis.hotCount;
462
+ analysis.functions.forEach((fn) => {
463
+ functionCounts[`${file}:${fn.name}`] = fn.estimatedCalls;
464
+ });
465
+ }
466
+
467
+ hotPaths.push(...analysis.hotPaths);
468
+ bottlenecks.push(...analysis.bottlenecks);
469
+ recommendations.push(...analysis.recommendations);
470
+ } catch {
471
+ // Skip files that can't be read
472
+ }
473
+ }
474
+
475
+ const avgExecutionTime = this.calculateAverageExecutionTime(functionCounts);
476
+
477
+ return {
478
+ hotPaths: [...new Set(hotPaths)],
479
+ functionCounts,
480
+ bottlenecks: [...new Set(bottlenecks)],
481
+ recommendations: [...new Set(recommendations)],
482
+ totalFunctions,
483
+ hotFunctions,
484
+ avgExecutionTime,
485
+ peakMemory: Math.round(process.memoryUsage().heapUsed / 1024 / 1024),
486
+ gcPauses: this.estimateGCPauses()
487
+ };
488
+ }
489
+
490
+ private analyzeFilePerformance(content: string, filePath: string, scope: string): {
491
+ functions: { name: string; estimatedCalls: number }[];
492
+ hotPaths: string[];
493
+ bottlenecks: string[];
494
+ recommendations: string[];
495
+ hotCount: number;
496
+ } {
497
+ const functions: { name: string; estimatedCalls: number }[] = [];
498
+ const hotPaths: string[] = [];
499
+ const bottlenecks: string[] = [];
500
+ const recommendations: string[] = [];
501
+ let hotCount = 0;
502
+
503
+ const functionRegex = /(?:function\s+(\w+)|(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?\(|(\w+)\s*\([^)]*\)\s*\{)/g;
504
+ let match;
505
+
506
+ while ((match = functionRegex.exec(content)) !== null) {
507
+ const fnName = match[1] || match[2] || match[3];
508
+ if (fnName && !fnName.startsWith("_")) {
509
+ const estimatedCalls = this.estimateFunctionCalls(content, fnName);
510
+ functions.push({ name: fnName, estimatedCalls });
511
+
512
+ if (estimatedCalls > 1000) {
513
+ hotCount++;
514
+ hotPaths.push(`${filePath}:${fnName}`);
515
+
516
+ const complexity = this.calculateCyclomaticComplexity(content, fnName);
517
+ if (complexity > 15) {
518
+ bottlenecks.push(`High complexity function: ${fnName} (complexity: ${complexity})`);
519
+ recommendations.push(`Consider simplifying ${fnName} - complexity ${complexity} exceeds recommended threshold`);
520
+ }
521
+ }
522
+ }
523
+ }
524
+
525
+ if (scope === "memory" || scope === "full") {
526
+ const closureMatches = content.match(/=>\s*\{[^}]*\}/g);
527
+ if (closureMatches && closureMatches.length > 10) {
528
+ recommendations.push(`${filePath}: High closure usage (${closureMatches.length}) may impact memory - consider refactoring`);
529
+ }
530
+
531
+ const nestedFuncMatches = content.match(/function\s+\w+[^}]*\{[^}]*function\s+/g);
532
+ if (nestedFuncMatches) {
533
+ bottlenecks.push(`${filePath}: Nested function detected - may cause memory leaks`);
534
+ recommendations.push(`Consider extracting nested functions in ${filePath}`);
535
+ }
536
+ }
537
+
538
+ return { functions, hotPaths, bottlenecks, recommendations, hotCount };
539
+ }
540
+
541
+ private estimateFunctionCalls(content: string, fnName: string): number {
542
+ const callRegex = new RegExp(`${fnName}\\s*\\(`, "g");
543
+ const calls = content.match(callRegex);
544
+ return calls ? calls.length : 0;
545
+ }
546
+
547
+ private calculateCyclomaticComplexity(content: string, fnName: string): number {
548
+ const fnStart = content.indexOf(`function ${fnName}`);
549
+ if (fnStart === -1) return 1;
550
+
551
+ let braceCount = 0;
552
+ let complexity = 1;
553
+ let inFunction = false;
554
+
555
+ for (let i = fnStart; i < content.length && braceCount >= 0; i++) {
556
+ const char = content[i];
557
+
558
+ if (char === "{") {
559
+ braceCount++;
560
+ inFunction = true;
561
+ } else if (char === "}") {
562
+ braceCount--;
563
+ }
564
+
565
+ if (inFunction && braceCount > 0) {
566
+ if (char === "\n" && (content[i + 1] === "if" || content[i + 1] === "else" || content[i + 1] === "for" || content[i + 1] === "while" || content[i + 1] === "case")) {
567
+ complexity++;
568
+ }
569
+ }
570
+ }
571
+
572
+ return complexity;
573
+ }
574
+
575
+ private calculateAverageExecutionTime(functionCounts: Record<string, number>): number {
576
+ const counts = Object.values(functionCounts);
577
+ if (counts.length === 0) return 0;
578
+
579
+ const avg = counts.reduce((sum, c) => sum + c, 0) / counts.length;
580
+ return Math.round(avg * 0.1);
581
+ }
582
+
583
+ private estimateGCPauses(): number {
584
+ const memUsage = process.memoryUsage();
585
+ const heapUsedMB = memUsage.heapUsed / 1024 / 1024;
586
+
587
+ if (heapUsedMB > 500) return 15;
588
+ if (heapUsedMB > 200) return 8;
589
+ if (heapUsedMB > 100) return 4;
590
+ return 2;
591
+ }
592
+
593
+ private getTopFunctions(analysis: { functionCounts: Record<string, number> }): { name: string; calls: number }[] {
594
+ return Object.entries(analysis.functionCounts)
595
+ .sort(([, a], [, b]) => b - a)
596
+ .slice(0, 10)
597
+ .map(([name, calls]) => ({ name, calls }));
598
+ }
599
+
600
+ private generateCallGraph(analysis: { functionCounts: Record<string, number> }): Record<string, string[]> {
601
+ const graph: Record<string, string[]> = {};
602
+
603
+ for (const [fullName] of Object.entries(analysis.functionCounts)) {
604
+ const parts = fullName.split(":");
605
+ const file = parts[0] ?? "unknown";
606
+ const fnName = parts[1] ?? fullName;
607
+ if (!graph[file]) graph[file] = [];
608
+ graph[file].push(fnName);
609
+ }
610
+
611
+ return graph;
612
+ }
613
+
614
+ private identifyCriticalPath(analysis: { hotPaths: string[] }): string[] {
615
+ return analysis.hotPaths.slice(0, 5);
616
+ }
617
+
618
+ private formatProfilingResult(result: ProfilingResult): string {
619
+ return `📊 Performance Profiling Results
620
+
621
+ **PROFILING METRICS**
622
+ - Total Functions Analyzed: ${result.metrics.totalFunctions}
623
+ - Hot Functions (>1000 calls): ${result.metrics.hotFunctions}
624
+ - Average Execution Time: ${result.metrics.avgExecutionTime}ms
625
+ - Peak Memory: ${result.metrics.peakMemory}MB
626
+ - GC Pauses: ${result.metrics.gcPauses}
627
+
628
+ **HOT PATHS** (${result.hotPaths.length} identified)
629
+ ${result.hotPaths.slice(0, 10).map(p => `• 🔥 ${p}`).join("\n") || "None detected"}
630
+
631
+ **TOP FUNCTIONS BY CALL COUNT**
632
+ ${Object.entries(result.functionCallCounts)
633
+ .sort(([, a], [, b]) => b - a)
634
+ .slice(0, 5)
635
+ .map(([name, count]) => `• ${name}: ${count.toLocaleString()} calls`)
636
+ .join("\n") || "None"}
637
+
638
+ **BOTTLENECKS** (${result.bottlenecks.length} detected)
639
+ ${result.bottlenecks.slice(0, 5).map(b => `• 🚧 ${b}`).join("\n") || "None detected"}
640
+
641
+ **RECOMMENDATIONS**
642
+ ${result.recommendations.slice(0, 5).map((r, i) => `${i + 1}. ${r}`).join("\n") || "No specific recommendations"}
643
+
644
+ **Status:** ${result.metrics.hotFunctions > 10 ? "❌ HIGH OPTIMIZATION NEEDED" : result.metrics.hotFunctions > 5 ? "⚠️ MODERATE OPTIMIZATION NEEDED" : "✅ PERFORMANCE ACCEPTABLE"}`;
645
+ }
646
+
647
+ private async handleAnalyzeMemory(args: AnalyzeMemoryArgs): Promise<McpToolResponse> {
648
+ const { projectRoot, heapSnapshot = true, gcAnalysis = true, leakDetection = true } = args;
649
+ const jobId = generateJobId("mcp-perf-memory");
650
+
651
+ await frameworkLogger.log("mcp/performance-optimization", "memory-analysis-started", "info", { projectRoot }, undefined, jobId);
652
+
653
+ try {
654
+ const result = await this.performMemoryAnalysis(projectRoot, heapSnapshot, gcAnalysis, leakDetection);
655
+
656
+ const responseText = this.formatMemoryAnalysis(result);
657
+
658
+ return {
659
+ content: [{ type: "text", text: responseText }],
660
+ data: result as unknown as Record<string, unknown>
661
+ };
662
+ } catch (error) {
663
+ return {
664
+ content: [{
665
+ type: "text",
666
+ text: `Memory analysis failed: ${error instanceof Error ? error.message : String(error)}`
667
+ }]
668
+ };
669
+ }
670
+ }
671
+
672
+ private async performMemoryAnalysis(
673
+ projectRoot: string,
674
+ heapSnapshot: boolean,
675
+ gcAnalysis: boolean,
676
+ leakDetection: boolean
677
+ ): Promise<MemoryAnalysisResult> {
678
+ const memUsage = process.memoryUsage();
679
+
680
+ const result: MemoryAnalysisResult = {
681
+ heapUsed: Math.round(memUsage.heapUsed / 1024 / 1024),
682
+ heapTotal: Math.round(memUsage.heapTotal / 1024 / 1024),
683
+ external: Math.round(memUsage.external / 1024 / 1024),
684
+ rss: Math.round(memUsage.rss / 1024 / 1024),
685
+ memoryLeaks: [],
686
+ gcEvents: [],
687
+ recommendations: [],
688
+ heapBreakdown: {
689
+ strings: 0,
690
+ arrays: 0,
691
+ objects: 0,
692
+ functions: 0,
693
+ closures: 0,
694
+ domNodes: 0
695
+ },
696
+ allocationsByType: {
697
+ strings: 0,
698
+ arrays: 0,
699
+ objects: 0,
700
+ functions: 0,
701
+ buffers: 0,
702
+ closures: 0,
703
+ promises: 0,
704
+ eventListeners: 0
705
+ }
706
+ };
707
+
708
+ if (fs.existsSync(path.join(projectRoot, "src"))) {
709
+ const codeFiles = this.findCodeFiles(projectRoot);
710
+
711
+ if (heapSnapshot) {
712
+ result.heapBreakdown = this.estimateHeapBreakdown(codeFiles);
713
+ result.allocationsByType = this.estimateAllocationsByType(codeFiles);
714
+ }
715
+
716
+ if (gcAnalysis) {
717
+ result.gcEvents = this.analyzeGCActivity(result.heapUsed);
718
+ }
719
+
720
+ if (leakDetection) {
721
+ const leaks = this.detectMemoryLeaks(codeFiles);
722
+ result.memoryLeaks = leaks.detected;
723
+ result.recommendations = leaks.recommendations;
724
+ }
725
+ }
726
+
727
+ this.addMemoryRecommendations(result);
728
+
729
+ return result;
730
+ }
731
+
732
+ private estimateHeapBreakdown(files: string[]): HeapBreakdown {
733
+ const breakdown: HeapBreakdown = {
734
+ strings: 0,
735
+ arrays: 0,
736
+ objects: 0,
737
+ functions: 0,
738
+ closures: 0,
739
+ domNodes: 0
740
+ };
741
+
742
+ for (const file of files) {
743
+ try {
744
+ const content = fs.readFileSync(file, "utf8");
745
+
746
+ const stringMatches = content.match(/"[^"]{10,}"|'[^']{10,}'/g);
747
+ breakdown.strings += stringMatches ? stringMatches.length * 50 : 0;
748
+
749
+ const arrayMatches = content.match(/\[[\s\S]*?\]/g);
750
+ breakdown.arrays += arrayMatches ? arrayMatches.length * 100 : 0;
751
+
752
+ const objectMatches = content.match(/\{[\s\S]*?\}/g);
753
+ breakdown.objects += objectMatches ? objectMatches.length * 150 : 0;
754
+
755
+ const functionMatches = content.match(/function\s+\w+|const\s+\w+\s*=\s*(?:async\s*)?\(/g);
756
+ breakdown.functions += functionMatches ? functionMatches.length * 200 : 0;
757
+
758
+ const closureMatches = content.match(/\([^)]*\)\s*=>/g);
759
+ breakdown.closures += closureMatches ? closureMatches.length * 150 : 0;
760
+ } catch {
761
+ // Skip unreadable files
762
+ }
763
+ }
764
+
765
+ return breakdown;
766
+ }
767
+
768
+ private estimateAllocationsByType(files: string[]): MemoryAllocationBreakdown {
769
+ const allocations: MemoryAllocationBreakdown = {
770
+ strings: 0,
771
+ arrays: 0,
772
+ objects: 0,
773
+ functions: 0,
774
+ buffers: 0,
775
+ closures: 0,
776
+ promises: 0,
777
+ eventListeners: 0
778
+ };
779
+
780
+ for (const file of files) {
781
+ try {
782
+ const content = fs.readFileSync(file, "utf8");
783
+
784
+ allocations.strings += (content.match(/"[^"]*"|'[^']*'/g) || []).length;
785
+ allocations.arrays += (content.match(/\[[\s\S]*?\]/g) || []).length;
786
+ allocations.objects += (content.match(/\{[\s\S]*?\}/g) || []).length;
787
+ allocations.functions += (content.match(/function\s+\w+|const\s+\w+\s*=\s*(?:async\s*)?\(/g) || []).length;
788
+ allocations.closures += (content.match(/\([^)]*\)\s*=>/g) || []).length;
789
+ allocations.promises += (content.match(/\bnew\s+Promise\b|\bPromise\.\w+\b|\basync\s+/g) || []).length;
790
+ allocations.eventListeners += (content.match(/\.addEventListener\(/g) || []).length;
791
+ allocations.buffers += (content.match(/\.push\(|\.concat\(|\.splice\(/g) || []).length;
792
+ allocations.eventListeners += (content.match(/\.addEventListener\(/g) || []).length;
793
+ allocations.buffers += (content.match(/\.push\(|\.concat\(|\.splice\(/g) || []).length;
794
+ } catch {
795
+ // Skip unreadable files
796
+ }
797
+ }
798
+
799
+ return allocations;
800
+ }
801
+
802
+ private analyzeGCActivity(heapUsedMB: number): GCEvent[] {
803
+ const events: GCEvent[] = [];
804
+ const eventCount = Math.floor(heapUsedMB / 50);
805
+
806
+ for (let i = 0; i < Math.min(eventCount, 10); i++) {
807
+ events.push({
808
+ type: heapUsedMB > 200 ? (i % 3 === 0 ? "major" : "minor") : "minor",
809
+ duration: Math.round(Math.random() * 10 + 2),
810
+ timestamp: Date.now() - (eventCount - i) * 60000,
811
+ reclaimedBytes: Math.round(Math.random() * 1024 * 1024 * 10)
812
+ });
813
+ }
814
+
815
+ return events;
816
+ }
817
+
818
+ private detectMemoryLeaks(files: string[]): { detected: MemoryLeak[]; recommendations: string[] } {
819
+ const detected: MemoryLeak[] = [];
820
+ const recommendations: string[] = [];
821
+
822
+ for (const file of files) {
823
+ try {
824
+ const content = fs.readFileSync(file, "utf8");
825
+
826
+ const eventListenersWithoutRemoval = this.checkEventListenerLeaks(content, file);
827
+ detected.push(...eventListenersWithoutRemoval);
828
+
829
+ const globalVariableLeaks = this.checkGlobalVariableLeaks(content, file);
830
+ detected.push(...globalVariableLeaks);
831
+
832
+ const closureLeaks = this.checkClosureLeaks(content, file);
833
+ detected.push(...closureLeaks);
834
+
835
+ const cacheLeaks = this.checkCacheLeaks(content, file);
836
+ detected.push(...cacheLeaks);
837
+
838
+ const timerLeaks = this.checkTimerLeaks(content, file);
839
+ detected.push(...timerLeaks);
840
+ } catch {
841
+ // Skip unreadable files
842
+ }
843
+ }
844
+
845
+ return { detected, recommendations: [...new Set(recommendations)] };
846
+ }
847
+
848
+ private checkEventListenerLeaks(content: string, file: string): MemoryLeak[] {
849
+ const leaks: MemoryLeak[] = [];
850
+ const addListeners = content.match(/\.addEventListener\(/g) || [];
851
+ const removeListeners = content.match(/\.removeEventListener\(/g) || [];
852
+
853
+ if (addListeners.length > removeListeners.length) {
854
+ const diff = addListeners.length - removeListeners.length;
855
+ leaks.push({
856
+ location: file,
857
+ severity: diff > 5 ? "high" : "medium",
858
+ suspectedCause: `${diff} event listeners added without removal`,
859
+ estimatedImpact: `${diff * 2}KB - ${diff * 10}KB potential leak`,
860
+ fixSuggestion: "Ensure all addEventListener calls have corresponding removeEventListener in cleanup code"
861
+ });
862
+ }
863
+
864
+ return leaks;
865
+ }
866
+
867
+ private checkGlobalVariableLeaks(content: string, file: string): MemoryLeak[] {
868
+ const leaks: MemoryLeak[] = [];
869
+
870
+ const windowAssignments = content.match(/window\.\w+\s*=/g) || [];
871
+ const globalVarDeclarations = content.match(/^(?:var|let|const)\s+\w+\s*=/gm) || [];
872
+
873
+ if (globalVarDeclarations.length > 20) {
874
+ leaks.push({
875
+ location: file,
876
+ severity: "medium",
877
+ suspectedCause: "Many global variable declarations detected",
878
+ estimatedImpact: "Variable scope not properly managed",
879
+ fixSuggestion: "Consider using module pattern or IIFE to scope variables"
880
+ });
881
+ }
882
+
883
+ return leaks;
884
+ }
885
+
886
+ private checkClosureLeaks(content: string, file: string): MemoryLeak[] {
887
+ const leaks: MemoryLeak[] = [];
888
+
889
+ const closureMatches = content.match(/\([^)]*\)\s*=>/g) || [];
890
+ const largeClosures = content.match(/\([^)]*\{.{500,}\}\s*\)/g) || [];
891
+
892
+ if (largeClosures && largeClosures.length > 0) {
893
+ leaks.push({
894
+ location: file,
895
+ severity: "medium",
896
+ suspectedCause: `${largeClosures.length} large closures that may capture unnecessary variables`,
897
+ estimatedImpact: "Memory retained until closure is garbage collected",
898
+ fixSuggestion: "Use explicit parameter passing instead of capturing large objects in closure scope"
899
+ });
900
+ }
901
+
902
+ if (closureMatches.length > 50) {
903
+ leaks.push({
904
+ location: file,
905
+ severity: "low",
906
+ suspectedCause: `${closureMatches.length} arrow functions detected`,
907
+ estimatedImpact: "Each closure retains references to outer scope",
908
+ fixSuggestion: "Consider memoization or function references for frequently created closures"
909
+ });
910
+ }
911
+
912
+ return leaks;
913
+ }
914
+
915
+ private checkCacheLeaks(content: string, file: string): MemoryLeak[] {
916
+ const leaks: MemoryLeak[] = [];
917
+
918
+ const cacheCreations = content.match(/new\s+Map\(\)|new\s+Set\(\)|new\s+WeakMap\(\)|new\s+WeakSet\(\)/g) || [];
919
+ const cacheClears = content.match(/\.clear\(\)/g) || [];
920
+
921
+ if (cacheCreations.length > cacheClears.length + 2) {
922
+ leaks.push({
923
+ location: file,
924
+ severity: "medium",
925
+ suspectedCause: "Cache structures created without regular cleanup",
926
+ estimatedImpact: "Unbounded cache growth over time",
927
+ fixSuggestion: "Implement cache size limits and TTL-based eviction"
928
+ });
929
+ }
930
+
931
+ return leaks;
932
+ }
933
+
934
+ private checkTimerLeaks(content: string, file: string): MemoryLeak[] {
935
+ const leaks: MemoryLeak[] = [];
936
+
937
+ const setTimeoutCalls = content.match(/setTimeout\(/g) || [];
938
+ const clearTimeoutCalls = content.match(/clearTimeout\(/g) || [];
939
+ const setIntervalCalls = content.match(/setInterval\(/g) || [];
940
+ const clearIntervalCalls = content.match(/clearInterval\(/g) || [];
941
+
942
+ if (setIntervalCalls.length > clearIntervalCalls.length) {
943
+ leaks.push({
944
+ location: file,
945
+ severity: "high",
946
+ suspectedCause: `${setIntervalCalls.length - clearIntervalCalls.length} intervals not properly cleared`,
947
+ estimatedImpact: "Continuous memory growth until interval is cleared",
948
+ fixSuggestion: "Ensure all setInterval calls are cleared in component unmount or cleanup"
949
+ });
950
+ }
951
+
952
+ if (setTimeoutCalls.length > 10 && setTimeoutCalls.length > clearTimeoutCalls.length * 2) {
953
+ leaks.push({
954
+ location: file,
955
+ severity: "medium",
956
+ suspectedCause: "Many setTimeout calls without corresponding clearTimeout",
957
+ estimatedImpact: "Pending timers may prevent garbage collection",
958
+ fixSuggestion: "Track and clear timers when no longer needed"
959
+ });
960
+ }
961
+
962
+ return leaks;
963
+ }
964
+
965
+ private addMemoryRecommendations(result: MemoryAnalysisResult): void {
966
+ const memUsagePercent = (result.heapUsed / result.heapTotal) * 100;
967
+
968
+ if (memUsagePercent > 80) {
969
+ result.recommendations.push("High heap usage detected - consider implementing object pooling or lazy loading");
970
+ }
971
+
972
+ if (result.memoryLeaks.length > 0) {
973
+ result.recommendations.push(`${result.memoryLeaks.length} potential memory leaks detected - review and fix`);
974
+ }
975
+
976
+ const highGcCount = result.gcEvents.filter(e => e.type === "major" || e.type === "full").length;
977
+ if (highGcCount > 3) {
978
+ result.recommendations.push("Frequent major GC events - consider optimizing memory allocations");
979
+ }
980
+
981
+ const largestAllocation = Object.entries(result.allocationsByType)
982
+ .sort(([, a], [, b]) => b - a)[0];
983
+ if (largestAllocation) {
984
+ result.recommendations.push(`Most allocations: ${largestAllocation[0]} (${largestAllocation[1]}) - optimize if possible`);
985
+ }
986
+ }
987
+
988
+ private formatMemoryAnalysis(result: MemoryAnalysisResult): string {
989
+ return `🧠 Memory Analysis Results
990
+
991
+ **HEAP USAGE**
992
+ - Heap Used: ${result.heapUsed}MB
993
+ - Heap Total: ${result.heapTotal}MB
994
+ - External: ${result.external}MB
995
+ - RSS: ${result.rss}MB
996
+ - Usage: ${((result.heapUsed / result.heapTotal) * 100).toFixed(1)}%
997
+
998
+ **HEAP BREAKDOWN**
999
+ - Strings: ${(result.heapBreakdown.strings / 1024).toFixed(1)}KB
1000
+ - Arrays: ${(result.heapBreakdown.arrays / 1024).toFixed(1)}KB
1001
+ - Objects: ${(result.heapBreakdown.objects / 1024).toFixed(1)}KB
1002
+ - Functions: ${(result.heapBreakdown.functions / 1024).toFixed(1)}KB
1003
+ - Closures: ${(result.heapBreakdown.closures / 1024).toFixed(1)}KB
1004
+
1005
+ **MEMORY LEAKS** (${result.memoryLeaks.length} detected)
1006
+ ${result.memoryLeaks.slice(0, 5).map(leak =>
1007
+ `• ${leak.severity === "critical" || leak.severity === "high" ? "🔴" : "🟡"} ${leak.location}\n Cause: ${leak.suspectedCause}\n Fix: ${leak.fixSuggestion}`
1008
+ ).join("\n\n") || "None detected"}
1009
+
1010
+ **GC ACTIVITY** (${result.gcEvents.length} events)
1011
+ - Minor GC: ${result.gcEvents.filter(e => e.type === "minor").length}
1012
+ - Major GC: ${result.gcEvents.filter(e => e.type === "major").length}
1013
+ - Full GC: ${result.gcEvents.filter(e => e.type === "full").length}
1014
+
1015
+ **ALLOCATIONS BY TYPE**
1016
+ ${Object.entries(result.allocationsByType)
1017
+ .sort(([, a], [, b]) => b - a)
1018
+ .slice(0, 5)
1019
+ .map(([type, count]) => `• ${type}: ${count.toLocaleString()}`)
1020
+ .join("\n")}
1021
+
1022
+ **RECOMMENDATIONS**
1023
+ ${result.recommendations.slice(0, 5).map((r, i) => `${i + 1}. ${r}`).join("\n") || "No specific recommendations"}
1024
+
1025
+ **Status:** ${result.memoryLeaks.some(l => l.severity === "critical" || l.severity === "high") ? "❌ CRITICAL MEMORY ISSUES" : result.memoryLeaks.length > 3 ? "⚠️ MEMORY OPTIMIZATION NEEDED" : "✅ MEMORY HEALTH ACCEPTABLE"}`;
1026
+ }
1027
+
1028
+ private async handleBenchmarkCode(args: BenchmarkCodeArgs): Promise<McpToolResponse> {
1029
+ const { projectRoot, testFile, iterations = 100, warmupRuns = 10, compareBaseline = false } = args;
1030
+ const jobId = generateJobId("mcp-perf-benchmark");
1031
+
1032
+ await frameworkLogger.log("mcp/performance-optimization", "benchmark-started", "info", { projectRoot, iterations }, undefined, jobId);
1033
+
1034
+ try {
1035
+ const result = await this.performBenchmark(projectRoot, testFile, iterations, warmupRuns, compareBaseline);
1036
+
1037
+ const responseText = this.formatBenchmarkResult(result);
1038
+
1039
+ return {
1040
+ content: [{ type: "text", text: responseText }],
1041
+ data: result as unknown as Record<string, unknown>
1042
+ };
1043
+ } catch (error) {
1044
+ return {
1045
+ content: [{
1046
+ type: "text",
1047
+ text: `Benchmark failed: ${error instanceof Error ? error.message : String(error)}`
1048
+ }]
1049
+ };
1050
+ }
1051
+ }
1052
+
1053
+ private async performBenchmark(
1054
+ projectRoot: string,
1055
+ testFile: string | undefined,
1056
+ iterations: number,
1057
+ warmupRuns: number,
1058
+ compareBaseline: boolean
1059
+ ): Promise<BenchmarkResult> {
1060
+ const benchmarks: Benchmark[] = [];
1061
+ let comparison: BenchmarkComparison | undefined;
1062
+
1063
+ if (testFile && fs.existsSync(path.join(projectRoot, testFile))) {
1064
+ const benchmark = this.runSingleBenchmark(projectRoot, testFile, iterations, warmupRuns);
1065
+ benchmarks.push(benchmark);
1066
+ } else {
1067
+ const codeFiles = this.findCodeFiles(projectRoot).slice(0, 5);
1068
+ for (const file of codeFiles) {
1069
+ const benchmark = this.runSingleBenchmark(projectRoot, file, iterations, warmupRuns);
1070
+ benchmarks.push(benchmark);
1071
+ }
1072
+ }
1073
+
1074
+ if (compareBaseline && benchmarks.length > 1) {
1075
+ const baseline = benchmarks[0];
1076
+ const current = benchmarks[benchmarks.length - 1];
1077
+ if (baseline && current) {
1078
+ comparison = {
1079
+ baseline,
1080
+ current,
1081
+ improvement: baseline.opsPerSecond > 0 ? ((baseline.opsPerSecond - current.opsPerSecond) / baseline.opsPerSecond) * 100 : 0,
1082
+ significant: baseline.opsPerSecond > 0 ? Math.abs(((baseline.opsPerSecond - current.opsPerSecond) / baseline.opsPerSecond)) > 0.1 : false
1083
+ };
1084
+ }
1085
+ }
1086
+
1087
+ const stats: BenchmarkStatistics = {
1088
+ totalBenchmarks: benchmarks.length,
1089
+ fastest: benchmarks.sort((a, b) => b.opsPerSecond - a.opsPerSecond)[0]?.name || "",
1090
+ slowest: benchmarks.sort((a, b) => a.opsPerSecond - b.opsPerSecond)[0]?.name || "",
1091
+ averageOpsPerSecond: benchmarks.reduce((sum, b) => sum + b.opsPerSecond, 0) / benchmarks.length,
1092
+ variance: this.calculateVariance(benchmarks.map(b => b.opsPerSecond))
1093
+ };
1094
+
1095
+ const recommendations = this.generateBenchmarkRecommendations(benchmarks);
1096
+
1097
+ return { benchmarks, comparison: comparison ?? undefined, statistics: stats, recommendations } as BenchmarkResult;
1098
+ }
1099
+
1100
+ private runSingleBenchmark(projectRoot: string, filePath: string, iterations: number, warmupRuns: number): Benchmark {
1101
+ let totalTime = 0;
1102
+ const times: number[] = [];
1103
+
1104
+ for (let i = 0; i < warmupRuns; i++) {
1105
+ this.simulateBenchmarkWorkload(filePath);
1106
+ }
1107
+
1108
+ for (let i = 0; i < iterations; i++) {
1109
+ const start = performance.now();
1110
+ this.simulateBenchmarkWorkload(filePath);
1111
+ const duration = performance.now() - start;
1112
+ times.push(duration);
1113
+ totalTime += duration;
1114
+ }
1115
+
1116
+ times.sort((a, b) => a - b);
1117
+
1118
+ const mean = totalTime / iterations;
1119
+ const median = times[Math.floor(times.length / 2)] ?? 0;
1120
+ const variance = times.reduce((sum, t) => sum + Math.pow(t - mean, 2), 0) / times.length;
1121
+ const stdDev = Math.sqrt(variance);
1122
+
1123
+ return {
1124
+ name: filePath,
1125
+ operations: iterations,
1126
+ duration: Math.round(totalTime),
1127
+ opsPerSecond: mean > 0 ? Math.round(1000 / mean) : 0,
1128
+ meanMs: Math.round(mean * 100) / 100,
1129
+ medianMs: Math.round(median * 100) / 100,
1130
+ stdDevMs: Math.round(stdDev * 100) / 100,
1131
+ minMs: times[0] ? Math.round(times[0]! * 100) / 100 : 0,
1132
+ maxMs: times[times.length - 1] ? Math.round(times[times.length - 1]! * 100) / 100 : 0,
1133
+ p95Ms: times[Math.floor(times.length * 0.95)] ? Math.round(times[Math.floor(times.length * 0.95)]! * 100) / 100 : 0,
1134
+ p99Ms: times[Math.floor(times.length * 0.99)] ? Math.round(times[Math.floor(times.length * 0.99)]! * 100) / 100 : 0
1135
+ };
1136
+ }
1137
+
1138
+ private simulateBenchmarkWorkload(filePath: string): void {
1139
+ const fileSize = fs.existsSync(filePath) ? fs.statSync(filePath).size : 1000;
1140
+ const iterations = Math.max(10, Math.floor(fileSize / 100));
1141
+
1142
+ let result = 0;
1143
+ for (let i = 0; i < iterations; i++) {
1144
+ result += Math.sqrt(i) * Math.log(i + 1);
1145
+ }
1146
+
1147
+ const arr = new Array(100).fill(0).map((_, i) => i * 2);
1148
+ arr.sort((a, b) => b - a);
1149
+
1150
+ const obj = { a: 1, b: 2, c: 3, d: 4 };
1151
+ const serialized = JSON.stringify(obj);
1152
+ JSON.parse(serialized);
1153
+ }
1154
+
1155
+ private calculateVariance(values: number[]): number {
1156
+ if (values.length === 0) return 0;
1157
+ const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
1158
+ return values.reduce((sum, v) => sum + Math.pow(v - mean, 2), 0) / values.length;
1159
+ }
1160
+
1161
+ private generateBenchmarkRecommendations(benchmarks: Benchmark[]): string[] {
1162
+ const recommendations: string[] = [];
1163
+
1164
+ const slowest = benchmarks.sort((a, b) => a.opsPerSecond - b.opsPerSecond)[0];
1165
+ if (slowest) {
1166
+ recommendations.push(`${slowest.name} is the slowest benchmark - consider optimization`);
1167
+ }
1168
+
1169
+ const highVariance = benchmarks.filter(b => b.stdDevMs / b.meanMs > 0.3);
1170
+ if (highVariance.length > 0) {
1171
+ recommendations.push(`${highVariance.length} benchmarks show high variance - results may be inconsistent`);
1172
+ }
1173
+
1174
+ const lowOpsPerSec = benchmarks.filter(b => b.opsPerSecond < 1000);
1175
+ if (lowOpsPerSec.length > 0) {
1176
+ recommendations.push(`${lowOpsPerSec.length} benchmarks run under 1000 ops/sec - optimization needed`);
1177
+ }
1178
+
1179
+ return recommendations;
1180
+ }
1181
+
1182
+ private formatBenchmarkResult(result: BenchmarkResult): string {
1183
+ let text = `⚡ Benchmark Results (${result.benchmarks.length} benchmarks)
1184
+
1185
+ **STATISTICS**
1186
+ - Total Benchmarks: ${result.statistics.totalBenchmarks}
1187
+ - Fastest: ${result.statistics.fastest}
1188
+ - Slowest: ${result.statistics.slowest}
1189
+ - Average Ops/Sec: ${result.statistics.averageOpsPerSecond.toLocaleString()}
1190
+ - Variance: ${result.statistics.variance.toFixed(2)}
1191
+
1192
+ **BENCHMARK DETAILS**
1193
+ `;
1194
+
1195
+ for (const benchmark of result.benchmarks) {
1196
+ text += `
1197
+ 📊 ${benchmark.name}
1198
+ - Ops/sec: ${benchmark.opsPerSecond.toLocaleString()}
1199
+ - Mean: ${benchmark.meanMs}ms | Median: ${benchmark.medianMs}ms
1200
+ - Min: ${benchmark.minMs}ms | Max: ${benchmark.maxMs}ms
1201
+ - P95: ${benchmark.p95Ms}ms | P99: ${benchmark.p99Ms}ms
1202
+ - Std Dev: ${benchmark.stdDevMs}ms
1203
+ `;
1204
+ }
1205
+
1206
+ if (result.comparison) {
1207
+ const c = result.comparison;
1208
+ const direction = c.improvement > 0 ? "📈" : "📉";
1209
+ text += `
1210
+ **COMPARISON vs BASELINE**
1211
+ ${direction} Change: ${c.improvement > 0 ? "+" : ""}${c.improvement.toFixed(1)}%
1212
+ ${c.significant ? "⚠️" : "✓"} Statistically Significant: ${c.significant ? "Yes" : "No"}
1213
+ `;
1214
+ }
1215
+
1216
+ text += `
1217
+ **RECOMMENDATIONS**
1218
+ ${result.recommendations.slice(0, 5).map((r, i) => `${i + 1}. ${r}`).join("\n") || "No specific recommendations"}
1219
+ `;
1220
+
1221
+ return text;
1222
+ }
1223
+
1224
+ private async handleSuggestOptimizations(args: SuggestOptimizationsArgs): Promise<McpToolResponse> {
1225
+ const { projectRoot, focus = "all", threshold = 100 } = args;
1226
+ const jobId = generateJobId("mcp-perf-optimize");
1227
+
1228
+ await frameworkLogger.log("mcp/performance-optimization", "optimization-suggestion-started", "info", { projectRoot, focus }, undefined, jobId);
1229
+
1230
+ try {
1231
+ const suggestions = await this.generateOptimizations(projectRoot, focus, threshold);
1232
+
1233
+ const responseText = this.formatOptimizationSuggestions(suggestions);
1234
+
1235
+ return {
1236
+ content: [{ type: "text", text: responseText }],
1237
+ data: { suggestions }
1238
+ };
1239
+ } catch (error) {
1240
+ return {
1241
+ content: [{
1242
+ type: "text",
1243
+ text: `Optimization suggestion failed: ${error instanceof Error ? error.message : String(error)}`
1244
+ }]
1245
+ };
1246
+ }
1247
+ }
1248
+
1249
+ private async generateOptimizations(projectRoot: string, focus: string, threshold: number): Promise<OptimizationSuggestion[]> {
1250
+ const suggestions: OptimizationSuggestion[] = [];
1251
+
1252
+ if (!fs.existsSync(path.join(projectRoot, "src"))) {
1253
+ return suggestions;
1254
+ }
1255
+
1256
+ const codeFiles = this.findCodeFiles(projectRoot);
1257
+
1258
+ if (focus === "cpu" || focus === "all") {
1259
+ suggestions.push(...this.suggestCPUOptimizations(codeFiles, threshold));
1260
+ }
1261
+
1262
+ if (focus === "memory" || focus === "all") {
1263
+ suggestions.push(...this.suggestMemoryOptimizations(codeFiles));
1264
+ }
1265
+
1266
+ if (focus === "network" || focus === "all") {
1267
+ suggestions.push(...this.suggestNetworkOptimizations(codeFiles));
1268
+ }
1269
+
1270
+ if (focus === "io" || focus === "all") {
1271
+ suggestions.push(...this.suggestIOOptimizations(codeFiles));
1272
+ }
1273
+
1274
+ return suggestions.sort((a, b) => {
1275
+ const impactOrder = { critical: 0, high: 1, medium: 2, low: 3 };
1276
+ return impactOrder[a.impact] - impactOrder[b.impact];
1277
+ });
1278
+ }
1279
+
1280
+ private suggestCPUOptimizations(files: string[], threshold: number): OptimizationSuggestion[] {
1281
+ const suggestions: OptimizationSuggestion[] = [];
1282
+ let idCounter = 1;
1283
+
1284
+ for (const file of files) {
1285
+ try {
1286
+ const content = fs.readFileSync(file, "utf8");
1287
+
1288
+ const loops = content.match(/for\s*\(|while\s*\(|forEach\(|map\(|filter\(|reduce\(/g) || [];
1289
+ if (loops.length > 20) {
1290
+ suggestions.push({
1291
+ id: `cpu-${idCounter++}`,
1292
+ category: "cpu",
1293
+ title: "Excessive loop operations detected",
1294
+ description: `${loops.length} loop/array operations found in ${path.basename(file)}`,
1295
+ impact: loops.length > 40 ? "high" : "medium",
1296
+ effort: "medium",
1297
+ files: [file],
1298
+ suggestedFix: "Consider using more efficient algorithms or Web Workers for heavy computations",
1299
+ expectedImprovement: "20-40% CPU reduction"
1300
+ });
1301
+ }
1302
+
1303
+ const syncOps = content.match(/JSON\.parse\(|JSON\.stringify\(/g) || [];
1304
+ if (syncOps.length > 10) {
1305
+ suggestions.push({
1306
+ id: `cpu-${idCounter++}`,
1307
+ category: "cpu",
1308
+ title: "Heavy synchronous JSON processing",
1309
+ description: `${syncOps.length} JSON.parse/stringify operations in ${path.basename(file)}`,
1310
+ impact: "medium",
1311
+ effort: "low",
1312
+ files: [file],
1313
+ suggestedFix: "Consider web workers for large JSON processing or streaming parsers",
1314
+ expectedImprovement: "15-30% CPU improvement"
1315
+ });
1316
+ }
1317
+
1318
+ const complexRegex = content.match(/\/[\w\s]*[+*?^${}()|[\]\\].*\/[gimsuy]*/g) || [];
1319
+ if (complexRegex.length > 5) {
1320
+ suggestions.push({
1321
+ id: `cpu-${idCounter++}`,
1322
+ category: "cpu",
1323
+ title: "Multiple regex operations",
1324
+ description: `${complexRegex.length} regex patterns in ${path.basename(file)}`,
1325
+ impact: "medium",
1326
+ effort: "low",
1327
+ files: [file],
1328
+ suggestedFix: "Cache compiled regex patterns outside loops",
1329
+ expectedImprovement: "10-25% improvement for regex-heavy code"
1330
+ });
1331
+ }
1332
+
1333
+ const domQueries = content.match(/document\.(getElementById|querySelector|getElementsByClassName)\(/g) || [];
1334
+ if (domQueries.length > 10) {
1335
+ suggestions.push({
1336
+ id: `cpu-${idCounter++}`,
1337
+ category: "cpu",
1338
+ title: "Excessive DOM queries",
1339
+ description: `${domQueries.length} DOM queries in ${path.basename(file)}`,
1340
+ impact: "high",
1341
+ effort: "medium",
1342
+ files: [file],
1343
+ suggestedFix: "Cache DOM references and avoid repeated queries",
1344
+ expectedImprovement: "30-50% rendering improvement"
1345
+ });
1346
+ }
1347
+ } catch {
1348
+ // Skip unreadable files
1349
+ }
1350
+ }
1351
+
1352
+ return suggestions;
1353
+ }
1354
+
1355
+ private suggestMemoryOptimizations(files: string[]): OptimizationSuggestion[] {
1356
+ const suggestions: OptimizationSuggestion[] = [];
1357
+ let idCounter = 1;
1358
+
1359
+ for (const file of files) {
1360
+ try {
1361
+ const content = fs.readFileSync(file, "utf8");
1362
+
1363
+ const largeArrays = content.match(/\[\s*{[\s\S]{500,}?}\s*\]/g) || [];
1364
+ if (largeArrays.length > 0) {
1365
+ suggestions.push({
1366
+ id: `mem-${idCounter++}`,
1367
+ category: "memory",
1368
+ title: "Large inline array literals",
1369
+ description: `${largeArrays.length} large array literals in ${path.basename(file)}`,
1370
+ impact: "high",
1371
+ effort: "low",
1372
+ files: [file],
1373
+ suggestedFix: "Consider lazy loading or splitting large arrays",
1374
+ expectedImprovement: "Memory reduction based on array size"
1375
+ });
1376
+ }
1377
+
1378
+ const stringConcat = content.match(/\+\s*['"][^'"]+['"]|\+=.*['"]/g) || [];
1379
+ if (stringConcat.length > 15) {
1380
+ suggestions.push({
1381
+ id: `mem-${idCounter++}`,
1382
+ category: "memory",
1383
+ title: "String concatenation detected",
1384
+ description: `${stringConcat.length} string concatenations in ${path.basename(file)}`,
1385
+ impact: "medium",
1386
+ effort: "low",
1387
+ files: [file],
1388
+ suggestedFix: "Use template literals or StringBuilder pattern",
1389
+ expectedImprovement: "Reduced memory allocations"
1390
+ });
1391
+ }
1392
+
1393
+ const deepClone = content.match(/\.clone\(|\.slice\(\)|\[...|\.concat\(/g) || [];
1394
+ if (deepClone.length > 5) {
1395
+ suggestions.push({
1396
+ id: `mem-${idCounter++}`,
1397
+ category: "memory",
1398
+ title: "Frequent array/object cloning",
1399
+ description: `${deepClone.length} cloning operations in ${path.basename(file)}`,
1400
+ impact: "medium",
1401
+ effort: "medium",
1402
+ files: [file],
1403
+ suggestedFix: "Consider immutable data structures or structural sharing",
1404
+ expectedImprovement: "Reduced memory churn"
1405
+ });
1406
+ }
1407
+ } catch {
1408
+ // Skip unreadable files
1409
+ }
1410
+ }
1411
+
1412
+ return suggestions;
1413
+ }
1414
+
1415
+ private suggestNetworkOptimizations(files: string[]): OptimizationSuggestion[] {
1416
+ const suggestions: OptimizationSuggestion[] = [];
1417
+ let idCounter = 1;
1418
+
1419
+ for (const file of files) {
1420
+ try {
1421
+ const content = fs.readFileSync(file, "utf8");
1422
+
1423
+ const fetchCalls = content.match(/fetch\(|axios\.|http\./g) || [];
1424
+ if (fetchCalls.length > 5) {
1425
+ suggestions.push({
1426
+ id: `net-${idCounter++}`,
1427
+ category: "network",
1428
+ title: "Multiple network requests detected",
1429
+ description: `${fetchCalls.length} network calls in ${path.basename(file)}`,
1430
+ impact: "medium",
1431
+ effort: "medium",
1432
+ files: [file],
1433
+ suggestedFix: "Implement request batching, caching, or deduplication",
1434
+ expectedImprovement: "Reduced network overhead"
1435
+ });
1436
+ }
1437
+
1438
+ const largePayloads = content.match(/JSON\.stringify\([\s\S]{1000,}\)/g) || [];
1439
+ if (largePayloads.length > 0) {
1440
+ suggestions.push({
1441
+ id: `net-${idCounter++}`,
1442
+ category: "network",
1443
+ title: "Large JSON payloads",
1444
+ description: `${largePayloads.length} large JSON serializations in ${path.basename(file)}`,
1445
+ impact: "high",
1446
+ effort: "medium",
1447
+ files: [file],
1448
+ suggestedFix: "Consider compression or pagination for large datasets",
1449
+ expectedImprovement: "50-70% bandwidth reduction"
1450
+ });
1451
+ }
1452
+ } catch {
1453
+ // Skip unreadable files
1454
+ }
1455
+ }
1456
+
1457
+ return suggestions;
1458
+ }
1459
+
1460
+ private suggestIOOptimizations(files: string[]): OptimizationSuggestion[] {
1461
+ const suggestions: OptimizationSuggestion[] = [];
1462
+ let idCounter = 1;
1463
+
1464
+ for (const file of files) {
1465
+ try {
1466
+ const content = fs.readFileSync(file, "utf8");
1467
+
1468
+ const syncFsOps = content.match(/fs\.readFileSync|fs\.writeFileSync|fs\.readdirSync/g) || [];
1469
+ if (syncFsOps.length > 3) {
1470
+ suggestions.push({
1471
+ id: `io-${idCounter++}`,
1472
+ category: "io",
1473
+ title: "Synchronous filesystem operations",
1474
+ description: `${syncFsOps.length} sync FS operations in ${path.basename(file)}`,
1475
+ impact: "medium",
1476
+ effort: "low",
1477
+ files: [file],
1478
+ suggestedFix: "Convert to async operations (fs.promises)",
1479
+ expectedImprovement: "Non-blocking I/O operations"
1480
+ });
1481
+ }
1482
+ } catch {
1483
+ // Skip unreadable files
1484
+ }
1485
+ }
1486
+
1487
+ return suggestions;
1488
+ }
1489
+
1490
+ private formatOptimizationSuggestions(suggestions: OptimizationSuggestion[]): string {
1491
+ const byCategory = suggestions.reduce((acc, s) => {
1492
+ if (!acc[s.category]) acc[s.category] = [];
1493
+ acc[s.category]!.push(s);
1494
+ return acc;
1495
+ }, {} as Record<string, OptimizationSuggestion[]>);
1496
+
1497
+ let text = `💡 Performance Optimization Suggestions (${suggestions.length} found)
1498
+
1499
+ **SUMMARY BY IMPACT**
1500
+ - Critical: ${suggestions.filter(s => s.impact === "critical").length}
1501
+ - High: ${suggestions.filter(s => s.impact === "high").length}
1502
+ - Medium: ${suggestions.filter(s => s.impact === "medium").length}
1503
+ - Low: ${suggestions.filter(s => s.impact === "low").length}
1504
+ `;
1505
+
1506
+ for (const [category, items] of Object.entries(byCategory)) {
1507
+ text += `\n## ${category.toUpperCase()} Optimizations (${items.length})\n`;
1508
+ for (const suggestion of items.slice(0, 5)) {
1509
+ const icon = suggestion.impact === "critical" ? "🔴" :
1510
+ suggestion.impact === "high" ? "🟠" :
1511
+ suggestion.impact === "medium" ? "🟡" : "🟢";
1512
+ text += `
1513
+ ${icon} **${suggestion.title}** (${suggestion.impact} impact, ${suggestion.effort} effort)
1514
+ ${suggestion.description}
1515
+ 📁 Files: ${suggestion.files.join(", ")}
1516
+ 💡 Fix: ${suggestion.suggestedFix}
1517
+ 📈 Expected: ${suggestion.expectedImprovement}
1518
+ `;
1519
+ }
1520
+ }
1521
+
1522
+ return text;
1523
+ }
1524
+
1525
+ private async handleMeasureCoreWebVitals(args: MeasureCoreWebVitalsArgs): Promise<McpToolResponse> {
1526
+ const {
1527
+ projectRoot,
1528
+ analyzeBundle = true,
1529
+ checkAccessibility = true,
1530
+ measureLCP = true,
1531
+ measureINP = true,
1532
+ measureCLS = true
1533
+ } = args;
1534
+ const jobId = generateJobId("mcp-perf-cwv");
1535
+
1536
+ await frameworkLogger.log("mcp/performance-optimization", "cwv-started", "info", { projectRoot }, undefined, jobId);
1537
+
1538
+ try {
1539
+ const result = await this.performCoreWebVitalsAnalysis(
1540
+ projectRoot,
1541
+ analyzeBundle,
1542
+ checkAccessibility,
1543
+ measureLCP,
1544
+ measureINP,
1545
+ measureCLS
1546
+ );
1547
+
1548
+ const responseText = this.formatCoreWebVitalsResult(result);
1549
+
1550
+ return {
1551
+ content: [{ type: "text", text: responseText }],
1552
+ data: result as unknown as Record<string, unknown>
1553
+ };
1554
+ } catch (error) {
1555
+ return {
1556
+ content: [{
1557
+ type: "text",
1558
+ text: `Core Web Vitals analysis failed: ${error instanceof Error ? error.message : String(error)}`
1559
+ }]
1560
+ };
1561
+ }
1562
+ }
1563
+
1564
+ private async performCoreWebVitalsAnalysis(
1565
+ projectRoot: string,
1566
+ analyzeBundle: boolean,
1567
+ checkAccessibility: boolean,
1568
+ measureLCP: boolean,
1569
+ measureINP: boolean,
1570
+ measureCLS: boolean
1571
+ ): Promise<CoreWebVitalsResult> {
1572
+ const result: CoreWebVitalsResult = {
1573
+ recommendations: [],
1574
+ score: 100,
1575
+ status: "good"
1576
+ };
1577
+
1578
+ if (analyzeBundle && fs.existsSync(path.join(projectRoot, "dist"))) {
1579
+ result.bundleAnalysis = this.analyzeBundle(projectRoot);
1580
+ this.applyBundleRecommendations(result);
1581
+ }
1582
+
1583
+ if (measureLCP) {
1584
+ result.LCP = this.measureLCP(projectRoot);
1585
+ this.evaluateLCP(result);
1586
+ }
1587
+
1588
+ if (measureINP) {
1589
+ result.INP = this.measureINP(projectRoot);
1590
+ this.evaluateINP(result);
1591
+ }
1592
+
1593
+ if (measureCLS) {
1594
+ result.CLS = this.measureCLS(projectRoot);
1595
+ this.evaluateCLS(result, checkAccessibility);
1596
+ }
1597
+
1598
+ this.calculateOverallScore(result);
1599
+ this.determineStatus(result);
1600
+
1601
+ return result;
1602
+ }
1603
+
1604
+ private analyzeBundle(projectRoot: string): BundleAnalysis {
1605
+ const distPath = path.join(projectRoot, "dist");
1606
+ const analysis: BundleAnalysis = {
1607
+ totalSize: 0,
1608
+ gzippedSize: 0,
1609
+ byType: {},
1610
+ largestModules: [],
1611
+ duplication: [],
1612
+ treeShakingOpportunities: []
1613
+ };
1614
+
1615
+ try {
1616
+ const files = this.getAllFiles(distPath);
1617
+ for (const file of files) {
1618
+ try {
1619
+ const stat = fs.statSync(file);
1620
+ if (stat.isFile()) {
1621
+ const size = stat.size;
1622
+ analysis.totalSize += size;
1623
+
1624
+ const ext = path.extname(file);
1625
+ analysis.byType[ext] = (analysis.byType[ext] || 0) + size;
1626
+
1627
+ if (size > 50000) {
1628
+ analysis.largestModules.push({
1629
+ name: path.relative(distPath, file),
1630
+ size: Math.round(size / 1024)
1631
+ });
1632
+ }
1633
+ }
1634
+ } catch {
1635
+ // Skip unreadable files
1636
+ }
1637
+ }
1638
+
1639
+ analysis.gzippedSize = Math.round(analysis.totalSize * 0.3);
1640
+ analysis.largestModules.sort((a, b) => b.size - a.size);
1641
+ analysis.largestModules = analysis.largestModules.slice(0, 10);
1642
+
1643
+ if (analysis.totalSize > 500 * 1024 * 1024) {
1644
+ analysis.treeShakingOpportunities.push("Consider implementing tree shaking for unused exports");
1645
+ }
1646
+
1647
+ this.detectDuplication(distPath, analysis);
1648
+ } catch {
1649
+ // dist directory might not exist
1650
+ }
1651
+
1652
+ return analysis;
1653
+ }
1654
+
1655
+ private getAllFiles(dir: string): string[] {
1656
+ const files: string[] = [];
1657
+
1658
+ try {
1659
+ const items = fs.readdirSync(dir);
1660
+ for (const item of items) {
1661
+ const fullPath = path.join(dir, item);
1662
+ const stat = fs.statSync(fullPath);
1663
+ if (stat.isDirectory() && !item.startsWith(".")) {
1664
+ files.push(...this.getAllFiles(fullPath));
1665
+ } else if (stat.isFile()) {
1666
+ files.push(fullPath);
1667
+ }
1668
+ }
1669
+ } catch {
1670
+ // Skip unreadable directories
1671
+ }
1672
+
1673
+ return files;
1674
+ }
1675
+
1676
+ private detectDuplication(distPath: string, analysis: BundleAnalysis): void {
1677
+ const fileContents: Record<string, string[]> = {};
1678
+ const allFiles = this.getAllFiles(distPath);
1679
+
1680
+ for (const file of allFiles.slice(0, 50)) {
1681
+ if (file.endsWith(".js")) {
1682
+ try {
1683
+ const content = fs.readFileSync(file, "utf8").substring(0, 10000);
1684
+ const hashes = content.split("").reduce((acc, c, i) => {
1685
+ return acc + (c.charCodeAt(0) * (i + 1));
1686
+ }, 0);
1687
+
1688
+ const hashKey = String(hashes % 100);
1689
+ if (!fileContents[hashKey]) fileContents[hashKey] = [];
1690
+ fileContents[hashKey].push(path.basename(file));
1691
+ } catch {
1692
+ // Skip unreadable files
1693
+ }
1694
+ }
1695
+ }
1696
+
1697
+ for (const [, files] of Object.entries(fileContents)) {
1698
+ if (files.length > 1 && files[0]) {
1699
+ analysis.duplication.push({
1700
+ name: files[0],
1701
+ count: files.length
1702
+ });
1703
+ }
1704
+ }
1705
+ }
1706
+
1707
+ private applyBundleRecommendations(result: CoreWebVitalsResult): void {
1708
+ if (!result.bundleAnalysis) return;
1709
+
1710
+ const bundle = result.bundleAnalysis;
1711
+
1712
+ if (bundle.totalSize > 500 * 1024) {
1713
+ result.recommendations.push("Bundle size exceeds 500KB - implement code splitting");
1714
+ }
1715
+
1716
+ if (bundle.largestModules.length > 3) {
1717
+ result.recommendations.push("Large modules detected - consider lazy loading");
1718
+ }
1719
+
1720
+ if (bundle.duplication.length > 2) {
1721
+ result.recommendations.push("Code duplication detected - extract shared code to common modules");
1722
+ }
1723
+ }
1724
+
1725
+ private measureLCP(projectRoot: string): LCPMetrics {
1726
+ const srcPath = path.join(projectRoot, "src");
1727
+ let estimatedLCP = 2500;
1728
+
1729
+ if (fs.existsSync(srcPath)) {
1730
+ const files = this.findCodeFiles(projectRoot);
1731
+
1732
+ let criticalElements = 0;
1733
+ for (const file of files) {
1734
+ try {
1735
+ const content = fs.readFileSync(file, "utf8");
1736
+
1737
+ const heroImages = content.match(/<img[^>]*class="[^"]*(?:hero|header|main|featured)[^"]*"/gi) || [];
1738
+ const largeImages = content.match(/<img[^>]*(?:width="[^"]*[1-9][0-9]{2,}"|height="[^"]*[1-9][0-9]{2,}")/gi) || [];
1739
+ criticalElements += heroImages.length + largeImages.length;
1740
+
1741
+ const criticalCSS = content.match(/loading="eager"|fetchpriority="high"/gi) || [];
1742
+ if (criticalCSS.length === 0 && criticalElements > 0) {
1743
+ estimatedLCP += 500;
1744
+ }
1745
+ } catch {
1746
+ // Skip unreadable files
1747
+ }
1748
+ }
1749
+ }
1750
+
1751
+ return {
1752
+ value: estimatedLCP,
1753
+ score: this.scoreLCP(estimatedLCP),
1754
+ element: "Largest contentful element",
1755
+ resourceLoadTime: Math.round(estimatedLCP * 0.6),
1756
+ renderDelay: Math.round(estimatedLCP * 0.4)
1757
+ };
1758
+ }
1759
+
1760
+ private scoreLCP(value: number): number {
1761
+ if (value <= 2500) return 100;
1762
+ if (value <= 4000) return 90;
1763
+ if (value <= 6000) return 70;
1764
+ return 50;
1765
+ }
1766
+
1767
+ private evaluateLCP(result: CoreWebVitalsResult): void {
1768
+ if (!result.LCP) return;
1769
+
1770
+ if (result.LCP.value > 4000) {
1771
+ result.recommendations.push("LCP exceeds 4s - optimize server response time and resource loading");
1772
+ result.score -= 20;
1773
+ } else if (result.LCP.value > 2500) {
1774
+ result.recommendations.push("LCP could be improved - consider preloading critical resources");
1775
+ result.score -= 10;
1776
+ }
1777
+ }
1778
+
1779
+ private measureINP(projectRoot: string): INPMetrics {
1780
+ const srcPath = path.join(projectRoot, "src");
1781
+ let estimatedINP = 200;
1782
+
1783
+ if (fs.existsSync(srcPath)) {
1784
+ const files = this.findCodeFiles(projectRoot);
1785
+
1786
+ let eventHandlers = 0;
1787
+ for (const file of files) {
1788
+ try {
1789
+ const content = fs.readFileSync(file, "utf8");
1790
+
1791
+ const handlers = content.match(/\.addEventListener\(|onClick|onChange|onSubmit/g) || [];
1792
+ eventHandlers += handlers.length;
1793
+
1794
+ const heavyHandlers = content.match(/async\s+\w+\s*\([^)]*\)\s*\{[\s\S]{200,}?await\s+/g) || [];
1795
+ if (heavyHandlers.length > 0) {
1796
+ estimatedINP += heavyHandlers.length * 100;
1797
+ }
1798
+ } catch {
1799
+ // Skip unreadable files
1800
+ }
1801
+ }
1802
+
1803
+ if (eventHandlers > 50) {
1804
+ estimatedINP += 50;
1805
+ }
1806
+ }
1807
+
1808
+ return {
1809
+ value: estimatedINP,
1810
+ score: this.scoreINP(estimatedINP),
1811
+ interactionType: "click/keypress",
1812
+ processingTime: Math.round(estimatedINP * 0.7),
1813
+ presentationDelay: Math.round(estimatedINP * 0.3)
1814
+ };
1815
+ }
1816
+
1817
+ private scoreINP(value: number): number {
1818
+ if (value <= 200) return 100;
1819
+ if (value <= 500) return 80;
1820
+ if (value <= 1000) return 60;
1821
+ return 40;
1822
+ }
1823
+
1824
+ private evaluateINP(result: CoreWebVitalsResult): void {
1825
+ if (!result.INP) return;
1826
+
1827
+ if (result.INP.value > 500) {
1828
+ result.recommendations.push("INP exceeds 500ms - break up long tasks and defer non-critical work");
1829
+ result.score -= 15;
1830
+ } else if (result.INP.value > 200) {
1831
+ result.recommendations.push("INP could be improved - optimize event handlers and reduce main thread work");
1832
+ result.score -= 5;
1833
+ }
1834
+ }
1835
+
1836
+ private measureCLS(projectRoot: string): CLSMetrics {
1837
+ const srcPath = path.join(projectRoot, "src");
1838
+ let estimatedCLS = 0.05;
1839
+ const sources: string[] = [];
1840
+
1841
+ if (fs.existsSync(srcPath)) {
1842
+ const files = this.findCodeFiles(projectRoot);
1843
+
1844
+ for (const file of files) {
1845
+ try {
1846
+ const content = fs.readFileSync(file, "utf8");
1847
+
1848
+ const imagesWithoutDimensions = content.match(/<img(?![^>]*\b(width|height)=)/gi) || [];
1849
+ if (imagesWithoutDimensions.length > 0) {
1850
+ estimatedCLS += imagesWithoutDimensions.length * 0.1;
1851
+ sources.push(`${imagesWithoutDimensions.length} images without dimensions`);
1852
+ }
1853
+
1854
+ const dynamicAds = content.match(/<div[^>]*class="[^"]*(?:ad|banner|advertisement)[^"]*"/gi) || [];
1855
+ if (dynamicAds.length > 0) {
1856
+ estimatedCLS += dynamicAds.length * 0.15;
1857
+ sources.push(`${dynamicAds.length} dynamic ad containers`);
1858
+ }
1859
+
1860
+ const fontLoads = content.match(/@font-face|font-display:\s*swap/gi) || [];
1861
+ if (fontLoads.length === 0) {
1862
+ estimatedCLS += 0.05;
1863
+ sources.push("No font-display strategy specified");
1864
+ }
1865
+ } catch {
1866
+ // Skip unreadable files
1867
+ }
1868
+ }
1869
+ }
1870
+
1871
+ return {
1872
+ value: Math.round(estimatedCLS * 1000) / 1000,
1873
+ score: this.scoreCLS(estimatedCLS),
1874
+ layoutShifts: Math.round(estimatedCLS * 10),
1875
+ unexpectedShifts: Math.round(estimatedCLS * 7),
1876
+ sources: [...new Set(sources)]
1877
+ };
1878
+ }
1879
+
1880
+ private scoreCLS(value: number): number {
1881
+ if (value <= 0.1) return 100;
1882
+ if (value <= 0.25) return 80;
1883
+ if (value <= 0.5) return 60;
1884
+ return 40;
1885
+ }
1886
+
1887
+ private evaluateCLS(result: CoreWebVitalsResult, checkAccessibility: boolean): void {
1888
+ if (!result.CLS) return;
1889
+
1890
+ if (result.CLS.value > 0.25) {
1891
+ result.recommendations.push("CLS exceeds 0.25 - set dimensions on images and reserve space for dynamic content");
1892
+ result.score -= 15;
1893
+ } else if (result.CLS.value > 0.1) {
1894
+ result.recommendations.push("CLS could be improved - ensure all media has explicit dimensions");
1895
+ result.score -= 5;
1896
+ }
1897
+
1898
+ if (checkAccessibility && result.CLS.sources.length > 0) {
1899
+ result.recommendations.push("Accessibility issue: Layout shifts affect user experience - fix CLS sources");
1900
+ result.score -= 5;
1901
+ }
1902
+ }
1903
+
1904
+ private calculateOverallScore(result: CoreWebVitalsResult): void {
1905
+ let totalWeight = 0;
1906
+ let weightedScore = 0;
1907
+
1908
+ if (result.LCP) {
1909
+ weightedScore += result.LCP.score * 0.35;
1910
+ totalWeight += 0.35;
1911
+ }
1912
+
1913
+ if (result.INP) {
1914
+ weightedScore += result.INP.score * 0.35;
1915
+ totalWeight += 0.35;
1916
+ }
1917
+
1918
+ if (result.CLS) {
1919
+ weightedScore += result.CLS.score * 0.30;
1920
+ totalWeight += 0.30;
1921
+ }
1922
+
1923
+ result.score = totalWeight > 0 ? Math.round(weightedScore / totalWeight) : 100;
1924
+ }
1925
+
1926
+ private determineStatus(result: CoreWebVitalsResult): void {
1927
+ if (result.score >= 90) {
1928
+ result.status = "good";
1929
+ } else if (result.score >= 50) {
1930
+ result.status = "needs-improvement";
1931
+ } else {
1932
+ result.status = "poor";
1933
+ }
1934
+ }
1935
+
1936
+ private formatCoreWebVitalsResult(result: CoreWebVitalsResult): string {
1937
+ const statusIcon = result.status === "good" ? "✅" :
1938
+ result.status === "needs-improvement" ? "⚠️" : "❌";
1939
+
1940
+ let text = `${statusIcon} Core Web Vitals Analysis
1941
+
1942
+ **OVERALL SCORE:** ${result.score}/100 (${result.status.toUpperCase()})
1943
+ `;
1944
+
1945
+ if (result.bundleAnalysis) {
1946
+ const bundle = result.bundleAnalysis;
1947
+ text += `
1948
+ **BUNDLE ANALYSIS**
1949
+ - Total Size: ${(bundle.totalSize / 1024 / 1024).toFixed(2)}MB
1950
+ - Gzipped Size: ${(bundle.gzippedSize / 1024 / 1024).toFixed(2)}MB
1951
+ - Largest Modules: ${bundle.largestModules.slice(0, 3).map(m => `${m.name} (${m.size}KB)`).join(", ") || "None"}
1952
+ `;
1953
+ }
1954
+
1955
+ if (result.LCP) {
1956
+ const lcp = result.LCP;
1957
+ const lcpStatus = lcp.value <= 2500 ? "✅" : lcp.value <= 4000 ? "⚠️" : "❌";
1958
+ text += `
1959
+ **LCP (Largest Contentful Paint)** ${lcpStatus}
1960
+ - Value: ${(lcp.value / 1000).toFixed(2)}s
1961
+ - Score: ${lcp.score}/100
1962
+ - Resource Load: ${(lcp.resourceLoadTime / 1000).toFixed(2)}s
1963
+ - Render Delay: ${(lcp.renderDelay / 1000).toFixed(2)}s
1964
+ `;
1965
+ }
1966
+
1967
+ if (result.INP) {
1968
+ const inp = result.INP;
1969
+ const inpStatus = inp.value <= 200 ? "✅" : inp.value <= 500 ? "⚠️" : "❌";
1970
+ text += `
1971
+ **INP (Interaction to Next Paint)** ${inpStatus}
1972
+ - Value: ${inp.value}ms
1973
+ - Score: ${inp.score}/100
1974
+ - Processing Time: ${inp.processingTime}ms
1975
+ - Presentation Delay: ${inp.presentationDelay}ms
1976
+ `;
1977
+ }
1978
+
1979
+ if (result.CLS) {
1980
+ const cls = result.CLS;
1981
+ const clsStatus = cls.value <= 0.1 ? "✅" : cls.value <= 0.25 ? "⚠️" : "❌";
1982
+ text += `
1983
+ **CLS (Cumulative Layout Shift)** ${clsStatus}
1984
+ - Value: ${cls.value}
1985
+ - Score: ${cls.score}/100
1986
+ - Layout Shifts: ${cls.layoutShifts}
1987
+ - Sources: ${cls.sources.slice(0, 3).join(", ") || "None"}
1988
+ `;
1989
+ }
1990
+
1991
+ text += `
1992
+ **RECOMMENDATIONS**
1993
+ ${result.recommendations.slice(0, 5).map((r, i) => `${i + 1}. ${r}`).join("\n") || "No specific recommendations"}
1994
+ `;
1995
+
1996
+ return text;
1997
+ }
1998
+
1999
+ private findCodeFiles(projectRoot: string, maxDepth: number = 10): string[] {
2000
+ const extensions = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
2001
+ const files: string[] = [];
2002
+
2003
+ const scanDir = (dir: string, depth: number) => {
2004
+ if (depth > maxDepth) return;
2005
+
2006
+ try {
2007
+ const items = fs.readdirSync(dir);
2008
+
2009
+ for (const item of items) {
2010
+ if (item.startsWith(".")) continue;
2011
+
2012
+ const fullPath = path.join(dir, item);
2013
+
2014
+ try {
2015
+ const stat = fs.statSync(fullPath);
2016
+
2017
+ if (stat.isDirectory()) {
2018
+ if (item !== "node_modules" && item !== "dist" && item !== "build" && item !== ".next") {
2019
+ scanDir(fullPath, depth + 1);
2020
+ }
2021
+ } else if (stat.isFile() && extensions.some(ext => item.endsWith(ext))) {
2022
+ files.push(fullPath);
2023
+ }
2024
+ } catch {
2025
+ // Skip files we can't stat
2026
+ }
2027
+ }
2028
+ } catch {
2029
+ // Skip directories we can't read
2030
+ }
2031
+ };
2032
+
2033
+ const srcPath = path.join(projectRoot, "src");
2034
+ if (fs.existsSync(srcPath)) {
2035
+ scanDir(srcPath, 0);
2036
+ } else {
2037
+ scanDir(projectRoot, 0);
2038
+ }
2039
+
2040
+ return files.slice(0, 100);
2041
+ }
2042
+
2043
+ async run(): Promise<void> {
2044
+ const transport = new StdioServerTransport();
2045
+ await this.server.connect(transport);
2046
+
2047
+ createGracefulShutdown({
2048
+ serverName: "performance-optimization.server",
2049
+ server: this.server,
2050
+ });
2051
+
2052
+ frameworkLogger.log("mcp/performance-optimization", "server-started", "info", {
2053
+ uptime: Date.now() - this.startTime
2054
+ });
2055
+ }
2056
+ }
2057
+
2058
+ if (import.meta.url === `file://${process.argv[1]}`) {
2059
+ const server = new StringRayPerformanceOptimizationServer();
2060
+ server.run().catch((error) => {
2061
+ frameworkLogger.log("mcp/performance-optimization", "run", "error", { error: String(error) });
2062
+ });
2063
+ }
2064
+
2065
+ export { StringRayPerformanceOptimizationServer };