forked from HKUDS/DeepCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_evaluation_workflow.py
More file actions
3056 lines (2642 loc) · 128 KB
/
code_evaluation_workflow.py
File metadata and controls
3056 lines (2642 loc) · 128 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Code Evaluation Workflow - Multi-Agent Collaborative Repository Validation
ENHANCED VERSION: Uses multi-file capabilities for efficient batch processing
"""
import json
import logging
import os
import sys
import time
import yaml
from typing import Dict, Any, Optional, List
from dataclasses import dataclass, asdict
from enum import Enum
# MCP Agent imports
from mcp_agent.agents.agent import Agent
# Local imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from prompts.evaluation_prompts import (
ORCHESTRATOR_AGENT_PROMPT,
CODE_ANALYZER_AGENT_PROMPT,
CODE_REVISE_AGENT_PROMPT,
)
from utils.llm_utils import get_preferred_llm_class, get_default_models
# Import Memory Agent for code summaries
from agents.memory_agent_concise_multi import ConciseMemoryAgent
class EvaluationPhase(Enum):
"""Evaluation workflow phases"""
INITIALIZED = "initialized"
ANALYZING = "analyzing"
REVISING = "revising"
STATIC_ANALYSIS = "static_analysis"
ERROR_ANALYSIS = (
"error_analysis" # NEW: Phase 4 - Advanced error analysis and remediation
)
COMPLETED = "completed"
FAILED = "failed"
@dataclass
class CodeAnalysisResult:
"""Code analysis results structure"""
repo_type: str # academic/engineering/library/application
languages: List[str]
frameworks: List[str]
dependencies: Dict[str, Any]
structure_summary: str
quality_issues: List[str]
documentation_completeness: float
reproduction_readiness: Dict[str, Any]
confidence_score: float
@dataclass
class CodeRevisionResult:
"""Code revision results structure"""
revision_success: bool
tasks_completed: List[str]
tasks_failed: List[str]
files_created: List[str]
files_modified: List[str]
empty_files_implemented: int
missing_files_created: int
quality_issues_fixed: int
revision_issues: List[str]
final_project_health: str
execution_logs: List[str]
total_tasks: int
completion_rate: float
batch_operations: List[Dict[str, Any]] # Track multi-file operations
@dataclass
class StaticAnalysisResult:
"""Static analysis results structure"""
analysis_success: bool
total_files_analyzed: int
languages_detected: List[str]
total_issues_found: int
auto_fixes_applied: int
analysis_duration_seconds: float
issues_by_severity: Dict[str, int]
tools_used: List[str]
syntax_errors_found: int
formatting_fixes_applied: int
most_problematic_files: List[str]
static_analysis_report: Optional[Dict[str, Any]] = None
@dataclass
class ErrorAnalysisResult:
"""Error analysis results structure for Phase 4"""
analysis_success: bool
error_reports_generated: int
suspect_files_identified: int
remediation_tasks_created: int
sandbox_executions_completed: int
critical_errors_found: int
high_confidence_fixes: int
analysis_duration_seconds: float
error_types_found: List[str]
most_problematic_files: List[str]
remediation_success_rate: float
error_analysis_reports: List[Dict[str, Any]] = None
def __post_init__(self):
if self.error_analysis_reports is None:
self.error_analysis_reports = []
@dataclass
class EvaluationState:
"""Shared state across all agents"""
phase: EvaluationPhase
repo_path: str
docs_path: str
memory_path: str
workspace_dir: str
start_time: float
code_analysis: Optional[CodeAnalysisResult] = None
code_revision: Optional[CodeRevisionResult] = None
static_analysis: Optional[StaticAnalysisResult] = (
None # Phase 3: Static analysis results
)
error_analysis: Optional[ErrorAnalysisResult] = (
None # NEW: Phase 4: Error analysis results
)
revision_report: Optional[Dict[str, Any]] = None
all_files_to_implement: List[str] = (
None # NEW: Track all files from revision report
)
errors: List[str] = None
warnings: List[str] = None
def __post_init__(self):
if self.errors is None:
self.errors = []
if self.warnings is None:
self.warnings = []
if self.all_files_to_implement is None:
self.all_files_to_implement = []
def to_dict(self) -> Dict[str, Any]:
"""Convert state to dictionary for serialization"""
result = asdict(self)
result["phase"] = self.phase.value
return result
def add_error(self, error: str):
"""Add error to state"""
self.errors.append(f"[{time.strftime('%H:%M:%S')}] {error}")
def add_warning(self, warning: str):
"""Add warning to state"""
self.warnings.append(f"[{time.strftime('%H:%M:%S')}] {warning}")
class CodeEvaluationWorkflow:
"""
Multi-Agent Code Evaluation Workflow Manager
ENHANCED: Uses multi-file capabilities for efficient batch processing
"""
def __init__(
self, config_path: str = "mcp_agent.secrets.yaml", max_files_per_batch: int = 3
):
"""Initialize workflow with configuration"""
self.config_path = config_path
self.api_config = self._load_api_config()
self.default_models = get_default_models("mcp_agent.config.yaml")
self.logger = self._create_logger()
self.max_files_per_batch = max_files_per_batch
# Agent instances
self.orchestrator = None
self.code_analyzer = None
self.code_revise = None
# Memory agent for iterative implementation
self.memory_agent = None
# Shared state
self.evaluation_state = None
def _load_api_config(self) -> Dict[str, Any]:
"""Load API configuration from YAML file"""
try:
with open(self.config_path, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
except Exception as e:
raise Exception(f"Failed to load API config: {e}")
def _create_logger(self) -> logging.Logger:
"""Create and configure logger"""
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Check if handlers already exist to avoid duplicates
if not logger.handlers:
# Create console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
# Create simple formatter (just the message, no timestamp)
formatter = logging.Formatter("%(message)s")
console_handler.setFormatter(formatter)
# Add handler to logger
logger.addHandler(console_handler)
return logger
async def run_evaluation(
self,
repo_path: str,
docs_path: str,
memory_path: str,
workspace_dir: Optional[str] = None,
) -> Dict[str, Any]:
"""
Run complete evaluation workflow with iterative code implementation using multi-file capabilities
Args:
repo_path: Path to repository to evaluate
docs_path: Path to reproduction documentation
memory_path: Path to memory file for code summaries
workspace_dir: Working directory for evaluation (auto-created if None)
Returns:
Comprehensive evaluation results
"""
try:
# Initialize workspace and state
if workspace_dir is None:
workspace_dir = os.path.join(
os.path.abspath(repo_path), ".evaluation", f"run_{int(time.time())}"
)
os.makedirs(workspace_dir, exist_ok=True)
self.logger.info(f"🎯 Workspace: {workspace_dir}")
self.evaluation_state = EvaluationState(
phase=EvaluationPhase.INITIALIZED,
repo_path=os.path.abspath(repo_path),
docs_path=os.path.abspath(docs_path),
memory_path=os.path.abspath(memory_path),
workspace_dir=workspace_dir,
start_time=time.time(),
)
self.logger.info("=" * 80)
self.logger.info("🚀 STARTING ENHANCED MULTI-FILE CODE EVALUATION WORKFLOW")
self.logger.info("=" * 80)
self.logger.info(f"📂 Repository: {repo_path}")
self.logger.info(f"📄 Documentation: {docs_path}")
self.logger.info(f"🧠 Memory Path: {memory_path}")
self.logger.info(f"🎯 Workspace: {workspace_dir}")
self.logger.info(f"📦 Max files per batch: {self.max_files_per_batch}")
self.logger.info("=" * 80)
# Initialize agents (including memory agent with multi-file support)
await self._initialize_agents()
# PHASE 1: Analysis and Revision Report Generation (ANALYZER AGENT ONLY)
self.logger.info(
"🔍 Phase 1: Repository Analysis & Revision Report Generation"
)
self.logger.info("📋 Analyzer Agent will generate ALL revision reports")
self.evaluation_state.phase = EvaluationPhase.ANALYZING
await self._run_analysis_and_generate_revision_reports()
# Verify that revision reports were generated
if not self.evaluation_state.revision_report:
raise Exception(
"Analyzer Agent failed to generate revision reports - cannot proceed to revision phase"
)
self.logger.info(
"✅ Analysis phase completed - revision reports generated by Analyzer Agent"
)
# PHASE 2: Iterative Multi-File Code Revision Execution (CODE REVISE AGENT + MEMORY AGENT)
self.logger.info("🔧 Phase 2: Enhanced Multi-File Code Revision Execution")
self.logger.info(
"⚙️ Code Revise Agent will execute ALL revision tasks with multi-file batching"
)
self.logger.info(
"🧠 Memory Agent will manage multi-file code summaries after each batch"
)
self.evaluation_state.phase = EvaluationPhase.REVISING
# Execute iterative revision with multi-file memory management
revision_completed = (
await self._run_iterative_multi_file_revision_execution()
)
if not revision_completed:
self.logger.error(
"❌ Multi-file code revision phase failed to complete properly"
)
raise Exception(
"Multi-file code revision phase did not complete successfully"
)
self.logger.info(
"✅ Enhanced multi-file revision phase completed - all tasks executed by Code Revise Agent"
)
# PHASE 3: Static Analysis and Automatic Fixes
self.logger.info("🔍 Phase 3: Static Analysis and Code Quality Fixes")
self.logger.info(
"🛠️ Analyzer Agent will perform static analysis and apply automatic fixes"
)
self.evaluation_state.phase = EvaluationPhase.STATIC_ANALYSIS
static_analysis_completed = await self._run_static_analysis_phase()
if not static_analysis_completed:
self.logger.warning(
"⚠️ Static analysis phase failed but continuing to error analysis"
)
self.logger.info("✅ Static analysis phase completed")
# PHASE 4: Advanced Error Analysis and Remediation
self.logger.info(
"🔬 Phase 4: Advanced Error Analysis and Targeted Remediation"
)
self.logger.info(
"🎯 Analyzer Agent will perform error analysis, sandbox execution, and targeted fixes"
)
self.evaluation_state.phase = EvaluationPhase.ERROR_ANALYSIS
error_analysis_completed = await self._run_error_analysis_phase()
if not error_analysis_completed:
self.logger.warning(
"⚠️ Error analysis phase failed but continuing to final evaluation"
)
self.logger.info("✅ Error analysis phase completed")
# PHASE 5: Final Evaluation
self.logger.info("📊 Phase 5: Final Evaluation")
self.evaluation_state.phase = EvaluationPhase.COMPLETED
results = await self._generate_final_report()
self.logger.info(
"✅ Enhanced multi-file evaluation workflow with static analysis and error analysis completed successfully"
)
return results
except Exception as e:
self.logger.error(f"❌ Evaluation workflow failed: {e}")
if self.evaluation_state:
self.evaluation_state.phase = EvaluationPhase.FAILED
self.evaluation_state.add_error(str(e))
return {
"status": "error",
"message": str(e),
"repo_path": repo_path,
"docs_path": docs_path,
}
finally:
await self._cleanup_agents()
async def _initialize_agents(self):
"""Initialize all agents with MCP connections"""
try:
# Initialize Orchestrator Agent
self.orchestrator = Agent(
name="EvaluationOrchestrator",
instruction=ORCHESTRATOR_AGENT_PROMPT,
server_names=["code-evaluation"],
)
await self.orchestrator.__aenter__()
await self.orchestrator.attach_llm(
get_preferred_llm_class(self.config_path)
)
# Initialize Code Analyzer Agent (RESPONSIBLE FOR ALL ANALYSIS AND REVISION REPORTS)
self.logger.info(
"🔬 Initializing Code Analyzer Agent - will handle ALL revision report generation"
)
self.code_analyzer = Agent(
name="CodeAnalyzer",
instruction=CODE_ANALYZER_AGENT_PROMPT,
server_names=["code-evaluation", "filesystem"],
)
await self.code_analyzer.__aenter__()
await self.code_analyzer.attach_llm(
get_preferred_llm_class(self.config_path)
)
# Initialize Code Revise Agent (RESPONSIBLE FOR ALL REVISION EXECUTION WITH MULTI-FILE SUPPORT)
self.logger.info(
"⚙️ Initializing Code Revise Agent - will handle ALL revision task execution with multi-file capabilities"
)
self.code_revise = Agent(
name="CodeRevise",
instruction=CODE_REVISE_AGENT_PROMPT,
server_names=["code-implementation", "code-evaluation"],
)
await self.code_revise.__aenter__()
await self.code_revise.attach_llm(get_preferred_llm_class(self.config_path))
# Test Code Revise Agent connectivity with improved error handling
try:
# Test basic connectivity with a simple tool call
test_result = await self.code_revise.call_tool(
"get_operation_history", {"last_n": 1}
)
self.logger.info("✅ Code Revise Agent connectivity test successful")
# Test multi-file tools availability more safely
await self._test_multi_file_tools_availability()
except Exception as e:
self.logger.error(f"❌ Code Revise Agent connectivity test failed: {e}")
# Don't fail initialization, just log the issue
self.logger.warning(
"⚠️ Continuing without full connectivity verification"
)
# Initialize Memory Agent for iterative multi-file implementation tracking
self.logger.info(
"🧠 Initializing Memory Agent - will manage multi-file code summaries and iteration"
)
await self._initialize_memory_agent()
self.logger.info(
"🤖 All agents initialized successfully with multi-file capabilities"
)
except Exception as e:
self.logger.error(f"Failed to initialize agents: {e}")
raise
async def _test_multi_file_tools_availability(self):
"""Test availability of multi-file tools with safe error handling"""
try:
# Test write_multiple_files availability
try:
# Try calling with invalid input to see if tool exists
await self.code_revise.call_tool(
"write_multiple_files",
{
"file_implementations": "{}" # Empty but valid JSON
},
)
self.logger.info("📦 write_multiple_files tool available")
except Exception as e:
# Tool might exist but fail due to empty input - check error message
if "write_multiple_files" in str(e) or "file_implementations" in str(e):
self.logger.info(
"📦 write_multiple_files tool available (validated via error response)"
)
else:
self.logger.warning(
f"📦 write_multiple_files tool may not be available: {e}"
)
# Test read_multiple_files availability
try:
await self.code_revise.call_tool(
"read_multiple_files",
{
"file_requests": "[]" # Empty but valid JSON array
},
)
self.logger.info("📖 read_multiple_files tool available")
except Exception as e:
if "read_multiple_files" in str(e) or "file_requests" in str(e):
self.logger.info(
"📖 read_multiple_files tool available (validated via error response)"
)
else:
self.logger.warning(
f"📖 read_multiple_files tool may not be available: {e}"
)
except Exception as e:
self.logger.warning(f"Multi-file tools availability test failed: {e}")
self.logger.info(
"📦 Will attempt to use tools during execution and handle errors gracefully"
)
async def _initialize_memory_agent(self):
"""Initialize Memory Agent for iterative multi-file code implementation"""
try:
# Read initial plan content
with open(self.evaluation_state.docs_path, "r", encoding="utf-8") as f:
initial_plan_content = f.read()
memory_path = os.path.dirname(self.evaluation_state.memory_path)
# Initialize memory agent with multi-file support
self.memory_agent = ConciseMemoryAgent(
initial_plan_content=initial_plan_content,
logger=self.logger,
target_directory=memory_path,
default_models=self.default_models,
max_files_per_batch=self.max_files_per_batch,
)
self.logger.info(
f"✅ Memory Agent initialized with multi-file support (max {self.max_files_per_batch} files per batch)"
)
except Exception as e:
self.logger.error(f"Failed to initialize Memory Agent: {e}")
raise
# TODO: The prompt is not good, need to be improved
# YOUR RESPONSIBILITIES (ANALYZER AGENT ONLY):
# 1. **Repository Analysis Tasks:**
# - Use detect_empty_files to identify empty files needing implementation
# - Use detect_missing_files to find missing essential files
# - Use analyze_repo_structure to get overall repository structure
# - Use detect_dependencies to identify project dependencies
# - Use assess_code_quality to evaluate code quality metrics
# - Use evaluate_documentation to assess documentation completeness
# - Use check_reproduction_readiness to determine readiness for reproduction
async def _run_analysis_and_generate_revision_reports(self):
"""
PHASE 1: Analysis and Revision Report Generation
ONLY the Analyzer Agent is responsible for this phase
"""
try:
self.logger.info(
"🔬 Starting comprehensive analysis and revision report generation"
)
self.logger.info(
"📋 Analyzer Agent has SOLE responsibility for generating revision reports"
)
# Initialize LLM client
client, client_type = await self._initialize_llm_client()
# Prepare tools for code analysis
tools = self._prepare_analyzer_tool_definitions()
# Enhanced system message for analyzer agent
system_message = CODE_ANALYZER_AGENT_PROMPT.format(
root_dir=self.evaluation_state.repo_path,
analysis_task=f"Comprehensive analysis and revision report generation for {self.evaluation_state.repo_path}",
)
# Create comprehensive analysis message
analysis_message = f"""You are the ANALYZER AGENT responsible for comprehensive repository analysis AND generating ALL revision reports.
Repository Path: {self.evaluation_state.repo_path}
Documentation Path: {self.evaluation_state.docs_path}
YOUR RESPONSIBILITIES:
1. **CRITICAL: Revision Report Generation (YOUR PRIMARY RESPONSIBILITY):**
- Use generate_code_revision_report to create the comprehensive revision plan
- This report will be passed to the Code Revise Agent for MULTI-FILE BATCH execution
- Ensure the revision report contains SPECIFIC FILE PATHS for each task
- Include detailed file lists with proper path structures for batch processing
2. **Final Summary:**
- Use generate_evaluation_summary to create analysis summary
WORKFLOW ORDER:
1. First: Generate comprehensive revision report using generate_code_revision_report
2. Second: Generate evaluation summary
CRITICAL: The Code Revise Agent will process your revision report using MULTI-FILE BATCHING - ensure each task contains SPECIFIC FILE PATHS suitable for batch processing!"""
messages = [{"role": "user", "content": analysis_message}]
# Call LLM with tools
response = await self._call_llm_with_tools(
client, client_type, system_message, messages, tools
)
# Handle tool calls from LLM
analysis_results = {}
revision_report_generated = False
if response.get("tool_calls"):
for tool_call in response["tool_calls"]:
tool_name = tool_call["name"]
tool_input = tool_call["input"]
# Execute the tool call through MCP agent
tool_result = await self.code_analyzer.call_tool(
tool_name, tool_input
)
analysis_results[tool_name] = tool_result
self.logger.info(f"✅ Analyzer Agent executed: {tool_name}")
# Track revision report generation
if tool_name == "generate_code_revision_report":
revision_report_generated = True
# CRITICAL: Ensure revision report was generated
if not revision_report_generated:
self.logger.warning(
"⚠️ Revision report not generated in main flow - generating now..."
)
revision_result = await self.code_analyzer.call_tool(
"generate_code_revision_report",
{
"repo_path": self.evaluation_state.repo_path,
"docs_path": self.evaluation_state.docs_path,
},
)
analysis_results["generate_code_revision_report"] = revision_result
revision_report_generated = True
# Process and store the revision report
if "generate_code_revision_report" in analysis_results:
revision_result = analysis_results["generate_code_revision_report"]
revision_content = self._extract_tool_result_content(revision_result)
revision_data = self._safe_parse_json(
revision_content, "Analyzer revision report"
)
revision_data = self._normalize_revision_data(
revision_data, "Analyzer revision report"
)
if (
isinstance(revision_data, dict)
and revision_data.get("status") == "success"
):
self.evaluation_state.revision_report = revision_data
self.logger.info(
"✅ Analyzer Agent successfully generated revision report"
)
# Extract all files from revision tasks for workflow tracking
revision_tasks = revision_data.get("revision_report", {}).get(
"revision_tasks", []
)
all_files = self._extract_all_files_from_revision_tasks(
revision_tasks
)
self.evaluation_state.all_files_to_implement = all_files
self.logger.info(
f"📋 Revision report contains {len(revision_tasks)} tasks for multi-file batch execution"
)
self.logger.info(
f"📁 Total unique files to implement: {len(all_files)}"
)
# Debug: Log file extraction for multi-file batching verification
total_files = len(all_files)
for task in revision_tasks:
files = self._extract_files_from_revision_task(task)
self.logger.info(
f"🔍 Task {task.get('task_id')}: Found {len(files)} files for batch processing"
)
if files:
self.logger.info(f" 📄 Files: {files[:]}...")
batches_needed = (
total_files + self.max_files_per_batch - 1
) // self.max_files_per_batch
self.logger.info(
f"📦 Estimated {batches_needed} multi-file batches needed for {total_files} total files"
)
else:
raise Exception(
f"Analyzer Agent failed to generate valid revision report: {revision_data}"
)
# Process analysis results for summary
analysis_result = self._process_analysis_results(analysis_results, response)
self.evaluation_state.code_analysis = analysis_result
self.logger.info("✅ Analyzer Agent completed all responsibilities:")
self.logger.info(" ✓ Repository analysis")
self.logger.info(" ✓ Revision report generation")
self.logger.info(" ✓ Evaluation summary")
except Exception as e:
self.evaluation_state.add_error(f"Analyzer Agent failed: {e}")
raise Exception(
f"Analyzer Agent failed to complete analysis and revision report generation: {e}"
)
def _extract_all_files_from_revision_tasks(
self, revision_tasks: List[Dict[str, Any]]
) -> List[str]:
"""
Extract all unique files from all revision tasks for workflow tracking
Args:
revision_tasks: List of revision tasks from the revision report
Returns:
List of all unique file paths mentioned in all tasks
"""
all_files = []
for task in revision_tasks:
task_files = self._extract_files_from_revision_task(task)
all_files.extend(task_files)
# Remove duplicates while preserving order
unique_files = []
seen = set()
for file_path in all_files:
if file_path not in seen:
seen.add(file_path)
unique_files.append(file_path)
self.logger.info(
f"📁 Extracted {len(unique_files)} unique files from {len(revision_tasks)} revision tasks"
)
return unique_files
async def _run_static_analysis_phase(self) -> bool:
"""
PHASE 3: Static Analysis and Automatic Code Quality Fixes
Uses the Analyzer Agent to perform comprehensive static analysis and apply automatic fixes
"""
try:
self.logger.info("🔍 Starting static analysis phase with automatic fixes")
# Use the Analyzer Agent to perform static analysis with automatic fixes
self.logger.info(
"🛠️ Running comprehensive static analysis with automatic formatting fixes"
)
static_analysis_result = await self.code_analyzer.call_tool(
"perform_static_analysis",
{
"repo_path": self.evaluation_state.repo_path,
"auto_fix": True, # Enable automatic fixes
"languages": None, # Auto-detect all languages
},
)
# Parse static analysis results
static_content = self._extract_tool_result_content(static_analysis_result)
static_data = self._safe_parse_json(static_content, "Static analysis")
if isinstance(static_data, dict) and static_data.get("status") == "success":
analysis = static_data.get("analysis", {})
summary = static_data.get("summary", {})
# Create StaticAnalysisResult
self.evaluation_state.static_analysis = StaticAnalysisResult(
analysis_success=True,
total_files_analyzed=summary.get("total_files_analyzed", 0),
languages_detected=analysis.get("languages_detected", []),
total_issues_found=summary.get("total_issues_found", 0),
auto_fixes_applied=summary.get("auto_fixes_applied", 0),
analysis_duration_seconds=summary.get(
"analysis_duration_seconds", 0.0
),
issues_by_severity=summary.get("issues_by_severity", {}),
tools_used=summary.get("tools_used", []),
syntax_errors_found=summary.get("issues_by_severity", {}).get(
"errors", 0
),
formatting_fixes_applied=summary.get("auto_fixes_applied", 0),
most_problematic_files=[],
static_analysis_report=static_data,
)
self.logger.info("✅ Static analysis completed:")
self.logger.info(
f" 📁 Files analyzed: {summary.get('total_files_analyzed', 0)}"
)
self.logger.info(
f" 🔧 Languages detected: {len(analysis.get('languages_detected', []))}"
)
self.logger.info(
f" ⚠️ Issues found: {summary.get('total_issues_found', 0)}"
)
self.logger.info(
f" 🔨 Auto-fixes applied: {summary.get('auto_fixes_applied', 0)}"
)
self.logger.info(
f" ⏱️ Duration: {summary.get('analysis_duration_seconds', 0.0):.2f}s"
)
self.logger.info(
f" 🛠️ Tools used: {', '.join(summary.get('tools_used', []))}"
)
# Generate detailed issues report if issues were found
if summary.get("total_issues_found", 0) > 0:
self.logger.info(
"📊 Generating detailed static analysis issues report"
)
issues_report_result = await self.code_analyzer.call_tool(
"generate_static_issues_report",
{
"repo_path": self.evaluation_state.repo_path,
"severity_filter": None, # Include all severities
"language_filter": None, # Include all languages
},
)
issues_content = self._extract_tool_result_content(
issues_report_result
)
issues_data = self._safe_parse_json(issues_content, "Issues report")
if (
isinstance(issues_data, dict)
and issues_data.get("status") == "success"
):
# Update most problematic files
problematic_files = issues_data.get(
"most_problematic_files", []
)
self.evaluation_state.static_analysis.most_problematic_files = [
f["file_path"] for f in problematic_files[:5]
]
self.logger.info(
f"📋 Issues report generated: {len(problematic_files)} problematic files identified"
)
# Log most problematic files
if problematic_files:
self.logger.info("🔍 Most problematic files:")
for i, file_info in enumerate(problematic_files[:5], 1):
self.logger.info(
f" {i}. {file_info['file_path']} ({file_info['issue_count']} issues)"
)
else:
self.logger.warning(
"⚠️ Failed to generate detailed issues report"
)
# Apply additional automatic formatting if tools are available
if summary.get("auto_fixes_applied", 0) < summary.get(
"total_issues_found", 0
):
self.logger.info(
"🔧 Attempting additional automatic formatting fixes"
)
format_result = await self.code_analyzer.call_tool(
"auto_fix_formatting",
{
"repo_path": self.evaluation_state.repo_path,
"languages": None, # Auto-detect all languages
"dry_run": False, # Apply actual fixes
},
)
format_content = self._extract_tool_result_content(format_result)
format_data = self._safe_parse_json(
format_content, "Auto-formatting"
)
if (
isinstance(format_data, dict)
and format_data.get("status") == "success"
):
format_results = format_data.get("formatting_results", {})
files_formatted = format_results.get("total_files_formatted", 0)
if files_formatted > 0:
self.evaluation_state.static_analysis.formatting_fixes_applied += files_formatted
self.logger.info(
f"✅ Additional formatting applied to {files_formatted} files"
)
else:
self.logger.info("ℹ️ No additional formatting fixes needed")
else:
self.logger.warning("⚠️ Additional formatting failed")
return True
else:
self.logger.error(f"❌ Static analysis failed: {static_data}")
# Create minimal static analysis result for failed analysis
self.evaluation_state.static_analysis = StaticAnalysisResult(
analysis_success=False,
total_files_analyzed=0,
languages_detected=[],
total_issues_found=0,
auto_fixes_applied=0,
analysis_duration_seconds=0.0,
issues_by_severity={},
tools_used=[],
syntax_errors_found=0,
formatting_fixes_applied=0,
most_problematic_files=[],
static_analysis_report=static_data,
)
return False
except Exception as e:
self.logger.error(f"❌ Static analysis phase failed: {e}")
self.evaluation_state.add_error(f"Static analysis phase failed: {e}")
# Create minimal static analysis result for exception
self.evaluation_state.static_analysis = StaticAnalysisResult(
analysis_success=False,
total_files_analyzed=0,
languages_detected=[],
total_issues_found=0,
auto_fixes_applied=0,
analysis_duration_seconds=0.0,
issues_by_severity={},
tools_used=[],
syntax_errors_found=0,
formatting_fixes_applied=0,
most_problematic_files=[],
static_analysis_report={"status": "error", "message": str(e)},
)
return False
async def _run_error_analysis_phase(self) -> bool:
"""
PHASE 4: Advanced Error Analysis and Targeted Remediation
Uses sandbox execution to identify runtime errors and provides targeted fixes
"""
try:
self.logger.info(
"🔬 Starting advanced error analysis phase with sandbox execution"
)
start_time = time.time()
error_reports_generated = 0
suspect_files_identified = 0
remediation_tasks_created = 0
sandbox_executions_completed = 0
critical_errors_found = 0
high_confidence_fixes = 0
error_types_found = []
most_problematic_files = []
error_analysis_reports = []
# 1. Run initial code validation in sandbox (placeholder interface)
self.logger.info("🏗️ Step 1: Running initial code validation in sandbox")
validation_result = await self.code_analyzer.call_tool(
"run_code_validation",
{
"repo_path": self.evaluation_state.repo_path,
"test_command": None, # Auto-detect test patterns
},
)
validation_content = self._extract_tool_result_content(validation_result)
validation_data = self._safe_parse_json(
validation_content, "Code validation"
)
if validation_data.get("status") == "todo":
self.logger.info(
"📝 Sandbox validation interface ready - TODO: Implement actual sandbox"
)
sandbox_executions_completed = 1 # Interface call completed
# 2. If we have error information, perform error analysis
# For demonstration, simulate some error scenarios
simulated_errors = self._generate_simulated_error_scenarios()
for error_scenario in simulated_errors:
self.logger.info(
f"🔍 Analyzing error scenario: {error_scenario['type']}"
)
# Generate error analysis report
error_analysis_result = await self.code_analyzer.call_tool(
"generate_error_analysis_report",
{
"traceback_text": error_scenario["traceback"],
"repo_path": self.evaluation_state.repo_path,
"execution_context": error_scenario["context"],
},
)
error_analysis_content = self._extract_tool_result_content(
error_analysis_result
)
error_analysis_data = self._safe_parse_json(
error_analysis_content, "Error analysis"
)
if error_analysis_data.get("status") == "success":
error_reports_generated += 1
report = error_analysis_data.get("error_analysis_report", {})
error_analysis_reports.append(error_analysis_data)