siada-cli 0.0.1__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 (215) hide show
  1. agent_config.yaml +34 -0
  2. siada/__init__.py +13 -0
  3. siada/agent_hub/__init__.py +10 -0
  4. siada/agent_hub/coder/bug_fix_agent.py +398 -0
  5. siada/agent_hub/coder/code_gen_agent.py +235 -0
  6. siada/agent_hub/coder/fe_gen_agent.py +37 -0
  7. siada/agent_hub/coder/issue_review_agent.py +68 -0
  8. siada/agent_hub/coder/prompt/__init__.py +0 -0
  9. siada/agent_hub/coder/prompt/base/__init__.py +0 -0
  10. siada/agent_hub/coder/prompt/base/capabilities.py +18 -0
  11. siada/agent_hub/coder/prompt/base/non_interactive.py +14 -0
  12. siada/agent_hub/coder/prompt/base/prompt_builder.py +33 -0
  13. siada/agent_hub/coder/prompt/base/rules.py +40 -0
  14. siada/agent_hub/coder/prompt/base/tool_use.py +14 -0
  15. siada/agent_hub/coder/prompt/bug_prompt/bug_fix_prompt.py +51 -0
  16. siada/agent_hub/coder/prompt/bug_prompt/rules.py +53 -0
  17. siada/agent_hub/coder/prompt/code_gen_prompt.py +45 -0
  18. siada/agent_hub/coder/prompt/fe_gen_prompt.py +45 -0
  19. siada/agent_hub/coder/prompt/issue_review_prompt.py +121 -0
  20. siada/agent_hub/coder/tracing/__init__.py +22 -0
  21. siada/agent_hub/coder/tracing/logger_tracing_processor.py +458 -0
  22. siada/agent_hub/hooks/__init__.py +0 -0
  23. siada/agent_hub/hooks/io_hooks.py +30 -0
  24. siada/agent_hub/siada_agent.py +214 -0
  25. siada/config/__init__.py +0 -0
  26. siada/config/config_loader.py +67 -0
  27. siada/entrypoint/__init__.py +3 -0
  28. siada/entrypoint/args_parser/__init__.py +0 -0
  29. siada/entrypoint/args_parser/args.py +195 -0
  30. siada/entrypoint/interaction/__init__.py +0 -0
  31. siada/entrypoint/interaction/base_turn.py +107 -0
  32. siada/entrypoint/interaction/config.py +30 -0
  33. siada/entrypoint/interaction/controller.py +122 -0
  34. siada/entrypoint/interaction/nointeractive_controller.py +27 -0
  35. siada/entrypoint/interaction/turn/interface.py +116 -0
  36. siada/entrypoint/interaction/turn/models.py +34 -0
  37. siada/entrypoint/interaction/turn/run_turn.py +641 -0
  38. siada/entrypoint/interaction/turn_factory.py +35 -0
  39. siada/entrypoint/interaction/turn_models.py +28 -0
  40. siada/entrypoint/siadahub.py +413 -0
  41. siada/foundation/__init__.py +0 -0
  42. siada/foundation/code_agent_context.py +48 -0
  43. siada/foundation/config.py +59 -0
  44. siada/foundation/constants.py +2 -0
  45. siada/foundation/context.py +76 -0
  46. siada/foundation/logging.py +341 -0
  47. siada/foundation/tools/__init__.py +0 -0
  48. siada/foundation/tools/get_git_diff.py +105 -0
  49. siada/io/__init__.py +0 -0
  50. siada/io/banner.py +148 -0
  51. siada/io/color_settings.py +207 -0
  52. siada/io/color_utils.py +16 -0
  53. siada/io/components/__init__.py +0 -0
  54. siada/io/components/mdstream.py +204 -0
  55. siada/io/console_printer.py +68 -0
  56. siada/io/io.py +661 -0
  57. siada/io/key_bindings.py +129 -0
  58. siada/io/notification_command.py +40 -0
  59. siada/io/test_banner.py +64 -0
  60. siada/models/__init__.py +0 -0
  61. siada/models/agent.py +47 -0
  62. siada/models/coder/__init__.py +0 -0
  63. siada/models/converter.py +27 -0
  64. siada/models/model_base_config.py +121 -0
  65. siada/models/model_run_config.py +153 -0
  66. siada/provider/__init__.py +0 -0
  67. siada/provider/client_factory.py +112 -0
  68. siada/provider/llm_client.py +11 -0
  69. siada/provider/openrouter/__init__.py +0 -0
  70. siada/provider/openrouter/coverter.py +17 -0
  71. siada/provider/openrouter/openroute_provider.py +33 -0
  72. siada/provider/provider_factory.py +53 -0
  73. siada/queries/tree-sitter-language-pack/README.md +7 -0
  74. siada/queries/tree-sitter-language-pack/arduino-tags.scm +5 -0
  75. siada/queries/tree-sitter-language-pack/c-tags.scm +9 -0
  76. siada/queries/tree-sitter-language-pack/chatito-tags.scm +16 -0
  77. siada/queries/tree-sitter-language-pack/commonlisp-tags.scm +122 -0
  78. siada/queries/tree-sitter-language-pack/cpp-tags.scm +15 -0
  79. siada/queries/tree-sitter-language-pack/csharp-tags.scm +26 -0
  80. siada/queries/tree-sitter-language-pack/d-tags.scm +26 -0
  81. siada/queries/tree-sitter-language-pack/dart-tags.scm +92 -0
  82. siada/queries/tree-sitter-language-pack/elisp-tags.scm +5 -0
  83. siada/queries/tree-sitter-language-pack/elixir-tags.scm +54 -0
  84. siada/queries/tree-sitter-language-pack/elm-tags.scm +19 -0
  85. siada/queries/tree-sitter-language-pack/gleam-tags.scm +41 -0
  86. siada/queries/tree-sitter-language-pack/go-tags.scm +42 -0
  87. siada/queries/tree-sitter-language-pack/java-tags.scm +20 -0
  88. siada/queries/tree-sitter-language-pack/javascript-tags.scm +88 -0
  89. siada/queries/tree-sitter-language-pack/lua-tags.scm +34 -0
  90. siada/queries/tree-sitter-language-pack/ocaml-tags.scm +115 -0
  91. siada/queries/tree-sitter-language-pack/ocaml_interface-tags.scm +98 -0
  92. siada/queries/tree-sitter-language-pack/pony-tags.scm +39 -0
  93. siada/queries/tree-sitter-language-pack/properties-tags.scm +5 -0
  94. siada/queries/tree-sitter-language-pack/python-tags.scm +14 -0
  95. siada/queries/tree-sitter-language-pack/r-tags.scm +21 -0
  96. siada/queries/tree-sitter-language-pack/racket-tags.scm +12 -0
  97. siada/queries/tree-sitter-language-pack/ruby-tags.scm +64 -0
  98. siada/queries/tree-sitter-language-pack/rust-tags.scm +60 -0
  99. siada/queries/tree-sitter-language-pack/solidity-tags.scm +43 -0
  100. siada/queries/tree-sitter-language-pack/swift-tags.scm +51 -0
  101. siada/queries/tree-sitter-language-pack/udev-tags.scm +20 -0
  102. siada/queries/tree-sitter-languages/README.md +23 -0
  103. siada/queries/tree-sitter-languages/c-tags.scm +9 -0
  104. siada/queries/tree-sitter-languages/c_sharp-tags.scm +46 -0
  105. siada/queries/tree-sitter-languages/cpp-tags.scm +15 -0
  106. siada/queries/tree-sitter-languages/dart-tags.scm +91 -0
  107. siada/queries/tree-sitter-languages/elisp-tags.scm +8 -0
  108. siada/queries/tree-sitter-languages/elixir-tags.scm +54 -0
  109. siada/queries/tree-sitter-languages/elm-tags.scm +19 -0
  110. siada/queries/tree-sitter-languages/go-tags.scm +30 -0
  111. siada/queries/tree-sitter-languages/hcl-tags.scm +77 -0
  112. siada/queries/tree-sitter-languages/java-tags.scm +20 -0
  113. siada/queries/tree-sitter-languages/javascript-tags.scm +88 -0
  114. siada/queries/tree-sitter-languages/kotlin-tags.scm +27 -0
  115. siada/queries/tree-sitter-languages/ocaml-tags.scm +115 -0
  116. siada/queries/tree-sitter-languages/ocaml_interface-tags.scm +98 -0
  117. siada/queries/tree-sitter-languages/php-tags.scm +26 -0
  118. siada/queries/tree-sitter-languages/python-tags.scm +12 -0
  119. siada/queries/tree-sitter-languages/ql-tags.scm +26 -0
  120. siada/queries/tree-sitter-languages/ruby-tags.scm +64 -0
  121. siada/queries/tree-sitter-languages/rust-tags.scm +60 -0
  122. siada/queries/tree-sitter-languages/scala-tags.scm +65 -0
  123. siada/queries/tree-sitter-languages/typescript-tags.scm +41 -0
  124. siada/services/__init__.py +30 -0
  125. siada/services/at_file_recommendation_design_document.md +1213 -0
  126. siada/services/code_context_manager.py +136 -0
  127. siada/services/enhanced_fix_result_check.py +546 -0
  128. siada/services/execution_trace_collector.py +207 -0
  129. siada/services/file_recommendation/__init__.py +136 -0
  130. siada/services/file_recommendation/core/__init__.py +17 -0
  131. siada/services/file_recommendation/core/completion_engine.py +351 -0
  132. siada/services/file_recommendation/core/config.py +62 -0
  133. siada/services/file_recommendation/core/file_discovery.py +353 -0
  134. siada/services/file_recommendation/core/suggestion.py +110 -0
  135. siada/services/file_recommendation/utils/__init__.py +22 -0
  136. siada/services/file_recommendation/utils/path_utils.py +138 -0
  137. siada/services/file_recommendation/utils/text_utils.py +253 -0
  138. siada/services/fix_result_check.py +377 -0
  139. siada/services/handle_at_command/README.md +247 -0
  140. siada/services/handle_at_command/__init__.py +115 -0
  141. siada/services/handle_at_command/exceptions.py +46 -0
  142. siada/services/handle_at_command/models.py +92 -0
  143. siada/services/handle_at_command/parser.py +189 -0
  144. siada/services/handle_at_command/processor.py +321 -0
  145. siada/services/handle_at_command/resolver.py +318 -0
  146. siada/services/handle_at_command/utils.py +345 -0
  147. siada/services/model_info_service.py +103 -0
  148. siada/services/siada_runner.py +170 -0
  149. siada/session/__init__.py +29 -0
  150. siada/session/session_manager.py +66 -0
  151. siada/session/session_models.py +43 -0
  152. siada/support/__init__.py +0 -0
  153. siada/support/completer.py +204 -0
  154. siada/support/editor.py +146 -0
  155. siada/support/envprocessor.py +54 -0
  156. siada/support/repo.py +51 -0
  157. siada/support/slash_commands.py +410 -0
  158. siada/support/spinner.py +320 -0
  159. siada/tools/__init__.py +0 -0
  160. siada/tools/ast/README.md +345 -0
  161. siada/tools/ast/ast_tool.py +341 -0
  162. siada/tools/ast/models.py +11 -0
  163. siada/tools/coder/__init__.py +0 -0
  164. siada/tools/coder/ask_followup_question.py +70 -0
  165. siada/tools/coder/cmd_runner.py +132 -0
  166. siada/tools/coder/file_operator.py +284 -0
  167. siada/tools/coder/file_search/README.md +223 -0
  168. siada/tools/coder/file_search/__init__.py +10 -0
  169. siada/tools/coder/file_search/bin/rg-linux-arm64 +0 -0
  170. siada/tools/coder/file_search/bin/rg-linux-x64 +0 -0
  171. siada/tools/coder/file_search/bin/rg-macos-arm64 +0 -0
  172. siada/tools/coder/file_search/bin/rg-macos-x64 +0 -0
  173. siada/tools/coder/file_search/bin/rg.exe +0 -0
  174. siada/tools/coder/file_search/search.py +437 -0
  175. siada/tools/coder/file_search/setup_package.py +150 -0
  176. siada/tools/coder/file_search/test_search.py +142 -0
  177. siada/tools/coder/files.py +147 -0
  178. siada/tools/coder/fix_attempt_completion.py +58 -0
  179. siada/tools/coder/issue_review_completion.py +29 -0
  180. siada/tools/coder/observation/__init__.py +0 -0
  181. siada/tools/coder/observation/error.py +22 -0
  182. siada/tools/coder/observation/file_observation.py +216 -0
  183. siada/tools/coder/observation/observation.py +71 -0
  184. siada/tools/coder/repo_map/__init__.py +157 -0
  185. siada/tools/coder/repo_map/dump.py +29 -0
  186. siada/tools/coder/repo_map/io.py +226 -0
  187. siada/tools/coder/repo_map/repo_map.py +881 -0
  188. siada/tools/coder/repo_map/special.py +203 -0
  189. siada/tools/coder/repo_map/token_counter.py +154 -0
  190. siada/tools/coder/repo_map/waiting.py +221 -0
  191. siada/tools/coder/reproduce_completion.py +39 -0
  192. siada/tools/coder/run_cmd.py +60 -0
  193. siada/tools/coder/test_completion.py +25 -0
  194. siada/tools/coder/tool_docs.py +44 -0
  195. siada/tools/compression_tool.py +200 -0
  196. siada/tools/read_many_files/README.md +220 -0
  197. siada/tools/read_many_files/__init__.py +25 -0
  198. siada/tools/read_many_files/file_processor.py +486 -0
  199. siada/tools/read_many_files/filters.py +326 -0
  200. siada/tools/read_many_files/formatters.py +204 -0
  201. siada/tools/read_many_files/models.py +189 -0
  202. siada/tools/read_many_files_tool.py +233 -0
  203. siada/tools/tool_call_format/__init__.py +55 -0
  204. siada/tools/tool_call_format/file_to_language.py +231 -0
  205. siada/tools/tool_call_format/formatter_factory.py +80 -0
  206. siada/tools/tool_call_format/formatters.py +282 -0
  207. siada/tools/tool_call_format/tool_call_formatter.py +54 -0
  208. siada/tools/web/__init__.py +0 -0
  209. siada/tools/web/web_crawl.py +208 -0
  210. siada/utils.py +194 -0
  211. siada_cli-0.0.1.dist-info/LICENSE +201 -0
  212. siada_cli-0.0.1.dist-info/METADATA +457 -0
  213. siada_cli-0.0.1.dist-info/RECORD +215 -0
  214. siada_cli-0.0.1.dist-info/WHEEL +4 -0
  215. siada_cli-0.0.1.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,136 @@
