tzero-mcp 10.7.3 → 11.0.0

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 (127) hide show
  1. package/CHANGELOG.md +44 -577
  2. package/CONTRIBUTING.md +71 -71
  3. package/README.md +64 -64
  4. package/bin/tzero-mcp.js +62 -65
  5. package/bin/tzero.js +61 -64
  6. package/index.d.ts +25 -25
  7. package/index.js +15 -15
  8. package/package.json +88 -67
  9. package/src/addmcp.py +14 -11
  10. package/src/app.py +1810 -0
  11. package/src/main.py +1 -1
  12. package/src/pc_fixer_mcp.py +25 -0
  13. package/src/tzero/__init__.py +54 -0
  14. package/src/tzero/__main__.py +6 -0
  15. package/src/tzero/siber_akademi.ico +0 -0
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +475 -475
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +546 -362
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/{tzero_ci.py → tzero/tzero_ci.py} +153 -153
  22. package/src/{tzero_commit.py → tzero/tzero_commit.py} +192 -192
  23. package/src/tzero/tzero_contracts.py +1093 -0
  24. package/src/{tzero_cost.py → tzero/tzero_cost.py} +166 -163
  25. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +531 -19
  26. package/src/tzero/tzero_debt.py +461 -0
  27. package/src/{tzero_deps.py → tzero/tzero_deps.py} +179 -4
  28. package/src/{tzero_drift.py → tzero/tzero_drift.py} +208 -208
  29. package/src/{tzero_explain.py → tzero/tzero_explain.py} +73 -7
  30. package/src/{tzero_features.py → tzero/tzero_features.py} +19 -17
  31. package/src/tzero/tzero_federation.py +299 -0
  32. package/src/{tzero_fix.py → tzero/tzero_fix.py} +228 -228
  33. package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +63 -63
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +464 -464
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +288 -288
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +127 -127
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +600 -600
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +174 -174
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +246 -246
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +151 -151
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +260 -260
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +171 -171
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +150 -150
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +309 -309
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +1 -1
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +1 -1
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +412 -412
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +91 -91
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +295 -295
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +940 -940
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +307 -307
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +49 -7
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +502 -502
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +600 -599
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +274 -274
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +313 -313
  58. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +1 -1
  59. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +318 -318
  60. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +372 -372
  61. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +1 -1
  62. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +305 -305
  63. package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +444 -444
  64. package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +114 -114
  65. package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +110 -110
  66. package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +326 -326
  67. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +223 -223
  68. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +220 -220
  69. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +1 -1
  70. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +447 -447
  71. package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +309 -309
  72. package/src/tzero/tzero_golden.py +319 -0
  73. package/src/tzero/tzero_graph_hud.html +338 -0
  74. package/src/tzero/tzero_graph_rag.py +263 -0
  75. package/src/{tzero_guard.py → tzero/tzero_guard.py} +243 -243
  76. package/src/tzero/tzero_hooks.py +565 -0
  77. package/src/{tzero_infra.py → tzero/tzero_infra.py} +274 -274
  78. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +124 -124
  79. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +310 -310
  80. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +395 -395
  81. package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +214 -214
  82. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +137 -137
  83. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +212 -212
  84. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +184 -184
  85. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +335 -335
  86. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +308 -308
  87. package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +887 -887
  88. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +261 -261
  89. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +144 -144
  90. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +1167 -1167
  91. package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +173 -173
  92. package/src/tzero/tzero_lsp.py +634 -0
  93. package/src/{tzero_mcp.py → tzero/tzero_mcp.py} +479 -100
  94. package/src/tzero/tzero_mutation.py +358 -0
  95. package/src/tzero/tzero_packer.py +577 -0
  96. package/src/{tzero_patch.py → tzero/tzero_patch.py} +624 -624
  97. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +12699 -12657
  98. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +95 -95
  99. package/src/tzero/tzero_polyglot.py +799 -0
  100. package/src/tzero/tzero_proxy.py +127 -0
  101. package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +272 -272
  102. package/src/{tzero_replay.py → tzero/tzero_replay.py} +141 -141
  103. package/src/tzero/tzero_rust_bridge.py +198 -0
  104. package/src/tzero/tzero_scip.py +368 -0
  105. package/src/{tzero_security.py → tzero/tzero_security.py} +5 -2
  106. package/src/tzero/tzero_semantic_merge.py +189 -0
  107. package/src/tzero/tzero_snapshot.py +471 -0
  108. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +313 -313
  109. package/src/tzero/tzero_subagent_engine.py +459 -0
  110. package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +774 -774
  111. package/src/{tzero_sync.py → tzero/tzero_sync.py} +241 -241
  112. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +458 -363
  113. package/src/{tzero_tui.py → tzero/tzero_tui.py} +91 -22
  114. package/src/tzero/tzero_turbo.py +264 -0
  115. package/src/{tzero_v3.py → tzero/tzero_v3.py} +628 -163
  116. package/src/tzero.py +2 -54
  117. package/test/package.test.js +55 -19
  118. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  119. package/src/tzero_gateway.py +0 -885
  120. package/src/tzero_packer.py +0 -370
  121. package/src/tzero_polyglot.py +0 -422
  122. package/src/tzero_snapshot.py +0 -258
  123. /package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +0 -0
  124. /package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +0 -0
  125. /package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +0 -0
  126. /package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +0 -0
  127. /package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +0 -0
