hermes-agent-evolution 3.0.0__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 (66) hide show
  1. evolution/__init__.py +14 -0
  2. evolution/cli.py +252 -0
  3. evolution/closed_loop/__init__.py +18 -0
  4. evolution/closed_loop/action_executor.py +355 -0
  5. evolution/closed_loop/daemon.py +476 -0
  6. evolution/closed_loop/metrics_collector.py +456 -0
  7. evolution/closed_loop/orchestrator.py +665 -0
  8. evolution/collaboration/__init__.py +57 -0
  9. evolution/collaboration/agent_orchestrator.py +568 -0
  10. evolution/collaboration/agent_registry.py +460 -0
  11. evolution/collaboration/message_bus.py +547 -0
  12. evolution/collaboration/task_dispatcher.py +503 -0
  13. evolution/db_utils.py +235 -0
  14. evolution/fusion/__init__.py +71 -0
  15. evolution/fusion/bridge.py +679 -0
  16. evolution/fusion/compatibility.py +555 -0
  17. evolution/fusion/unified_entry.py +861 -0
  18. evolution/learning/__init__.py +44 -0
  19. evolution/learning/analyzer.py +273 -0
  20. evolution/learning/experience.py +154 -0
  21. evolution/learning/observer.py +474 -0
  22. evolution/learning/pattern_recognizer.py +606 -0
  23. evolution/learning/tool_strategy_learner.py +376 -0
  24. evolution/logging_config.py +149 -0
  25. evolution/memory/__init__.py +16 -0
  26. evolution/memory/association_discoverer.py +776 -0
  27. evolution/memory/association_optimizer.py +495 -0
  28. evolution/memory/database.py +420 -0
  29. evolution/memory/retrieval_optimizer.py +538 -0
  30. evolution/security/__init__.py +72 -0
  31. evolution/security/audit_logger.py +653 -0
  32. evolution/security/permission_manager.py +436 -0
  33. evolution/security/sandbox_executor.py +505 -0
  34. evolution/security/threat_detector.py +580 -0
  35. evolution/self_monitor.py +193 -0
  36. evolution/tools/__init__.py +79 -0
  37. evolution/tools/enhanced_tool_creator.py +878 -0
  38. evolution/tools/tool_auto_generator.py +741 -0
  39. evolution/tools/tool_creator.py +445 -0
  40. evolution/tools/tool_integration.py +478 -0
  41. evolution/tools/tool_performance_analyzer.py +796 -0
  42. evolution/tools/tool_registry.py +525 -0
  43. hermes_agent_evolution-3.0.0.dist-info/METADATA +236 -0
  44. hermes_agent_evolution-3.0.0.dist-info/RECORD +66 -0
  45. hermes_agent_evolution-3.0.0.dist-info/WHEEL +5 -0
  46. hermes_agent_evolution-3.0.0.dist-info/entry_points.txt +2 -0
  47. hermes_agent_evolution-3.0.0.dist-info/top_level.txt +3 -0
  48. services/__init__.py +13 -0
  49. services/core/__init__.py +1 -0
  50. services/core/config/config_manager.py +480 -0
  51. services/core/events/event_bus.py +205 -0
  52. services/core/services/service_manager.py +283 -0
  53. services/learning/__init__.py +1 -0
  54. services/learning/meta/meta_learning_service.py +469 -0
  55. services/learning/reflection/reflection_service.py +807 -0
  56. services/learning/reinforcement/rl_service.py +540 -0
  57. services/system/__init__.py +1 -0
  58. services/system/deployment/deployment_service.py +875 -0
  59. services/system/monitoring/monitoring_service.py +937 -0
  60. services/system/testing/test_service.py +780 -0
  61. services/tools/__init__.py +1 -0
  62. services/tools/composition/tool_composition_service.py +958 -0
  63. services/tools/discovery/tool_discovery_service.py +794 -0
  64. utils/__init__.py +1 -0
  65. utils/feishu_notifier.py +343 -0
  66. utils/progress_reporter.py +269 -0
