File size: 7,279 Bytes
828589c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# auto_debug.py (Mythos-Killer v7.3)
import re
import logging
from typing import Dict, Any, Optional
from datetime import datetime


class AutoDebugLoop:
    """
    v7.3 का ऑटो-डिबग लूप — टेस्टर और कोडर के बीच एक स्वचालित
    "जाँचो-और-सुधारो" चक्र चलाता है। एरर को पार्स करके Coder को
    एक सटीक "निदान परचा" भेजता है और पैच लागू करके दोबारा टेस्ट करता है।
    """

    MAX_AUTO_DEBUG_ATTEMPTS = 3

    ERROR_PATTERNS = {
        "python": r'File "(?P<file>[^"]+)", line (?P<line>\d+).*\n(?P<error_type>\w+): (?P<message>.*)',
        "node":   r'(?P<error_type>\w+): (?P<message>.*)\s+at\s+(?P<file>[^:]+):(?P<line>\d+)',
        "generic": r'(?P<error_type>\w+): (?P<message>.*)'
    }

    def __init__(self):
        pass

    def parse_error(self, error_log: str, language: str = "python") -> Dict[str, Any]:
        """
        कच्चे एरर लॉग को पार्स करके एक संरचित "निदान परचा" तैयार करता है।

        लौटाए गए डिक्शनरी में शामिल हैं:
            - error_type: एरर का प्रकार (जैसे "ModuleNotFoundError")
            - file_path:  वह फ़ाइल जहाँ एरर आया
            - line_number: लाइन नंबर
            - message:    एरर का मुख्य संदेश
            - raw_log:    मूल कच्चा लॉग (संदर्भ के लिए)
        """
        pattern = self.ERROR_PATTERNS.get(language, self.ERROR_PATTERNS["generic"])
        match = re.search(pattern, error_log, re.DOTALL)

        if match:
            groups = match.groupdict()
            line_str = groups.get("line", "0")
            line_number = int(line_str) if str(line_str).isdigit() else 0
            return {
                "error_type": groups.get("error_type", "Unknown"),
                "file_path": groups.get("file", "unknown"),
                "line_number": line_number,
                "message": groups.get("message", "").strip(),
                "raw_log": error_log
            }
        else:
            # कोई ज्ञात पैटर्न मेल नहीं खाया — raw_log का पहला भाग लौटाएँ
            return {
                "error_type": "Unknown",
                "file_path": "unknown",
                "line_number": 0,
                "message": error_log[:200],
                "raw_log": error_log
            }

    def request_fix(self, diagnosis: Dict[str, Any],
                    coder_agent: Any,
                    state: Dict[str, Any]) -> Optional[str]:
        """
        CoderAgent को "निदान परचा" भेजकर एक केंद्रित पैच (Unified Diff) माँगता है।
        """
        instruction = (
            f"URGENT: Fix the following error in file {diagnosis['file_path']} "
            f"at line {diagnosis['line_number']}.\n"
            f"Error: {diagnosis['error_type']}: {diagnosis['message']}\n\n"
            f"Provide ONLY a Unified Diff patch that fixes this specific error. "
            f"Do NOT rewrite the entire file."
        )

        try:
            # CoderAgent.run को instruction पास करते हैं
            patch_state = coder_agent.run(state.copy(), instruction=instruction)
            return patch_state.get("generated_code")
        except Exception as e:
            logging.error(f"Coder agent failed: {e}")
            return None

    def run(self, error_log: str,
            coder_agent: Any,
            tester_agent: Any,
            state: Dict[str, Any],
            language: str = "python") -> Dict[str, Any]:
        """
        पूरा Auto-Debug Loop चलाता है — अधिकतम 3 प्रयास।
        सफल होने पर {"success": True, ...} लौटाता है, अन्यथा {"success": False, ...}
        """
        timeline_entries = []
        current_error_log = error_log

        for attempt in range(1, self.MAX_AUTO_DEBUG_ATTEMPTS + 1):
            # 1. एरर पार्स करो
            diagnosis = self.parse_error(current_error_log, language)
            timeline_entries.append({
                "timestamp": datetime.now().strftime("%H:%M:%S"),
                "agent": "AutoDebug",
                "status": "running",
                "message": (
                    f"प्रयास {attempt}/{self.MAX_AUTO_DEBUG_ATTEMPTS}: "
                    f"{diagnosis['error_type']} को ठीक करने की कोशिश"
                )
            })

            # 2. Coder से पैच माँगो
            patch = self.request_fix(diagnosis, coder_agent, state)
            if patch is None:
                timeline_entries.append({
                    "timestamp": datetime.now().strftime("%H:%M:%S"),
                    "agent": "AutoDebug",
                    "status": "failed",
                    "message": f"प्रयास {attempt}: Coder पैच नहीं बना पाया"
                })
                continue

            # 3. पैच को स्टेट में डालो और टेस्टर को फिर से चलाओ
            state["generated_code"] = patch
            state["file_path"] = diagnosis["file_path"]
            test_state = tester_agent.run(state)

            if test_state.get("test_passed", False):
                timeline_entries.append({
                    "timestamp": datetime.now().strftime("%H:%M:%S"),
                    "agent": "AutoDebug",
                    "status": "success",
                    "message": f"प्रयास {attempt}: सफल! बग ठीक हो गया।"
                })
                return {
                    "success": True,
                    "attempts": attempt,
                    "final_logs": test_state.get("test_logs", ""),
                    "timeline_entries": timeline_entries
                }
            else:
                # अगली कोशिश के लिए नया एरर लॉग लो
                current_error_log = test_state.get("test_logs", current_error_log)

        # सभी प्रयास विफल
        timeline_entries.append({
            "timestamp": datetime.now().strftime("%H:%M:%S"),
            "agent": "AutoDebug",
            "status": "failed",
            "message": (
                f"सभी {self.MAX_AUTO_DEBUG_ATTEMPTS} प्रयास विफल। "
                "Supervisor को सूचित किया जा रहा है।"
            )
        })
        return {
            "success": False,
            "attempts": self.MAX_AUTO_DEBUG_ATTEMPTS,
            "final_logs": current_error_log,
            "timeline_entries": timeline_entries
        }