empathy-framework 5.3.0__py3-none-any.whl → 5.4.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 (458) hide show
  1. empathy_framework-5.4.0.dist-info/METADATA +47 -0
  2. empathy_framework-5.4.0.dist-info/RECORD +8 -0
  3. {empathy_framework-5.3.0.dist-info → empathy_framework-5.4.0.dist-info}/top_level.txt +0 -1
  4. empathy_healthcare_plugin/__init__.py +12 -11
  5. empathy_llm_toolkit/__init__.py +12 -26
  6. empathy_os/__init__.py +12 -356
  7. empathy_software_plugin/__init__.py +12 -11
  8. empathy_framework-5.3.0.dist-info/METADATA +0 -1026
  9. empathy_framework-5.3.0.dist-info/RECORD +0 -456
  10. empathy_framework-5.3.0.dist-info/entry_points.txt +0 -26
  11. empathy_framework-5.3.0.dist-info/licenses/LICENSE +0 -201
  12. empathy_framework-5.3.0.dist-info/licenses/LICENSE_CHANGE_ANNOUNCEMENT.md +0 -101
  13. empathy_healthcare_plugin/monitors/__init__.py +0 -9
  14. empathy_healthcare_plugin/monitors/clinical_protocol_monitor.py +0 -315
  15. empathy_healthcare_plugin/monitors/monitoring/__init__.py +0 -44
  16. empathy_healthcare_plugin/monitors/monitoring/protocol_checker.py +0 -300
  17. empathy_healthcare_plugin/monitors/monitoring/protocol_loader.py +0 -214
  18. empathy_healthcare_plugin/monitors/monitoring/sensor_parsers.py +0 -306
  19. empathy_healthcare_plugin/monitors/monitoring/trajectory_analyzer.py +0 -389
  20. empathy_healthcare_plugin/protocols/cardiac.json +0 -93
  21. empathy_healthcare_plugin/protocols/post_operative.json +0 -92
  22. empathy_healthcare_plugin/protocols/respiratory.json +0 -92
  23. empathy_healthcare_plugin/protocols/sepsis.json +0 -141
  24. empathy_llm_toolkit/README.md +0 -553
  25. empathy_llm_toolkit/agent_factory/__init__.py +0 -53
  26. empathy_llm_toolkit/agent_factory/adapters/__init__.py +0 -85
  27. empathy_llm_toolkit/agent_factory/adapters/autogen_adapter.py +0 -312
  28. empathy_llm_toolkit/agent_factory/adapters/crewai_adapter.py +0 -483
  29. empathy_llm_toolkit/agent_factory/adapters/haystack_adapter.py +0 -298
  30. empathy_llm_toolkit/agent_factory/adapters/langchain_adapter.py +0 -362
  31. empathy_llm_toolkit/agent_factory/adapters/langgraph_adapter.py +0 -333
  32. empathy_llm_toolkit/agent_factory/adapters/native.py +0 -228
  33. empathy_llm_toolkit/agent_factory/adapters/wizard_adapter.py +0 -423
  34. empathy_llm_toolkit/agent_factory/base.py +0 -305
  35. empathy_llm_toolkit/agent_factory/crews/__init__.py +0 -67
  36. empathy_llm_toolkit/agent_factory/crews/code_review.py +0 -1113
  37. empathy_llm_toolkit/agent_factory/crews/health_check.py +0 -1262
  38. empathy_llm_toolkit/agent_factory/crews/refactoring.py +0 -1128
  39. empathy_llm_toolkit/agent_factory/crews/security_audit.py +0 -1018
  40. empathy_llm_toolkit/agent_factory/decorators.py +0 -287
  41. empathy_llm_toolkit/agent_factory/factory.py +0 -558
  42. empathy_llm_toolkit/agent_factory/framework.py +0 -193
  43. empathy_llm_toolkit/agent_factory/memory_integration.py +0 -328
  44. empathy_llm_toolkit/agent_factory/resilient.py +0 -320
  45. empathy_llm_toolkit/agents_md/__init__.py +0 -22
  46. empathy_llm_toolkit/agents_md/loader.py +0 -218
  47. empathy_llm_toolkit/agents_md/parser.py +0 -271
  48. empathy_llm_toolkit/agents_md/registry.py +0 -307
  49. empathy_llm_toolkit/claude_memory.py +0 -466
  50. empathy_llm_toolkit/cli/__init__.py +0 -8
  51. empathy_llm_toolkit/cli/sync_claude.py +0 -487
  52. empathy_llm_toolkit/code_health.py +0 -1313
  53. empathy_llm_toolkit/commands/__init__.py +0 -51
  54. empathy_llm_toolkit/commands/context.py +0 -375
  55. empathy_llm_toolkit/commands/loader.py +0 -301
  56. empathy_llm_toolkit/commands/models.py +0 -231
  57. empathy_llm_toolkit/commands/parser.py +0 -371
  58. empathy_llm_toolkit/commands/registry.py +0 -429
  59. empathy_llm_toolkit/config/__init__.py +0 -29
  60. empathy_llm_toolkit/config/unified.py +0 -291
  61. empathy_llm_toolkit/context/__init__.py +0 -22
  62. empathy_llm_toolkit/context/compaction.py +0 -455
  63. empathy_llm_toolkit/context/manager.py +0 -434
  64. empathy_llm_toolkit/contextual_patterns.py +0 -361
  65. empathy_llm_toolkit/core.py +0 -907
  66. empathy_llm_toolkit/git_pattern_extractor.py +0 -435
  67. empathy_llm_toolkit/hooks/__init__.py +0 -24
  68. empathy_llm_toolkit/hooks/config.py +0 -306
  69. empathy_llm_toolkit/hooks/executor.py +0 -289
  70. empathy_llm_toolkit/hooks/registry.py +0 -302
  71. empathy_llm_toolkit/hooks/scripts/__init__.py +0 -39
  72. empathy_llm_toolkit/hooks/scripts/evaluate_session.py +0 -201
  73. empathy_llm_toolkit/hooks/scripts/first_time_init.py +0 -285
  74. empathy_llm_toolkit/hooks/scripts/pre_compact.py +0 -207
  75. empathy_llm_toolkit/hooks/scripts/session_end.py +0 -183
  76. empathy_llm_toolkit/hooks/scripts/session_start.py +0 -163
  77. empathy_llm_toolkit/hooks/scripts/suggest_compact.py +0 -225
  78. empathy_llm_toolkit/learning/__init__.py +0 -30
  79. empathy_llm_toolkit/learning/evaluator.py +0 -438
  80. empathy_llm_toolkit/learning/extractor.py +0 -514
  81. empathy_llm_toolkit/learning/storage.py +0 -560
  82. empathy_llm_toolkit/levels.py +0 -227
  83. empathy_llm_toolkit/pattern_confidence.py +0 -414
  84. empathy_llm_toolkit/pattern_resolver.py +0 -272
  85. empathy_llm_toolkit/pattern_summary.py +0 -350
  86. empathy_llm_toolkit/providers.py +0 -967
  87. empathy_llm_toolkit/routing/__init__.py +0 -32
  88. empathy_llm_toolkit/routing/model_router.py +0 -362
  89. empathy_llm_toolkit/security/IMPLEMENTATION_SUMMARY.md +0 -413
  90. empathy_llm_toolkit/security/PHASE2_COMPLETE.md +0 -384
  91. empathy_llm_toolkit/security/PHASE2_SECRETS_DETECTOR_COMPLETE.md +0 -271
  92. empathy_llm_toolkit/security/QUICK_REFERENCE.md +0 -316
  93. empathy_llm_toolkit/security/README.md +0 -262
  94. empathy_llm_toolkit/security/__init__.py +0 -62
  95. empathy_llm_toolkit/security/audit_logger.py +0 -929
  96. empathy_llm_toolkit/security/audit_logger_example.py +0 -152
  97. empathy_llm_toolkit/security/pii_scrubber.py +0 -640
  98. empathy_llm_toolkit/security/secrets_detector.py +0 -678
  99. empathy_llm_toolkit/security/secrets_detector_example.py +0 -304
  100. empathy_llm_toolkit/security/secure_memdocs.py +0 -1192
  101. empathy_llm_toolkit/security/secure_memdocs_example.py +0 -278
  102. empathy_llm_toolkit/session_status.py +0 -745
  103. empathy_llm_toolkit/state.py +0 -246
  104. empathy_llm_toolkit/utils/__init__.py +0 -5
  105. empathy_llm_toolkit/utils/tokens.py +0 -349
  106. empathy_os/adaptive/__init__.py +0 -13
  107. empathy_os/adaptive/task_complexity.py +0 -127
  108. empathy_os/agent_monitoring.py +0 -414
  109. empathy_os/cache/__init__.py +0 -117
  110. empathy_os/cache/base.py +0 -166
  111. empathy_os/cache/dependency_manager.py +0 -256
  112. empathy_os/cache/hash_only.py +0 -251
  113. empathy_os/cache/hybrid.py +0 -457
  114. empathy_os/cache/storage.py +0 -285
  115. empathy_os/cache_monitor.py +0 -356
  116. empathy_os/cache_stats.py +0 -298
  117. empathy_os/cli/__init__.py +0 -152
  118. empathy_os/cli/__main__.py +0 -12
  119. empathy_os/cli/commands/__init__.py +0 -1
  120. empathy_os/cli/commands/batch.py +0 -264
  121. empathy_os/cli/commands/cache.py +0 -248
  122. empathy_os/cli/commands/help.py +0 -331
  123. empathy_os/cli/commands/info.py +0 -140
  124. empathy_os/cli/commands/inspect.py +0 -436
  125. empathy_os/cli/commands/inspection.py +0 -57
  126. empathy_os/cli/commands/memory.py +0 -48
  127. empathy_os/cli/commands/metrics.py +0 -92
  128. empathy_os/cli/commands/orchestrate.py +0 -184
  129. empathy_os/cli/commands/patterns.py +0 -207
  130. empathy_os/cli/commands/profiling.py +0 -202
  131. empathy_os/cli/commands/provider.py +0 -98
  132. empathy_os/cli/commands/routing.py +0 -285
  133. empathy_os/cli/commands/setup.py +0 -96
  134. empathy_os/cli/commands/status.py +0 -235
  135. empathy_os/cli/commands/sync.py +0 -166
  136. empathy_os/cli/commands/tier.py +0 -121
  137. empathy_os/cli/commands/utilities.py +0 -114
  138. empathy_os/cli/commands/workflow.py +0 -579
  139. empathy_os/cli/core.py +0 -32
  140. empathy_os/cli/parsers/__init__.py +0 -68
  141. empathy_os/cli/parsers/batch.py +0 -118
  142. empathy_os/cli/parsers/cache.py +0 -65
  143. empathy_os/cli/parsers/help.py +0 -41
  144. empathy_os/cli/parsers/info.py +0 -26
  145. empathy_os/cli/parsers/inspect.py +0 -66
  146. empathy_os/cli/parsers/metrics.py +0 -42
  147. empathy_os/cli/parsers/orchestrate.py +0 -61
  148. empathy_os/cli/parsers/patterns.py +0 -54
  149. empathy_os/cli/parsers/provider.py +0 -40
  150. empathy_os/cli/parsers/routing.py +0 -110
  151. empathy_os/cli/parsers/setup.py +0 -42
  152. empathy_os/cli/parsers/status.py +0 -47
  153. empathy_os/cli/parsers/sync.py +0 -31
  154. empathy_os/cli/parsers/tier.py +0 -33
  155. empathy_os/cli/parsers/workflow.py +0 -77
  156. empathy_os/cli/utils/__init__.py +0 -1
  157. empathy_os/cli/utils/data.py +0 -242
  158. empathy_os/cli/utils/helpers.py +0 -68
  159. empathy_os/cli_legacy.py +0 -3957
  160. empathy_os/cli_minimal.py +0 -1159
  161. empathy_os/cli_router.py +0 -437
  162. empathy_os/cli_unified.py +0 -814
  163. empathy_os/config/__init__.py +0 -66
  164. empathy_os/config/xml_config.py +0 -286
  165. empathy_os/config.py +0 -545
  166. empathy_os/coordination.py +0 -870
  167. empathy_os/core.py +0 -1511
  168. empathy_os/core_modules/__init__.py +0 -15
  169. empathy_os/cost_tracker.py +0 -626
  170. empathy_os/dashboard/__init__.py +0 -41
  171. empathy_os/dashboard/app.py +0 -512
  172. empathy_os/dashboard/simple_server.py +0 -435
  173. empathy_os/dashboard/standalone_server.py +0 -547
  174. empathy_os/discovery.py +0 -306
  175. empathy_os/emergence.py +0 -306
  176. empathy_os/exceptions.py +0 -123
  177. empathy_os/feedback_loops.py +0 -373
  178. empathy_os/hot_reload/README.md +0 -473
  179. empathy_os/hot_reload/__init__.py +0 -62
  180. empathy_os/hot_reload/config.py +0 -83
  181. empathy_os/hot_reload/integration.py +0 -229
  182. empathy_os/hot_reload/reloader.py +0 -298
  183. empathy_os/hot_reload/watcher.py +0 -183
  184. empathy_os/hot_reload/websocket.py +0 -177
  185. empathy_os/levels.py +0 -577
  186. empathy_os/leverage_points.py +0 -441
  187. empathy_os/logging_config.py +0 -261
  188. empathy_os/mcp/__init__.py +0 -10
  189. empathy_os/mcp/server.py +0 -506
  190. empathy_os/memory/__init__.py +0 -237
  191. empathy_os/memory/claude_memory.py +0 -469
  192. empathy_os/memory/config.py +0 -224
  193. empathy_os/memory/control_panel.py +0 -1290
  194. empathy_os/memory/control_panel_support.py +0 -145
  195. empathy_os/memory/cross_session.py +0 -845
  196. empathy_os/memory/edges.py +0 -179
  197. empathy_os/memory/encryption.py +0 -159
  198. empathy_os/memory/file_session.py +0 -770
  199. empathy_os/memory/graph.py +0 -570
  200. empathy_os/memory/long_term.py +0 -913
  201. empathy_os/memory/long_term_types.py +0 -99
  202. empathy_os/memory/mixins/__init__.py +0 -25
  203. empathy_os/memory/mixins/backend_init_mixin.py +0 -249
  204. empathy_os/memory/mixins/capabilities_mixin.py +0 -208
  205. empathy_os/memory/mixins/handoff_mixin.py +0 -208
  206. empathy_os/memory/mixins/lifecycle_mixin.py +0 -49
  207. empathy_os/memory/mixins/long_term_mixin.py +0 -352
  208. empathy_os/memory/mixins/promotion_mixin.py +0 -109
  209. empathy_os/memory/mixins/short_term_mixin.py +0 -182
  210. empathy_os/memory/nodes.py +0 -179
  211. empathy_os/memory/redis_bootstrap.py +0 -540
  212. empathy_os/memory/security/__init__.py +0 -31
  213. empathy_os/memory/security/audit_logger.py +0 -932
  214. empathy_os/memory/security/pii_scrubber.py +0 -640
  215. empathy_os/memory/security/secrets_detector.py +0 -678
  216. empathy_os/memory/short_term.py +0 -2192
  217. empathy_os/memory/simple_storage.py +0 -302
  218. empathy_os/memory/storage/__init__.py +0 -15
  219. empathy_os/memory/storage_backend.py +0 -167
  220. empathy_os/memory/summary_index.py +0 -583
  221. empathy_os/memory/types.py +0 -446
  222. empathy_os/memory/unified.py +0 -182
  223. empathy_os/meta_workflows/__init__.py +0 -74
  224. empathy_os/meta_workflows/agent_creator.py +0 -248
  225. empathy_os/meta_workflows/builtin_templates.py +0 -567
  226. empathy_os/meta_workflows/cli_commands/__init__.py +0 -56
  227. empathy_os/meta_workflows/cli_commands/agent_commands.py +0 -321
  228. empathy_os/meta_workflows/cli_commands/analytics_commands.py +0 -442
  229. empathy_os/meta_workflows/cli_commands/config_commands.py +0 -232
  230. empathy_os/meta_workflows/cli_commands/memory_commands.py +0 -182
  231. empathy_os/meta_workflows/cli_commands/template_commands.py +0 -354
  232. empathy_os/meta_workflows/cli_commands/workflow_commands.py +0 -382
  233. empathy_os/meta_workflows/cli_meta_workflows.py +0 -59
  234. empathy_os/meta_workflows/form_engine.py +0 -292
  235. empathy_os/meta_workflows/intent_detector.py +0 -409
  236. empathy_os/meta_workflows/models.py +0 -569
  237. empathy_os/meta_workflows/pattern_learner.py +0 -738
  238. empathy_os/meta_workflows/plan_generator.py +0 -384
  239. empathy_os/meta_workflows/session_context.py +0 -397
  240. empathy_os/meta_workflows/template_registry.py +0 -229
  241. empathy_os/meta_workflows/workflow.py +0 -984
  242. empathy_os/metrics/__init__.py +0 -12
  243. empathy_os/metrics/collector.py +0 -31
  244. empathy_os/metrics/prompt_metrics.py +0 -194
  245. empathy_os/models/__init__.py +0 -172
  246. empathy_os/models/__main__.py +0 -13
  247. empathy_os/models/adaptive_routing.py +0 -437
  248. empathy_os/models/auth_cli.py +0 -444
  249. empathy_os/models/auth_strategy.py +0 -450
  250. empathy_os/models/cli.py +0 -655
  251. empathy_os/models/empathy_executor.py +0 -354
  252. empathy_os/models/executor.py +0 -257
  253. empathy_os/models/fallback.py +0 -762
  254. empathy_os/models/provider_config.py +0 -282
  255. empathy_os/models/registry.py +0 -472
  256. empathy_os/models/tasks.py +0 -359
  257. empathy_os/models/telemetry/__init__.py +0 -71
  258. empathy_os/models/telemetry/analytics.py +0 -594
  259. empathy_os/models/telemetry/backend.py +0 -196
  260. empathy_os/models/telemetry/data_models.py +0 -431
  261. empathy_os/models/telemetry/storage.py +0 -489
  262. empathy_os/models/token_estimator.py +0 -420
  263. empathy_os/models/validation.py +0 -280
  264. empathy_os/monitoring/__init__.py +0 -52
  265. empathy_os/monitoring/alerts.py +0 -946
  266. empathy_os/monitoring/alerts_cli.py +0 -448
  267. empathy_os/monitoring/multi_backend.py +0 -271
  268. empathy_os/monitoring/otel_backend.py +0 -362
  269. empathy_os/optimization/__init__.py +0 -19
  270. empathy_os/optimization/context_optimizer.py +0 -272
  271. empathy_os/orchestration/__init__.py +0 -67
  272. empathy_os/orchestration/agent_templates.py +0 -707
  273. empathy_os/orchestration/config_store.py +0 -499
  274. empathy_os/orchestration/execution_strategies.py +0 -2111
  275. empathy_os/orchestration/meta_orchestrator.py +0 -1168
  276. empathy_os/orchestration/pattern_learner.py +0 -696
  277. empathy_os/orchestration/real_tools.py +0 -931
  278. empathy_os/pattern_cache.py +0 -187
  279. empathy_os/pattern_library.py +0 -542
  280. empathy_os/patterns/debugging/all_patterns.json +0 -81
  281. empathy_os/patterns/debugging/workflow_20260107_1770825e.json +0 -77
  282. empathy_os/patterns/refactoring_memory.json +0 -89
  283. empathy_os/persistence.py +0 -564
  284. empathy_os/platform_utils.py +0 -265
  285. empathy_os/plugins/__init__.py +0 -28
  286. empathy_os/plugins/base.py +0 -361
  287. empathy_os/plugins/registry.py +0 -268
  288. empathy_os/project_index/__init__.py +0 -32
  289. empathy_os/project_index/cli.py +0 -335
  290. empathy_os/project_index/index.py +0 -667
  291. empathy_os/project_index/models.py +0 -504
  292. empathy_os/project_index/reports.py +0 -474
  293. empathy_os/project_index/scanner.py +0 -777
  294. empathy_os/project_index/scanner_parallel.py +0 -291
  295. empathy_os/prompts/__init__.py +0 -61
  296. empathy_os/prompts/config.py +0 -77
  297. empathy_os/prompts/context.py +0 -177
  298. empathy_os/prompts/parser.py +0 -285
  299. empathy_os/prompts/registry.py +0 -313
  300. empathy_os/prompts/templates.py +0 -208
  301. empathy_os/redis_config.py +0 -302
  302. empathy_os/redis_memory.py +0 -799
  303. empathy_os/resilience/__init__.py +0 -56
  304. empathy_os/resilience/circuit_breaker.py +0 -256
  305. empathy_os/resilience/fallback.py +0 -179
  306. empathy_os/resilience/health.py +0 -300
  307. empathy_os/resilience/retry.py +0 -209
  308. empathy_os/resilience/timeout.py +0 -135
  309. empathy_os/routing/__init__.py +0 -43
  310. empathy_os/routing/chain_executor.py +0 -433
  311. empathy_os/routing/classifier.py +0 -217
  312. empathy_os/routing/smart_router.py +0 -234
  313. empathy_os/routing/workflow_registry.py +0 -343
  314. empathy_os/scaffolding/README.md +0 -589
  315. empathy_os/scaffolding/__init__.py +0 -35
  316. empathy_os/scaffolding/__main__.py +0 -14
  317. empathy_os/scaffolding/cli.py +0 -240
  318. empathy_os/socratic/__init__.py +0 -256
  319. empathy_os/socratic/ab_testing.py +0 -958
  320. empathy_os/socratic/blueprint.py +0 -533
  321. empathy_os/socratic/cli.py +0 -703
  322. empathy_os/socratic/collaboration.py +0 -1114
  323. empathy_os/socratic/domain_templates.py +0 -924
  324. empathy_os/socratic/embeddings.py +0 -738
  325. empathy_os/socratic/engine.py +0 -794
  326. empathy_os/socratic/explainer.py +0 -682
  327. empathy_os/socratic/feedback.py +0 -772
  328. empathy_os/socratic/forms.py +0 -629
  329. empathy_os/socratic/generator.py +0 -732
  330. empathy_os/socratic/llm_analyzer.py +0 -637
  331. empathy_os/socratic/mcp_server.py +0 -702
  332. empathy_os/socratic/session.py +0 -312
  333. empathy_os/socratic/storage.py +0 -667
  334. empathy_os/socratic/success.py +0 -730
  335. empathy_os/socratic/visual_editor.py +0 -860
  336. empathy_os/socratic/web_ui.py +0 -958
  337. empathy_os/telemetry/__init__.py +0 -39
  338. empathy_os/telemetry/agent_coordination.py +0 -475
  339. empathy_os/telemetry/agent_tracking.py +0 -367
  340. empathy_os/telemetry/approval_gates.py +0 -545
  341. empathy_os/telemetry/cli.py +0 -1231
  342. empathy_os/telemetry/commands/__init__.py +0 -14
  343. empathy_os/telemetry/commands/dashboard_commands.py +0 -696
  344. empathy_os/telemetry/event_streaming.py +0 -409
  345. empathy_os/telemetry/feedback_loop.py +0 -567
  346. empathy_os/telemetry/usage_tracker.py +0 -591
  347. empathy_os/templates.py +0 -754
  348. empathy_os/test_generator/__init__.py +0 -38
  349. empathy_os/test_generator/__main__.py +0 -14
  350. empathy_os/test_generator/cli.py +0 -234
  351. empathy_os/test_generator/generator.py +0 -355
  352. empathy_os/test_generator/risk_analyzer.py +0 -216
  353. empathy_os/tier_recommender.py +0 -384
  354. empathy_os/tools.py +0 -183
  355. empathy_os/trust/__init__.py +0 -28
  356. empathy_os/trust/circuit_breaker.py +0 -579
  357. empathy_os/trust_building.py +0 -527
  358. empathy_os/validation/__init__.py +0 -19
  359. empathy_os/validation/xml_validator.py +0 -281
  360. empathy_os/vscode_bridge.py +0 -173
  361. empathy_os/workflow_commands.py +0 -780
  362. empathy_os/workflow_patterns/__init__.py +0 -33
  363. empathy_os/workflow_patterns/behavior.py +0 -249
  364. empathy_os/workflow_patterns/core.py +0 -76
  365. empathy_os/workflow_patterns/output.py +0 -99
  366. empathy_os/workflow_patterns/registry.py +0 -255
  367. empathy_os/workflow_patterns/structural.py +0 -288
  368. empathy_os/workflows/__init__.py +0 -539
  369. empathy_os/workflows/autonomous_test_gen.py +0 -1268
  370. empathy_os/workflows/base.py +0 -2667
  371. empathy_os/workflows/batch_processing.py +0 -342
  372. empathy_os/workflows/bug_predict.py +0 -1084
  373. empathy_os/workflows/builder.py +0 -273
  374. empathy_os/workflows/caching.py +0 -253
  375. empathy_os/workflows/code_review.py +0 -1048
  376. empathy_os/workflows/code_review_adapters.py +0 -312
  377. empathy_os/workflows/code_review_pipeline.py +0 -722
  378. empathy_os/workflows/config.py +0 -645
  379. empathy_os/workflows/dependency_check.py +0 -644
  380. empathy_os/workflows/document_gen/__init__.py +0 -25
  381. empathy_os/workflows/document_gen/config.py +0 -30
  382. empathy_os/workflows/document_gen/report_formatter.py +0 -162
  383. empathy_os/workflows/document_gen/workflow.py +0 -1426
  384. empathy_os/workflows/document_manager.py +0 -216
  385. empathy_os/workflows/document_manager_README.md +0 -134
  386. empathy_os/workflows/documentation_orchestrator.py +0 -1205
  387. empathy_os/workflows/history.py +0 -510
  388. empathy_os/workflows/keyboard_shortcuts/__init__.py +0 -39
  389. empathy_os/workflows/keyboard_shortcuts/generators.py +0 -391
  390. empathy_os/workflows/keyboard_shortcuts/parsers.py +0 -416
  391. empathy_os/workflows/keyboard_shortcuts/prompts.py +0 -295
  392. empathy_os/workflows/keyboard_shortcuts/schema.py +0 -193
  393. empathy_os/workflows/keyboard_shortcuts/workflow.py +0 -509
  394. empathy_os/workflows/llm_base.py +0 -363
  395. empathy_os/workflows/manage_docs.py +0 -87
  396. empathy_os/workflows/manage_docs_README.md +0 -134
  397. empathy_os/workflows/manage_documentation.py +0 -821
  398. empathy_os/workflows/new_sample_workflow1.py +0 -149
  399. empathy_os/workflows/new_sample_workflow1_README.md +0 -150
  400. empathy_os/workflows/orchestrated_health_check.py +0 -849
  401. empathy_os/workflows/orchestrated_release_prep.py +0 -600
  402. empathy_os/workflows/output.py +0 -413
  403. empathy_os/workflows/perf_audit.py +0 -863
  404. empathy_os/workflows/pr_review.py +0 -762
  405. empathy_os/workflows/progress.py +0 -785
  406. empathy_os/workflows/progress_server.py +0 -322
  407. empathy_os/workflows/progressive/README 2.md +0 -454
  408. empathy_os/workflows/progressive/README.md +0 -454
  409. empathy_os/workflows/progressive/__init__.py +0 -82
  410. empathy_os/workflows/progressive/cli.py +0 -219
  411. empathy_os/workflows/progressive/core.py +0 -488
  412. empathy_os/workflows/progressive/orchestrator.py +0 -723
  413. empathy_os/workflows/progressive/reports.py +0 -520
  414. empathy_os/workflows/progressive/telemetry.py +0 -274
  415. empathy_os/workflows/progressive/test_gen.py +0 -495
  416. empathy_os/workflows/progressive/workflow.py +0 -589
  417. empathy_os/workflows/refactor_plan.py +0 -694
  418. empathy_os/workflows/release_prep.py +0 -895
  419. empathy_os/workflows/release_prep_crew.py +0 -969
  420. empathy_os/workflows/research_synthesis.py +0 -404
  421. empathy_os/workflows/routing.py +0 -168
  422. empathy_os/workflows/secure_release.py +0 -593
  423. empathy_os/workflows/security_adapters.py +0 -297
  424. empathy_os/workflows/security_audit.py +0 -1329
  425. empathy_os/workflows/security_audit_phase3.py +0 -355
  426. empathy_os/workflows/seo_optimization.py +0 -633
  427. empathy_os/workflows/step_config.py +0 -234
  428. empathy_os/workflows/telemetry_mixin.py +0 -269
  429. empathy_os/workflows/test5.py +0 -125
  430. empathy_os/workflows/test5_README.md +0 -158
  431. empathy_os/workflows/test_coverage_boost_crew.py +0 -849
  432. empathy_os/workflows/test_gen/__init__.py +0 -52
  433. empathy_os/workflows/test_gen/ast_analyzer.py +0 -249
  434. empathy_os/workflows/test_gen/config.py +0 -88
  435. empathy_os/workflows/test_gen/data_models.py +0 -38
  436. empathy_os/workflows/test_gen/report_formatter.py +0 -289
  437. empathy_os/workflows/test_gen/test_templates.py +0 -381
  438. empathy_os/workflows/test_gen/workflow.py +0 -655
  439. empathy_os/workflows/test_gen.py +0 -54
  440. empathy_os/workflows/test_gen_behavioral.py +0 -477
  441. empathy_os/workflows/test_gen_parallel.py +0 -341
  442. empathy_os/workflows/test_lifecycle.py +0 -526
  443. empathy_os/workflows/test_maintenance.py +0 -627
  444. empathy_os/workflows/test_maintenance_cli.py +0 -590
  445. empathy_os/workflows/test_maintenance_crew.py +0 -840
  446. empathy_os/workflows/test_runner.py +0 -622
  447. empathy_os/workflows/tier_tracking.py +0 -531
  448. empathy_os/workflows/xml_enhanced_crew.py +0 -285
  449. empathy_software_plugin/SOFTWARE_PLUGIN_README.md +0 -57
  450. empathy_software_plugin/cli/__init__.py +0 -120
  451. empathy_software_plugin/cli/inspect.py +0 -362
  452. empathy_software_plugin/cli.py +0 -574
  453. empathy_software_plugin/plugin.py +0 -188
  454. workflow_scaffolding/__init__.py +0 -11
  455. workflow_scaffolding/__main__.py +0 -12
  456. workflow_scaffolding/cli.py +0 -206
  457. workflow_scaffolding/generator.py +0 -265
  458. {empathy_framework-5.3.0.dist-info → empathy_framework-5.4.0.dist-info}/WHEEL +0 -0
