1+ #!/usr/bin/env python3
2+ import os
3+ import io
4+ import sys
5+ import json
6+ import argparse
7+ import subprocess
8+ from pathlib import Path
9+ from registry import registry
10+
11+
12+ def main ():
13+ parser = argparse .ArgumentParser (description = "Complete code analysis and generate JSON output" )
14+ parser .add_argument ("-o" , "--output" , default = "/root/analysis.json" , help = "Output JSON file path" )
15+ parser .add_argument ("-f" , "--force" , action = "store_true" , help = "Force completion without validation" )
16+ # Handle the case where model passes literal parameter names
17+ cleaned_args = []
18+ skip_next = False
19+ for i , arg in enumerate (sys .argv [1 :]):
20+ if skip_next :
21+ skip_next = False
22+ continue
23+ # Handle literal parameter examples from model
24+ if arg == "[-o" and i + 1 < len (sys .argv [1 :]) and sys .argv [i + 2 ] == "OUTPUT_FILE]" :
25+ # Skip this literal example
26+ skip_next = True
27+ continue
28+ elif arg == "[-f]" or arg == "OUTPUT_FILE]" or arg .startswith ("[-" ):
29+ # Skip literal examples
30+ continue
31+ else :
32+ cleaned_args .append (arg )
33+ # Parse cleaned arguments
34+ try :
35+ args = parser .parse_args (cleaned_args )
36+ except SystemExit :
37+ # If parsing still fails, use defaults
38+ args = parser .parse_args ([])
39+ repo_root = registry .get ("ROOT" , os .getenv ("ROOT" ))
40+ assert repo_root
41+ # Check if we have analysis results in the registry or from previous steps
42+ analysis_results = registry .get ("ANALYSIS_RESULTS" , None )
43+ # Get completion stage
44+ complete_review_messages = registry .get ("ANALYSIS_COMPLETE_MESSAGES" , [])
45+ n_stages = len (complete_review_messages )
46+ current_stage = registry .get ("ANALYSIS_STAGE" , 0 )
47+ if not args .force and current_stage != n_stages and complete_review_messages :
48+ # Show review message and wait for final JSON input
49+ message = complete_review_messages [current_stage ]
50+ message = message .replace ("{{problem_statement}}" , registry .get ("PROBLEM_STATEMENT" , "" ))
51+ registry ["ANALYSIS_STAGE" ] = current_stage + 1
52+ print (message )
53+ sys .exit (0 )
54+ # Look for JSON analysis in recent output or registry
55+ json_content = None
56+ # Try to extract JSON from registry first
57+ if analysis_results :
58+ json_content = analysis_results
59+ else :
60+ # Try to find JSON in the last command output or current directory
61+ possible_json_files = [Path (args .output ), Path ("/root/analysis.json" ), Path (repo_root ) / "analysis.json" , Path ("/tmp/analysis.json" )]
62+ for json_file in possible_json_files :
63+ if json_file .exists ():
64+ try :
65+ json_content = json_file .read_text ()
66+ print (f"Found analysis file: { json_file } " )
67+ break
68+ except Exception as e :
69+ print (f"Error reading { json_file } : { e } " )
70+ continue
71+ # If still no JSON found, prompt for it
72+ if not json_content :
73+ print ("No analysis JSON file found. Please create one first." )
74+ print ("Expected locations checked:" )
75+ for path in possible_json_files :
76+ print (f" - { path } " )
77+ print ("\n Expected JSON format:" )
78+ print (json .dumps ({
79+ "analysis_summary" : "Brief description of the issue and approach" ,
80+ "relevant_files" : [
81+ {
82+ "file_path" : "path/to/file.py" ,
83+ "relevance_reason" : "Contains the main logic for the reported functionality" ,
84+ "key_functions" : ["function1" , "function2" ],
85+ "code_snippets" : [
86+ {
87+ "lines" : "45-50" ,
88+ "content" : "def example_function():\\ n # relevant code here" ,
89+ "description" : "Function that handles the core logic"
90+ }
91+ ]
92+ }
93+ ],
94+ "potential_root_causes" : [
95+ {
96+ "description" : "Specific issue description" ,
97+ "file_path" : "path/to/file.py" ,
98+ "code_snippet" : [
99+ {
100+ "content" : "actual code content" ,
101+ "description" : "Why this causes problems"
102+ }
103+ ]
104+ }
105+ ],
106+ "recommended_investigation_order" : [
107+ "path/to/primary_file.py" ,
108+ "path/to/secondary_file.py"
109+ ],
110+ "related_test_files" : ["path/to/test_file.py" ],
111+ "dependencies" : ["module1" , "module2" ]
112+ }, indent = 2 ))
113+ print ("\n Please create the JSON file first, then run 'analysis_complete' again." )
114+ sys .exit (0 )
115+ # Validate JSON content
116+ try :
117+ analysis_data = json .loads (json_content ) if isinstance (json_content , str ) else json_content
118+ # Basic validation of required fields
119+ required_fields = ["analysis_summary" , "relevant_files" , "potential_root_causes" , "recommended_investigation_order" ]
120+ missing_fields = [field for field in required_fields if field not in analysis_data ]
121+ if missing_fields :
122+ print (f"Error: Missing required fields in analysis JSON: { missing_fields } " )
123+ sys .exit (1 )
124+ except json .JSONDecodeError as e :
125+ print (f"Error: Invalid JSON format - { e } " )
126+ sys .exit (1 )
127+ # Save the analysis results to the final output location
128+ output_path = Path (args .output )
129+ output_path .parent .mkdir (parents = True , exist_ok = True )
130+ # Add metadata
131+ # analysis_data["metadata"] = {"repo_root": repo_root, "problem_statement": registry.get("PROBLEM_STATEMENT", ""), "analysis_tool_version": "1.0.0"}
132+ # Write final JSON
133+ with open (output_path , 'w' , encoding = 'utf-8' ) as f :
134+ json .dump (analysis_data , f , indent = 2 , ensure_ascii = False )
135+ # Signal completion to SWE-agent
136+ print ("<<SWE_AGENT_ANALYSIS_COMPLETE>>" )
137+ print (f"Analysis saved to: { output_path } " )
138+ print ("Analysis Summary:" )
139+ print (f"- Found { len (analysis_data .get ('relevant_files' , []))} relevant files" )
140+ print (f"- Identified { len (analysis_data .get ('potential_root_causes' , []))} potential root causes" )
141+ print (f"- Recommended investigation order: { len (analysis_data .get ('recommended_investigation_order' , []))} files" )
142+ print ("<<SWE_AGENT_ANALYSIS_COMPLETE>>" )
143+
144+ if __name__ == "__main__" :
145+ # Handle encoding issues similar to the original tool
146+ sys .stdout = io .TextIOWrapper (sys .stdout .buffer , encoding = "utf-8" )
147+ main ()
0 commit comments