evolution/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """
2
+ Hermes Agent Evolution - AI助手自我进化系统 V1/V2/V3 融合版
3
+
4
+ 架构:
5
+ - src/evolution/ — V1 单体模块 (记忆/学习/工具/安全/协作/闭环进化)
6
+ - src/services/ — V2 微服务层 (事件总线/服务管理/学习服务/工具服务)
7
+ - src/utils/ — 共享工具 (飞书通知/进度报告)
8
+
9
+ 使AI助手能够从经验中学习并持续改进自身能力。
10
+ """
11
+
12
+ __version__ = "3.0.0"
13
+ __author__ = "HermesAgentEvolution Team"
14
+ __description__ = "AI助手自我进化系统 - V1/V2/V3融合版"
evolution/cli.py ADDED
@@ -0,0 +1,252 @@
1
+ """
2
+ HermesAgentEvolution CLI — 命令行工具
3
+
4
+ 用法:
5
+ python3 -m src.evolution.cli check # 环境自检
6
+ python3 -m src.evolution.cli setup # 一键部署到 Hermes
7
+ python3 -m src.evolution.cli status # 查看系统状态
8
+ python3 -m src.evolution.cli test # 运行自测
9
+ """
10
+
11
+ import sys
12
+ import os
13
+ from pathlib import Path
14
+
15
+ # 确保项目根在 sys.path
16
+ _project_root = Path(__file__).resolve().parent.parent.parent
17
+ if str(_project_root) not in sys.path:
18
+ sys.path.insert(0, str(_project_root))
19
+
20
+
21
+ def _add_src_to_path():
22
+ """确保 src/ 可导入"""
23
+ src_dir = Path(__file__).resolve().parent.parent
24
+ if str(src_dir) not in sys.path:
25
+ sys.path.insert(0, str(src_dir))
26
+
27
+
28
+ def cmd_check() -> bool:
29
+ """环境自检:Python版本、模块导入、DB连接、插件部署"""
30
+ _add_src_to_path()
31
+
32
+ all_ok = True
33
+ results = []
34
+
35
+ def _check(name: str, ok: bool, detail: str = ""):
36
+ nonlocal all_ok
37
+ if not ok:
38
+ all_ok = False
39
+ results.append((name, ok, detail))
40
+
41
+ # 1. Python 版本
42
+ vi = sys.version_info
43
+ _check(
44
+ f"Python {vi.major}.{vi.minor}.{vi.micro} ≥ 3.9",
45
+ vi >= (3, 9),
46
+ f"当前 Python {vi.major}.{vi.minor}" if vi < (3, 9) else ""
47
+ )
48
+
49
+ # 2. 核心模块导入
50
+ core_modules = [
51
+ ("evolution.tools.tool_registry", "工具注册表"),
52
+ ("evolution.learning.observer", "学习观察器"),
53
+ ("evolution.memory.database", "记忆数据库"),
54
+ ("evolution.security.audit_logger", "安全审计"),
55
+ ("evolution.collaboration.agent_orchestrator", "协作编排"),
56
+ ("evolution.closed_loop.orchestrator", "闭环编排"),
57
+ ("evolution.self_monitor", "自我监控"),
58
+ ("evolution.db_utils", "DB工具"),
59
+ ]
60
+
61
+ for mod_name, desc in core_modules:
62
+ try:
63
+ __import__(mod_name)
64
+ _check(f"模块 {desc}", True)
65
+ except ImportError as e:
66
+ _check(f"模块 {desc}", False, str(e))
67
+
68
+ # 3. DB 可读写
69
+ try:
70
+ from evolution.db_utils import get_evolution_db, close_all_connections
71
+ conn = get_evolution_db("_cli_check.db")
72
+ conn.execute("CREATE TABLE IF NOT EXISTS _check (id INTEGER)")
73
+ conn.execute("INSERT INTO _check VALUES (1)")
74
+ conn.execute("DROP TABLE _check")
75
+ conn.commit()
76
+ close_all_connections()
77
+ _check("DB 可读写", True)
78
+ except Exception as e:
79
+ _check("DB 可读写", False, str(e))
80
+
81
+ # 4. Hermes 插件已部署
82
+ plugin_dir = Path.home() / ".hermes" / "plugins" / "hermes-evolution"
83
+ plugin_yaml = plugin_dir / "plugin.yaml"
84
+ _check(
85
+ "Hermes 插件已部署",
86
+ plugin_yaml.exists(),
87
+ f"未找到 {plugin_yaml}" if not plugin_yaml.exists() else ""
88
+ )
89
+
90
+ # 5. 数据目录
91
+ from evolution.db_utils import _resolve_data_dir
92
+ data_dir = _resolve_data_dir()
93
+ _check(f"数据目录: {data_dir}", data_dir.exists())
94
+
95
+ # 输出
96
+ print()
97
+ print("🔍 HermesAgentEvolution 环境自检")
98
+ print("=" * 50)
99
+ for name, ok, detail in results:
100
+ icon = "✅" if ok else "❌"
101
+ print(f" {icon} {name}")
102
+ if detail:
103
+ print(f" → {detail}")
104
+ print("=" * 50)
105
+
106
+ if all_ok:
107
+ print(" 🎉 环境就绪,可以正常使用")
108
+ else:
109
+ print(" ⚠️ 存在异常,请根据上述提示修复")
110
+
111
+ return all_ok
112
+
113
+
114
+ def cmd_setup() -> bool:
115
+ """一键部署:复制插件到 ~/.hermes/plugins/"""
116
+ _add_src_to_path()
117
+
118
+ project_root = Path(__file__).resolve().parent.parent.parent
119
+ plugin_src = project_root / "hermes-plugin"
120
+ plugin_dst = Path.home() / ".hermes" / "plugins" / "hermes-evolution"
121
+
122
+ if not plugin_src.exists():
123
+ print(f"❌ 源目录不存在: {plugin_src}")
124
+ return False
125
+
126
+ print("🚀 HermesAgentEvolution 插件部署")
127
+ print(f" 源: {plugin_src}")
128
+ print(f" 目标: {plugin_dst}")
129
+
130
+ # 复制文件
131
+ import shutil
132
+ plugin_dst.mkdir(parents=True, exist_ok=True)
133
+
134
+ for item in plugin_src.iterdir():
135
+ dst = plugin_dst / item.name
136
+ if item.is_file():
137
+ shutil.copy2(item, dst)
138
+ elif item.is_dir():
139
+ if dst.exists():
140
+ shutil.rmtree(dst)
141
+ shutil.copytree(item, dst)
142
+
143
+ print(f" ✅ 插件已部署")
144
+
145
+ # 提示重启
146
+ print()
147
+ print(" ⚠️ 请重启 Hermes Gateway 使插件生效:")
148
+ print(" hermes gateway restart")
149
+
150
+ return True
151
+
152
+
153
+ def cmd_status() -> bool:
154
+ """查看系统状态"""
155
+ _add_src_to_path()
156
+
157
+ print("📊 HermesAgentEvolution 系统状态")
158
+ print("=" * 50)
159
+
160
+ # 版本
161
+ try:
162
+ import re
163
+ pyproject = _project_root / "pyproject.toml"
164
+ content = pyproject.read_text()
165
+ m = re.search(r'version\s*=\s*"([^"]+)"', content)
166
+ version = m.group(1) if m else "unknown"
167
+ print(f" 版本: v{version}")
168
+ except Exception:
169
+ print(f" 版本: 无法读取")
170
+
171
+ # 模块统计
172
+ try:
173
+ src_dir = _project_root / "src" / "evolution"
174
+ py_files = list(src_dir.rglob("*.py"))
175
+ total_lines = 0
176
+ for f in py_files:
177
+ total_lines += len(f.read_text().splitlines())
178
+ print(f" 模块: {len(py_files)} 文件")
179
+ print(f" 代码: {total_lines} 行")
180
+ except Exception as e:
181
+ print(f" 代码统计失败: {e}")
182
+
183
+ # 测试状态
184
+ import subprocess
185
+ result = subprocess.run(
186
+ [sys.executable, "-m", "pytest", "tests/", "-q", "--tb=no"],
187
+ cwd=_project_root,
188
+ capture_output=True, text=True, timeout=60
189
+ )
190
+ print(f" 测试: {result.stdout.strip().splitlines()[-1] if result.stdout else '无法运行'}")
191
+
192
+ # DB 统计
193
+ try:
194
+ from evolution.db_utils import get_data_dir, db_get_stats
195
+ data_dir = get_data_dir()
196
+ db_files = list(data_dir.glob("*.db"))
197
+ print(f" DB文件: {len(db_files)} 个 ({data_dir})")
198
+ for db in db_files:
199
+ size_kb = db.stat().st_size / 1024
200
+ print(f" - {db.name}: {size_kb:.1f} KB")
201
+ except Exception as e:
202
+ print(f" DB统计失败: {e}")
203
+
204
+ print("=" * 50)
205
+ return True
206
+
207
+
208
+ def cmd_test() -> bool:
209
+ """运行自测"""
210
+ import subprocess
211
+ result = subprocess.run(
212
+ [sys.executable, "-m", "pytest", "tests/", "-q", "--tb=line"],
213
+ cwd=_project_root,
214
+ timeout=180
215
+ )
216
+ return result.returncode == 0
217
+
218
+
219
+ # ── CLI 入口 ────────────────────────────────────────────────────────────────────
220
+
221
+ COMMANDS = {
222
+ "check": (cmd_check, "环境自检"),
223
+ "setup": (cmd_setup, "一键部署到 Hermes"),
224
+ "status": (cmd_status, "查看系统状态"),
225
+ "test": (cmd_test, "运行自测"),
226
+ }
227
+
228
+
229
+ def main():
230
+ """CLI 主入口"""
231
+ if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help", "help"):
232
+ print("HermesAgentEvolution CLI v3.0.0")
233
+ print()
234
+ print("用法: python3 -m src.evolution.cli <命令>")
235
+ print()
236
+ for name, (_, desc) in COMMANDS.items():
237
+ print(f" {name:<10s} {desc}")
238
+ sys.exit(0)
239
+
240
+ cmd = sys.argv[1]
241
+ if cmd not in COMMANDS:
242
+ print(f"❌ 未知命令: {cmd}")
243
+ print(f" 可用: {', '.join(COMMANDS.keys())}")
244
+ sys.exit(1)
245
+
246
+ func, _ = COMMANDS[cmd]
247
+ success = func()
248
+ sys.exit(0 if success else 1)
249
+
250
+
251
+ if __name__ == "__main__":
252
+ main()
@@ -0,0 +1,18 @@
1
+ """
2
+ 持续进化闭环模块 — HermesAgentEvolution Iteration 5
3
+ 实现完整的 Monitor → Analyze → Plan → Execute → Verify 闭环
4
+ """
5
+
6
+ from .daemon import EvolutionDaemon, EvolutionPhase, LoopState
7
+ from .orchestrator import ClosedLoopOrchestrator
8
+ from .metrics_collector import SystemMetricsCollector
9
+ from .action_executor import ActionExecutor
10
+
11
+ __all__ = [
12
+ 'EvolutionDaemon',
13
+ 'EvolutionPhase',
14
+ 'LoopState',
15
+ 'ClosedLoopOrchestrator',
16
+ 'SystemMetricsCollector',
17
+ 'ActionExecutor',
18
+ ]
@@ -0,0 +1,355 @@
1
+ """
2
+ ActionExecutor — 改进动作执行器
3
+ 负责将改进计划中的动作实际执行,产生真实效果
4
+
5
+ 支持的动作类型:
6
+ - strategy_switch: 切换工具选择策略
7
+ - tool_optimization: 优化工具参数/性能
8
+ - parameter_tuning: 调整系统参数
9
+ - tool_creation: 创建新工具
10
+ - tool_deprecation: 废弃低效工具
11
+ """
12
+
13
+ import logging
14
+ from typing import Dict, Any, List, Optional
15
+ from datetime import datetime
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class ActionExecutor:
21
+ """
22
+ 改进动作执行器
23
+
24
+ 接收改进动作定义,执行实际系统变更。
25
+ 每个动作类型有对应的执行器方法。
26
+
27
+ 用法:
28
+ executor = ActionExecutor(strategy_learner, tool_engine, registry)
29
+ result = executor.execute(action)
30
+ """
31
+
32
+ def __init__(self,
33
+ strategy_learner=None,
34
+ tool_evolution_engine=None,
35
+ tool_registry=None,
36
+ tool_performance_analyzer=None,
37
+ pattern_recognizer=None,
38
+ config: Optional[Dict[str, Any]] = None):
39
+ """
40
+ Args:
41
+ strategy_learner: 工具策略学习器
42
+ tool_evolution_engine: 工具进化引擎
43
+ tool_registry: 工具注册表
44
+ tool_performance_analyzer: 工具性能分析器
45
+ pattern_recognizer: 模式识别器
46
+ config: 配置
47
+ """
48
+ self.strategy_learner = strategy_learner
49
+ self.tool_evolution_engine = tool_evolution_engine
50
+ self.tool_registry = tool_registry
51
+ self.tool_performance_analyzer = tool_performance_analyzer
52
+ self.pattern_recognizer = pattern_recognizer
53
+ self.config = config or {}
54
+
55
+ # 执行历史
56
+ self.execution_history: List[Dict[str, Any]] = []
57
+
58
+ # 安全模式 — dry_run 时不执行实际变更
59
+ self.dry_run = self.config.get('dry_run', False)
60
+
61
+ logger.info(f"ActionExecutor 初始化 (dry_run={self.dry_run})")
62
+
63
+ def execute(self, action: 'ImprovementAction') -> Dict[str, Any]:
64
+ """
65
+ 执行单个改进动作
66
+
67
+ Args:
68
+ action: 改进动作
69
+
70
+ Returns:
71
+ {'success': bool, 'message': str, 'output': dict}
72
+ """
73
+ logger.info(f"执行动作: {action.action_type} → {action.target} [{action.priority}]")
74
+
75
+ handlers = {
76
+ 'strategy_switch': self._execute_strategy_switch,
77
+ 'tool_optimization': self._execute_tool_optimization,
78
+ 'parameter_tuning': self._execute_parameter_tuning,
79
+ 'tool_creation': self._execute_tool_creation,
80
+ 'tool_deprecation': self._execute_tool_deprecation,
81
+ }
82
+
83
+ handler = handlers.get(action.action_type)
84
+ if not handler:
85
+ return {
86
+ 'success': False,
87
+ 'message': f"未知动作类型: {action.action_type}",
88
+ 'output': {},
89
+ }
90
+
91
+ try:
92
+ if self.dry_run:
93
+ result = self._simulate_action(action)
94
+ else:
95
+ result = handler(action)
96
+
97
+ # 记录历史
98
+ self.execution_history.append({
99
+ 'timestamp': datetime.now().isoformat(),
100
+ 'action': {
101
+ 'type': action.action_type,
102
+ 'target': action.target,
103
+ 'priority': action.priority,
104
+ },
105
+ 'result': result,
106
+ })
107
+
108
+ return result
109
+
110
+ except Exception as e:
111
+ logger.error(f"执行动作失败 [{action.action_type}→{action.target}]: {e}")
112
+ return {
113
+ 'success': False,
114
+ 'message': str(e),
115
+ 'output': {},
116
+ }
117
+
118
+ # ═══════════════════════════════════════════
119
+ # 动作执行器
120
+ # ═══════════════════════════════════════════
121
+
122
+ def _execute_strategy_switch(self, action: 'ImprovementAction') -> Dict[str, Any]:
123
+ """
124
+ 切换工具选择策略
125
+
126
+ 当检测到当前策略表现不佳时,切换到更优策略
127
+ """
128
+ if not self.strategy_learner:
129
+ return {'success': False, 'message': '策略学习器未初始化', 'output': {}}
130
+
131
+ try:
132
+ current = self.strategy_learner.get_current_strategy()
133
+
134
+ # 通过记录模拟使用来触发策略自适应(内部会根据性能自动切换)
135
+ # 记录一些代表性的使用数据促使策略评估
136
+ sample_tools = ['terminal', 'read_file', 'write_file', 'search_files']
137
+ for tool in sample_tools:
138
+ self.strategy_learner.record_tool_usage(
139
+ tool_name=tool,
140
+ success=True,
141
+ execution_time=0.5,
142
+ context={'complexity': 0.3, 'source': 'strategy_switch'}
143
+ )
144
+
145
+ new_strategy = self.strategy_learner.get_current_strategy()
146
+ changed = new_strategy != current
147
+
148
+ return {
149
+ 'success': True,
150
+ 'message': (
151
+ f"策略评估完成: {current.value} → {new_strategy.value}"
152
+ if changed else
153
+ f"策略保持 {current.value}(无需切换)"
154
+ ),
155
+ 'output': {
156
+ 'previous_strategy': current.value,
157
+ 'new_strategy': new_strategy.value,
158
+ 'changed': changed,
159
+ },
160
+ }
161
+ except Exception as e:
162
+ return {'success': False, 'message': f"策略切换失败: {e}", 'output': {}}
163
+
164
+ def _execute_tool_optimization(self, action: 'ImprovementAction') -> Dict[str, Any]:
165
+ """
166
+ 优化工具性能
167
+
168
+ 通过工具进化引擎优化指定工具
169
+ """
170
+ if not self.tool_evolution_engine:
171
+ return {'success': False, 'message': '工具进化引擎未初始化', 'output': {}}
172
+
173
+ try:
174
+ tool_name = action.parameters.get('tool_name', action.target)
175
+
176
+ # 运行工具进化周期
177
+ result = self.tool_evolution_engine.run_evolution_cycle()
178
+
179
+ # 检查是否对目标工具有改进
180
+ tool_optimized = any(
181
+ opt.get('tool_name') == tool_name
182
+ for opt in result.get('optimizations', [])
183
+ )
184
+
185
+ return {
186
+ 'success': result.get('success', False),
187
+ 'message': (
188
+ f"工具 '{tool_name}' 进化完成"
189
+ if tool_optimized else
190
+ f"工具 '{tool_name}' 当前不需要优化"
191
+ ),
192
+ 'output': {
193
+ 'tool_name': tool_name,
194
+ 'evolution_success': result.get('success', False),
195
+ 'optimizations_count': len(result.get('optimizations', [])),
196
+ 'deprecated_count': len(result.get('deprecated_tools', [])),
197
+ },
198
+ }
199
+ except Exception as e:
200
+ return {'success': False, 'message': f"工具优化失败: {e}", 'output': {}}
201
+
202
+ def _execute_parameter_tuning(self, action: 'ImprovementAction') -> Dict[str, Any]:
203
+ """
204
+ 调整系统参数
205
+
206
+ 根据分析结果调整系统运行参数
207
+ """
208
+ params = action.parameters
209
+ changes = []
210
+
211
+ # 调整探索率(如果策略学习器支持)
212
+ if self.strategy_learner and 'exploration_rate' in params:
213
+ try:
214
+ new_rate = params['exploration_rate']
215
+ if hasattr(self.strategy_learner, 'set_exploration_rate'):
216
+ self.strategy_learner.set_exploration_rate(new_rate)
217
+ changes.append(f"探索率 → {new_rate}")
218
+ except Exception as e:
219
+ logger.debug(f"调整探索率失败: {e}")
220
+
221
+ # 调整性能阈值
222
+ if self.tool_evolution_engine and 'min_performance_score' in params:
223
+ try:
224
+ new_threshold = params['min_performance_score']
225
+ if hasattr(self.tool_evolution_engine, 'config'):
226
+ old = self.tool_evolution_engine.config.min_performance_score
227
+ self.tool_evolution_engine.config.min_performance_score = new_threshold
228
+ changes.append(f"性能阈值 {old} → {new_threshold}")
229
+ except Exception as e:
230
+ logger.debug(f"调整性能阈值失败: {e}")
231
+
232
+ if changes:
233
+ return {
234
+ 'success': True,
235
+ 'message': f"参数已调整: {', '.join(changes)}",
236
+ 'output': {'changes': changes},
237
+ }
238
+ else:
239
+ return {
240
+ 'success': True,
241
+ 'message': '无可调参数(参数调优暂未实现)',
242
+ 'output': {'changes': []},
243
+ }
244
+
245
+ def _execute_tool_creation(self, action: 'ImprovementAction') -> Dict[str, Any]:
246
+ """
247
+ 创建新工具
248
+
249
+ 根据需求描述自动生成新工具
250
+ """
251
+ if not self.tool_evolution_engine:
252
+ return {'success': False, 'message': '工具进化引擎未初始化', 'output': {}}
253
+
254
+ try:
255
+ requirement = action.description
256
+
257
+ result = self.tool_evolution_engine.auto_generate_tool(requirement)
258
+
259
+ return {
260
+ 'success': result.success if hasattr(result, 'success') else False,
261
+ 'message': f"工具生成: {getattr(result, 'tool_name', 'unknown')}",
262
+ 'output': {
263
+ 'tool_name': getattr(result, 'tool_name', ''),
264
+ 'success': getattr(result, 'success', False),
265
+ },
266
+ }
267
+ except Exception as e:
268
+ return {'success': False, 'message': f"工具创建失败: {e}", 'output': {}}
269
+
270
+ def _execute_tool_deprecation(self, action: 'ImprovementAction') -> Dict[str, Any]:
271
+ """
272
+ 废弃低效工具
273
+
274
+ 将使用率低、性能差的工具标记为废弃
275
+ """
276
+ if not self.tool_registry:
277
+ return {'success': False, 'message': '工具注册表未初始化', 'output': {}}
278
+
279
+ try:
280
+ tool_name = action.parameters.get('tool_name', action.target)
281
+
282
+ tool = self.tool_registry.get(tool_name)
283
+ if not tool:
284
+ return {'success': False, 'message': f"工具 '{tool_name}' 不存在", 'output': {}}
285
+
286
+ # 标记为废弃
287
+ from ..tools.tool_registry import ToolStatus
288
+ tool.status = ToolStatus.DEPRECATED
289
+ self.tool_registry.register(tool)
290
+
291
+ return {
292
+ 'success': True,
293
+ 'message': f"工具 '{tool_name}' 已标记为废弃",
294
+ 'output': {'tool_name': tool_name},
295
+ }
296
+ except Exception as e:
297
+ return {'success': False, 'message': f"工具废弃失败: {e}", 'output': {}}
298
+
299
+ # ═══════════════════════════════════════════
300
+ # Dry Run 模式
301
+ # ═══════════════════════════════════════════
302
+
303
+ def _simulate_action(self, action: 'ImprovementAction') -> Dict[str, Any]:
304
+ """模拟执行(不对系统做任何实际变更)"""
305
+ return {
306
+ 'success': True,
307
+ 'message': f"[DRY-RUN] 将执行: {action.action_type} → {action.target}",
308
+ 'output': {
309
+ 'simulated': True,
310
+ 'action_type': action.action_type,
311
+ 'target': action.target,
312
+ 'priority': action.priority,
313
+ 'expected_benefit': action.expected_benefit,
314
+ 'risk': action.risk,
315
+ },
316
+ }
317
+
318
+ # ═══════════════════════════════════════════
319
+ # 便捷方法
320
+ # ═══════════════════════════════════════════
321
+
322
+ def execute_batch(self, actions: List['ImprovementAction']) -> List[Dict[str, Any]]:
323
+ """
324
+ 批量执行动作
325
+
326
+ Args:
327
+ actions: 动作列表
328
+
329
+ Returns:
330
+ 执行结果列表
331
+ """
332
+ results = []
333
+ for action in actions:
334
+ result = self.execute(action)
335
+ results.append(result)
336
+ return results
337
+
338
+ def get_execution_stats(self) -> Dict[str, Any]:
339
+ """获取执行统计"""
340
+ total = len(self.execution_history)
341
+ if total == 0:
342
+ return {'total': 0}
343
+
344
+ success_count = sum(
345
+ 1 for r in self.execution_history
346
+ if r.get('result', {}).get('success', False)
347
+ )
348
+
349
+ return {
350
+ 'total_executions': total,
351
+ 'success_count': success_count,
352
+ 'failure_count': total - success_count,
353
+ 'success_rate': f"{success_count/total:.1%}",
354
+ 'last_execution': self.execution_history[-1]['timestamp'] if self.execution_history else None,
355
+ }