@@ -1,308 +1,308 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- T-ZERO AUTONOMOUS SELF-HEALING EXECUTION ENGINE
4
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
- Version: 4.4.0
6
-
7
- Bu modül, kodları ve terminal komutlarını izole bir şekilde yürüten,
8
- oluşan hataları (SyntaxError, NameError, ImportError, runtime panic vb.)
9
- AST ve kural tabanlı cerrahi yamalarla otomatik olarak onaran (Auto-Patch)
10
- ve çözümü nedensellik çizgesine kaydeden otonom onarım motorudur.
11
- """
12
-
13
- from __future__ import annotations
14
- import os
15
- import sys
16
- import re
17
- import ast
18
- import time
19
- import subprocess
20
- import traceback
21
- from typing import Dict, List, Optional, Tuple, Any
22
- from dataclasses import dataclass, field
23
- from tzero_jarvis.causal_graph import CausalTemporalGraph, CausalRelationType
24
-
25
-
26
- @dataclass
27
- class ExecutionResult:
28
- command: str
29
- exit_code: int
30
- stdout: str
31
- stderr: str
32
- duration_ms: float
33
- success: bool
34
- error_type: Optional[str] = None
35
- error_line: Optional[int] = None
36
- error_file: Optional[str] = None
37
- applied_patches: List[str] = field(default_factory=list)
38
- resolved: bool = False
39
-
40
- def to_dict(self) -> Dict[str, Any]:
41
- return {
42
- "command": self.command,
43
- "exit_code": self.exit_code,
44
- "stdout": self.stdout,
45
- "stderr": self.stderr,
46
- "duration_ms": self.duration_ms,
47
- "success": self.success,
48
- "error_type": self.error_type,
49
- "error_line": self.error_line,
50
- "error_file": self.error_file,
51
- "applied_patches": self.applied_patches,
52
- "resolved": self.resolved
53
- }
54
-
55
-
56
- class SelfHealingExecutionEngine:
57
- """
58
- Otonom Hata Yakalama, Teşhis ve AST Tabanlı Otomatik Onarım Motoru.
59
- """
60
-
61
- def __init__(self, causal_graph: Optional[CausalTemporalGraph] = None, work_dir: Optional[str] = None):
62
- self.causal_graph = causal_graph or CausalTemporalGraph()
63
- self.work_dir = work_dir or os.getcwd()
64
-
65
- def run_command(self, command: str, timeout: int = 30) -> ExecutionResult:
66
- """
67
- Komutu çalıştırır, süreyi ve çıktıları ölçer.
68
- """
69
- start_time = time.time()
70
- try:
71
- res = subprocess.run(
72
- command,
73
- shell=True,
74
- capture_output=True,
75
- text=True,
76
- timeout=timeout,
77
- cwd=self.work_dir
78
- )
79
- duration_ms = (time.time() - start_time) * 1000.0
80
- success = (res.returncode == 0)
81
-
82
- error_type, error_file, error_line = None, None, None
83
- if not success:
84
- error_type, error_file, error_line = self.diagnose_error(res.stderr or res.stdout)
85
-
86
- return ExecutionResult(
87
- command=command,
88
- exit_code=res.returncode,
89
- stdout=res.stdout,
90
- stderr=res.stderr,
91
- duration_ms=round(duration_ms, 2),
92
- success=success,
93
- error_type=error_type,
94
- error_file=error_file,
95
- error_line=error_line,
96
- resolved=success
97
- )
98
- except subprocess.TimeoutExpired:
99
- return ExecutionResult(
100
- command=command,
101
- exit_code=-1,
102
- stdout="",
103
- stderr=f"TimeoutExpired after {timeout} seconds",
104
- duration_ms=timeout * 1000.0,
105
- success=False,
106
- error_type="TimeoutExpired",
107
- resolved=False
108
- )
109
- except Exception as e:
110
- return ExecutionResult(
111
- command=command,
112
- exit_code=-2,
113
- stdout="",
114
- stderr=str(e),
115
- duration_ms=(time.time() - start_time) * 1000.0,
116
- success=False,
117
- error_type=type(e).__name__,
118
- resolved=False
119
- )
120
-
121
- def diagnose_error(self, error_text: str) -> Tuple[Optional[str], Optional[str], Optional[int]]:
122
- """
123
- Stderr ve stacktrace içinden hata türünü, dosya yolunu ve satır numarasını ayıklar.
124
- """
125
- if not error_text:
126
- return None, None, None
127
-
128
- # 1. Python Traceback: File "...", line X, in ...
129
- py_tb_match = re.findall(r'File "([^"]+)", line (\d+)', error_text)
130
- error_file, error_line = None, None
131
- if py_tb_match:
132
- error_file, line_str = py_tb_match[-1]
133
- try:
134
- error_line = int(line_str)
135
- except ValueError:
136
- pass
137
-
138
- # 2. Rust/Cargo Error: --> src/main.rs:12:5
139
- rust_match = re.search(r'-->\s+([^:]+):(\d+):(\d+)', error_text)
140
- if rust_match:
141
- error_file = rust_match.group(1)
142
- try:
143
- error_line = int(rust_match.group(2))
144
- except ValueError:
145
- pass
146
-
147
- # 3. Hata Tipi Tespiti
148
- err_type = "GenericExecutionError"
149
- for line in reversed(error_text.strip().splitlines()):
150
- line_str = line.strip()
151
- # Örn: NameError: name 'foo' is not defined
152
- # SyntaxError: invalid syntax
153
- # ModuleNotFoundError: No module named '...'
154
- match = re.match(r'^([A-Z][a-zA-Z0-9_]+Error|Exception|Panic|error\[E\d+\]):\s*(.*)', line_str)
155
- if match:
156
- err_type = match.group(1)
157
- break
158
- if "panic" in line_str.lower():
159
- err_type = "RustPanic"
160
- break
161
- if "syntax error" in line_str.lower():
162
- err_type = "SyntaxError"
163
- break
164
-
165
- return err_type, error_file, error_line
166
-
167
- def auto_repair_python_file(self, file_path: str, error_type: str, error_line: Optional[int], stderr: str) -> bool:
168
- """
169
- Belirtilen Python dosyasındaki yaygın hataları AST ve kural tabanlı olarak otomatik onarır.
170
- """
171
- if not os.path.exists(file_path):
172
- return False
173
-
174
- try:
175
- with open(file_path, "r", encoding="utf-8") as f:
176
- content = f.read()
177
- except Exception:
178
- return False
179
-
180
- lines = content.splitlines(keepends=True)
181
- modified = False
182
- patch_note = ""
183
-
184
- # Hata 1: ModuleNotFoundError / ImportError: No module named 'xxx'
185
- mod_match = re.search(r"No module named ['\"]([^'\"]+)['\"]", stderr)
186
- if mod_match:
187
- missing_mod = mod_match.group(1)
188
- # Eğer dahili bir alt paket veya standart kütüphane eksikliği ise sys.path ekle
189
- if missing_mod in ("tzero_jarvis", "tzero", "crates"):
190
- sys_path_inject = f"import sys, os\nsys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))\n"
191
- if sys_path_inject not in content:
192
- lines.insert(0, sys_path_inject)
193
- modified = True
194
- patch_note = f"Injected sys.path for missing internal module {missing_mod}"
195
-
196
- # Hata 2: NameError: name 'X' is not defined (Yaygın: os, sys, json, time, re, math)
197
- name_match = re.search(r"name ['\"]([^'\"]+)['\"] is not defined", stderr)
198
- if name_match:
199
- missing_name = name_match.group(1)
200
- common_std_libs = {
201
- "os": "import os\n",
202
- "sys": "import sys\n",
203
- "json": "import json\n",
204
- "time": "import time\n",
205
- "re": "import re\n",
206
- "math": "import math\n",
207
- "Path": "from pathlib import Path\n",
208
- "Optional": "from typing import Optional\n",
209
- "List": "from typing import List\n",
210
- "Dict": "from typing import Dict\n",
211
- "Tuple": "from typing import Tuple\n",
212
- "Any": "from typing import Any\n",
213
- }
214
- if missing_name in common_std_libs:
215
- lines.insert(0, common_std_libs[missing_name])
216
- modified = True
217
- patch_note = f"Imported missing name '{missing_name}'"
218
-
219
- # Hata 3: SyntaxError / IndentationError satır sonu eksik parantez veya iki nokta ':'
220
- if error_type in ("SyntaxError", "IndentationError") and error_line and 1 <= error_line <= len(lines):
221
- idx = error_line - 1
222
- bad_line = lines[idx]
223
- stripped = bad_line.strip()
224
- # if, for, while, def, class sonuna ':' ekleme
225
- for kw in ("if ", "for ", "while ", "def ", "class ", "elif ", "else:", "except"):
226
- if stripped.startswith(kw) and not stripped.endswith(":"):
227
- lines[idx] = bad_line.rstrip() + ":\n"
228
- modified = True
229
- patch_note = f"Added missing colon ':' on line {error_line}"
230
- break
231
-
232
- if modified:
233
- try:
234
- # AST syntax kontrolü yap, eğer geçerliyse kaydet
235
- ast.parse("".join(lines))
236
- with open(file_path, "w", encoding="utf-8") as f:
237
- f.writelines(lines)
238
- return True
239
- except SyntaxError:
240
- # AST yine geçmediyse geri al
241
- return False
242
-
243
- return False
244
-
245
- def execute_and_heal(self, command: str, max_retries: int = 3) -> ExecutionResult:
246
- """
247
- Komutu çalıştırır. Hata olursa teşhis eder, otomatik onarım uygular
248
- ve başarıya ulaşana kadar (veya max_retries dolana kadar) döngüyü sürdürür.
249
- Sonucu Causal Graph'a kaydeder.
250
- """
251
- attempt = 0
252
- current_res = self.run_command(command)
253
- applied_patches = []
254
-
255
- while not current_res.success and attempt < max_retries:
256
- attempt += 1
257
- error_type = current_res.error_type or "UnknownError"
258
- error_file = current_res.error_file
259
-
260
- # Causal Graph'a hatayı düğüm olarak ekle
261
- err_node_id = f"err_{int(time.time()*1000)%100000}"
262
- self.causal_graph.add_node(
263
- node_id=err_node_id,
264
- label=f"Failure: {error_type} in {error_file or 'command'}",
265
- entity_type="VULN",
266
- attributes={"stderr": current_res.stderr[:200]}
267
- )
268
-
269
- repaired = False
270
- if error_file and error_file.endswith(".py") and os.path.isabs(error_file):
271
- repaired = self.auto_repair_python_file(
272
- error_file,
273
- error_type,
274
- current_res.error_line,
275
- current_res.stderr
276
- )
277
- elif error_file and error_file.endswith(".py"):
278
- # Göreceli yol ise work_dir ile birleştir
279
- full_path = os.path.join(self.work_dir, error_file)
280
- if os.path.exists(full_path):
281
- repaired = self.auto_repair_python_file(
282
- full_path,
283
- error_type,
284
- current_res.error_line,
285
- current_res.stderr
286
- )
287
-
288
- if repaired:
289
- patch_id = f"patch_{int(time.time()*1000)%100000}"
290
- self.causal_graph.add_node(
291
- node_id=patch_id,
292
- label=f"AutoPatch applied to {error_file}",
293
- entity_type="SOFTWARE"
294
- )
295
- self.causal_graph.add_edge(patch_id, err_node_id, relation=CausalRelationType.FIXES)
296
- applied_patches.append(f"Auto-patched {error_file} on line {current_res.error_line}")
297
-
298
- # Tekrar dene
299
- current_res = self.run_command(command)
300
- if current_res.success:
301
- current_res.resolved = True
302
- break
303
- else:
304
- # Otomatik kural bulunamadı, döngüden çık
305
- break
306
-
307
- current_res.applied_patches = applied_patches
308
- return current_res
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-ZERO AUTONOMOUS SELF-HEALING EXECUTION ENGINE
4
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
+ Version: 4.4.0
6
+
7
+ Bu modül, kodları ve terminal komutlarını izole bir şekilde yürüten,
8
+ oluşan hataları (SyntaxError, NameError, ImportError, runtime panic vb.)
9
+ AST ve kural tabanlı cerrahi yamalarla otomatik olarak onaran (Auto-Patch)
10
+ ve çözümü nedensellik çizgesine kaydeden otonom onarım motorudur.
11
+ """
12
+
13
+ from __future__ import annotations
14
+ import os
15
+ import sys
16
+ import re
17
+ import ast
18
+ import time
19
+ import subprocess
20
+ import traceback
21
+ from typing import Dict, List, Optional, Tuple, Any
22
+ from dataclasses import dataclass, field
23
+ from tzero.tzero_jarvis.causal_graph import CausalTemporalGraph, CausalRelationType
24
+
25
+
26
+ @dataclass
27
+ class ExecutionResult:
28
+ command: str
29
+ exit_code: int
30
+ stdout: str
31
+ stderr: str
32
+ duration_ms: float
33
+ success: bool
34
+ error_type: Optional[str] = None
35
+ error_line: Optional[int] = None
36
+ error_file: Optional[str] = None
37
+ applied_patches: List[str] = field(default_factory=list)
38
+ resolved: bool = False
39
+
40
+ def to_dict(self) -> Dict[str, Any]:
41
+ return {
42
+ "command": self.command,
43
+ "exit_code": self.exit_code,
44
+ "stdout": self.stdout,
45
+ "stderr": self.stderr,
46
+ "duration_ms": self.duration_ms,
47
+ "success": self.success,
48
+ "error_type": self.error_type,
49
+ "error_line": self.error_line,
50
+ "error_file": self.error_file,
51
+ "applied_patches": self.applied_patches,
52
+ "resolved": self.resolved
53
+ }
54
+
55
+
56
+ class SelfHealingExecutionEngine:
57
+ """
58
+ Otonom Hata Yakalama, Teşhis ve AST Tabanlı Otomatik Onarım Motoru.
59
+ """
60
+
61
+ def __init__(self, causal_graph: Optional[CausalTemporalGraph] = None, work_dir: Optional[str] = None):
62
+ self.causal_graph = causal_graph or CausalTemporalGraph()
63
+ self.work_dir = work_dir or os.getcwd()
64
+
65
+ def run_command(self, command: str, timeout: int = 30) -> ExecutionResult:
66
+ """
67
+ Komutu çalıştırır, süreyi ve çıktıları ölçer.
68
+ """
69
+ start_time = time.time()
70
+ try:
71
+ res = subprocess.run(
72
+ command,
73
+ shell=True,
74
+ capture_output=True,
75
+ text=True,
76
+ timeout=timeout,
77
+ cwd=self.work_dir
78
+ )
79
+ duration_ms = (time.time() - start_time) * 1000.0
80
+ success = (res.returncode == 0)
81
+
82
+ error_type, error_file, error_line = None, None, None
83
+ if not success:
84
+ error_type, error_file, error_line = self.diagnose_error(res.stderr or res.stdout)
85
+
86
+ return ExecutionResult(
87
+ command=command,
88
+ exit_code=res.returncode,
89
+ stdout=res.stdout,
90
+ stderr=res.stderr,
91
+ duration_ms=round(duration_ms, 2),
92
+ success=success,
93
+ error_type=error_type,
94
+ error_file=error_file,
95
+ error_line=error_line,
96
+ resolved=success
97
+ )
98
+ except subprocess.TimeoutExpired:
99
+ return ExecutionResult(
100
+ command=command,
101
+ exit_code=-1,
102
+ stdout="",
103
+ stderr=f"TimeoutExpired after {timeout} seconds",
104
+ duration_ms=timeout * 1000.0,
105
+ success=False,
106
+ error_type="TimeoutExpired",
107
+ resolved=False
108
+ )
109
+ except Exception as e:
110
+ return ExecutionResult(
111
+ command=command,
112
+ exit_code=-2,
113
+ stdout="",
114
+ stderr=str(e),
115
+ duration_ms=(time.time() - start_time) * 1000.0,
116
+ success=False,
117
+ error_type=type(e).__name__,
118
+ resolved=False
119
+ )
120
+
121
+ def diagnose_error(self, error_text: str) -> Tuple[Optional[str], Optional[str], Optional[int]]:
122
+ """
123
+ Stderr ve stacktrace içinden hata türünü, dosya yolunu ve satır numarasını ayıklar.
124
+ """
125
+ if not error_text:
126
+ return None, None, None
127
+
128
+ # 1. Python Traceback: File "...", line X, in ...
129
+ py_tb_match = re.findall(r'File "([^"]+)", line (\d+)', error_text)
130
+ error_file, error_line = None, None
131
+ if py_tb_match:
132
+ error_file, line_str = py_tb_match[-1]
133
+ try:
134
+ error_line = int(line_str)
135
+ except ValueError:
136
+ pass
137
+
138
+ # 2. Rust/Cargo Error: --> src/main.rs:12:5
139
+ rust_match = re.search(r'-->\s+([^:]+):(\d+):(\d+)', error_text)
140
+ if rust_match:
141
+ error_file = rust_match.group(1)
142
+ try:
143
+ error_line = int(rust_match.group(2))
144
+ except ValueError:
145
+ pass
146
+
147
+ # 3. Hata Tipi Tespiti
148
+ err_type = "GenericExecutionError"
149
+ for line in reversed(error_text.strip().splitlines()):
150
+ line_str = line.strip()
151
+ # Örn: NameError: name 'foo' is not defined
152
+ # SyntaxError: invalid syntax
153
+ # ModuleNotFoundError: No module named '...'
154
+ match = re.match(r'^([A-Z][a-zA-Z0-9_]+Error|Exception|Panic|error\[E\d+\]):\s*(.*)', line_str)
155
+ if match:
156
+ err_type = match.group(1)
157
+ break
158
+ if "panic" in line_str.lower():
159
+ err_type = "RustPanic"
160
+ break
161
+ if "syntax error" in line_str.lower():
162
+ err_type = "SyntaxError"
163
+ break
164
+
165
+ return err_type, error_file, error_line
166
+
167
+ def auto_repair_python_file(self, file_path: str, error_type: str, error_line: Optional[int], stderr: str) -> bool:
168
+ """
169
+ Belirtilen Python dosyasındaki yaygın hataları AST ve kural tabanlı olarak otomatik onarır.
170
+ """
171
+ if not os.path.exists(file_path):
172
+ return False
173
+
174
+ try:
175
+ with open(file_path, "r", encoding="utf-8") as f:
176
+ content = f.read()
177
+ except Exception:
178
+ return False
179
+
180
+ lines = content.splitlines(keepends=True)
181
+ modified = False
182
+ patch_note = ""
183
+
184
+ # Hata 1: ModuleNotFoundError / ImportError: No module named 'xxx'
185
+ mod_match = re.search(r"No module named ['\"]([^'\"]+)['\"]", stderr)
186
+ if mod_match:
187
+ missing_mod = mod_match.group(1)
188
+ # Eğer dahili bir alt paket veya standart kütüphane eksikliği ise sys.path ekle
189
+ if missing_mod in ("tzero_jarvis", "tzero", "crates"):
190
+ sys_path_inject = f"import sys, os\nsys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))\n"
191
+ if sys_path_inject not in content:
192
+ lines.insert(0, sys_path_inject)
193
+ modified = True
194
+ patch_note = f"Injected sys.path for missing internal module {missing_mod}"
195
+
196
+ # Hata 2: NameError: name 'X' is not defined (Yaygın: os, sys, json, time, re, math)
197
+ name_match = re.search(r"name ['\"]([^'\"]+)['\"] is not defined", stderr)
198
+ if name_match:
199
+ missing_name = name_match.group(1)
200
+ common_std_libs = {
201
+ "os": "import os\n",
202
+ "sys": "import sys\n",
203
+ "json": "import json\n",
204
+ "time": "import time\n",
205
+ "re": "import re\n",
206
+ "math": "import math\n",
207
+ "Path": "from pathlib import Path\n",
208
+ "Optional": "from typing import Optional\n",
209
+ "List": "from typing import List\n",
210
+ "Dict": "from typing import Dict\n",
211
+ "Tuple": "from typing import Tuple\n",
212
+ "Any": "from typing import Any\n",
213
+ }
214
+ if missing_name in common_std_libs:
215
+ lines.insert(0, common_std_libs[missing_name])
216
+ modified = True
217
+ patch_note = f"Imported missing name '{missing_name}'"
218
+
219
+ # Hata 3: SyntaxError / IndentationError satır sonu eksik parantez veya iki nokta ':'
220
+ if error_type in ("SyntaxError", "IndentationError") and error_line and 1 <= error_line <= len(lines):
221
+ idx = error_line - 1
222
+ bad_line = lines[idx]
223
+ stripped = bad_line.strip()
224
+ # if, for, while, def, class sonuna ':' ekleme
225
+ for kw in ("if ", "for ", "while ", "def ", "class ", "elif ", "else:", "except"):
226
+ if stripped.startswith(kw) and not stripped.endswith(":"):
227
+ lines[idx] = bad_line.rstrip() + ":\n"
228
+ modified = True
229
+ patch_note = f"Added missing colon ':' on line {error_line}"
230
+ break
231
+
232
+ if modified:
233
+ try:
234
+ # AST syntax kontrolü yap, eğer geçerliyse kaydet
235
+ ast.parse("".join(lines))
236
+ with open(file_path, "w", encoding="utf-8") as f:
237
+ f.writelines(lines)
238
+ return True
239
+ except SyntaxError:
240
+ # AST yine geçmediyse geri al
241
+ return False
242
+
243
+ return False
244
+
245
+ def execute_and_heal(self, command: str, max_retries: int = 3) -> ExecutionResult:
246
+ """
247
+ Komutu çalıştırır. Hata olursa teşhis eder, otomatik onarım uygular
248
+ ve başarıya ulaşana kadar (veya max_retries dolana kadar) döngüyü sürdürür.
249
+ Sonucu Causal Graph'a kaydeder.
250
+ """
251
+ attempt = 0
252
+ current_res = self.run_command(command)
253
+ applied_patches = []
254
+
255
+ while not current_res.success and attempt < max_retries:
256
+ attempt += 1
257
+ error_type = current_res.error_type or "UnknownError"
258
+ error_file = current_res.error_file
259
+
260
+ # Causal Graph'a hatayı düğüm olarak ekle
261
+ err_node_id = f"err_{int(time.time()*1000)%100000}"
262
+ self.causal_graph.add_node(
263
+ node_id=err_node_id,
264
+ label=f"Failure: {error_type} in {error_file or 'command'}",
265
+ entity_type="VULN",
266
+ attributes={"stderr": current_res.stderr[:200]}
267
+ )
268
+
269
+ repaired = False
270
+ if error_file and error_file.endswith(".py") and os.path.isabs(error_file):
271
+ repaired = self.auto_repair_python_file(
272
+ error_file,
273
+ error_type,
274
+ current_res.error_line,
275
+ current_res.stderr
276
+ )
277
+ elif error_file and error_file.endswith(".py"):
278
+ # Göreceli yol ise work_dir ile birleştir
279
+ full_path = os.path.join(self.work_dir, error_file)
280
+ if os.path.exists(full_path):
281
+ repaired = self.auto_repair_python_file(
282
+ full_path,
283
+ error_type,
284
+ current_res.error_line,
285
+ current_res.stderr
286
+ )
287
+
288
+ if repaired:
289
+ patch_id = f"patch_{int(time.time()*1000)%100000}"
290
+ self.causal_graph.add_node(
291
+ node_id=patch_id,
292
+ label=f"AutoPatch applied to {error_file}",
293
+ entity_type="SOFTWARE"
294
+ )
295
+ self.causal_graph.add_edge(patch_id, err_node_id, relation=CausalRelationType.FIXES)
296
+ applied_patches.append(f"Auto-patched {error_file} on line {current_res.error_line}")
297
+
298
+ # Tekrar dene
299
+ current_res = self.run_command(command)
300
+ if current_res.success:
301
+ current_res.resolved = True
302
+ break
303
+ else:
304
+ # Otomatik kural bulunamadı, döngüden çık
305
+ break
306
+
307
+ current_res.applied_patches = applied_patches
308
+ return current_res