jarvis-ai-assistant 0.3.30__py3-none-any.whl → 0.7.6__py3-none-any.whl

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 (181) hide show
  1. jarvis/__init__.py +1 -1
  2. jarvis/jarvis_agent/__init__.py +458 -152
  3. jarvis/jarvis_agent/agent_manager.py +17 -13
  4. jarvis/jarvis_agent/builtin_input_handler.py +2 -6
  5. jarvis/jarvis_agent/config_editor.py +2 -7
  6. jarvis/jarvis_agent/event_bus.py +82 -12
  7. jarvis/jarvis_agent/file_context_handler.py +329 -0
  8. jarvis/jarvis_agent/file_methodology_manager.py +3 -4
  9. jarvis/jarvis_agent/jarvis.py +628 -55
  10. jarvis/jarvis_agent/language_extractors/__init__.py +57 -0
  11. jarvis/jarvis_agent/language_extractors/c_extractor.py +21 -0
  12. jarvis/jarvis_agent/language_extractors/cpp_extractor.py +21 -0
  13. jarvis/jarvis_agent/language_extractors/go_extractor.py +21 -0
  14. jarvis/jarvis_agent/language_extractors/java_extractor.py +84 -0
  15. jarvis/jarvis_agent/language_extractors/javascript_extractor.py +79 -0
  16. jarvis/jarvis_agent/language_extractors/python_extractor.py +21 -0
  17. jarvis/jarvis_agent/language_extractors/rust_extractor.py +21 -0
  18. jarvis/jarvis_agent/language_extractors/typescript_extractor.py +84 -0
  19. jarvis/jarvis_agent/language_support_info.py +486 -0
  20. jarvis/jarvis_agent/main.py +34 -10
  21. jarvis/jarvis_agent/memory_manager.py +7 -16
  22. jarvis/jarvis_agent/methodology_share_manager.py +10 -16
  23. jarvis/jarvis_agent/prompt_manager.py +1 -1
  24. jarvis/jarvis_agent/prompts.py +193 -171
  25. jarvis/jarvis_agent/protocols.py +8 -12
  26. jarvis/jarvis_agent/run_loop.py +105 -9
  27. jarvis/jarvis_agent/session_manager.py +2 -3
  28. jarvis/jarvis_agent/share_manager.py +20 -22
  29. jarvis/jarvis_agent/shell_input_handler.py +1 -2
  30. jarvis/jarvis_agent/stdio_redirect.py +295 -0
  31. jarvis/jarvis_agent/task_analyzer.py +31 -6
  32. jarvis/jarvis_agent/task_manager.py +11 -27
  33. jarvis/jarvis_agent/tool_executor.py +2 -3
  34. jarvis/jarvis_agent/tool_share_manager.py +12 -24
  35. jarvis/jarvis_agent/utils.py +5 -1
  36. jarvis/jarvis_agent/web_bridge.py +189 -0
  37. jarvis/jarvis_agent/web_output_sink.py +53 -0
  38. jarvis/jarvis_agent/web_server.py +786 -0
  39. jarvis/jarvis_c2rust/__init__.py +26 -0
  40. jarvis/jarvis_c2rust/cli.py +575 -0
  41. jarvis/jarvis_c2rust/collector.py +250 -0
  42. jarvis/jarvis_c2rust/constants.py +26 -0
  43. jarvis/jarvis_c2rust/library_replacer.py +1254 -0
  44. jarvis/jarvis_c2rust/llm_module_agent.py +1272 -0
  45. jarvis/jarvis_c2rust/loaders.py +207 -0
  46. jarvis/jarvis_c2rust/models.py +28 -0
  47. jarvis/jarvis_c2rust/optimizer.py +2157 -0
  48. jarvis/jarvis_c2rust/scanner.py +1681 -0
  49. jarvis/jarvis_c2rust/transpiler.py +2983 -0
  50. jarvis/jarvis_c2rust/utils.py +385 -0
  51. jarvis/jarvis_code_agent/build_validation_config.py +132 -0
  52. jarvis/jarvis_code_agent/code_agent.py +1371 -220
  53. jarvis/jarvis_code_agent/code_analyzer/__init__.py +65 -0
  54. jarvis/jarvis_code_agent/code_analyzer/base_language.py +74 -0
  55. jarvis/jarvis_code_agent/code_analyzer/build_validator/__init__.py +44 -0
  56. jarvis/jarvis_code_agent/code_analyzer/build_validator/base.py +106 -0
  57. jarvis/jarvis_code_agent/code_analyzer/build_validator/cmake.py +74 -0
  58. jarvis/jarvis_code_agent/code_analyzer/build_validator/detector.py +125 -0
  59. jarvis/jarvis_code_agent/code_analyzer/build_validator/fallback.py +72 -0
  60. jarvis/jarvis_code_agent/code_analyzer/build_validator/go.py +70 -0
  61. jarvis/jarvis_code_agent/code_analyzer/build_validator/java_gradle.py +53 -0
  62. jarvis/jarvis_code_agent/code_analyzer/build_validator/java_maven.py +47 -0
  63. jarvis/jarvis_code_agent/code_analyzer/build_validator/makefile.py +61 -0
  64. jarvis/jarvis_code_agent/code_analyzer/build_validator/nodejs.py +110 -0
  65. jarvis/jarvis_code_agent/code_analyzer/build_validator/python.py +154 -0
  66. jarvis/jarvis_code_agent/code_analyzer/build_validator/rust.py +110 -0
  67. jarvis/jarvis_code_agent/code_analyzer/build_validator/validator.py +153 -0
  68. jarvis/jarvis_code_agent/code_analyzer/build_validator.py +43 -0
  69. jarvis/jarvis_code_agent/code_analyzer/context_manager.py +648 -0
  70. jarvis/jarvis_code_agent/code_analyzer/context_recommender.py +18 -0
  71. jarvis/jarvis_code_agent/code_analyzer/dependency_analyzer.py +132 -0
  72. jarvis/jarvis_code_agent/code_analyzer/file_ignore.py +330 -0
  73. jarvis/jarvis_code_agent/code_analyzer/impact_analyzer.py +781 -0
  74. jarvis/jarvis_code_agent/code_analyzer/language_registry.py +185 -0
  75. jarvis/jarvis_code_agent/code_analyzer/language_support.py +110 -0
  76. jarvis/jarvis_code_agent/code_analyzer/languages/__init__.py +49 -0
  77. jarvis/jarvis_code_agent/code_analyzer/languages/c_cpp_language.py +299 -0
  78. jarvis/jarvis_code_agent/code_analyzer/languages/go_language.py +215 -0
  79. jarvis/jarvis_code_agent/code_analyzer/languages/java_language.py +212 -0
  80. jarvis/jarvis_code_agent/code_analyzer/languages/javascript_language.py +254 -0
  81. jarvis/jarvis_code_agent/code_analyzer/languages/python_language.py +269 -0
  82. jarvis/jarvis_code_agent/code_analyzer/languages/rust_language.py +281 -0
  83. jarvis/jarvis_code_agent/code_analyzer/languages/typescript_language.py +280 -0
  84. jarvis/jarvis_code_agent/code_analyzer/llm_context_recommender.py +605 -0
  85. jarvis/jarvis_code_agent/code_analyzer/structured_code.py +556 -0
  86. jarvis/jarvis_code_agent/code_analyzer/symbol_extractor.py +252 -0
  87. jarvis/jarvis_code_agent/code_analyzer/tree_sitter_extractor.py +58 -0
  88. jarvis/jarvis_code_agent/lint.py +501 -8
  89. jarvis/jarvis_code_agent/utils.py +141 -0
  90. jarvis/jarvis_code_analysis/code_review.py +493 -584
  91. jarvis/jarvis_data/config_schema.json +128 -12
  92. jarvis/jarvis_git_squash/main.py +4 -5
  93. jarvis/jarvis_git_utils/git_commiter.py +82 -75
  94. jarvis/jarvis_mcp/sse_mcp_client.py +22 -29
  95. jarvis/jarvis_mcp/stdio_mcp_client.py +12 -13
  96. jarvis/jarvis_mcp/streamable_mcp_client.py +15 -14
  97. jarvis/jarvis_memory_organizer/memory_organizer.py +55 -74
  98. jarvis/jarvis_methodology/main.py +32 -48
  99. jarvis/jarvis_multi_agent/__init__.py +287 -55
  100. jarvis/jarvis_multi_agent/main.py +36 -4
  101. jarvis/jarvis_platform/base.py +524 -202
  102. jarvis/jarvis_platform/human.py +7 -8
  103. jarvis/jarvis_platform/kimi.py +30 -36
  104. jarvis/jarvis_platform/openai.py +88 -25
  105. jarvis/jarvis_platform/registry.py +26 -10
  106. jarvis/jarvis_platform/tongyi.py +24 -25
  107. jarvis/jarvis_platform/yuanbao.py +32 -43
  108. jarvis/jarvis_platform_manager/main.py +66 -77
  109. jarvis/jarvis_platform_manager/service.py +8 -13
  110. jarvis/jarvis_rag/cli.py +53 -55
  111. jarvis/jarvis_rag/embedding_manager.py +13 -18
  112. jarvis/jarvis_rag/llm_interface.py +8 -9
  113. jarvis/jarvis_rag/query_rewriter.py +10 -21
  114. jarvis/jarvis_rag/rag_pipeline.py +24 -27
  115. jarvis/jarvis_rag/reranker.py +4 -5
  116. jarvis/jarvis_rag/retriever.py +28 -30
  117. jarvis/jarvis_sec/__init__.py +305 -0
  118. jarvis/jarvis_sec/agents.py +143 -0
  119. jarvis/jarvis_sec/analysis.py +276 -0
  120. jarvis/jarvis_sec/checkers/__init__.py +32 -0
  121. jarvis/jarvis_sec/checkers/c_checker.py +2680 -0
  122. jarvis/jarvis_sec/checkers/rust_checker.py +1108 -0
  123. jarvis/jarvis_sec/cli.py +139 -0
  124. jarvis/jarvis_sec/clustering.py +1439 -0
  125. jarvis/jarvis_sec/file_manager.py +427 -0
  126. jarvis/jarvis_sec/parsers.py +73 -0
  127. jarvis/jarvis_sec/prompts.py +268 -0
  128. jarvis/jarvis_sec/report.py +336 -0
  129. jarvis/jarvis_sec/review.py +453 -0
  130. jarvis/jarvis_sec/status.py +264 -0
  131. jarvis/jarvis_sec/types.py +20 -0
  132. jarvis/jarvis_sec/utils.py +499 -0
  133. jarvis/jarvis_sec/verification.py +848 -0
  134. jarvis/jarvis_sec/workflow.py +226 -0
  135. jarvis/jarvis_smart_shell/main.py +38 -87
  136. jarvis/jarvis_stats/cli.py +2 -2
  137. jarvis/jarvis_stats/stats.py +8 -8
  138. jarvis/jarvis_stats/storage.py +15 -21
  139. jarvis/jarvis_stats/visualizer.py +1 -1
  140. jarvis/jarvis_tools/clear_memory.py +3 -20
  141. jarvis/jarvis_tools/cli/main.py +21 -23
  142. jarvis/jarvis_tools/edit_file.py +1019 -132
  143. jarvis/jarvis_tools/execute_script.py +83 -25
  144. jarvis/jarvis_tools/file_analyzer.py +6 -9
  145. jarvis/jarvis_tools/generate_new_tool.py +14 -21
  146. jarvis/jarvis_tools/lsp_client.py +1552 -0
  147. jarvis/jarvis_tools/methodology.py +2 -3
  148. jarvis/jarvis_tools/read_code.py +1736 -35
  149. jarvis/jarvis_tools/read_symbols.py +140 -0
  150. jarvis/jarvis_tools/read_webpage.py +12 -13
  151. jarvis/jarvis_tools/registry.py +427 -200
  152. jarvis/jarvis_tools/retrieve_memory.py +20 -19
  153. jarvis/jarvis_tools/rewrite_file.py +72 -158
  154. jarvis/jarvis_tools/save_memory.py +3 -15
  155. jarvis/jarvis_tools/search_web.py +18 -18
  156. jarvis/jarvis_tools/sub_agent.py +36 -43
  157. jarvis/jarvis_tools/sub_code_agent.py +25 -26
  158. jarvis/jarvis_tools/virtual_tty.py +55 -33
  159. jarvis/jarvis_utils/clipboard.py +7 -10
  160. jarvis/jarvis_utils/config.py +232 -45
  161. jarvis/jarvis_utils/embedding.py +8 -5
  162. jarvis/jarvis_utils/fzf.py +8 -8
  163. jarvis/jarvis_utils/git_utils.py +225 -36
  164. jarvis/jarvis_utils/globals.py +3 -3
  165. jarvis/jarvis_utils/http.py +1 -1
  166. jarvis/jarvis_utils/input.py +99 -48
  167. jarvis/jarvis_utils/jsonnet_compat.py +465 -0
  168. jarvis/jarvis_utils/methodology.py +52 -48
  169. jarvis/jarvis_utils/utils.py +819 -491
  170. jarvis_ai_assistant-0.7.6.dist-info/METADATA +600 -0
  171. jarvis_ai_assistant-0.7.6.dist-info/RECORD +218 -0
  172. {jarvis_ai_assistant-0.3.30.dist-info → jarvis_ai_assistant-0.7.6.dist-info}/entry_points.txt +4 -0
  173. jarvis/jarvis_agent/config.py +0 -92
  174. jarvis/jarvis_agent/edit_file_handler.py +0 -296
  175. jarvis/jarvis_platform/ai8.py +0 -332
  176. jarvis/jarvis_tools/ask_user.py +0 -54
  177. jarvis_ai_assistant-0.3.30.dist-info/METADATA +0 -381
  178. jarvis_ai_assistant-0.3.30.dist-info/RECORD +0 -137
  179. {jarvis_ai_assistant-0.3.30.dist-info → jarvis_ai_assistant-0.7.6.dist-info}/WHEEL +0 -0
  180. {jarvis_ai_assistant-0.3.30.dist-info → jarvis_ai_assistant-0.7.6.dist-info}/licenses/LICENSE +0 -0
  181. {jarvis_ai_assistant-0.3.30.dist-info → jarvis_ai_assistant-0.7.6.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Java Maven构建验证器模块
6
+
7
+ 提供Java Maven项目的构建验证功能。
8
+ """
9
+
10
+ import time
11
+ from typing import List, Optional
12
+
13
+ from .base import BuildValidatorBase, BuildResult, BuildSystem
14
+
15
+
16
+ class JavaMavenBuildValidator(BuildValidatorBase):
17
+ """Java Maven构建验证器"""
18
+
19
+ BUILD_SYSTEM_NAME = "Maven"
20
+ SUPPORTED_LANGUAGES = ["java"]
21
+
22
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
23
+ start_time = time.time()
24
+
25
+ # 使用 mvn compile 进行编译验证
26
+ cmd = ["mvn", "compile", "-q"] # -q 静默模式
27
+
28
+ returncode, stdout, stderr = self._run_command(cmd, timeout=60)
29
+ duration = time.time() - start_time
30
+
31
+ success = returncode == 0
32
+ output = stdout + stderr
33
+
34
+ if success:
35
+ print(f"✅ Maven 构建验证成功(耗时 {duration:.2f} 秒)")
36
+ else:
37
+ print(f"❌ Maven 构建验证失败(耗时 {duration:.2f} 秒)")
38
+ print(f"错误信息:Maven编译失败\n{output[:500]}")
39
+
40
+ return BuildResult(
41
+ success=success,
42
+ output=output,
43
+ error_message=None if success else "Maven编译失败",
44
+ build_system=BuildSystem.JAVA_MAVEN,
45
+ duration=duration,
46
+ )
47
+
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Makefile构建验证器模块
6
+
7
+ 提供Makefile项目的构建验证功能。
8
+ """
9
+
10
+ import os
11
+ import time
12
+ from typing import List, Optional
13
+
14
+ from .base import BuildValidatorBase, BuildResult, BuildSystem
15
+
16
+
17
+ class MakefileBuildValidator(BuildValidatorBase):
18
+ """Makefile构建验证器"""
19
+
20
+ BUILD_SYSTEM_NAME = "Makefile"
21
+ SUPPORTED_LANGUAGES = ["c", "cpp"]
22
+
23
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
24
+ start_time = time.time()
25
+
26
+ # 尝试运行 make(如果存在Makefile)
27
+ makefile = os.path.join(self.project_root, "Makefile")
28
+ if not os.path.exists(makefile):
29
+ duration = time.time() - start_time
30
+ print(f"❌ Makefile 构建验证失败(耗时 {duration:.2f} 秒)")
31
+ print("错误信息:Makefile不存在")
32
+ return BuildResult(
33
+ success=False,
34
+ output="Makefile不存在",
35
+ error_message="Makefile不存在",
36
+ build_system=BuildSystem.C_MAKEFILE,
37
+ duration=duration,
38
+ )
39
+
40
+ # 尝试 make -n(dry-run)来验证语法
41
+ returncode, stdout, stderr = self._run_command(
42
+ ["make", "-n"],
43
+ timeout=10,
44
+ )
45
+ duration = time.time() - start_time
46
+
47
+ success = returncode == 0
48
+ output = stdout + stderr
49
+ if success:
50
+ print(f"✅ Makefile 构建验证成功(耗时 {duration:.2f} 秒)")
51
+ else:
52
+ print(f"❌ Makefile 构建验证失败(耗时 {duration:.2f} 秒)")
53
+ print(f"错误信息:Makefile语法检查失败\n{output[:500]}")
54
+ return BuildResult(
55
+ success=success,
56
+ output=output,
57
+ error_message=None if success else "Makefile语法检查失败",
58
+ build_system=BuildSystem.C_MAKEFILE,
59
+ duration=duration,
60
+ )
61
+
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Node.js构建验证器模块
6
+
7
+ 提供Node.js项目的构建验证功能。
8
+ """
9
+
10
+ import json
11
+ import os
12
+ import time
13
+ from typing import List, Optional
14
+
15
+ from .base import BuildValidatorBase, BuildResult, BuildSystem
16
+
17
+
18
+ class NodeJSBuildValidator(BuildValidatorBase):
19
+ """Node.js构建验证器"""
20
+
21
+ BUILD_SYSTEM_NAME = "npm/Node.js"
22
+ SUPPORTED_LANGUAGES = ["javascript", "typescript"]
23
+
24
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
25
+ start_time = time.time()
26
+
27
+ # 策略1: 尝试使用 tsc --noEmit(如果存在TypeScript)
28
+ tsconfig = os.path.join(self.project_root, "tsconfig.json")
29
+ if os.path.exists(tsconfig):
30
+ returncode, stdout, stderr = self._run_command(
31
+ ["npx", "tsc", "--noEmit"],
32
+ timeout=20,
33
+ )
34
+ duration = time.time() - start_time
35
+ success = returncode == 0
36
+ output = stdout + stderr
37
+ if success:
38
+ print(f"✅ Node.js (TypeScript) 构建验证成功(耗时 {duration:.2f} 秒)")
39
+ else:
40
+ print(f"❌ Node.js (TypeScript) 构建验证失败(耗时 {duration:.2f} 秒)")
41
+ print(f"错误信息:TypeScript类型检查失败\n{output[:500]}")
42
+ return BuildResult(
43
+ success=success,
44
+ output=output,
45
+ error_message=None if success else "TypeScript类型检查失败",
46
+ build_system=BuildSystem.NODEJS,
47
+ duration=duration,
48
+ )
49
+
50
+ # 策略2: 尝试运行 npm run build(如果存在build脚本)
51
+ package_json = os.path.join(self.project_root, "package.json")
52
+ if os.path.exists(package_json):
53
+ try:
54
+ with open(package_json, "r", encoding="utf-8") as f:
55
+ package_data = json.load(f)
56
+ scripts = package_data.get("scripts", {})
57
+ if "build" in scripts:
58
+ returncode, stdout, stderr = self._run_command(
59
+ ["npm", "run", "build"],
60
+ timeout=30,
61
+ )
62
+ duration = time.time() - start_time
63
+ success = returncode == 0
64
+ output = stdout + stderr
65
+ if success:
66
+ print(f"✅ Node.js (npm build) 构建验证成功(耗时 {duration:.2f} 秒)")
67
+ else:
68
+ print(f"❌ Node.js (npm build) 构建验证失败(耗时 {duration:.2f} 秒)")
69
+ print(f"错误信息:npm build失败\n{output[:500]}")
70
+ return BuildResult(
71
+ success=success,
72
+ output=output,
73
+ error_message=None if success else "npm build失败",
74
+ build_system=BuildSystem.NODEJS,
75
+ duration=duration,
76
+ )
77
+ except Exception as e:
78
+ print(f"⚠️ 读取package.json失败: {e}")
79
+
80
+ # 策略3: 使用 eslint 进行语法检查(如果存在)
81
+ if modified_files:
82
+ js_files = [f for f in modified_files if f.endswith((".js", ".jsx", ".ts", ".tsx"))]
83
+ if js_files:
84
+ # 尝试使用 eslint
85
+ returncode, stdout, stderr = self._run_command(
86
+ ["npx", "eslint", "--max-warnings=0"] + js_files[:5], # 限制文件数量
87
+ timeout=15,
88
+ )
89
+ duration = time.time() - start_time
90
+ output = stdout + stderr
91
+ # eslint返回非0可能是警告,不算失败
92
+ print(f"✅ Node.js (eslint) 构建验证成功(耗时 {duration:.2f} 秒)")
93
+ return BuildResult(
94
+ success=True, # 仅检查语法,警告不算失败
95
+ output=output,
96
+ error_message=None,
97
+ build_system=BuildSystem.NODEJS,
98
+ duration=duration,
99
+ )
100
+
101
+ duration = time.time() - start_time
102
+ print(f"✅ Node.js 构建验证成功(耗时 {duration:.2f} 秒,无构建脚本)")
103
+ return BuildResult(
104
+ success=True,
105
+ output="Node.js项目验证通过(无构建脚本)",
106
+ error_message=None,
107
+ build_system=BuildSystem.NODEJS,
108
+ duration=duration,
109
+ )
110
+
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Python构建验证器模块
6
+
7
+ 提供Python项目的构建验证功能。
8
+ """
9
+
10
+ import os
11
+ import time
12
+ from typing import List, Optional
13
+
14
+ from .base import BuildValidatorBase, BuildResult, BuildSystem
15
+
16
+
17
+ class PythonBuildValidator(BuildValidatorBase):
18
+ """Python构建验证器(包括编译和测试)"""
19
+
20
+ BUILD_SYSTEM_NAME = "Python"
21
+ SUPPORTED_LANGUAGES = ["python"]
22
+
23
+ def _extract_python_errors(self, output: str) -> str:
24
+ """提取Python错误信息(包括编译错误和测试失败)"""
25
+ if not output:
26
+ return ""
27
+
28
+ lines = output.split("\n")
29
+ errors = []
30
+ in_error = False
31
+
32
+ for line in lines:
33
+ line_lower = line.lower()
34
+ # 检测错误关键词(包括编译错误和测试失败)
35
+ if any(keyword in line_lower for keyword in [
36
+ "error", "failed", "exception", "traceback",
37
+ "syntaxerror", "indentationerror", "assertionerror",
38
+ "failed:", "failures:", "test", "assert"
39
+ ]):
40
+ in_error = True
41
+ errors.append(line.strip())
42
+ elif in_error and line.strip():
43
+ # 继续收集错误相关的行
44
+ if line.strip().startswith(("File", " File", " ", "E ", "FAILED", "FAILURES", "assert")):
45
+ errors.append(line.strip())
46
+ elif not line.strip().startswith("="):
47
+ # 如果遇到非错误相关的行,停止收集
48
+ if len(errors) > 0 and not any(keyword in line_lower for keyword in ["error", "failed", "exception", "assert", "test"]):
49
+ break
50
+
51
+ # 如果收集到错误,返回前20行(限制长度)
52
+ if errors:
53
+ error_text = "\n".join(errors[:20])
54
+ # 如果太长,截断
55
+ if len(error_text) > 1000:
56
+ error_text = error_text[:1000] + "\n... (错误信息已截断)"
57
+ return error_text
58
+
59
+ # 如果没有提取到结构化错误,返回原始输出的前500字符
60
+ return output[:500] if output else ""
61
+
62
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
63
+ start_time = time.time()
64
+
65
+ # 策略1: 尝试使用 py_compile 编译修改的文件
66
+ if modified_files:
67
+ errors = []
68
+ error_outputs = []
69
+ for file_path in modified_files:
70
+ if not file_path.endswith(".py"):
71
+ continue
72
+ full_path = os.path.join(self.project_root, file_path)
73
+ if os.path.exists(full_path):
74
+ returncode, stdout, stderr = self._run_command(
75
+ ["python", "-m", "py_compile", full_path],
76
+ timeout=5,
77
+ )
78
+ if returncode != 0:
79
+ error_msg = f"{file_path}: {stderr}".strip()
80
+ errors.append(error_msg)
81
+ error_outputs.append(stdout + stderr)
82
+
83
+ if errors:
84
+ duration = time.time() - start_time
85
+ # 合并所有错误输出
86
+ full_output = "\n".join(error_outputs)
87
+ # 提取关键错误信息
88
+ error_message = self._extract_python_errors(full_output)
89
+ if not error_message:
90
+ # 如果没有提取到结构化错误,使用简化的错误列表
91
+ error_message = "\n".join(errors[:5]) # 最多显示5个文件的错误
92
+ if len(errors) > 5:
93
+ error_message += f"\n... 还有 {len(errors) - 5} 个文件存在错误"
94
+ print(f"❌ Python 构建验证失败(耗时 {duration:.2f} 秒)")
95
+ print(f"错误信息:\n{error_message}")
96
+ return BuildResult(
97
+ success=False,
98
+ output=full_output,
99
+ error_message=error_message,
100
+ build_system=BuildSystem.PYTHON,
101
+ duration=duration,
102
+ )
103
+
104
+ # 策略2: 尝试运行 pytest(会自动编译并运行测试,即使没有配置文件也会自动发现测试)
105
+ # 首先尝试 pytest
106
+ returncode, stdout, stderr = self._run_command(
107
+ ["python", "-m", "pytest", "-v"],
108
+ timeout=30,
109
+ )
110
+ # 如果 pytest 命令本身失败(如未安装),尝试 unittest
111
+ if returncode == 1 and "No module named pytest" in stderr:
112
+ # pytest 未安装,尝试使用 unittest
113
+ returncode, stdout, stderr = self._run_command(
114
+ ["python", "-m", "unittest", "discover", "-v"],
115
+ timeout=30,
116
+ )
117
+
118
+ duration = time.time() - start_time
119
+ success = returncode == 0
120
+ output = stdout + stderr
121
+
122
+ # 如果失败,提取关键错误信息(包括编译错误和测试失败)
123
+ if not success:
124
+ error_msg = self._extract_python_errors(output)
125
+ if not error_msg:
126
+ # 检查是否是"没有找到测试"的情况(这不算失败)
127
+ if "no tests ran" in output.lower() or "no tests found" in output.lower():
128
+ # 没有测试文件,但语法检查通过,视为成功
129
+ print(f"✅ Python 构建验证成功(耗时 {duration:.2f} 秒,未发现测试文件)")
130
+ return BuildResult(
131
+ success=True,
132
+ output="Python语法检查通过(未发现测试文件)",
133
+ error_message=None,
134
+ build_system=BuildSystem.PYTHON,
135
+ duration=duration,
136
+ )
137
+ error_msg = "Python项目验证失败(编译或测试失败)"
138
+ print(f"❌ Python 构建验证失败(耗时 {duration:.2f} 秒)")
139
+ if error_msg:
140
+ print(f"错误信息:\n{error_msg}")
141
+ else:
142
+ print(f"输出:\n{output[:500]}")
143
+ else:
144
+ error_msg = None
145
+ print(f"✅ Python 构建验证成功(耗时 {duration:.2f} 秒)")
146
+
147
+ return BuildResult(
148
+ success=success,
149
+ output=output,
150
+ error_message=error_msg,
151
+ build_system=BuildSystem.PYTHON,
152
+ duration=duration,
153
+ )
154
+
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Rust构建验证器模块
6
+
7
+ 提供Rust项目的构建验证功能。
8
+ """
9
+
10
+ import os
11
+ import subprocess
12
+ import time
13
+ from typing import List, Optional
14
+
15
+ from .base import BuildValidatorBase, BuildResult, BuildSystem
16
+
17
+
18
+ class RustBuildValidator(BuildValidatorBase):
19
+ """Rust构建验证器(使用cargo test,包括编译和测试)"""
20
+
21
+ BUILD_SYSTEM_NAME = "Cargo"
22
+ SUPPORTED_LANGUAGES = ["rust"]
23
+
24
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
25
+ start_time = time.time()
26
+
27
+ # 使用 cargo test 进行构建和测试验证(会自动编译并运行测试)
28
+ # 设置 RUST_BACKTRACE=1 以启用调用链回溯
29
+ # 设置 RUSTFLAGS="-A warnings" 以屏蔽警告,只显示错误
30
+ cmd = ["cargo", "test", "--", "--nocapture"]
31
+
32
+ # 准备环境变量(继承当前环境并设置 RUST_BACKTRACE 和 RUSTFLAGS)
33
+ env = os.environ.copy()
34
+ env["RUST_BACKTRACE"] = "1"
35
+ # 如果已存在 RUSTFLAGS,则追加;否则新建
36
+ if "RUSTFLAGS" in env:
37
+ env["RUSTFLAGS"] = env["RUSTFLAGS"] + " -A warnings"
38
+ else:
39
+ env["RUSTFLAGS"] = "-A warnings"
40
+
41
+ # 直接使用 subprocess.run 以支持环境变量
42
+ try:
43
+ result = subprocess.run(
44
+ cmd,
45
+ cwd=self.project_root,
46
+ timeout=self.timeout,
47
+ capture_output=True,
48
+ text=True,
49
+ encoding="utf-8",
50
+ errors="replace",
51
+ env=env,
52
+ )
53
+ returncode = result.returncode
54
+ stdout = result.stdout
55
+ stderr = result.stderr
56
+ except subprocess.TimeoutExpired:
57
+ returncode = -1
58
+ stdout = ""
59
+ stderr = f"命令执行超时({self.timeout}秒)"
60
+ except FileNotFoundError:
61
+ returncode = -1
62
+ stdout = ""
63
+ stderr = f"命令未找到: {cmd[0]}"
64
+ except Exception as e:
65
+ returncode = -1
66
+ stdout = ""
67
+ stderr = f"执行命令时出错: {str(e)}"
68
+
69
+ duration = time.time() - start_time
70
+
71
+ success = returncode == 0
72
+ output = stdout + stderr
73
+
74
+ if not success:
75
+ # 尝试解析错误信息(包括编译错误和测试失败)
76
+ error_message = self._parse_cargo_errors(output)
77
+ print(f"❌ Rust 构建验证失败(耗时 {duration:.2f} 秒)")
78
+ if error_message:
79
+ print(f"错误信息:\n{error_message}")
80
+ else:
81
+ print(f"输出:\n{output[:500]}")
82
+ else:
83
+ error_message = None
84
+ print(f"✅ Rust 构建验证成功(耗时 {duration:.2f} 秒)")
85
+
86
+ return BuildResult(
87
+ success=success,
88
+ output=output,
89
+ error_message=error_message,
90
+ build_system=BuildSystem.RUST,
91
+ duration=duration,
92
+ )
93
+
94
+ def _parse_cargo_errors(self, output: str) -> str:
95
+ """解析cargo的错误输出(包括编译错误和测试失败)"""
96
+ # 简化处理:提取关键错误信息
97
+ lines = output.split("\n")
98
+ errors = []
99
+ for line in lines:
100
+ # 匹配编译错误
101
+ if "error[" in line or "error:" in line.lower():
102
+ errors.append(line.strip())
103
+ # 匹配测试失败
104
+ elif "test" in line.lower() and ("failed" in line.lower() or "panic" in line.lower()):
105
+ errors.append(line.strip())
106
+ # 匹配断言失败
107
+ elif "assertion" in line.lower() and "failed" in line.lower():
108
+ errors.append(line.strip())
109
+ return "\n".join(errors[:10]) if errors else output[:500] # 限制长度
110
+
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ 构建验证器主模块
6
+
7
+ 提供构建验证器的主类,负责协调各个语言的验证器。
8
+ """
9
+
10
+ from typing import Dict, List, Optional
11
+
12
+
13
+ from .base import BuildSystem, BuildValidatorBase, BuildResult
14
+ from .detector import BuildSystemDetector
15
+ from .rust import RustBuildValidator
16
+ from .python import PythonBuildValidator
17
+ from .nodejs import NodeJSBuildValidator
18
+ from .java_maven import JavaMavenBuildValidator
19
+ from .java_gradle import JavaGradleBuildValidator
20
+ from .go import GoBuildValidator
21
+ from .cmake import CMakeBuildValidator
22
+ from .makefile import MakefileBuildValidator
23
+ from .fallback import FallbackBuildValidator
24
+
25
+
26
+ class BuildValidator:
27
+ """构建验证器主类"""
28
+
29
+ def __init__(self, project_root: str, timeout: int = 30):
30
+ self.project_root = project_root
31
+ self.timeout = timeout
32
+ self.detector = BuildSystemDetector(project_root)
33
+
34
+ # 导入配置管理器
35
+ from jarvis.jarvis_code_agent.build_validation_config import BuildValidationConfig
36
+ self.config = BuildValidationConfig(project_root)
37
+
38
+ # 注册构建系统验证器
39
+ self._validators: Dict[BuildSystem, BuildValidatorBase] = {
40
+ BuildSystem.RUST: RustBuildValidator(project_root, timeout),
41
+ BuildSystem.PYTHON: PythonBuildValidator(project_root, timeout),
42
+ BuildSystem.NODEJS: NodeJSBuildValidator(project_root, timeout),
43
+ BuildSystem.JAVA_MAVEN: JavaMavenBuildValidator(project_root, timeout),
44
+ BuildSystem.JAVA_GRADLE: JavaGradleBuildValidator(project_root, timeout),
45
+ BuildSystem.GO: GoBuildValidator(project_root, timeout),
46
+ BuildSystem.C_CMAKE: CMakeBuildValidator(project_root, timeout),
47
+ BuildSystem.C_MAKEFILE: MakefileBuildValidator(project_root, timeout),
48
+ BuildSystem.C_MAKEFILE_CMAKE: CMakeBuildValidator(project_root, timeout),
49
+ }
50
+
51
+ # 兜底验证器
52
+ self._fallback_validator = FallbackBuildValidator(project_root, timeout)
53
+
54
+ def _select_build_system(self, detected_systems: List[BuildSystem]) -> Optional[BuildSystem]:
55
+ """让用户选择构建系统
56
+
57
+ Args:
58
+ detected_systems: 检测到的所有构建系统列表
59
+
60
+ Returns:
61
+ 用户选择的构建系统,如果用户取消则返回None
62
+ """
63
+ if not detected_systems:
64
+ return None
65
+
66
+ if len(detected_systems) == 1:
67
+ # 只有一个构建系统,直接返回
68
+ return detected_systems[0]
69
+
70
+ # 检查配置文件中是否已有选择
71
+ saved_system = self.config.get_selected_build_system()
72
+ if saved_system:
73
+ try:
74
+ saved_enum = BuildSystem(saved_system)
75
+ if saved_enum in detected_systems:
76
+ print(f"ℹ️ 使用配置文件中保存的构建系统: {saved_system}")
77
+ return saved_enum
78
+ except ValueError:
79
+ # 配置文件中保存的构建系统无效,忽略
80
+ pass
81
+
82
+ # 多个构建系统,需要用户选择
83
+ print("\n检测到多个构建系统,请选择要使用的构建系统:")
84
+ for idx, system in enumerate(detected_systems, start=1):
85
+ print(f" {idx}. {system.value}")
86
+ print(f" {len(detected_systems) + 1}. 取消(使用兜底验证器)")
87
+
88
+ while True:
89
+ try:
90
+ choice = input(f"\n请选择 (1-{len(detected_systems) + 1}): ").strip()
91
+ choice_num = int(choice)
92
+
93
+ if 1 <= choice_num <= len(detected_systems):
94
+ selected = detected_systems[choice_num - 1]
95
+ # 保存用户选择
96
+ self.config.set_selected_build_system(selected.value)
97
+ print(f"ℹ️ 用户选择构建系统: {selected.value}")
98
+ return selected
99
+ elif choice_num == len(detected_systems) + 1:
100
+ print("ℹ️ 用户取消选择,使用兜底验证器")
101
+ return None
102
+ else:
103
+ print(f"无效选择,请输入 1-{len(detected_systems) + 1}")
104
+ except ValueError:
105
+ print("请输入有效的数字")
106
+ except (KeyboardInterrupt, EOFError):
107
+ print("\n用户取消,使用兜底验证器")
108
+ return None
109
+
110
+ def validate(self, modified_files: Optional[List[str]] = None) -> BuildResult:
111
+ """验证构建
112
+
113
+ Args:
114
+ modified_files: 修改的文件列表(可选,用于增量验证)
115
+
116
+ Returns:
117
+ BuildResult: 验证结果
118
+ """
119
+ # 检测所有可能的构建系统
120
+ detected_systems = self.detector.detect_all()
121
+
122
+ if not detected_systems:
123
+ # 未检测到构建系统,使用兜底验证器
124
+ print("ℹ️ 未检测到构建系统,使用兜底验证器")
125
+ return self._fallback_validator.validate(modified_files)
126
+
127
+ # 让用户选择构建系统(如果多个)
128
+ build_system = self._select_build_system(detected_systems)
129
+
130
+ if build_system and build_system in self._validators:
131
+ validator = self._validators[build_system]
132
+ print(f"ℹ️ 使用构建系统: {build_system.value}, 验证器: {validator.__class__.__name__}")
133
+ try:
134
+ return validator.validate(modified_files)
135
+ except Exception as e:
136
+ print(f"⚠️ 验证器 {validator.__class__.__name__} 执行失败: {e}, 使用兜底验证器")
137
+ # 验证器执行失败时,使用兜底验证器
138
+ return self._fallback_validator.validate(modified_files)
139
+ else:
140
+ # 用户取消或未选择,使用兜底验证器
141
+ print("ℹ️ 使用兜底验证器")
142
+ return self._fallback_validator.validate(modified_files)
143
+
144
+ def register_validator(self, build_system: BuildSystem, validator: BuildValidatorBase):
145
+ """注册自定义验证器(扩展点)
146
+
147
+ Args:
148
+ build_system: 构建系统类型
149
+ validator: 验证器实例
150
+ """
151
+ self._validators[build_system] = validator
152
+ print(f"ℹ️ 注册自定义验证器: {build_system.value} -> {validator.__class__.__name__}")
153
+
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ 构建验证模块(向后兼容导入)
6
+
7
+ 此文件保持向后兼容,实际实现已迁移到 build_validator 包中。
8
+ """
9
+
10
+ # 从新模块导入所有内容,保持向后兼容
11
+ from jarvis.jarvis_code_agent.code_analyzer.build_validator import (
12
+ BuildSystem,
13
+ BuildResult,
14
+ BuildValidatorBase,
15
+ BuildSystemDetector,
16
+ BuildValidator,
17
+ RustBuildValidator,
18
+ PythonBuildValidator,
19
+ NodeJSBuildValidator,
20
+ JavaMavenBuildValidator,
21
+ JavaGradleBuildValidator,
22
+ GoBuildValidator,
23
+ CMakeBuildValidator,
24
+ MakefileBuildValidator,
25
+ FallbackBuildValidator,
26
+ )
27
+
28
+ __all__ = [
29
+ "BuildSystem",
30
+ "BuildResult",
31
+ "BuildValidatorBase",
32
+ "BuildSystemDetector",
33
+ "BuildValidator",
34
+ "RustBuildValidator",
35
+ "PythonBuildValidator",
36
+ "NodeJSBuildValidator",
37
+ "JavaMavenBuildValidator",
38
+ "JavaGradleBuildValidator",
39
+ "GoBuildValidator",
40
+ "CMakeBuildValidator",
41
+ "MakefileBuildValidator",
42
+ "FallbackBuildValidator",
43
+ ]