1
+ """
2
+ 混合上下文管理器
3
+ 结合TracingProcessor和AgentHooks来确保完整的消息历史维护
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+ from agents import Agent, RunContextWrapper
10
+ from agents.lifecycle import AgentHooks
11
+ from agents.tool import Tool
12
+ from agents.tracing import TracingProcessor, Trace, Span
13
+ from agents.tracing.span_data import GenerationSpanData, FunctionSpanData
14
+ from agents.items import TResponseInputItem
15
+
16
+ from siada.foundation.code_agent_context import CodeAgentContext
17
+
18
+
19
+ class ContextHooks(AgentHooks[CodeAgentContext]):
20
+ """混合上下文管理器
21
+
22
+ 使用AgentHooks来捕获Agent级别的事件,
23
+ 确保用户输入和助手输出都被正确记录
24
+ """
25
+
26
+ def __init__(self):
27
+ super().__init__()
28
+ print("🔧 HybridContextManager 初始化完成")
29
+
30
+ async def on_start(
31
+ self,
32
+ context: RunContextWrapper[CodeAgentContext],
33
+ agent: Agent[CodeAgentContext]
34
+ ) -> None:
35
+ pass
36
+
37
+
38
+ async def on_end(
39
+ self,
40
+ context: RunContextWrapper[CodeAgentContext],
41
+ agent: Agent[CodeAgentContext],
42
+ output: Any
43
+ ) -> None:
44
+ pass
45
+
46
+ async def on_tool_start(
47
+ self,
48
+ context: RunContextWrapper[CodeAgentContext],
49
+ agent: Agent[CodeAgentContext],
50
+ tool: Tool
51
+ ) -> None:
52
+ pass
53
+
54
+ async def on_tool_end(
55
+ self,
56
+ context: RunContextWrapper[CodeAgentContext],
57
+ agent: Agent[CodeAgentContext],
58
+ tool: Tool,
59
+ result: str
60
+ ) -> None:
61
+ if tool.name == "compress_context_tool" and context.context:
62
+ try:
63
+ # 解析工具返回的结果
64
+ import json
65
+ compression_result = json.loads(result)
66
+
67
+ # 检查压缩是否成功
68
+ if compression_result.get("status") == 1:
69
+ start_index = compression_result.get("start_index")
70
+ end_index = compression_result.get("end_index")
71
+ summary = compression_result.get("summary")
72
+
73
+ # 验证索引有效性
74
+ if (start_index is not None and end_index is not None and
75
+ 0 <= start_index < end_index <= len(context.context.message_history)):
76
+
77
+ # 删除被压缩的消息范围
78
+ del context.context.message_history[start_index:end_index]
79
+
80
+ # 在删除位置插入压缩摘要作为新消息
81
+ summary_message = {
82
+ "role": "system",
83
+ "content": summary
84
+ }
85
+ context.context.message_history.insert(start_index, summary_message)
86
+
87
+ print(f"✅ 成功压缩消息 [{start_index}:{end_index}],替换为摘要")
88
+ else:
89
+ print(f"❌ 压缩索引无效: start_index={start_index}, end_index={end_index}")
90
+ else:
91
+ print(f"❌ 压缩失败: {compression_result.get('summary', '未知错误')}")
92
+
93
+ except json.JSONDecodeError as e:
94
+ print(f"❌ 解析压缩工具结果失败: {e}")
95
+ except Exception as e:
96
+ print(f"❌ 处理压缩结果时发生错误: {e}")
97
+
98
+
99
+ class ContextTracingProcessor(TracingProcessor):
100
+
101
+
102
+ def __init__(self, context: CodeAgentContext):
103
+ self.context = context
104
+
105
+ def on_trace_start(self, trace: "Trace") -> None:
106
+ pass
107
+
108
+ def on_span_start(self, span: "Span[Any]") -> None:
109
+
110
+
111
+ if hasattr(span.span_data, "input") and span.span_data.input:
112
+ if isinstance(span.span_data.input, list):
113
+ self.context.message_history = span.span_data.input
114
+ else:
115
+ self.context.add_message(span.span_data.input)
116
+
117
+
118
+ def on_span_end(self, span: "Span[Any]") -> None:
119
+
120
+ if hasattr(span.span_data, "output"):
121
+ output = span.span_data.output
122
+ if output:
123
+ if isinstance(output, list):
124
+ self.context.add_messages(output)
125
+ else:
126
+ self.context.add_message(output)
127
+
128
+
129
+ def on_trace_end(self, trace: "Trace") -> None:
130
+ pass
131
+
132
+ def shutdown(self) -> None:
133
+ pass
134
+
135
+ def force_flush(self) -> None:
136
+ pass
@@ -0,0 +1,546 @@
1
+ """
2
+ Enhanced Fix Result Checker with Execution Trace Analysis
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ from typing import Dict, Any, Optional
8
+
9
+ from openai.types.chat import ChatCompletionMessageParam
10
+
11
+ from siada.provider.client_factory import get_client_with_kwargs
12
+ from siada.foundation.config import settings
13
+ from siada.services.execution_trace_collector import ExecutionTrace
14
+
15
+
16
+ class EnhancedFixResultChecker:
17
+ """Enhanced Fix Result Checker
18
+ """
19
+
20
+ async def check_with_trace(
21
+ self,
22
+ issue_desc: str,
23
+ fix_code: str,
24
+ context: Any,
25
+ execution_trace: Optional[ExecutionTrace] = None
26
+ ) -> Dict[str, Any]:
27
+ """check the fix result with enhanced analysis
28
+
29
+ Args:
30
+ issue_desc
31
+ fix_code
32
+ execution_trace
33
+
34
+ Returns:
35
+ Dict[str, Any]:
36
+ {
37
+ "is_fixed": bool,
38
+ "check_summary": str,
39
+ "fix_analysis": str,
40
+ "trace_analysis": str,
41
+ "efficiency_suggestions": List[str],
42
+ "strategy_suggestions": List[str],
43
+ "overall_score": float,
44
+
45
+ "expert_assessment": {
46
+ "confidence_level": str,
47
+ "technical_depth_analysis": {},
48
+ "cognitive_analysis": {}
49
+ },
50
+ "execution_intelligence": {
51
+ "strategy_effectiveness": {},
52
+ "efficiency_analysis": {},
53
+ "learning_patterns": {}
54
+ },
55
+ "professional_recommendations": {
56
+ "immediate_actions": [],
57
+ "strategic_improvements": [],
58
+ "learning_opportunities": []
59
+ },
60
+ "risk_assessment": {
61
+ "production_risks": [],
62
+ "technical_debt_impact": str,
63
+ "regression_potential": str
64
+ },
65
+ "quality_metrics": {
66
+ "detailed_scores": {},
67
+ "score_justification": str
68
+ },
69
+ "executive_summary": {
70
+ "verdict": str,
71
+ "key_concerns": str,
72
+ "success_criteria": str,
73
+ "next_steps": str
74
+ }
75
+ }
76
+ """
77
+ try:
78
+ analysis_result = await self._call_model_for_enhanced_analysis(
79
+ issue_desc, fix_code, context, execution_trace
80
+ )
81
+ return self._parse_enhanced_analysis_result(analysis_result)
82
+ except Exception as e:
83
+ return {
84
+ "is_fixed": False,
85
+ "check_summary": f"Error: {str(e)}",
86
+ "fix_analysis": f"Error details: {str(e)}",
87
+ "trace_analysis": "",
88
+ "efficiency_suggestions": [],
89
+ "strategy_suggestions": [],
90
+ "overall_score": 0.0
91
+ }
92
+
93
+ async def _call_model_for_enhanced_analysis(
94
+ self,
95
+ issue_desc: str,
96
+ fix_code: str,
97
+ context: Any,
98
+ execution_trace: Optional[ExecutionTrace]
99
+ ) -> str:
100
+ """call the model for enhanced analysis
101
+
102
+ Args:
103
+ issue_desc
104
+ fix_code
105
+ execution_trace
106
+
107
+ Returns:
108
+ str: the analysis result in JSON format
109
+ """
110
+ user_task = self._build_enhanced_prompt(issue_desc, fix_code, execution_trace)
111
+
112
+ model_messages: list[ChatCompletionMessageParam] = [
113
+ {"role": "user", "content": user_task},
114
+ ]
115
+
116
+ print("Enhanced checking fix task with trace analysis...")
117
+
118
+ # Call the model with context support
119
+ default_kwargs = {
120
+ "model": settings.Claude_4_0_SONNET,
121
+ "messages": model_messages,
122
+ "stream": False,
123
+ "temperature": 0.2, # Lower temperature for accuracy
124
+ }
125
+
126
+ # Use get_client_with_kwargs to support context parameter overrides
127
+ client, complete_kwargs = get_client_with_kwargs(context, default_kwargs)
128
+ response = await client.chat_complete(**complete_kwargs)
129
+
130
+ if response and response.choices and response.choices[0].message:
131
+ analysis = response.choices[0].message.content
132
+ if analysis:
133
+ return analysis.strip()
134
+
135
+ raise Exception("can't get analysis result from model response")
136
+
137
+ def _build_enhanced_prompt(
138
+ self,
139
+ issue_desc: str,
140
+ fix_code: str,
141
+ execution_trace: Optional[ExecutionTrace]
142
+ ) -> str:
143
+
144
+ expert_prompt = f"""
145
+ # 🎯 **SIADA PROJECT EXPERT & PR ANALYSIS SPECIALIST**
146
+
147
+ You are **Siada**, a **Senior Software Architect** and **AI Agent Execution Specialist** with 15+ years of experience in:
148
+
149
+ ## **🔧 CORE EXPERTISE**
150
+ - **Enterprise Software Architecture**: Microservices, distributed systems, scalability patterns
151
+ - **Code Quality & Security**: SOLID principles, security vulnerabilities, performance optimization
152
+ - **AI Agent Behavior Analysis**: Execution pattern recognition, strategy optimization, failure analysis
153
+ - **Pull Request Deep Review**: Impact assessment, regression analysis, integration concerns
154
+ - **Root Cause Investigation**: Multi-layer problem decomposition, systemic issue identification
155
+ - **Project Context Understanding**: Business logic, domain constraints, technical debt implications
156
+
157
+ ---
158
+
159
+ ## **🎯 MISSION: COMPREHENSIVE PR IMPACT ANALYSIS**
160
+
161
+ As a **project expert with deep codebase knowledge**, your mission is to:
162
+
163
+ 1. **🔍 Perform forensic analysis** of the issue and proposed fix
164
+ 2. **🧠 Identify cognitive biases** and thinking errors in the fix approach
165
+ 3. **⚡ Assess execution strategy effectiveness** from the trace data
166
+ 4. **🎯 Provide actionable insights** for both immediate fixes and long-term improvements
167
+ 5. **📊 Deliver a professional assessment** that prevents production incidents
168
+
169
+ ---
170
+
171
+ ## **📋 ANALYSIS FRAMEWORK**
172
+
173
+ ### **🔍 PHASE 1: ISSUE FORENSICS & CONTEXT ANALYSIS**
174
+
175
+ #### **1.1 Multi-Dimensional Issue Decomposition**
176
+ - **🎯 Primary Problem**: Core functional failure or requirement gap
177
+ - **🔗 Dependency Chain**: What upstream/downstream components are affected?
178
+ - **👥 User Impact**: Which user journeys, APIs, or business processes break?
179
+ - **⏰ Timing Concerns**: Race conditions, async issues, state management problems
180
+ - **🔒 Security Implications**: Authentication, authorization, data exposure risks
181
+ - **📈 Performance Impact**: Scalability, memory usage, database query implications
182
+
183
+ #### **1.2 Business & Technical Context Assessment**
184
+ - **💼 Business Logic Constraints**: Domain rules, compliance requirements, workflow dependencies
185
+ - **🏗️ Architectural Patterns**: How does this fit with existing design patterns?
186
+ - **📚 Technical Debt**: What legacy constraints or shortcuts affect the solution space?
187
+ - **🔄 Integration Points**: APIs, databases, external services, event systems
188
+ - **🧪 Testing Strategy**: Unit, integration, end-to-end testing requirements
189
+
190
+ ---
191
+
192
+ ### **🧠 PHASE 2: COGNITIVE ANALYSIS & THINKING ERROR DETECTION**
193
+
194
+ #### **2.1 Fix Strategy Evaluation**
195
+ Analyze the **mental model** behind the fix:
196
+ - **🎯 Problem Framing**: Did the agent correctly identify the root cause vs symptoms?
197
+ - **🔍 Scope Definition**: Was the problem boundary appropriately defined?
198
+ - **⚖️ Solution Selection**: Why was this approach chosen over alternatives?
199
+ - **🔄 Implementation Strategy**: Was the execution sequence logical and safe?
200
+ - **✅ Validation Approach**: How was the fix verified and tested?
201
+
202
+ #### **2.2 Critical Thinking Error Categories**
203
+
204
+ **🚨 SCOPE & CONTEXT ERRORS**:
205
+ - **Tunnel Vision**: Focusing only on immediate symptoms
206
+ - **Context Blindness**: Missing project-specific constraints or patterns
207
+ - **Integration Ignorance**: Not considering downstream/upstream effects
208
+
209
+ **🧩 SOLUTION DESIGN ERRORS**:
210
+ - **Pattern Misapplication**: Using inappropriate design patterns
211
+ - **Over-Engineering**: Adding unnecessary complexity
212
+ - **Under-Engineering**: Missing essential robustness features
213
+
214
+ **🔍 VERIFICATION ERRORS**:
215
+ - **Testing Gaps**: Insufficient edge case coverage
216
+ - **Assumption Validation**: Not verifying critical assumptions
217
+ - **Regression Blindness**: Missing potential side effects
218
+
219
+ **⚡ EXECUTION ERRORS**:
220
+ - **Premature Optimization**: Focusing on performance before correctness
221
+ - **Error Handling Gaps**: Missing exception scenarios
222
+ - **State Management Issues**: Concurrency, persistence, consistency problems
223
+
224
+ ---
225
+
226
+ ### **📊 PHASE 3: EXECUTION TRACE DEEP ANALYSIS**
227
+
228
+ #### **3.1 Strategic Decision Analysis**
229
+ From the execution trace, evaluate:
230
+ - **🎯 Problem-Solving Strategy**: Was the approach systematic and thorough?
231
+ - **📚 Information Gathering**: Did the agent collect sufficient context?
232
+ - **🔄 Iterative Refinement**: How well did the agent adapt based on feedback?
233
+ - **⚡ Decision Speed vs Quality**: Balance between efficiency and thoroughness
234
+
235
+ #### **3.2 Tool Usage & Efficiency Assessment**
236
+ - **🛠️ Tool Selection Patterns**: Were the most appropriate tools chosen?
237
+ - **🔄 Call Sequence Optimization**: Could the workflow be more efficient?
238
+ - **❌ Error Recovery**: How well were failures handled and recovered?
239
+ - **💡 Missed Opportunities**: What better approaches were available?
240
+
241
+ ---
242
+
243
+ ## **📝 INPUT DATA**
244
+
245
+ ### **🐛 ISSUE DESCRIPTION**
246
+ ```
247
+ {issue_desc}
248
+ ```
249
+
250
+ ### **🔧 PROPOSED FIX (PR DIFF)**
251
+ ```
252
+ {fix_code}
253
+ ```
254
+
255
+ ---
256
+ """
257
+
258
+ if execution_trace:
259
+ trace_data = execution_trace.to_dict()
260
+ trace_section = f"""
261
+ ### **📈 EXECUTION TRACE DATA**
262
+ ```json
263
+ {json.dumps(trace_data, indent=2, ensure_ascii=False)}
264
+ ```
265
+
266
+ ### **🔍 TRACE ANALYSIS REQUIREMENTS**
267
+
268
+ #### **3.3 Execution Pattern Analysis**
269
+ 1. **🧠 Model Interaction Quality**:
270
+ - **Prompt Engineering**: Were the prompts clear, specific, and context-rich?
271
+ - **Response Utilization**: How effectively were model responses used?
272
+ - **Conversation Flow**: Was the dialogue with the model productive?
273
+ - **Token Efficiency**: Was the context window used optimally?
274
+
275
+ 2. **🛠️ Tool Orchestration Analysis**:
276
+ - **Tool Selection Logic**: Why were specific tools chosen at each step?
277
+ - **Parameter Optimization**: Were tool parameters configured optimally?
278
+ - **Error Handling**: How were tool failures managed and recovered?
279
+ - **Workflow Efficiency**: Could the tool sequence be optimized?
280
+
281
+ 3. **⏱️ Execution Timeline Analysis**:
282
+ - **Critical Path**: What were the bottlenecks in the execution?
283
+ - **Parallel Opportunities**: Could any operations be parallelized?
284
+ - **Resource Utilization**: Was compute/memory used efficiently?
285
+ - **Failure Points**: Where did the execution struggle or fail?
286
+
287
+ #### **3.4 Strategic Learning Analysis**
288
+ - **📚 Context Accumulation**: How did understanding evolve throughout execution?
289
+ - **🔄 Adaptation Patterns**: How well did the agent adapt to new information?
290
+ - **🎯 Goal Refinement**: Did the objectives become clearer over time?
291
+ - **💡 Insight Generation**: What key insights emerged during execution?
292
+
293
+ ---
294
+ """
295
+ expert_prompt += trace_section
296
+
297
+ output_requirements = """
298
+ ## **📋 EXPERT-LEVEL OUTPUT REQUIREMENTS**
299
+
300
+ ### **🎯 CHECK SUMMARY SPECIFICATION**
301
+
302
+ The `check_summary` is your **PROFESSIONAL ASSESSMENT** as a senior architect. It must be:
303
+
304
+ 1. **🔍 Forensically Detailed**: Specific evidence-based analysis, not generic observations
305
+ 2. **🧠 Cognitively Aware**: Explicit identification of thinking patterns and biases
306
+ 3. **⚡ Strategically Insightful**: Clear understanding of why certain approaches were chosen
307
+ 4. **🎯 Impact-Focused**: Concrete consequences and risk assessment
308
+ 5. **💡 Solution-Oriented**: Actionable recommendations for improvement
309
+
310
+ **🏆 PROFESSIONAL CHECK SUMMARY FORMAT**:
311
+ ```
312
+ "check_summary": "🔍 **EXPERT ANALYSIS**: [Specific technical assessment]. 🧠 **COGNITIVE PATTERN**: [Thinking approach analysis]. ⚠️ **CRITICAL GAPS**: [Missing considerations with evidence]. 🎯 **IMPACT ASSESSMENT**: [Concrete consequences]. 💡 **STRATEGIC RECOMMENDATION**: [Professional guidance for resolution]."
313
+ ```
314
+
315
+ ### **📊 REQUIRED EXPERT OUTPUT FORMAT**
316
+
317
+ ```json
318
+ {
319
+ "expert_assessment": {
320
+ "is_fixed": false,
321
+ "confidence_level": "High|Medium|Low",
322
+ "check_summary": "🔍 **EXPERT ANALYSIS**: [Detailed technical assessment with specific evidence]. 🧠 **COGNITIVE PATTERN**: [Analysis of thinking approach and decision-making]. ⚠️ **CRITICAL GAPS**: [Specific missing considerations with concrete examples]. 🎯 **IMPACT ASSESSMENT**: [Detailed consequences and risk analysis]. 💡 **STRATEGIC RECOMMENDATION**: [Professional guidance for complete resolution].",
323
+ "technical_depth_analysis": {
324
+ "architecture_impact": "How this change affects the overall system architecture",
325
+ "integration_concerns": "Specific integration points that may be affected",
326
+ "performance_implications": "Detailed performance impact analysis",
327
+ "security_considerations": "Security vulnerabilities or improvements",
328
+ "maintainability_assessment": "Long-term maintenance and evolution concerns"
329
+ },
330
+ "cognitive_analysis": {
331
+ "problem_framing_quality": "How well was the problem understood and framed",
332
+ "solution_strategy_assessment": "Evaluation of the chosen solution approach",
333
+ "decision_making_patterns": "Analysis of key decisions and their rationale",
334
+ "blind_spots_identified": "Specific areas where awareness was lacking"
335
+ }
336
+ },
337
+ "execution_intelligence": {
338
+ "strategy_effectiveness": {
339
+ "overall_approach": "Assessment of the high-level problem-solving strategy",
340
+ "information_gathering": "Quality and completeness of context collection",
341
+ "solution_development": "How the solution was developed and refined",
342
+ "validation_strategy": "Approach to testing and verification"
343
+ },
344
+ "efficiency_analysis": {
345
+ "resource_utilization": "How efficiently were computational resources used",
346
+ "workflow_optimization": "Analysis of the execution workflow efficiency",
347
+ "bottleneck_identification": "Specific performance bottlenecks identified",
348
+ "improvement_opportunities": "Concrete opportunities for optimization"
349
+ },
350
+ "learning_patterns": {
351
+ "adaptation_quality": "How well the agent adapted to new information",
352
+ "insight_generation": "Quality of insights generated during execution",
353
+ "error_recovery": "How effectively errors and failures were handled",
354
+ "knowledge_integration": "How well different pieces of information were integrated"
355
+ }
356
+ },
357
+ "professional_recommendations": {
358
+ "immediate_actions": [
359
+ "**CRITICAL**: [Urgent action needed to prevent issues]",
360
+ "**IMPORTANT**: [Significant improvement with clear impact]",
361
+ "**RECOMMENDED**: [Good practice improvement]"
362
+ ],
363
+ "strategic_improvements": [
364
+ "**ARCHITECTURE**: [System-level improvements]",
365
+ "**PROCESS**: [Development process enhancements]",
366
+ "**TOOLING**: [Tool and automation improvements]"
367
+ ],
368
+ "learning_opportunities": [
369
+ "**PATTERN RECOGNITION**: [Patterns to learn for future similar issues]",
370
+ "**SKILL DEVELOPMENT**: [Specific skills to develop]",
371
+ "**KNOWLEDGE GAPS**: [Areas requiring deeper understanding]"
372
+ ]
373
+ },
374
+ "risk_assessment": {
375
+ "production_risks": [
376
+ {
377
+ "risk_type": "Performance|Security|Functionality|Integration|Maintenance",
378
+ "severity": "Critical|High|Medium|Low",
379
+ "probability": "High|Medium|Low",
380
+ "description": "Specific risk description with evidence",
381
+ "mitigation": "Concrete steps to mitigate this risk"
382
+ }
383
+ ],
384
+ "technical_debt_impact": "How this change affects technical debt",
385
+ "regression_potential": "Likelihood and areas of potential regressions"
386
+ },
387
+ "quality_metrics": {
388
+ "overall_score": 4.2,
389
+ "detailed_scores": {
390
+ "problem_understanding": 3.5,
391
+ "solution_completeness": 4.0,
392
+ "implementation_quality": 4.5,
393
+ "testing_coverage": 3.0,
394
+ "documentation_quality": 4.0,
395
+ "execution_efficiency": 4.5,
396
+ "strategic_thinking": 3.5
397
+ },
398
+ "score_justification": "Detailed explanation of scoring rationale with specific evidence"
399
+ },
400
+ "executive_summary": {
401
+ "verdict": "**PROFESSIONAL VERDICT**: [Clear assessment of fix quality and completeness]",
402
+ "key_concerns": "**PRIMARY CONCERNS**: [Top 3 most critical issues that must be addressed]",
403
+ "success_criteria": "**SUCCESS CRITERIA**: [Specific criteria that must be met for this to be considered complete]",
404
+ "next_steps": "**RECOMMENDED NEXT STEPS**: [Prioritized action plan for resolution]"
405
+ }
406
+ }
407
+ ```
408
+
409
+ ### **🎯 EXPERT SCORING METHODOLOGY**
410
+
411
+ **📊 SCORING CRITERIA** (0.0 - 10.0 scale):
412
+
413
+ - **🔴 0-2**: **Critical Failure** - Fundamental misunderstanding, introduces new problems
414
+ - **🟠 3-4**: **Significant Issues** - Partially addresses problem but with major gaps
415
+ - **🟡 5-6**: **Adequate with Concerns** - Addresses main issue but missing important aspects
416
+ - **🟢 7-8**: **Good Quality** - Solid solution with minor improvements needed
417
+ - **🔵 9-10**: **Exceptional** - Comprehensive, robust, well-architected solution
418
+
419
+ ### **⚠️ CRITICAL ASSESSMENT RULES**
420
+
421
+ 1. **🚨 ALWAYS set `is_fixed: false`** if ANY of these exist:
422
+ - Incomplete root cause resolution
423
+ - Missing critical edge cases or error handling
424
+ - Performance degradation or scalability concerns
425
+ - Security vulnerabilities introduced or not addressed
426
+ - Integration problems with existing systems
427
+ - Insufficient testing or validation
428
+ - Technical debt increase without justification
429
+
430
+ 2. **🎯 PROFESSIONAL STANDARDS**:
431
+ - **Evidence-Based**: Every claim must be supported by specific evidence
432
+ - **Risk-Aware**: Consider production impact and failure scenarios
433
+ - **Context-Sensitive**: Account for project-specific constraints and patterns
434
+ - **Future-Oriented**: Consider long-term maintenance and evolution
435
+
436
+ 3. **💡 ACTIONABLE INSIGHTS**:
437
+ - Provide specific, implementable recommendations
438
+ - Prioritize suggestions by impact and effort
439
+ - Include concrete examples and code patterns where helpful
440
+ - Focus on both immediate fixes and strategic improvements
441
+
442
+ ---
443
+
444
+ ## **🎯 FINAL DIRECTIVE**
445
+
446
+ Conduct a **forensic-level analysis** as a senior architect would during a critical production incident review. Your assessment will be used to:
447
+
448
+ 1. **🚨 Prevent production incidents** through thorough risk identification
449
+ 2. **📈 Improve development processes** through strategic insights
450
+ 3. **🧠 Enhance AI agent capabilities** through execution pattern analysis
451
+ 4. **🎯 Guide future similar issues** through pattern recognition
452
+
453
+ **Be thorough, be specific, be professional. Lives depend on the software we build.**
454
+ """
455
+
456
+ return expert_prompt + output_requirements
457
+
458
+ def _parse_enhanced_analysis_result(self, analysis_result: str) -> Dict[str, Any]:
459
+ """
460
+ Args:
461
+ analysis_result
462
+
463
+ Returns:
464
+ Dict[str, Any]
465
+ """
466
+ try:
467
+ if not analysis_result or not analysis_result.strip():
468
+ raise ValueError("the analysis result is empty")
469
+
470
+ json_content = analysis_result.strip()
471
+
472
+ if '```json' in json_content:
473
+ json_start = json_content.find('```json')+len('```json')
474
+ json_end = json_content.rfind('```')
475
+
476
+ if json_start != -1 and json_end != -1 and json_end > json_start:
477
+ json_content = json_content[json_start:json_end]
478
+
479
+ if not json_content:
480
+ raise ValueError("the extracted JSON content is empty")
481
+
482
+ parsed_json = json.loads(json_content)
483
+
484
+ expert_assessment = parsed_json.get("expert_assessment", {})
485
+ execution_intelligence = parsed_json.get("execution_intelligence", {})
486
+ professional_recommendations = parsed_json.get("professional_recommendations", {})
487
+ risk_assessment = parsed_json.get("risk_assessment", {})
488
+ quality_metrics = parsed_json.get("quality_metrics", {})
489
+ executive_summary = parsed_json.get("executive_summary", {})
490
+
491
+ result = {
492
+ "is_fixed": expert_assessment.get("is_fixed", False),
493
+ "check_summary": expert_assessment.get("check_summary", "未提供专家分析摘要"),
494
+ "fix_analysis": expert_assessment.get("technical_depth_analysis", {}).get("architecture_impact", "未提供详细分析"),
495
+ "trace_analysis": execution_intelligence.get("strategy_effectiveness", {}).get("overall_approach", "未提供轨迹分析"),
496
+ "efficiency_suggestions": professional_recommendations.get("immediate_actions", []),
497
+ "strategy_suggestions": professional_recommendations.get("strategic_improvements", []),
498
+ "overall_score": quality_metrics.get("overall_score", 0.0),
499
+
500
+ "expert_assessment": {
501
+ "confidence_level": expert_assessment.get("confidence_level", "Medium"),
502
+ "technical_depth_analysis": expert_assessment.get("technical_depth_analysis", {}),
503
+ "cognitive_analysis": expert_assessment.get("cognitive_analysis", {})
504
+ },
505
+
506
+ "execution_intelligence": {
507
+ "strategy_effectiveness": execution_intelligence.get("strategy_effectiveness", {}),
508
+ "efficiency_analysis": execution_intelligence.get("efficiency_analysis", {}),
509
+ "learning_patterns": execution_intelligence.get("learning_patterns", {})
510
+ },
511
+
512
+ "professional_recommendations": {
513
+ "immediate_actions": professional_recommendations.get("immediate_actions", []),
514
+ "strategic_improvements": professional_recommendations.get("strategic_improvements", []),
515
+ "learning_opportunities": professional_recommendations.get("learning_opportunities", [])
516
+ },
517
+
518
+ "risk_assessment": {
519
+ "production_risks": risk_assessment.get("production_risks", []),
520
+ "technical_debt_impact": risk_assessment.get("technical_debt_impact", "未评估"),
521
+ "regression_potential": risk_assessment.get("regression_potential", "未评估")
522
+ },
523
+
524
+ "quality_metrics": {
525
+ "detailed_scores": quality_metrics.get("detailed_scores", {}),
526
+ "score_justification": quality_metrics.get("score_justification", "未提供评分说明")
527
+ },
528
+
529
+ "executive_summary": {
530
+ "verdict": executive_summary.get("verdict", "未提供专业判断"),
531
+ "key_concerns": executive_summary.get("key_concerns", "未识别关键问题"),
532
+ "success_criteria": executive_summary.get("success_criteria", "未定义成功标准"),
533
+ "next_steps": executive_summary.get("next_steps", "未提供后续步骤")
534
+ },
535
+
536
+ "score_breakdown": quality_metrics.get("detailed_scores", {}),
537
+ "overall_summary": executive_summary.get("verdict", "未提供综合评估")
538
+ }
539
+
540
+ return result
541
+
542
+ except (json.JSONDecodeError, ValueError, KeyError) as e:
543
+ raise ValueError(
544
+ f"Failed to parse enhanced analysis result: {str(e)}. "
545
+ "Please ensure the model output is in the correct JSON format."
546
+ )