tzero-mcp 11.14.0 → 11.15.2
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.
- package/LICENSE +661 -21
- package/NOTICE +22 -0
- package/README.md +3 -3
- package/index.js +5 -0
- package/package.json +3 -2
- package/src/addmcp.py +2 -2
- package/src/app.py +1 -1
- package/src/tzero/__init__.py +5 -0
- package/src/tzero/tzero_benchmark.py +2 -2
- package/src/tzero/tzero_blackboard.py +1 -1
- package/src/tzero/tzero_budget.py +1 -1
- package/src/tzero/tzero_ci.py +658 -10
- package/src/tzero/tzero_commit.py +1 -1
- package/src/tzero/tzero_contracts.py +2 -2
- package/src/tzero/tzero_cost.py +1 -1
- package/src/tzero/tzero_dashboard.py +3 -3
- package/src/tzero/tzero_debt.py +1 -1
- package/src/tzero/tzero_drift.py +1 -1
- package/src/tzero/tzero_explain.py +1 -1
- package/src/tzero/tzero_golden.py +2 -2
- package/src/tzero/tzero_infra.py +1 -1
- package/src/tzero/tzero_jarvis/__init__.py +15 -1
- package/src/tzero/tzero_jarvis/agent_guard.py +620 -0
- package/src/tzero/tzero_jarvis/creative_director.py +1 -1
- package/src/tzero/tzero_jarvis/orchestrator.py +36 -34
- package/src/tzero/tzero_jarvis/self_healing.py +325 -250
- package/src/tzero/tzero_lsp.py +1 -1
- package/src/tzero/tzero_mcp.py +121 -63
- package/src/tzero/tzero_promo.py +504 -0
- package/src/tzero/tzero_replay.py +1 -1
- package/src/tzero/tzero_semantic_merge.py +1 -1
- package/src/tzero/tzero_stubs.py +1 -1
- package/src/tzero/tzero_task_benchmark.py +2 -2
- package/src/tzero/tzero_tui.py +2 -2
- package/src/tzero/tzero_turbo.py +1 -1
- package/src/tzero/tzero_v3.py +61 -8
- package/src/tzero/tzero_welcome.py +2 -2
- package/test/package.test.js +1 -1
|
@@ -1,26 +1,42 @@
|
|
|
1
|
-
|
|
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
|
-
"""
|
|
1
|
+
"""Conservative, local Python repair with verification, policy guards, and rollback.
|
|
12
2
|
|
|
3
|
+
Commands are run locally with risk assessment and secret redaction.
|
|
4
|
+
Repairs are intentionally limited to cases that can be checked syntactically
|
|
5
|
+
and verified against local workspace ground truth.
|
|
6
|
+
"""
|
|
13
7
|
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import ast
|
|
10
|
+
import difflib
|
|
11
|
+
import hashlib
|
|
12
|
+
import io
|
|
14
13
|
import os
|
|
15
|
-
import
|
|
14
|
+
from pathlib import Path
|
|
16
15
|
import re
|
|
17
|
-
import ast
|
|
18
|
-
import time
|
|
19
16
|
import subprocess
|
|
20
|
-
import
|
|
21
|
-
|
|
17
|
+
import tempfile
|
|
18
|
+
import time
|
|
19
|
+
import tokenize
|
|
22
20
|
from dataclasses import dataclass, field
|
|
23
|
-
from
|
|
21
|
+
from typing import Any, Dict, List, Optional, Set, Tuple
|
|
22
|
+
|
|
23
|
+
from tzero.tzero_jarvis.causal_graph import CausalTemporalGraph
|
|
24
|
+
from tzero.tzero_jarvis.agent_guard import (
|
|
25
|
+
CommandRiskLevel,
|
|
26
|
+
CommandEvaluation,
|
|
27
|
+
CommandRiskAssessor,
|
|
28
|
+
CommandExecutionPolicy,
|
|
29
|
+
PathGuard,
|
|
30
|
+
SecretRedactor,
|
|
31
|
+
AIGroundingVerifier,
|
|
32
|
+
MultiFileRollbackStack,
|
|
33
|
+
GLOBAL_AUDIT_LOGGER,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def agent_command_execution_enabled() -> bool:
|
|
38
|
+
"""Require the server operator to opt in before agent shell execution."""
|
|
39
|
+
return os.environ.get("TZERO_ALLOW_AGENT_SHELL") == "1"
|
|
24
40
|
|
|
25
41
|
|
|
26
42
|
@dataclass
|
|
@@ -36,273 +52,332 @@ class ExecutionResult:
|
|
|
36
52
|
error_file: Optional[str] = None
|
|
37
53
|
applied_patches: List[str] = field(default_factory=list)
|
|
38
54
|
resolved: bool = False
|
|
55
|
+
diagnostics: List[str] = field(default_factory=list)
|
|
56
|
+
risk_level: Optional[str] = None
|
|
57
|
+
blocked_by_policy: bool = False
|
|
58
|
+
dry_run: bool = False
|
|
59
|
+
verified_evidence: Optional[Dict[str, Any]] = None
|
|
39
60
|
|
|
40
61
|
def to_dict(self) -> Dict[str, Any]:
|
|
41
|
-
return
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
"resolved": self.resolved
|
|
53
|
-
}
|
|
62
|
+
return dict(self.__dict__)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class RepairProposal:
|
|
67
|
+
path: Path
|
|
68
|
+
original: bytes
|
|
69
|
+
replacement: bytes
|
|
70
|
+
description: str
|
|
71
|
+
diff: str
|
|
72
|
+
sha256: str = ""
|
|
54
73
|
|
|
55
74
|
|
|
56
75
|
class SelfHealingExecutionEngine:
|
|
57
|
-
"""
|
|
58
|
-
Otonom Hata Yakalama, Teşhis ve AST Tabanlı Otomatik Onarım Motoru.
|
|
59
|
-
"""
|
|
76
|
+
"""Propose limited repairs, then retain them only after command success."""
|
|
60
77
|
|
|
61
|
-
def __init__(
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
causal_graph: Optional[CausalTemporalGraph] = None,
|
|
81
|
+
work_dir: Optional[str] = None,
|
|
82
|
+
policy: Optional[CommandExecutionPolicy] = None,
|
|
83
|
+
enforce_agent_policy: bool = False
|
|
84
|
+
):
|
|
62
85
|
self.causal_graph = causal_graph or CausalTemporalGraph()
|
|
63
|
-
self.work_dir = work_dir or os.getcwd()
|
|
86
|
+
self.work_dir = str(Path(work_dir or os.getcwd()).resolve())
|
|
87
|
+
self.policy = policy or CommandExecutionPolicy.from_environment()
|
|
88
|
+
self.enforce_agent_policy = enforce_agent_policy or (os.environ.get("TZERO_ENFORCE_AGENT_POLICY") == "1")
|
|
89
|
+
self.rollback_stack = MultiFileRollbackStack()
|
|
90
|
+
self._attempted_patch_hashes: Set[str] = set()
|
|
64
91
|
|
|
65
|
-
def run_command(self, command: str, timeout: int = 30) -> ExecutionResult:
|
|
66
|
-
"""
|
|
67
|
-
|
|
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)
|
|
92
|
+
def run_command(self, command: str, timeout: int = 30, dry_run: Optional[bool] = None) -> ExecutionResult:
|
|
93
|
+
"""Execute command with risk assessment, policy gate, and secret sanitization."""
|
|
94
|
+
evaluation = CommandRiskAssessor.assess(command)
|
|
85
95
|
|
|
96
|
+
# Enforce operator security policy when running under agent execution context
|
|
97
|
+
if self.enforce_agent_policy:
|
|
98
|
+
allowed, reason = self.policy.is_command_allowed(evaluation)
|
|
99
|
+
if not allowed:
|
|
100
|
+
GLOBAL_AUDIT_LOGGER.record("COMMAND_BLOCKED", command, "DENY", reason)
|
|
101
|
+
return ExecutionResult(
|
|
102
|
+
command=command,
|
|
103
|
+
exit_code=-1,
|
|
104
|
+
stdout="",
|
|
105
|
+
stderr=f"Command blocked by safety policy: {reason}",
|
|
106
|
+
duration_ms=0.0,
|
|
107
|
+
success=False,
|
|
108
|
+
error_type="SecurityPolicyViolation",
|
|
109
|
+
diagnostics=[f"Security policy violation: {reason}"],
|
|
110
|
+
risk_level=evaluation.risk_level.value,
|
|
111
|
+
blocked_by_policy=True
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
is_dry = self.policy.dry_run if dry_run is None else dry_run
|
|
115
|
+
if is_dry:
|
|
116
|
+
GLOBAL_AUDIT_LOGGER.record("COMMAND_DRY_RUN", command, "PREVIEW", "Dry-run mode active; execution skipped.")
|
|
86
117
|
return ExecutionResult(
|
|
87
118
|
command=command,
|
|
88
|
-
exit_code=
|
|
89
|
-
stdout=
|
|
90
|
-
stderr=
|
|
91
|
-
duration_ms=
|
|
92
|
-
success=
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
resolved=
|
|
119
|
+
exit_code=0,
|
|
120
|
+
stdout="[Dry-Run] Command execution skipped.",
|
|
121
|
+
stderr="",
|
|
122
|
+
duration_ms=0.0,
|
|
123
|
+
success=True,
|
|
124
|
+
diagnostics=["[Dry-Run] Command execution skipped by safety policy."],
|
|
125
|
+
risk_level=evaluation.risk_level.value,
|
|
126
|
+
dry_run=True,
|
|
127
|
+
resolved=True
|
|
97
128
|
)
|
|
98
|
-
|
|
129
|
+
|
|
130
|
+
start = time.monotonic()
|
|
131
|
+
try:
|
|
132
|
+
# Prefer direct argument list execution (shell=False) when command can be cleanly tokenized
|
|
133
|
+
# and does not rely on shell metacharacters.
|
|
134
|
+
use_argv = (
|
|
135
|
+
self.policy.prefer_argv
|
|
136
|
+
and evaluation.argv
|
|
137
|
+
and not evaluation.is_chained
|
|
138
|
+
and not evaluation.has_redirection
|
|
139
|
+
and not evaluation.has_substitution
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
if use_argv:
|
|
143
|
+
try:
|
|
144
|
+
proc = subprocess.run(
|
|
145
|
+
evaluation.argv, shell=False, capture_output=True,
|
|
146
|
+
text=True, errors="replace", timeout=timeout,
|
|
147
|
+
cwd=self.work_dir
|
|
148
|
+
)
|
|
149
|
+
except (FileNotFoundError, OSError):
|
|
150
|
+
# Fall back to shell if direct binary execution failed but shell is permitted
|
|
151
|
+
proc = subprocess.run(
|
|
152
|
+
command, shell=True, capture_output=True,
|
|
153
|
+
text=True, errors="replace", timeout=timeout,
|
|
154
|
+
cwd=self.work_dir
|
|
155
|
+
)
|
|
156
|
+
else:
|
|
157
|
+
proc = subprocess.run(
|
|
158
|
+
command, shell=True, capture_output=True,
|
|
159
|
+
text=True, errors="replace", timeout=timeout,
|
|
160
|
+
cwd=self.work_dir
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
# Redact accidental secret disclosures in stdout / stderr
|
|
164
|
+
safe_stdout = SecretRedactor.sanitize(proc.stdout)
|
|
165
|
+
safe_stderr = SecretRedactor.sanitize(proc.stderr)
|
|
166
|
+
|
|
167
|
+
if proc.returncode != 0:
|
|
168
|
+
kind, path, line = self.diagnose_error(safe_stderr or safe_stdout)
|
|
169
|
+
evidence = AIGroundingVerifier.audit_traceback_evidence(self.work_dir, safe_stderr or safe_stdout)
|
|
170
|
+
else:
|
|
171
|
+
kind, path, line = None, None, None
|
|
172
|
+
evidence = None
|
|
173
|
+
|
|
174
|
+
duration_ms = round((time.monotonic() - start) * 1000, 2)
|
|
99
175
|
return ExecutionResult(
|
|
100
176
|
command=command,
|
|
101
|
-
exit_code
|
|
102
|
-
stdout=
|
|
103
|
-
stderr=
|
|
104
|
-
duration_ms=
|
|
105
|
-
success=
|
|
106
|
-
error_type=
|
|
107
|
-
|
|
177
|
+
exit_code=proc.returncode,
|
|
178
|
+
stdout=safe_stdout,
|
|
179
|
+
stderr=safe_stderr,
|
|
180
|
+
duration_ms=duration_ms,
|
|
181
|
+
success=(proc.returncode == 0),
|
|
182
|
+
error_type=kind,
|
|
183
|
+
error_line=line,
|
|
184
|
+
error_file=path,
|
|
185
|
+
resolved=(proc.returncode == 0),
|
|
186
|
+
risk_level=evaluation.risk_level.value,
|
|
187
|
+
verified_evidence=evidence
|
|
108
188
|
)
|
|
109
|
-
except
|
|
189
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
190
|
+
duration_ms = round((time.monotonic() - start) * 1000, 2)
|
|
191
|
+
err_msg = SecretRedactor.sanitize(str(exc))
|
|
192
|
+
GLOBAL_AUDIT_LOGGER.record("COMMAND_ERROR", command, "ERROR", err_msg)
|
|
110
193
|
return ExecutionResult(
|
|
111
194
|
command=command,
|
|
112
|
-
exit_code=-
|
|
195
|
+
exit_code=-1,
|
|
113
196
|
stdout="",
|
|
114
|
-
stderr=
|
|
115
|
-
duration_ms=
|
|
197
|
+
stderr=err_msg,
|
|
198
|
+
duration_ms=duration_ms,
|
|
116
199
|
success=False,
|
|
117
|
-
error_type=type(
|
|
118
|
-
|
|
200
|
+
error_type=type(exc).__name__,
|
|
201
|
+
diagnostics=[f"Execution process error: {err_msg}"],
|
|
202
|
+
risk_level=evaluation.risk_level.value
|
|
119
203
|
)
|
|
120
204
|
|
|
121
205
|
def diagnose_error(self, error_text: str) -> Tuple[Optional[str], Optional[str], Optional[int]]:
|
|
122
|
-
"""
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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)
|
|
206
|
+
matches = re.findall(r'File "([^"\n]+)", line (\d+)', error_text or "")
|
|
207
|
+
path, line = (matches[-1][0], int(matches[-1][1])) if matches else (None, None)
|
|
208
|
+
kind = None
|
|
209
|
+
for text in reversed((error_text or "").splitlines()):
|
|
210
|
+
match = re.match(r'^\s*([A-Za-z_][\w.]*(?:Error|Exception))(?::|$)', text)
|
|
155
211
|
if match:
|
|
156
|
-
|
|
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"
|
|
212
|
+
kind = match.group(1)
|
|
163
213
|
break
|
|
214
|
+
return kind or ("GenericExecutionError" if error_text else None), path, line
|
|
164
215
|
|
|
165
|
-
|
|
216
|
+
def _target(self, file_path: str) -> Optional[Path]:
|
|
217
|
+
"""Validate target path within workspace boundary and without symlink escapes."""
|
|
218
|
+
valid, reason, resolved = PathGuard.validate_target_path(file_path, self.work_dir, for_write=True)
|
|
219
|
+
if not valid or not resolved or resolved.suffix != ".py":
|
|
220
|
+
GLOBAL_AUDIT_LOGGER.record("PATH_BLOCKED", str(file_path), "DENY", reason)
|
|
221
|
+
return None
|
|
222
|
+
return resolved
|
|
166
223
|
|
|
167
|
-
def
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
224
|
+
def propose_repair(self, file_path: str, error_type: str,
|
|
225
|
+
error_line: Optional[int], stderr: str) -> Optional[RepairProposal]:
|
|
226
|
+
path = self._target(file_path)
|
|
227
|
+
if path is None:
|
|
228
|
+
return None
|
|
229
|
+
try:
|
|
230
|
+
original = path.read_bytes()
|
|
231
|
+
encoding, _ = tokenize.detect_encoding(io.BytesIO(original).readline)
|
|
232
|
+
source = original.decode(encoding)
|
|
233
|
+
except (OSError, SyntaxError, UnicodeError):
|
|
234
|
+
return None
|
|
235
|
+
lines = source.splitlines(keepends=True)
|
|
236
|
+
if error_type not in ("SyntaxError", "IndentationError") or not error_line or not 1 <= error_line <= len(lines):
|
|
237
|
+
return None
|
|
238
|
+
|
|
239
|
+
# Verify ground truth of line using AIGroundingVerifier
|
|
240
|
+
is_grounded, _ = AIGroundingVerifier.verify_line(self.work_dir, str(path), error_line)
|
|
241
|
+
if not is_grounded:
|
|
242
|
+
return None
|
|
243
|
+
|
|
244
|
+
# Only act on Python's explicit missing-colon diagnostic, and only
|
|
245
|
+
# on simple, single-line compound statements without comments.
|
|
246
|
+
if not re.search(r"expected ['\"]:['\"]", stderr):
|
|
247
|
+
return None
|
|
248
|
+
idx = error_line - 1
|
|
249
|
+
line = lines[idx]
|
|
250
|
+
body = line.rstrip("\r\n")
|
|
251
|
+
if not re.match(r'^\s*(?:async\s+def|def|class|if|elif|else|for|while|with|try|except|finally)\b', body):
|
|
252
|
+
return None
|
|
253
|
+
if body.rstrip().endswith(":") or "#" in body or "\\" in body:
|
|
254
|
+
return None
|
|
255
|
+
ending = line[len(body):]
|
|
256
|
+
lines[idx] = body.rstrip() + ":" + ending
|
|
257
|
+
replacement_text = "".join(lines)
|
|
258
|
+
try:
|
|
259
|
+
ast.parse(replacement_text, filename=str(path))
|
|
260
|
+
replacement = replacement_text.encode(encoding)
|
|
261
|
+
except (SyntaxError, UnicodeError):
|
|
262
|
+
return None
|
|
173
263
|
|
|
264
|
+
diff = "".join(difflib.unified_diff(source.splitlines(True), replacement_text.splitlines(True),
|
|
265
|
+
fromfile=str(path), tofile=str(path)))
|
|
266
|
+
sha256 = hashlib.sha256(original).hexdigest()
|
|
267
|
+
return RepairProposal(path, original, replacement, f"Add missing colon at line {error_line}", diff, sha256)
|
|
268
|
+
|
|
269
|
+
def auto_repair_python_file(self, file_path: str, error_type: str,
|
|
270
|
+
error_line: Optional[int], stderr: str) -> bool:
|
|
271
|
+
"""Legacy direct repair: syntax checked, but not command verified."""
|
|
272
|
+
proposal = self.propose_repair(file_path, error_type, error_line, stderr)
|
|
273
|
+
if proposal is None:
|
|
274
|
+
return False
|
|
174
275
|
try:
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
except Exception:
|
|
276
|
+
return self._replace_if_unchanged(proposal.path, proposal.original, proposal.replacement)
|
|
277
|
+
except OSError:
|
|
178
278
|
return False
|
|
179
279
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
if
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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
|
|
280
|
+
def _replace_if_unchanged(self, path: Path, expected: bytes, replacement: bytes) -> bool:
|
|
281
|
+
"""Replace from a same-directory temporary file; refuse observed changes.
|
|
282
|
+
|
|
283
|
+
This is not a compare-and-swap: another process can still race the final
|
|
284
|
+
check. Atomic replacement avoids exposing a partially written file.
|
|
285
|
+
"""
|
|
286
|
+
if self._target(str(path)) != path or path.read_bytes() != expected:
|
|
287
|
+
return False
|
|
288
|
+
mode = path.stat().st_mode & 0o777
|
|
289
|
+
temp_name = None
|
|
290
|
+
try:
|
|
291
|
+
with tempfile.NamedTemporaryFile(dir=str(path.parent), prefix=".tzero-heal-", delete=False) as temp:
|
|
292
|
+
temp_name = temp.name
|
|
293
|
+
temp.write(replacement)
|
|
294
|
+
temp.flush()
|
|
295
|
+
os.fsync(temp.fileno())
|
|
296
|
+
os.chmod(temp_name, mode)
|
|
297
|
+
if self._target(str(path)) != path or path.read_bytes() != expected:
|
|
241
298
|
return False
|
|
299
|
+
os.replace(temp_name, path)
|
|
300
|
+
temp_name = None
|
|
301
|
+
GLOBAL_AUDIT_LOGGER.record("FILE_REPLACED", str(path), "SUCCESS", "Atomic file replacement completed.")
|
|
302
|
+
return True
|
|
303
|
+
finally:
|
|
304
|
+
if temp_name is not None:
|
|
305
|
+
try:
|
|
306
|
+
os.unlink(temp_name)
|
|
307
|
+
except FileNotFoundError:
|
|
308
|
+
pass
|
|
242
309
|
|
|
243
|
-
|
|
310
|
+
def execute_and_heal(self, command: str, max_retries: int = 3, dry_run: Optional[bool] = None) -> ExecutionResult:
|
|
311
|
+
"""Execute command and apply verified, syntax-checked repairs with rollback on failure."""
|
|
312
|
+
is_dry = self.policy.dry_run if dry_run is None else dry_run
|
|
313
|
+
if is_dry:
|
|
314
|
+
result = self.run_command(command, dry_run=True)
|
|
315
|
+
return result
|
|
244
316
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
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
|
-
)
|
|
317
|
+
result = self.run_command(command)
|
|
318
|
+
if result.success or max_retries <= 0 or result.blocked_by_policy:
|
|
319
|
+
return result
|
|
268
320
|
|
|
269
|
-
|
|
270
|
-
|
|
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
|
-
)
|
|
321
|
+
if not result.error_file:
|
|
322
|
+
return result
|
|
287
323
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
324
|
+
proposal = self.propose_repair(result.error_file, result.error_type or "", result.error_line,
|
|
325
|
+
result.stderr or result.stdout)
|
|
326
|
+
if proposal is None:
|
|
327
|
+
result.diagnostics.append("No supported safe repair proposal found.")
|
|
328
|
+
return result
|
|
329
|
+
|
|
330
|
+
# Anti-cycling guard: avoid reapplying identical failed patches
|
|
331
|
+
patch_hash = hashlib.sha256(proposal.diff.encode()).hexdigest()
|
|
332
|
+
if patch_hash in self._attempted_patch_hashes:
|
|
333
|
+
result.diagnostics.append(f"Anti-cycling guard: Identical patch ({patch_hash[:8]}) previously failed; skipping re-application.")
|
|
334
|
+
return result
|
|
335
|
+
self._attempted_patch_hashes.add(patch_hash)
|
|
336
|
+
|
|
337
|
+
try:
|
|
338
|
+
if not self._replace_if_unchanged(proposal.path, proposal.original, proposal.replacement):
|
|
339
|
+
result.diagnostics.append("File changed before repair; no patch applied.")
|
|
340
|
+
return result
|
|
341
|
+
|
|
342
|
+
# Register in multi-file rollback stack
|
|
343
|
+
self.rollback_stack.push(proposal.path, proposal.original, proposal.replacement, proposal.diff)
|
|
344
|
+
|
|
345
|
+
verified = self.run_command(command)
|
|
346
|
+
# Strict evidence of success
|
|
347
|
+
if (
|
|
348
|
+
verified.success
|
|
349
|
+
and self._target(str(proposal.path)) == proposal.path
|
|
350
|
+
and proposal.path.read_bytes() == proposal.replacement
|
|
351
|
+
):
|
|
352
|
+
# Ensure post-repair file AST parses without error
|
|
353
|
+
try:
|
|
354
|
+
ast.parse(proposal.replacement.decode("utf-8", errors="replace"), filename=str(proposal.path))
|
|
355
|
+
verified.applied_patches.append(proposal.description + "\n" + proposal.diff)
|
|
356
|
+
self.rollback_stack.clear()
|
|
357
|
+
GLOBAL_AUDIT_LOGGER.record("REPAIR_VERIFIED", str(proposal.path), "SUCCESS", proposal.description)
|
|
358
|
+
return verified
|
|
359
|
+
except SyntaxError as parse_err:
|
|
360
|
+
verified.success = False
|
|
361
|
+
verified.resolved = False
|
|
362
|
+
verified.diagnostics.append(f"Post-verification AST parse failed: {parse_err}")
|
|
363
|
+
|
|
364
|
+
# Verification failed: restore original bytes
|
|
365
|
+
if self._replace_if_unchanged(proposal.path, proposal.replacement, proposal.original):
|
|
366
|
+
verified.diagnostics.append("Verification failed; original file restored.")
|
|
367
|
+
self.rollback_stack.clear()
|
|
303
368
|
else:
|
|
304
|
-
|
|
305
|
-
|
|
369
|
+
verified.success = False
|
|
370
|
+
verified.resolved = False
|
|
371
|
+
verified.diagnostics.append("File changed during verification; repair is unverified and automatic rollback was skipped.")
|
|
306
372
|
|
|
307
|
-
|
|
308
|
-
|
|
373
|
+
GLOBAL_AUDIT_LOGGER.record("REPAIR_ROLLED_BACK", str(proposal.path), "FAILURE", "Verification failed; rolled back.")
|
|
374
|
+
return verified
|
|
375
|
+
except OSError as exc:
|
|
376
|
+
result.diagnostics.append(f"Repair failed: {exc}")
|
|
377
|
+
try:
|
|
378
|
+
if self._replace_if_unchanged(proposal.path, proposal.replacement, proposal.original):
|
|
379
|
+
result.diagnostics.append("Original file restored after repair error.")
|
|
380
|
+
self.rollback_stack.clear()
|
|
381
|
+
except OSError as rollback_error:
|
|
382
|
+
result.diagnostics.append(f"Rollback failed: {rollback_error}")
|
|
383
|
+
return result
|
package/src/tzero/tzero_lsp.py
CHANGED