@@ -1,863 +0,0 @@
1
- """Performance Audit Workflow
2
-
3
- Identifies performance bottlenecks and optimization opportunities
4
- through static analysis.
5
-
6
- Stages:
7
- 1. profile (CHEAP) - Static analysis for common perf anti-patterns
8
- 2. analyze (CAPABLE) - Deep analysis of algorithmic complexity
9
- 3. hotspots (CAPABLE) - Identify performance hotspots
10
- 4. optimize (PREMIUM) - Generate optimization recommendations (conditional)
11
-
12
- Copyright 2025 Smart-AI-Memory
13
- Licensed under Fair Source License 0.9
14
- """
15
-
16
- import heapq
17
- import json
18
- import re
19
- from pathlib import Path
20
- from typing import Any
21
-
22
- from .base import BaseWorkflow, ModelTier
23
- from .output import Finding, WorkflowReport, get_console
24
- from .step_config import WorkflowStepConfig
25
-
26
- # Define step configurations for executor-based execution
27
- PERF_AUDIT_STEPS = {
28
- "optimize": WorkflowStepConfig(
29
- name="optimize",
30
- task_type="final_review", # Premium tier task
31
- tier_hint="premium",
32
- description="Generate performance optimization recommendations",
33
- max_tokens=3000,
34
- ),
35
- }
36
-
37
- # Performance anti-patterns to detect
38
- PERF_PATTERNS = {
39
- "n_plus_one": {
40
- "patterns": [
41
- r"for\s+\w+\s+in\s+\w+:.*?\.get\(",
42
- r"for\s+\w+\s+in\s+\w+:.*?\.query\(",
43
- r"for\s+\w+\s+in\s+\w+:.*?\.fetch\(",
44
- ],
45
- "description": "Potential N+1 query pattern",
46
- "impact": "high",
47
- },
48
- "sync_in_async": {
49
- "patterns": [
50
- r"async\s+def.*?time\.sleep\(",
51
- r"async\s+def.*?requests\.get\(",
52
- r"async\s+def.*?open\([^)]+\)\.read\(",
53
- ],
54
- "description": "Synchronous operation in async context",
55
- "impact": "high",
56
- },
57
- "list_comprehension_in_loop": {
58
- "patterns": [
59
- r"for\s+\w+\s+in\s+\[.*for.*\]:",
60
- ],
61
- "description": "List comprehension recreated in loop",
62
- "impact": "medium",
63
- },
64
- "string_concat_loop": {
65
- "patterns": [
66
- # Match: for x in y: \n str += "..." (actual loop, not generator expression)
67
- # Exclude: any(... for x in ...) by requiring standalone for statement
68
- r'^[ \t]*for\s+\w+\s+in\s+[^:]+:\s*\n[ \t]+\w+\s*\+=\s*["\']',
69
- ],
70
- "description": "String concatenation in loop (use join)",
71
- "impact": "medium",
72
- },
73
- "global_import": {
74
- "patterns": [
75
- r"^from\s+\w+\s+import\s+\*",
76
- ],
77
- "description": "Wildcard import may slow startup",
78
- "impact": "low",
79
- },
80
- "large_list_copy": {
81
- "patterns": [
82
- r"list\(\w+\)",
83
- r"\w+\[:\]",
84
- ],
85
- "description": "Full list copy (may be inefficient for large lists)",
86
- "impact": "low",
87
- },
88
- "repeated_regex": {
89
- "patterns": [
90
- r're\.(search|match|findall)\s*\(["\'][^"\']+["\']',
91
- ],
92
- "description": "Regex pattern not pre-compiled",
93
- "impact": "medium",
94
- },
95
- "nested_loops": {
96
- "patterns": [
97
- r"for\s+\w+\s+in\s+\w+:\s*\n\s+for\s+\w+\s+in\s+\w+:\s*\n\s+for",
98
- ],
99
- "description": "Triple nested loop (O(n³) complexity)",
100
- "impact": "high",
101
- },
102
- }
103
-
104
- # Known false positives - patterns that match but aren't performance issues
105
- # These are documented for transparency; the regex-based detection has limitations.
106
- #
107
- # IMPROVED: string_concat_loop
108
- # - Pattern now requires line to START with 'for' (excludes generator expressions)
109
- # - Previously matched: any(x for x in y) followed by += on next line
110
- # - Now correctly excludes: generator expressions inside any(), all(), etc.
111
- # - Sequential string building (code += "line1"; code += "line2") correctly ignored
112
- #
113
- # FALSE POSITIVE: large_list_copy
114
- # - list(x) or x[:] used for defensive copying or type conversion
115
- # - Often intentional to avoid mutating original data
116
- # - Verdict: OK - usually intentional, low impact
117
- #
118
- # FALSE POSITIVE: repeated_regex (edge cases)
119
- # - Single-use regex in rarely-called functions
120
- # - Verdict: OK - pre-compilation only matters for hot paths
121
-
122
-
123
- class PerformanceAuditWorkflow(BaseWorkflow):
124
- """Identify performance bottlenecks and optimization opportunities.
125
-
126
- Uses static analysis to find common performance anti-patterns
127
- and algorithmic complexity issues.
128
- """
129
-
130
- name = "perf-audit"
131
- description = "Identify performance bottlenecks and optimization opportunities"
132
- stages = ["profile", "analyze", "hotspots", "optimize"]
133
- tier_map = {
134
- "profile": ModelTier.CHEAP,
135
- "analyze": ModelTier.CAPABLE,
136
- "hotspots": ModelTier.CAPABLE,
137
- "optimize": ModelTier.PREMIUM,
138
- }
139
-
140
- def __init__(
141
- self,
142
- min_hotspots_for_premium: int = 3,
143
- enable_auth_strategy: bool = True,
144
- **kwargs: Any,
145
- ):
146
- """Initialize performance audit workflow.
147
-
148
- Args:
149
- min_hotspots_for_premium: Minimum hotspots to trigger premium optimization
150
- enable_auth_strategy: Enable intelligent auth routing (default: True)
151
- **kwargs: Additional arguments passed to BaseWorkflow
152
-
153
- """
154
- super().__init__(**kwargs)
155
- self.min_hotspots_for_premium = min_hotspots_for_premium
156
- self.enable_auth_strategy = enable_auth_strategy
157
- self._hotspot_count: int = 0
158
- self._auth_mode_used: str | None = None
159
-
160
- def should_skip_stage(self, stage_name: str, input_data: Any) -> tuple[bool, str | None]:
161
- """Downgrade optimize stage if few hotspots.
162
-
163
- Args:
164
- stage_name: Name of the stage to check
165
- input_data: Current workflow data
166
-
167
- Returns:
168
- Tuple of (should_skip, reason)
169
-
170
- """
171
- if stage_name == "optimize":
172
- if self._hotspot_count < self.min_hotspots_for_premium:
173
- self.tier_map["optimize"] = ModelTier.CAPABLE
174
- return False, None
175
- return False, None
176
-
177
- async def run_stage(
178
- self,
179
- stage_name: str,
180
- tier: ModelTier,
181
- input_data: Any,
182
- ) -> tuple[Any, int, int]:
183
- """Route to specific stage implementation."""
184
- if stage_name == "profile":
185
- return await self._profile(input_data, tier)
186
- if stage_name == "analyze":
187
- return await self._analyze(input_data, tier)
188
- if stage_name == "hotspots":
189
- return await self._hotspots(input_data, tier)
190
- if stage_name == "optimize":
191
- return await self._optimize(input_data, tier)
192
- raise ValueError(f"Unknown stage: {stage_name}")
193
-
194
- async def _profile(self, input_data: dict, tier: ModelTier) -> tuple[dict, int, int]:
195
- """Static analysis for common performance anti-patterns.
196
-
197
- Scans code for known performance issues.
198
- """
199
- target_path = input_data.get("path", ".")
200
- file_types = input_data.get("file_types", [".py"])
201
-
202
- findings: list[dict] = []
203
- files_scanned = 0
204
-
205
- target = Path(target_path)
206
-
207
- # === AUTH STRATEGY INTEGRATION ===
208
- if self.enable_auth_strategy:
209
- try:
210
- import logging
211
-
212
- from empathy_os.models import (
213
- count_lines_of_code,
214
- get_auth_strategy,
215
- get_module_size_category,
216
- )
217
-
218
- logger = logging.getLogger(__name__)
219
-
220
- # Calculate total LOC for the project/path
221
- total_lines = 0
222
- if target.is_file():
223
- total_lines = count_lines_of_code(target)
224
- elif target.is_dir():
225
- # Estimate total lines for directory
226
- for ext in file_types:
227
- for file_path in target.rglob(f"*{ext}"):
228
- if any(
229
- skip in str(file_path)
230
- for skip in [".git", "node_modules", "__pycache__", "venv", "test"]
231
- ):
232
- continue
233
- try:
234
- total_lines += count_lines_of_code(file_path)
235
- except Exception:
236
- pass
237
-
238
- if total_lines > 0:
239
- strategy = get_auth_strategy()
240
- recommended_mode = strategy.get_recommended_mode(total_lines)
241
- self._auth_mode_used = recommended_mode.value
242
-
243
- size_category = get_module_size_category(total_lines)
244
- logger.info(
245
- f"Performance audit target: {target_path} "
246
- f"({total_lines:,} LOC, {size_category})"
247
- )
248
- logger.info(f"Recommended auth mode: {recommended_mode.value}")
249
-
250
- cost_estimate = strategy.estimate_cost(total_lines, recommended_mode)
251
- if recommended_mode.value == "subscription":
252
- logger.info(
253
- f"Cost estimate: ~${cost_estimate:.4f} "
254
- "(significantly cheaper with subscription)"
255
- )
256
- else:
257
- logger.info(f"Cost estimate: ~${cost_estimate:.4f} (API-based)")
258
-
259
- except ImportError as e:
260
- import logging
261
-
262
- logger = logging.getLogger(__name__)
263
- logger.debug(f"Auth strategy not available: {e}")
264
- except Exception as e:
265
- import logging
266
-
267
- logger = logging.getLogger(__name__)
268
- logger.warning(f"Auth strategy detection failed: {e}")
269
- # === END AUTH STRATEGY INTEGRATION ===
270
- if target.exists():
271
- for ext in file_types:
272
- for file_path in target.rglob(f"*{ext}"):
273
- if any(
274
- skip in str(file_path)
275
- for skip in [".git", "node_modules", "__pycache__", "venv", "test"]
276
- ):
277
- continue
278
-
279
- try:
280
- content = file_path.read_text(errors="ignore")
281
- files_scanned += 1
282
-
283
- for pattern_name, pattern_info in PERF_PATTERNS.items():
284
- for pattern in pattern_info["patterns"]:
285
- matches = list(re.finditer(pattern, content, re.MULTILINE))
286
- for match in matches:
287
- line_num = content[: match.start()].count("\n") + 1
288
- findings.append(
289
- {
290
- "type": pattern_name,
291
- "file": str(file_path),
292
- "line": line_num,
293
- "description": pattern_info["description"],
294
- "impact": pattern_info["impact"],
295
- "match": match.group()[:80],
296
- },
297
- )
298
- except OSError:
299
- continue
300
-
301
- # Group by impact
302
- by_impact: dict[str, list] = {"high": [], "medium": [], "low": []}
303
- for f in findings:
304
- impact = f.get("impact", "low")
305
- by_impact[impact].append(f)
306
-
307
- input_tokens = len(str(input_data)) // 4
308
- output_tokens = len(str(findings)) // 4
309
-
310
- return (
311
- {
312
- "findings": findings,
313
- "finding_count": len(findings),
314
- "files_scanned": files_scanned,
315
- "by_impact": {k: len(v) for k, v in by_impact.items()},
316
- **input_data,
317
- },
318
- input_tokens,
319
- output_tokens,
320
- )
321
-
322
- async def _analyze(self, input_data: dict, tier: ModelTier) -> tuple[dict, int, int]:
323
- """Deep analysis of algorithmic complexity.
324
-
325
- Examines code structure for complexity issues.
326
- """
327
- findings = input_data.get("findings", [])
328
-
329
- # Group findings by file
330
- by_file: dict[str, list] = {}
331
- for f in findings:
332
- file_path = f.get("file", "")
333
- if file_path not in by_file:
334
- by_file[file_path] = []
335
- by_file[file_path].append(f)
336
-
337
- # Analyze each file
338
- analysis: list[dict] = []
339
- for file_path, file_findings in by_file.items():
340
- # Calculate file complexity score (generator expressions for memory efficiency)
341
- high_count = sum(1 for f in file_findings if f["impact"] == "high")
342
- medium_count = sum(1 for f in file_findings if f["impact"] == "medium")
343
- low_count = sum(1 for f in file_findings if f["impact"] == "low")
344
-
345
- complexity_score = high_count * 10 + medium_count * 5 + low_count * 1
346
-
347
- # Identify primary concerns
348
- concerns = list({f["type"] for f in file_findings})
349
-
350
- analysis.append(
351
- {
352
- "file": file_path,
353
- "complexity_score": complexity_score,
354
- "finding_count": len(file_findings),
355
- "high_impact": high_count,
356
- "concerns": concerns[:5],
357
- },
358
- )
359
-
360
- # Sort by complexity score
361
- analysis.sort(key=lambda x: -x["complexity_score"])
362
-
363
- input_tokens = len(str(input_data)) // 4
364
- output_tokens = len(str(analysis)) // 4
365
-
366
- return (
367
- {
368
- "analysis": analysis,
369
- "analyzed_files": len(analysis),
370
- **input_data,
371
- },
372
- input_tokens,
373
- output_tokens,
374
- )
375
-
376
- async def _hotspots(self, input_data: dict, tier: ModelTier) -> tuple[dict, int, int]:
377
- """Identify performance hotspots.
378
-
379
- Pinpoints files and areas requiring immediate attention.
380
- """
381
- analysis = input_data.get("analysis", [])
382
-
383
- # Top hotspots (highest complexity scores)
384
- hotspots = [a for a in analysis if a["complexity_score"] >= 10 or a["high_impact"] >= 2]
385
-
386
- self._hotspot_count = len(hotspots)
387
-
388
- # Categorize hotspots
389
- critical = [h for h in hotspots if h["complexity_score"] >= 20]
390
- moderate = [h for h in hotspots if 10 <= h["complexity_score"] < 20]
391
-
392
- # Calculate overall perf score (inverse of problems)
393
- total_score = sum(a["complexity_score"] for a in analysis)
394
- max_score = len(analysis) * 30 # Max possible score
395
- perf_score = max(0, 100 - int((total_score / max(max_score, 1)) * 100))
396
-
397
- hotspot_result = {
398
- "hotspots": hotspots[:15], # Top 15
399
- "hotspot_count": self._hotspot_count,
400
- "critical_count": len(critical),
401
- "moderate_count": len(moderate),
402
- "perf_score": perf_score,
403
- "perf_level": (
404
- "critical" if perf_score < 50 else "warning" if perf_score < 75 else "good"
405
- ),
406
- }
407
-
408
- input_tokens = len(str(input_data)) // 4
409
- output_tokens = len(str(hotspot_result)) // 4
410
-
411
- return (
412
- {
413
- "hotspot_result": hotspot_result,
414
- **input_data,
415
- },
416
- input_tokens,
417
- output_tokens,
418
- )
419
-
420
- async def _optimize(self, input_data: dict, tier: ModelTier) -> tuple[dict, int, int]:
421
- """Generate optimization recommendations using LLM.
422
-
423
- Creates actionable recommendations for performance improvements.
424
-
425
- Supports XML-enhanced prompts when enabled in workflow config.
426
- """
427
- hotspot_result = input_data.get("hotspot_result", {})
428
- hotspots = hotspot_result.get("hotspots", [])
429
- findings = input_data.get("findings", [])
430
- target = input_data.get("target", "")
431
-
432
- # Build hotspots summary for LLM
433
- hotspots_summary = []
434
- for h in hotspots[:10]:
435
- hotspots_summary.append(
436
- f"- {h.get('file')}: score={h.get('complexity_score', 0)}, "
437
- f"concerns={', '.join(h.get('concerns', []))}",
438
- )
439
-
440
- # Summary of most common issues
441
- issue_counts: dict[str, int] = {}
442
- for f in findings:
443
- t = f.get("type", "unknown")
444
- issue_counts[t] = issue_counts.get(t, 0) + 1
445
- top_issues = heapq.nlargest(5, issue_counts.items(), key=lambda x: x[1])
446
-
447
- # Build input payload for prompt
448
- input_payload = f"""Target: {target or "codebase"}
449
-
450
- Performance Score: {hotspot_result.get("perf_score", 0)}/100
451
- Performance Level: {hotspot_result.get("perf_level", "unknown")}
452
-
453
- Hotspots:
454
- {chr(10).join(hotspots_summary) if hotspots_summary else "No hotspots identified"}
455
-
456
- Top Issues:
457
- {json.dumps([{"type": t, "count": c} for t, c in top_issues], indent=2)}"""
458
-
459
- # Check if XML prompts are enabled
460
- if self._is_xml_enabled():
461
- # Use XML-enhanced prompt
462
- user_message = self._render_xml_prompt(
463
- role="performance engineer specializing in optimization",
464
- goal="Generate comprehensive optimization recommendations for performance issues",
465
- instructions=[
466
- "Analyze each performance hotspot and its concerns",
467
- "Provide specific optimization strategies with code examples",
468
- "Estimate the impact of each optimization (high/medium/low)",
469
- "Prioritize recommendations by potential performance gain",
470
- "Include before/after code patterns where helpful",
471
- ],
472
- constraints=[
473
- "Be specific about which files and patterns to optimize",
474
- "Include actionable code changes",
475
- "Focus on high-impact optimizations first",
476
- ],
477
- input_type="performance_hotspots",
478
- input_payload=input_payload,
479
- extra={
480
- "perf_score": hotspot_result.get("perf_score", 0),
481
- "hotspot_count": len(hotspots),
482
- },
483
- )
484
- system = None # XML prompt includes all context
485
- else:
486
- # Use legacy plain text prompts
487
- system = """You are a performance engineer specializing in code optimization.
488
- Analyze the identified performance hotspots and generate actionable recommendations.
489
-
490
- For each hotspot:
491
- 1. Explain why the pattern causes performance issues
492
- 2. Provide specific optimization strategies with code examples
493
- 3. Estimate the impact of the optimization
494
-
495
- Prioritize by potential performance gain."""
496
-
497
- user_message = f"""Generate optimization recommendations for these performance issues:
498
-
499
- {input_payload}
500
-
501
- Provide detailed optimization strategies."""
502
-
503
- # Try executor-based execution first (Phase 3 pattern)
504
- if self._executor is not None or self._api_key:
505
- try:
506
- step = PERF_AUDIT_STEPS["optimize"]
507
- response, input_tokens, output_tokens, cost = await self.run_step_with_executor(
508
- step=step,
509
- prompt=user_message,
510
- system=system,
511
- )
512
- except Exception:
513
- # Fall back to legacy _call_llm if executor fails
514
- response, input_tokens, output_tokens = await self._call_llm(
515
- tier,
516
- system or "",
517
- user_message,
518
- max_tokens=3000,
519
- )
520
- else:
521
- # Legacy path for backward compatibility
522
- response, input_tokens, output_tokens = await self._call_llm(
523
- tier,
524
- system or "",
525
- user_message,
526
- max_tokens=3000,
527
- )
528
-
529
- # Parse XML response if enforcement is enabled
530
- parsed_data = self._parse_xml_response(response)
531
-
532
- result = {
533
- "optimization_plan": response,
534
- "recommendation_count": len(hotspots),
535
- "top_issues": [{"type": t, "count": c} for t, c in top_issues],
536
- "perf_score": hotspot_result.get("perf_score", 0),
537
- "perf_level": hotspot_result.get("perf_level", "unknown"),
538
- "model_tier_used": tier.value,
539
- "auth_mode_used": self._auth_mode_used,
540
- }
541
-
542
- # Merge parsed XML data if available
543
- if parsed_data.get("xml_parsed"):
544
- result.update(
545
- {
546
- "xml_parsed": True,
547
- "summary": parsed_data.get("summary"),
548
- "findings": parsed_data.get("findings", []),
549
- "checklist": parsed_data.get("checklist", []),
550
- },
551
- )
552
-
553
- # Add formatted report for human readability
554
- result["formatted_report"] = format_perf_audit_report(result, input_data)
555
-
556
- # Add structured WorkflowReport for Rich rendering
557
- result["workflow_report"] = create_perf_audit_workflow_report(result, input_data)
558
-
559
- return (result, input_tokens, output_tokens)
560
-
561
- def _get_optimization_action(self, concern: str) -> dict | None:
562
- """Generate specific optimization action for a concern type."""
563
- actions = {
564
- "n_plus_one": {
565
- "action": "Batch database queries",
566
- "description": "Use prefetch_related/select_related or batch queries",
567
- "estimated_impact": "high",
568
- },
569
- "sync_in_async": {
570
- "action": "Use async alternatives",
571
- "description": "Replace sync operations with async versions",
572
- "estimated_impact": "high",
573
- },
574
- "string_concat_loop": {
575
- "action": "Use str.join()",
576
- "description": "Build list of strings and join at the end instead of concatenating",
577
- "estimated_impact": "medium",
578
- },
579
- "repeated_regex": {
580
- "action": "Pre-compile regex",
581
- "description": "Use re.compile() and reuse the compiled pattern",
582
- "estimated_impact": "medium",
583
- },
584
- "nested_loops": {
585
- "action": "Optimize algorithm",
586
- "description": "Consider using sets, dicts, or itertools to reduce complexity",
587
- "estimated_impact": "high",
588
- },
589
- "list_comprehension_in_loop": {
590
- "action": "Move comprehension outside loop",
591
- "description": "Create the list once before the loop",
592
- "estimated_impact": "medium",
593
- },
594
- "large_list_copy": {
595
- "action": "Use iterators",
596
- "description": "Consider using iterators instead of copying entire lists",
597
- "estimated_impact": "low",
598
- },
599
- "global_import": {
600
- "action": "Use specific imports",
601
- "description": "Import only needed names to reduce memory and startup time",
602
- "estimated_impact": "low",
603
- },
604
- }
605
- return actions.get(concern)
606
-
607
-
608
- def create_perf_audit_workflow_report(result: dict, input_data: dict) -> WorkflowReport:
609
- """Create a WorkflowReport from performance audit results.
610
-
611
- Args:
612
- result: The optimize stage result
613
- input_data: Input data from previous stages
614
-
615
- Returns:
616
- WorkflowReport instance for Rich or plain text rendering
617
- """
618
- perf_score = result.get("perf_score", 0)
619
- perf_level = result.get("perf_level", "unknown")
620
-
621
- # Determine report level
622
- if perf_score >= 85:
623
- level = "success"
624
- elif perf_score >= 50:
625
- level = "warning"
626
- else:
627
- level = "error"
628
-
629
- # Build summary
630
- files_scanned = input_data.get("files_scanned", 0)
631
- finding_count = input_data.get("finding_count", 0)
632
- by_impact = input_data.get("by_impact", {})
633
-
634
- summary = (
635
- f"Scanned {files_scanned} files, found {finding_count} issues. "
636
- f"High: {by_impact.get('high', 0)}, Medium: {by_impact.get('medium', 0)}, "
637
- f"Low: {by_impact.get('low', 0)}"
638
- )
639
-
640
- report = WorkflowReport(
641
- title="Performance Audit Report",
642
- summary=summary,
643
- score=perf_score,
644
- level=level,
645
- metadata={
646
- "perf_level": perf_level,
647
- "files_scanned": files_scanned,
648
- "finding_count": finding_count,
649
- },
650
- )
651
-
652
- # Add top issues section
653
- top_issues = result.get("top_issues", [])
654
- if top_issues:
655
- issues_content = {
656
- issue.get("type", "unknown").replace("_", " ").title(): f"{issue.get('count', 0)} occurrences"
657
- for issue in top_issues
658
- }
659
- report.add_section("Top Performance Issues", issues_content)
660
-
661
- # Add hotspots section
662
- hotspot_result = input_data.get("hotspot_result", {})
663
- hotspots = hotspot_result.get("hotspots", [])
664
- if hotspots:
665
- hotspot_content = {
666
- "Critical Hotspots": hotspot_result.get("critical_count", 0),
667
- "Moderate Hotspots": hotspot_result.get("moderate_count", 0),
668
- }
669
- report.add_section("Hotspot Summary", hotspot_content)
670
-
671
- # Add findings section
672
- findings = input_data.get("findings", [])
673
- high_impact = [f for f in findings if f.get("impact") == "high"]
674
- if high_impact:
675
- finding_objs = [
676
- Finding(
677
- severity="high",
678
- file=f.get("file", "unknown"),
679
- line=f.get("line"),
680
- message=f.get("description", ""),
681
- )
682
- for f in high_impact[:10]
683
- ]
684
- report.add_section("High Impact Findings", finding_objs, style="error")
685
-
686
- # Add recommendations section
687
- optimization_plan = result.get("optimization_plan", "")
688
- if optimization_plan:
689
- report.add_section("Optimization Recommendations", optimization_plan)
690
-
691
- return report
692
-
693
-
694
- def format_perf_audit_report(result: dict, input_data: dict) -> str:
695
- """Format performance audit output as a human-readable report.
696
-
697
- Args:
698
- result: The optimize stage result
699
- input_data: Input data from previous stages
700
-
701
- Returns:
702
- Formatted report string
703
-
704
- """
705
- lines = []
706
-
707
- # Header with performance score
708
- perf_score = result.get("perf_score", 0)
709
- perf_level = result.get("perf_level", "unknown").upper()
710
-
711
- if perf_score >= 85:
712
- perf_icon = "🟢"
713
- perf_text = "EXCELLENT"
714
- elif perf_score >= 75:
715
- perf_icon = "🟡"
716
- perf_text = "GOOD"
717
- elif perf_score >= 50:
718
- perf_icon = "🟠"
719
- perf_text = "NEEDS OPTIMIZATION"
720
- else:
721
- perf_icon = "🔴"
722
- perf_text = "CRITICAL"
723
-
724
- lines.append("=" * 60)
725
- lines.append("PERFORMANCE AUDIT REPORT")
726
- lines.append("=" * 60)
727
- lines.append("")
728
- lines.append(f"Performance Score: {perf_icon} {perf_score}/100 ({perf_text})")
729
- lines.append(f"Performance Level: {perf_level}")
730
- lines.append("")
731
-
732
- # Scan summary
733
- files_scanned = input_data.get("files_scanned", 0)
734
- finding_count = input_data.get("finding_count", 0)
735
- by_impact = input_data.get("by_impact", {})
736
-
737
- lines.append("-" * 60)
738
- lines.append("SCAN SUMMARY")
739
- lines.append("-" * 60)
740
- lines.append(f"Files Scanned: {files_scanned}")
741
- lines.append(f"Issues Found: {finding_count}")
742
- lines.append("")
743
- lines.append("Issues by Impact:")
744
- lines.append(f" 🔴 High: {by_impact.get('high', 0)}")
745
- lines.append(f" 🟡 Medium: {by_impact.get('medium', 0)}")
746
- lines.append(f" 🟢 Low: {by_impact.get('low', 0)}")
747
- lines.append("")
748
-
749
- # Top issues
750
- top_issues = result.get("top_issues", [])
751
- if top_issues:
752
- lines.append("-" * 60)
753
- lines.append("TOP PERFORMANCE ISSUES")
754
- lines.append("-" * 60)
755
- for issue in top_issues:
756
- issue_type = issue.get("type", "unknown").replace("_", " ").title()
757
- count = issue.get("count", 0)
758
- lines.append(f" • {issue_type}: {count} occurrences")
759
- lines.append("")
760
-
761
- # Hotspots
762
- hotspot_result = input_data.get("hotspot_result", {})
763
- hotspots = hotspot_result.get("hotspots", [])
764
- if hotspots:
765
- lines.append("-" * 60)
766
- lines.append("PERFORMANCE HOTSPOTS")
767
- lines.append("-" * 60)
768
- lines.append(f"Critical Hotspots: {hotspot_result.get('critical_count', 0)}")
769
- lines.append(f"Moderate Hotspots: {hotspot_result.get('moderate_count', 0)}")
770
- lines.append("")
771
- for h in hotspots[:8]:
772
- file_path = h.get("file", "unknown")
773
- score = h.get("complexity_score", 0)
774
- concerns = h.get("concerns", [])
775
- score_icon = "🔴" if score >= 20 else "🟠" if score >= 10 else "🟡"
776
- lines.append(f" {score_icon} {file_path}")
777
- lines.append(f" Score: {score} | Concerns: {', '.join(concerns[:3])}")
778
- lines.append("")
779
-
780
- # High impact findings
781
- findings = input_data.get("findings", [])
782
- high_impact = [f for f in findings if f.get("impact") == "high"]
783
- if high_impact:
784
- lines.append("-" * 60)
785
- lines.append("HIGH IMPACT FINDINGS")
786
- lines.append("-" * 60)
787
- for f in high_impact[:10]:
788
- file_path = f.get("file", "unknown")
789
- line = f.get("line", "?")
790
- desc = f.get("description", "Unknown issue")
791
- lines.append(f" 🔴 {file_path}:{line}")
792
- lines.append(f" {desc}")
793
- lines.append("")
794
-
795
- # Optimization recommendations
796
- optimization_plan = result.get("optimization_plan", "")
797
- if optimization_plan:
798
- lines.append("-" * 60)
799
- lines.append("OPTIMIZATION RECOMMENDATIONS")
800
- lines.append("-" * 60)
801
- lines.append(optimization_plan)
802
- lines.append("")
803
-
804
- # Footer
805
- lines.append("=" * 60)
806
- model_tier = result.get("model_tier_used", "unknown")
807
- rec_count = result.get("recommendation_count", 0)
808
- lines.append(f"Analyzed {rec_count} hotspots using {model_tier} tier model")
809
- lines.append("=" * 60)
810
-
811
- return "\n".join(lines)
812
-
813
-
814
- def main():
815
- """CLI entry point for performance audit workflow."""
816
- import asyncio
817
-
818
- async def run():
819
- workflow = PerformanceAuditWorkflow()
820
- result = await workflow.execute(path=".", file_types=[".py"])
821
-
822
- output = result.final_output
823
-
824
- # Try Rich output first
825
- console = get_console()
826
- workflow_report = output.get("workflow_report")
827
-
828
- if console and workflow_report:
829
- # Render with Rich
830
- workflow_report.render(console, use_rich=True)
831
- console.print()
832
- console.print(f"[dim]Provider: {result.provider}[/dim]")
833
- console.print(f"[dim]Cost: ${result.cost_report.total_cost:.4f}[/dim]")
834
- savings = result.cost_report.savings
835
- pct = result.cost_report.savings_percent
836
- console.print(f"[dim]Savings: ${savings:.4f} ({pct:.1f}%)[/dim]")
837
- else:
838
- # Fallback to plain text
839
- print("\nPerformance Audit Results")
840
- print("=" * 50)
841
- print(f"Provider: {result.provider}")
842
- print(f"Success: {result.success}")
843
-
844
- print(f"Performance Level: {output.get('perf_level', 'N/A')}")
845
- print(f"Performance Score: {output.get('perf_score', 0)}/100")
846
- print(f"Recommendations: {output.get('recommendation_count', 0)}")
847
-
848
- if output.get("top_issues"):
849
- print("\nTop Issues:")
850
- for issue in output["top_issues"]:
851
- print(f" - {issue['type']}: {issue['count']} occurrences")
852
-
853
- print("\nCost Report:")
854
- print(f" Total Cost: ${result.cost_report.total_cost:.4f}")
855
- savings = result.cost_report.savings
856
- pct = result.cost_report.savings_percent
857
- print(f" Savings: ${savings:.4f} ({pct:.1f}%)")
858
-
859
- asyncio.run(run())
860
-
861
-
862
- if __name__ == "__main__":
863
- main()