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.
- package/CHANGELOG.md +44 -577
- package/CONTRIBUTING.md +71 -71
- package/README.md +64 -64
- package/bin/tzero-mcp.js +62 -65
- package/bin/tzero.js +61 -64
- package/index.d.ts +25 -25
- package/index.js +15 -15
- package/package.json +88 -67
- package/src/addmcp.py +14 -11
- package/src/app.py +1810 -0
- package/src/main.py +1 -1
- package/src/pc_fixer_mcp.py +25 -0
- package/src/tzero/__init__.py +54 -0
- package/src/tzero/__main__.py +6 -0
- package/src/tzero/siber_akademi.ico +0 -0
- package/src/tzero/tzero_arch_test.py +463 -0
- package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +475 -475
- package/src/tzero/tzero_blackboard.py +257 -0
- package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +546 -362
- package/src/tzero/tzero_budget.py +195 -0
- package/src/{tzero_ci.py → tzero/tzero_ci.py} +153 -153
- package/src/{tzero_commit.py → tzero/tzero_commit.py} +192 -192
- package/src/tzero/tzero_contracts.py +1093 -0
- package/src/{tzero_cost.py → tzero/tzero_cost.py} +166 -163
- package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +531 -19
- package/src/tzero/tzero_debt.py +461 -0
- package/src/{tzero_deps.py → tzero/tzero_deps.py} +179 -4
- package/src/{tzero_drift.py → tzero/tzero_drift.py} +208 -208
- package/src/{tzero_explain.py → tzero/tzero_explain.py} +73 -7
- package/src/{tzero_features.py → tzero/tzero_features.py} +19 -17
- package/src/tzero/tzero_federation.py +299 -0
- package/src/{tzero_fix.py → tzero/tzero_fix.py} +228 -228
- package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +63 -63
- package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +464 -464
- package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +288 -288
- package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +127 -127
- package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +600 -600
- package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +174 -174
- package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +246 -246
- package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +151 -151
- package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +260 -260
- package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +171 -171
- package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +150 -150
- package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +309 -309
- package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +412 -412
- package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +91 -91
- package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +295 -295
- package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +940 -940
- package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +307 -307
- package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +49 -7
- package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +502 -502
- package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +600 -599
- package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +274 -274
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +313 -313
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +318 -318
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +372 -372
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +305 -305
- package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +444 -444
- package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +114 -114
- package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +110 -110
- package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +326 -326
- package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +223 -223
- package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +220 -220
- package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +447 -447
- package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +309 -309
- package/src/tzero/tzero_golden.py +319 -0
- package/src/tzero/tzero_graph_hud.html +338 -0
- package/src/tzero/tzero_graph_rag.py +263 -0
- package/src/{tzero_guard.py → tzero/tzero_guard.py} +243 -243
- package/src/tzero/tzero_hooks.py +565 -0
- package/src/{tzero_infra.py → tzero/tzero_infra.py} +274 -274
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +124 -124
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +310 -310
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +395 -395
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +214 -214
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +137 -137
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +212 -212
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +184 -184
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +335 -335
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +308 -308
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +887 -887
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +261 -261
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +144 -144
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +1167 -1167
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +173 -173
- package/src/tzero/tzero_lsp.py +634 -0
- package/src/{tzero_mcp.py → tzero/tzero_mcp.py} +479 -100
- package/src/tzero/tzero_mutation.py +358 -0
- package/src/tzero/tzero_packer.py +577 -0
- package/src/{tzero_patch.py → tzero/tzero_patch.py} +624 -624
- package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +12699 -12657
- package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +95 -95
- package/src/tzero/tzero_polyglot.py +799 -0
- package/src/tzero/tzero_proxy.py +127 -0
- package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +272 -272
- package/src/{tzero_replay.py → tzero/tzero_replay.py} +141 -141
- package/src/tzero/tzero_rust_bridge.py +198 -0
- package/src/tzero/tzero_scip.py +368 -0
- package/src/{tzero_security.py → tzero/tzero_security.py} +5 -2
- package/src/tzero/tzero_semantic_merge.py +189 -0
- package/src/tzero/tzero_snapshot.py +471 -0
- package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +313 -313
- package/src/tzero/tzero_subagent_engine.py +459 -0
- package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +774 -774
- package/src/{tzero_sync.py → tzero/tzero_sync.py} +241 -241
- package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +458 -363
- package/src/{tzero_tui.py → tzero/tzero_tui.py} +91 -22
- package/src/tzero/tzero_turbo.py +264 -0
- package/src/{tzero_v3.py → tzero/tzero_v3.py} +628 -163
- package/src/tzero.py +2 -54
- package/test/package.test.js +55 -19
- package/src/tzero/jarvis/semantic_compressor.py +0 -373
- package/src/tzero_gateway.py +0 -885
- package/src/tzero_packer.py +0 -370
- package/src/tzero_polyglot.py +0 -422
- package/src/tzero_snapshot.py +0 -258
- /package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +0 -0
- /package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +0 -0
|
@@ -1,228 +1,228 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""
|
|
3
|
-
Siber Akademi — T-Zero Self-Healing AST Hallucination Auto-Corrector.
|
|
4
|
-
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
5
|
-
License: MIT
|
|
6
|
-
|
|
7
|
-
Statically inspects candidate code against verified workspace AST symbol tables.
|
|
8
|
-
Detects phantom imports, misspelled identifiers, and hallucinated method calls,
|
|
9
|
-
and automatically rewrites the AST to the correct valid local identifier.
|
|
10
|
-
"""
|
|
11
|
-
|
|
12
|
-
import os
|
|
13
|
-
import sys
|
|
14
|
-
import ast
|
|
15
|
-
import difflib
|
|
16
|
-
from dataclasses import dataclass, field
|
|
17
|
-
from typing import Dict, List, Set, Any, Optional, Tuple
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
@dataclass
|
|
21
|
-
class HealingAction:
|
|
22
|
-
original_symbol: str
|
|
23
|
-
healed_symbol: str
|
|
24
|
-
symbol_type: str # "import", "method_call", "function_call"
|
|
25
|
-
line_number: int
|
|
26
|
-
confidence: float
|
|
27
|
-
context_hint: str = ""
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
@dataclass
|
|
31
|
-
class HealingReport:
|
|
32
|
-
success: bool
|
|
33
|
-
original_code: str
|
|
34
|
-
healed_code: str
|
|
35
|
-
total_fixes: int
|
|
36
|
-
actions: List[HealingAction] = field(default_factory=list)
|
|
37
|
-
diff: str = ""
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
class _ASTHealerTransformer(ast.NodeTransformer):
|
|
41
|
-
def __init__(self, known_functions: Set[str], known_imports: Set[str], known_methods: Set[str]):
|
|
42
|
-
super().__init__()
|
|
43
|
-
self.known_functions = known_functions
|
|
44
|
-
self.known_imports = known_imports
|
|
45
|
-
self.known_methods = known_methods
|
|
46
|
-
self.actions: List[HealingAction] = []
|
|
47
|
-
|
|
48
|
-
def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.AST:
|
|
49
|
-
# Check imported names against known symbols
|
|
50
|
-
new_names = []
|
|
51
|
-
for alias in node.names:
|
|
52
|
-
name = alias.name
|
|
53
|
-
if self.known_imports and name not in self.known_imports:
|
|
54
|
-
matches = difflib.get_close_matches(name, list(self.known_imports), n=1, cutoff=0.65)
|
|
55
|
-
if matches:
|
|
56
|
-
best = matches[0]
|
|
57
|
-
ratio = difflib.SequenceMatcher(None, name, best).ratio()
|
|
58
|
-
self.actions.append(HealingAction(
|
|
59
|
-
original_symbol=name,
|
|
60
|
-
healed_symbol=best,
|
|
61
|
-
symbol_type="import",
|
|
62
|
-
line_number=getattr(node, "lineno", 1),
|
|
63
|
-
confidence=round(ratio, 2),
|
|
64
|
-
context_hint=f"Module: {node.module or ''}"
|
|
65
|
-
))
|
|
66
|
-
new_names.append(ast.alias(name=best, asname=alias.asname))
|
|
67
|
-
continue
|
|
68
|
-
new_names.append(alias)
|
|
69
|
-
node.names = new_names
|
|
70
|
-
return node
|
|
71
|
-
|
|
72
|
-
def visit_Call(self, node: ast.Call) -> ast.AST:
|
|
73
|
-
self.generic_visit(node)
|
|
74
|
-
# Check attribute calls (e.g. obj.calc_cost())
|
|
75
|
-
if isinstance(node.func, ast.Attribute):
|
|
76
|
-
attr_name = node.func.attr
|
|
77
|
-
if self.known_methods and attr_name not in self.known_methods:
|
|
78
|
-
matches = difflib.get_close_matches(attr_name, list(self.known_methods), n=1, cutoff=0.65)
|
|
79
|
-
if matches:
|
|
80
|
-
best = matches[0]
|
|
81
|
-
ratio = difflib.SequenceMatcher(None, attr_name, best).ratio()
|
|
82
|
-
self.actions.append(HealingAction(
|
|
83
|
-
original_symbol=attr_name,
|
|
84
|
-
healed_symbol=best,
|
|
85
|
-
symbol_type="method_call",
|
|
86
|
-
line_number=getattr(node, "lineno", 1),
|
|
87
|
-
confidence=round(ratio, 2)
|
|
88
|
-
))
|
|
89
|
-
node.func.attr = best
|
|
90
|
-
# Check standalone function calls (e.g. calculate_tokens())
|
|
91
|
-
elif isinstance(node.func, ast.Name):
|
|
92
|
-
func_name = node.func.id
|
|
93
|
-
if self.known_functions and func_name not in self.known_functions:
|
|
94
|
-
matches = difflib.get_close_matches(func_name, list(self.known_functions), n=1, cutoff=0.70)
|
|
95
|
-
if matches:
|
|
96
|
-
best = matches[0]
|
|
97
|
-
ratio = difflib.SequenceMatcher(None, func_name, best).ratio()
|
|
98
|
-
self.actions.append(HealingAction(
|
|
99
|
-
original_symbol=func_name,
|
|
100
|
-
healed_symbol=best,
|
|
101
|
-
symbol_type="function_call",
|
|
102
|
-
line_number=getattr(node, "lineno", 1),
|
|
103
|
-
confidence=round(ratio, 2)
|
|
104
|
-
))
|
|
105
|
-
node.func.id = best
|
|
106
|
-
return node
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
class ASTHallucinationAutoCorrector:
|
|
110
|
-
"""Self-healing engine to detect and repair hallucinated AI symbols."""
|
|
111
|
-
|
|
112
|
-
SKIP_DIRS = {
|
|
113
|
-
".git", "__pycache__", ".pytest_cache", "target", "dist",
|
|
114
|
-
"build", ".venv", "venv", "node_modules", ".superpowers", "bin"
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
@classmethod
|
|
118
|
-
def collect_workspace_symbols(cls, workspace_dir: str) -> Tuple[Set[str], Set[str], Set[str]]:
|
|
119
|
-
"""Collects all real functions, imports, and methods defined across workspace."""
|
|
120
|
-
functions: Set[str] = set()
|
|
121
|
-
imports: Set[str] = set()
|
|
122
|
-
methods: Set[str] = set()
|
|
123
|
-
|
|
124
|
-
abs_root = os.path.abspath(workspace_dir)
|
|
125
|
-
for root, dirs, fnames in os.walk(abs_root):
|
|
126
|
-
dirs[:] = [d for d in dirs if d not in cls.SKIP_DIRS and not d.startswith(".")]
|
|
127
|
-
for fname in fnames:
|
|
128
|
-
if fname.endswith(".py"):
|
|
129
|
-
fpath = os.path.join(root, fname)
|
|
130
|
-
try:
|
|
131
|
-
with open(fpath, "r", encoding="utf-8", errors="replace") as f:
|
|
132
|
-
tree = ast.parse(f.read(), filename=fname)
|
|
133
|
-
for node in ast.walk(tree):
|
|
134
|
-
if isinstance(node, ast.ClassDef):
|
|
135
|
-
for item in node.body:
|
|
136
|
-
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
137
|
-
methods.add(item.name)
|
|
138
|
-
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
139
|
-
functions.add(node.name)
|
|
140
|
-
imports.add(node.name)
|
|
141
|
-
elif isinstance(node, ast.ClassDef):
|
|
142
|
-
imports.add(node.name)
|
|
143
|
-
except Exception:
|
|
144
|
-
pass
|
|
145
|
-
|
|
146
|
-
return functions, imports, methods
|
|
147
|
-
|
|
148
|
-
@classmethod
|
|
149
|
-
def heal_code(cls, code: str, workspace_dir: str = ".") -> HealingReport:
|
|
150
|
-
"""Parses candidate code, fixes hallucinated symbols, and returns report."""
|
|
151
|
-
try:
|
|
152
|
-
tree = ast.parse(code)
|
|
153
|
-
except SyntaxError as e:
|
|
154
|
-
return HealingReport(
|
|
155
|
-
success=False,
|
|
156
|
-
original_code=code,
|
|
157
|
-
healed_code=code,
|
|
158
|
-
total_fixes=0,
|
|
159
|
-
diff=f"SyntaxError in code: {e}"
|
|
160
|
-
)
|
|
161
|
-
|
|
162
|
-
known_funcs, known_imports, known_methods = cls.collect_workspace_symbols(workspace_dir)
|
|
163
|
-
transformer = _ASTHealerTransformer(known_funcs, known_imports, known_methods)
|
|
164
|
-
healed_tree = transformer.visit(tree)
|
|
165
|
-
ast.fix_missing_locations(healed_tree)
|
|
166
|
-
|
|
167
|
-
try:
|
|
168
|
-
healed_code = ast.unparse(healed_tree)
|
|
169
|
-
except Exception:
|
|
170
|
-
healed_code = code
|
|
171
|
-
|
|
172
|
-
# Generate diff
|
|
173
|
-
orig_lines = code.splitlines(keepends=True)
|
|
174
|
-
healed_lines = healed_code.splitlines(keepends=True)
|
|
175
|
-
diff_lines = list(difflib.unified_diff(
|
|
176
|
-
orig_lines, healed_lines, fromfile="candidate.py (ai_generated)", tofile="healed.py (ast_corrected)"
|
|
177
|
-
))
|
|
178
|
-
diff_str = "".join(diff_lines)
|
|
179
|
-
|
|
180
|
-
return HealingReport(
|
|
181
|
-
success=True,
|
|
182
|
-
original_code=code,
|
|
183
|
-
healed_code=healed_code,
|
|
184
|
-
total_fixes=len(transformer.actions),
|
|
185
|
-
actions=transformer.actions,
|
|
186
|
-
diff=diff_str
|
|
187
|
-
)
|
|
188
|
-
|
|
189
|
-
@classmethod
|
|
190
|
-
def heal_file(cls, file_path: str, workspace_dir: str = ".", apply_write: bool = False) -> HealingReport:
|
|
191
|
-
"""Reads file, applies healing, optionally overwrites if apply_write is True."""
|
|
192
|
-
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
193
|
-
code = f.read()
|
|
194
|
-
|
|
195
|
-
report = cls.heal_code(code, workspace_dir=workspace_dir)
|
|
196
|
-
if apply_write and report.total_fixes > 0:
|
|
197
|
-
with open(file_path, "w", encoding="utf-8") as f:
|
|
198
|
-
f.write(report.healed_code)
|
|
199
|
-
|
|
200
|
-
return report
|
|
201
|
-
|
|
202
|
-
@classmethod
|
|
203
|
-
def render_cli(cls, rep: HealingReport, target_hint: str = ""):
|
|
204
|
-
print("\n🔧 \033[1mT-ZERO SELF-HEALING AST AUTO-CORRECTOR\033[0m")
|
|
205
|
-
print("=" * 70)
|
|
206
|
-
if target_hint:
|
|
207
|
-
print(f"🎯 Target File: {target_hint}")
|
|
208
|
-
print(f"📊 Auto-Repaired Hallucinations: \033[1m{rep.total_fixes}\033[0m")
|
|
209
|
-
|
|
210
|
-
if rep.actions:
|
|
211
|
-
print("\n📋 Detected & Repaired Symbols:")
|
|
212
|
-
for a in rep.actions:
|
|
213
|
-
conf_pct = int(a.confidence * 100)
|
|
214
|
-
print(f" • Line {a.line_number} [{a.symbol_type}]: \033[31m{a.original_symbol}\033[0m ➔ \033[32m{a.healed_symbol}\033[0m (Confidence: {conf_pct}%)")
|
|
215
|
-
|
|
216
|
-
if rep.diff:
|
|
217
|
-
print("\n🔍 AST Unified Diff:")
|
|
218
|
-
for line in rep.diff.splitlines()[:20]:
|
|
219
|
-
if line.startswith("+"):
|
|
220
|
-
print(f"\033[32m{line}\033[0m")
|
|
221
|
-
elif line.startswith("-"):
|
|
222
|
-
print(f"\033[31m{line}\033[0m")
|
|
223
|
-
else:
|
|
224
|
-
print(line)
|
|
225
|
-
else:
|
|
226
|
-
print("\033[32m✅ Flawless Code: 0 hallucinated symbols detected! AST matches workspace.\033[0m")
|
|
227
|
-
print("=" * 70)
|
|
228
|
-
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Siber Akademi — T-Zero Self-Healing AST Hallucination Auto-Corrector.
|
|
4
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
5
|
+
License: MIT
|
|
6
|
+
|
|
7
|
+
Statically inspects candidate code against verified workspace AST symbol tables.
|
|
8
|
+
Detects phantom imports, misspelled identifiers, and hallucinated method calls,
|
|
9
|
+
and automatically rewrites the AST to the correct valid local identifier.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
import ast
|
|
15
|
+
import difflib
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Dict, List, Set, Any, Optional, Tuple
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class HealingAction:
|
|
22
|
+
original_symbol: str
|
|
23
|
+
healed_symbol: str
|
|
24
|
+
symbol_type: str # "import", "method_call", "function_call"
|
|
25
|
+
line_number: int
|
|
26
|
+
confidence: float
|
|
27
|
+
context_hint: str = ""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class HealingReport:
|
|
32
|
+
success: bool
|
|
33
|
+
original_code: str
|
|
34
|
+
healed_code: str
|
|
35
|
+
total_fixes: int
|
|
36
|
+
actions: List[HealingAction] = field(default_factory=list)
|
|
37
|
+
diff: str = ""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _ASTHealerTransformer(ast.NodeTransformer):
|
|
41
|
+
def __init__(self, known_functions: Set[str], known_imports: Set[str], known_methods: Set[str]):
|
|
42
|
+
super().__init__()
|
|
43
|
+
self.known_functions = known_functions
|
|
44
|
+
self.known_imports = known_imports
|
|
45
|
+
self.known_methods = known_methods
|
|
46
|
+
self.actions: List[HealingAction] = []
|
|
47
|
+
|
|
48
|
+
def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.AST:
|
|
49
|
+
# Check imported names against known symbols
|
|
50
|
+
new_names = []
|
|
51
|
+
for alias in node.names:
|
|
52
|
+
name = alias.name
|
|
53
|
+
if self.known_imports and name not in self.known_imports:
|
|
54
|
+
matches = difflib.get_close_matches(name, list(self.known_imports), n=1, cutoff=0.65)
|
|
55
|
+
if matches:
|
|
56
|
+
best = matches[0]
|
|
57
|
+
ratio = difflib.SequenceMatcher(None, name, best).ratio()
|
|
58
|
+
self.actions.append(HealingAction(
|
|
59
|
+
original_symbol=name,
|
|
60
|
+
healed_symbol=best,
|
|
61
|
+
symbol_type="import",
|
|
62
|
+
line_number=getattr(node, "lineno", 1),
|
|
63
|
+
confidence=round(ratio, 2),
|
|
64
|
+
context_hint=f"Module: {node.module or ''}"
|
|
65
|
+
))
|
|
66
|
+
new_names.append(ast.alias(name=best, asname=alias.asname))
|
|
67
|
+
continue
|
|
68
|
+
new_names.append(alias)
|
|
69
|
+
node.names = new_names
|
|
70
|
+
return node
|
|
71
|
+
|
|
72
|
+
def visit_Call(self, node: ast.Call) -> ast.AST:
|
|
73
|
+
self.generic_visit(node)
|
|
74
|
+
# Check attribute calls (e.g. obj.calc_cost())
|
|
75
|
+
if isinstance(node.func, ast.Attribute):
|
|
76
|
+
attr_name = node.func.attr
|
|
77
|
+
if self.known_methods and attr_name not in self.known_methods:
|
|
78
|
+
matches = difflib.get_close_matches(attr_name, list(self.known_methods), n=1, cutoff=0.65)
|
|
79
|
+
if matches:
|
|
80
|
+
best = matches[0]
|
|
81
|
+
ratio = difflib.SequenceMatcher(None, attr_name, best).ratio()
|
|
82
|
+
self.actions.append(HealingAction(
|
|
83
|
+
original_symbol=attr_name,
|
|
84
|
+
healed_symbol=best,
|
|
85
|
+
symbol_type="method_call",
|
|
86
|
+
line_number=getattr(node, "lineno", 1),
|
|
87
|
+
confidence=round(ratio, 2)
|
|
88
|
+
))
|
|
89
|
+
node.func.attr = best
|
|
90
|
+
# Check standalone function calls (e.g. calculate_tokens())
|
|
91
|
+
elif isinstance(node.func, ast.Name):
|
|
92
|
+
func_name = node.func.id
|
|
93
|
+
if self.known_functions and func_name not in self.known_functions:
|
|
94
|
+
matches = difflib.get_close_matches(func_name, list(self.known_functions), n=1, cutoff=0.70)
|
|
95
|
+
if matches:
|
|
96
|
+
best = matches[0]
|
|
97
|
+
ratio = difflib.SequenceMatcher(None, func_name, best).ratio()
|
|
98
|
+
self.actions.append(HealingAction(
|
|
99
|
+
original_symbol=func_name,
|
|
100
|
+
healed_symbol=best,
|
|
101
|
+
symbol_type="function_call",
|
|
102
|
+
line_number=getattr(node, "lineno", 1),
|
|
103
|
+
confidence=round(ratio, 2)
|
|
104
|
+
))
|
|
105
|
+
node.func.id = best
|
|
106
|
+
return node
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class ASTHallucinationAutoCorrector:
|
|
110
|
+
"""Self-healing engine to detect and repair hallucinated AI symbols."""
|
|
111
|
+
|
|
112
|
+
SKIP_DIRS = {
|
|
113
|
+
".git", "__pycache__", ".pytest_cache", "target", "dist",
|
|
114
|
+
"build", ".venv", "venv", "node_modules", ".superpowers", "bin"
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
@classmethod
|
|
118
|
+
def collect_workspace_symbols(cls, workspace_dir: str) -> Tuple[Set[str], Set[str], Set[str]]:
|
|
119
|
+
"""Collects all real functions, imports, and methods defined across workspace."""
|
|
120
|
+
functions: Set[str] = set()
|
|
121
|
+
imports: Set[str] = set()
|
|
122
|
+
methods: Set[str] = set()
|
|
123
|
+
|
|
124
|
+
abs_root = os.path.abspath(workspace_dir)
|
|
125
|
+
for root, dirs, fnames in os.walk(abs_root):
|
|
126
|
+
dirs[:] = [d for d in dirs if d not in cls.SKIP_DIRS and not d.startswith(".")]
|
|
127
|
+
for fname in fnames:
|
|
128
|
+
if fname.endswith(".py"):
|
|
129
|
+
fpath = os.path.join(root, fname)
|
|
130
|
+
try:
|
|
131
|
+
with open(fpath, "r", encoding="utf-8", errors="replace") as f:
|
|
132
|
+
tree = ast.parse(f.read(), filename=fname)
|
|
133
|
+
for node in ast.walk(tree):
|
|
134
|
+
if isinstance(node, ast.ClassDef):
|
|
135
|
+
for item in node.body:
|
|
136
|
+
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
137
|
+
methods.add(item.name)
|
|
138
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
139
|
+
functions.add(node.name)
|
|
140
|
+
imports.add(node.name)
|
|
141
|
+
elif isinstance(node, ast.ClassDef):
|
|
142
|
+
imports.add(node.name)
|
|
143
|
+
except Exception:
|
|
144
|
+
pass
|
|
145
|
+
|
|
146
|
+
return functions, imports, methods
|
|
147
|
+
|
|
148
|
+
@classmethod
|
|
149
|
+
def heal_code(cls, code: str, workspace_dir: str = ".") -> HealingReport:
|
|
150
|
+
"""Parses candidate code, fixes hallucinated symbols, and returns report."""
|
|
151
|
+
try:
|
|
152
|
+
tree = ast.parse(code)
|
|
153
|
+
except SyntaxError as e:
|
|
154
|
+
return HealingReport(
|
|
155
|
+
success=False,
|
|
156
|
+
original_code=code,
|
|
157
|
+
healed_code=code,
|
|
158
|
+
total_fixes=0,
|
|
159
|
+
diff=f"SyntaxError in code: {e}"
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
known_funcs, known_imports, known_methods = cls.collect_workspace_symbols(workspace_dir)
|
|
163
|
+
transformer = _ASTHealerTransformer(known_funcs, known_imports, known_methods)
|
|
164
|
+
healed_tree = transformer.visit(tree)
|
|
165
|
+
ast.fix_missing_locations(healed_tree)
|
|
166
|
+
|
|
167
|
+
try:
|
|
168
|
+
healed_code = ast.unparse(healed_tree)
|
|
169
|
+
except Exception:
|
|
170
|
+
healed_code = code
|
|
171
|
+
|
|
172
|
+
# Generate diff
|
|
173
|
+
orig_lines = code.splitlines(keepends=True)
|
|
174
|
+
healed_lines = healed_code.splitlines(keepends=True)
|
|
175
|
+
diff_lines = list(difflib.unified_diff(
|
|
176
|
+
orig_lines, healed_lines, fromfile="candidate.py (ai_generated)", tofile="healed.py (ast_corrected)"
|
|
177
|
+
))
|
|
178
|
+
diff_str = "".join(diff_lines)
|
|
179
|
+
|
|
180
|
+
return HealingReport(
|
|
181
|
+
success=True,
|
|
182
|
+
original_code=code,
|
|
183
|
+
healed_code=healed_code,
|
|
184
|
+
total_fixes=len(transformer.actions),
|
|
185
|
+
actions=transformer.actions,
|
|
186
|
+
diff=diff_str
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
@classmethod
|
|
190
|
+
def heal_file(cls, file_path: str, workspace_dir: str = ".", apply_write: bool = False) -> HealingReport:
|
|
191
|
+
"""Reads file, applies healing, optionally overwrites if apply_write is True."""
|
|
192
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
193
|
+
code = f.read()
|
|
194
|
+
|
|
195
|
+
report = cls.heal_code(code, workspace_dir=workspace_dir)
|
|
196
|
+
if apply_write and report.total_fixes > 0:
|
|
197
|
+
with open(file_path, "w", encoding="utf-8") as f:
|
|
198
|
+
f.write(report.healed_code)
|
|
199
|
+
|
|
200
|
+
return report
|
|
201
|
+
|
|
202
|
+
@classmethod
|
|
203
|
+
def render_cli(cls, rep: HealingReport, target_hint: str = ""):
|
|
204
|
+
print("\n🔧 \033[1mT-ZERO SELF-HEALING AST AUTO-CORRECTOR\033[0m")
|
|
205
|
+
print("=" * 70)
|
|
206
|
+
if target_hint:
|
|
207
|
+
print(f"🎯 Target File: {target_hint}")
|
|
208
|
+
print(f"📊 Auto-Repaired Hallucinations: \033[1m{rep.total_fixes}\033[0m")
|
|
209
|
+
|
|
210
|
+
if rep.actions:
|
|
211
|
+
print("\n📋 Detected & Repaired Symbols:")
|
|
212
|
+
for a in rep.actions:
|
|
213
|
+
conf_pct = int(a.confidence * 100)
|
|
214
|
+
print(f" • Line {a.line_number} [{a.symbol_type}]: \033[31m{a.original_symbol}\033[0m ➔ \033[32m{a.healed_symbol}\033[0m (Confidence: {conf_pct}%)")
|
|
215
|
+
|
|
216
|
+
if rep.diff:
|
|
217
|
+
print("\n🔍 AST Unified Diff:")
|
|
218
|
+
for line in rep.diff.splitlines()[:20]:
|
|
219
|
+
if line.startswith("+"):
|
|
220
|
+
print(f"\033[32m{line}\033[0m")
|
|
221
|
+
elif line.startswith("-"):
|
|
222
|
+
print(f"\033[31m{line}\033[0m")
|
|
223
|
+
else:
|
|
224
|
+
print(line)
|
|
225
|
+
else:
|
|
226
|
+
print("\033[32m✅ Flawless Code: 0 hallucinated symbols detected! AST matches workspace.\033[0m")
|
|
227
|
+
print("=" * 70)
|
|
228
|
+
|
|
@@ -1,63 +1,63 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""T-Zero Autonomous PC-Fixer & Codebase Doctor Package.
|
|
3
|
-
|
|
4
|
-
Author: Toprak Ahmet Aydogmus (Siber Akademi)
|
|
5
|
-
Version: 10.5.0
|
|
6
|
-
"""
|
|
7
|
-
|
|
8
|
-
from .models import (
|
|
9
|
-
SeverityLevel,
|
|
10
|
-
DiagnosticCategory,
|
|
11
|
-
SystemPlatform,
|
|
12
|
-
DiagnosticIssue,
|
|
13
|
-
HealAction,
|
|
14
|
-
DiagnosticReport,
|
|
15
|
-
HealReport,
|
|
16
|
-
EnvironmentSnapshot,
|
|
17
|
-
RollbackManifest,
|
|
18
|
-
ToolStatus,
|
|
19
|
-
)
|
|
20
|
-
from .os_doctor import OSDoctor
|
|
21
|
-
from .venv_doctor import VenvDoctor
|
|
22
|
-
from .ast_syntax_healer import ASTSyntaxHealer
|
|
23
|
-
from .import_graph_healer import ImportGraphHealer
|
|
24
|
-
from .code_smells_healer import CodeSmellsHealer
|
|
25
|
-
from .security_zero_leak import SecurityZeroLeakDoctor
|
|
26
|
-
from .hardware_and_disk_doctor import HardwareAndDiskSurgeon
|
|
27
|
-
from .packaging_abi_surgeon import PackagingAbiSurgeon
|
|
28
|
-
from .git_advanced_surgeon import GitAdvancedSurgeon
|
|
29
|
-
from .polyglot_build_healer import PolyglotBuildHealer
|
|
30
|
-
from .cwe_remediator import SecurityCweRemediator
|
|
31
|
-
from .dead_code_eliminator import DeadCodeEliminator
|
|
32
|
-
from .async_io_modernizer import AsyncIoModernizer
|
|
33
|
-
from .mcp_server import PCFixerMcpServer
|
|
34
|
-
from .orchestrator import FixerOrchestrator
|
|
35
|
-
|
|
36
|
-
__version__ = "10.5.0"
|
|
37
|
-
__all__ = [
|
|
38
|
-
"SeverityLevel",
|
|
39
|
-
"DiagnosticCategory",
|
|
40
|
-
"SystemPlatform",
|
|
41
|
-
"DiagnosticIssue",
|
|
42
|
-
"HealAction",
|
|
43
|
-
"DiagnosticReport",
|
|
44
|
-
"HealReport",
|
|
45
|
-
"EnvironmentSnapshot",
|
|
46
|
-
"RollbackManifest",
|
|
47
|
-
"ToolStatus",
|
|
48
|
-
"OSDoctor",
|
|
49
|
-
"VenvDoctor",
|
|
50
|
-
"ASTSyntaxHealer",
|
|
51
|
-
"ImportGraphHealer",
|
|
52
|
-
"CodeSmellsHealer",
|
|
53
|
-
"SecurityZeroLeakDoctor",
|
|
54
|
-
"HardwareAndDiskSurgeon",
|
|
55
|
-
"PackagingAbiSurgeon",
|
|
56
|
-
"GitAdvancedSurgeon",
|
|
57
|
-
"PolyglotBuildHealer",
|
|
58
|
-
"SecurityCweRemediator",
|
|
59
|
-
"DeadCodeEliminator",
|
|
60
|
-
"AsyncIoModernizer",
|
|
61
|
-
"PCFixerMcpServer",
|
|
62
|
-
"FixerOrchestrator",
|
|
63
|
-
]
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""T-Zero Autonomous PC-Fixer & Codebase Doctor Package.
|
|
3
|
+
|
|
4
|
+
Author: Toprak Ahmet Aydogmus (Siber Akademi)
|
|
5
|
+
Version: 10.5.0
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .models import (
|
|
9
|
+
SeverityLevel,
|
|
10
|
+
DiagnosticCategory,
|
|
11
|
+
SystemPlatform,
|
|
12
|
+
DiagnosticIssue,
|
|
13
|
+
HealAction,
|
|
14
|
+
DiagnosticReport,
|
|
15
|
+
HealReport,
|
|
16
|
+
EnvironmentSnapshot,
|
|
17
|
+
RollbackManifest,
|
|
18
|
+
ToolStatus,
|
|
19
|
+
)
|
|
20
|
+
from .os_doctor import OSDoctor
|
|
21
|
+
from .venv_doctor import VenvDoctor
|
|
22
|
+
from .ast_syntax_healer import ASTSyntaxHealer
|
|
23
|
+
from .import_graph_healer import ImportGraphHealer
|
|
24
|
+
from .code_smells_healer import CodeSmellsHealer
|
|
25
|
+
from .security_zero_leak import SecurityZeroLeakDoctor
|
|
26
|
+
from .hardware_and_disk_doctor import HardwareAndDiskSurgeon
|
|
27
|
+
from .packaging_abi_surgeon import PackagingAbiSurgeon
|
|
28
|
+
from .git_advanced_surgeon import GitAdvancedSurgeon
|
|
29
|
+
from .polyglot_build_healer import PolyglotBuildHealer
|
|
30
|
+
from .cwe_remediator import SecurityCweRemediator
|
|
31
|
+
from .dead_code_eliminator import DeadCodeEliminator
|
|
32
|
+
from .async_io_modernizer import AsyncIoModernizer
|
|
33
|
+
from .mcp_server import PCFixerMcpServer
|
|
34
|
+
from .orchestrator import FixerOrchestrator
|
|
35
|
+
|
|
36
|
+
__version__ = "10.5.0"
|
|
37
|
+
__all__ = [
|
|
38
|
+
"SeverityLevel",
|
|
39
|
+
"DiagnosticCategory",
|
|
40
|
+
"SystemPlatform",
|
|
41
|
+
"DiagnosticIssue",
|
|
42
|
+
"HealAction",
|
|
43
|
+
"DiagnosticReport",
|
|
44
|
+
"HealReport",
|
|
45
|
+
"EnvironmentSnapshot",
|
|
46
|
+
"RollbackManifest",
|
|
47
|
+
"ToolStatus",
|
|
48
|
+
"OSDoctor",
|
|
49
|
+
"VenvDoctor",
|
|
50
|
+
"ASTSyntaxHealer",
|
|
51
|
+
"ImportGraphHealer",
|
|
52
|
+
"CodeSmellsHealer",
|
|
53
|
+
"SecurityZeroLeakDoctor",
|
|
54
|
+
"HardwareAndDiskSurgeon",
|
|
55
|
+
"PackagingAbiSurgeon",
|
|
56
|
+
"GitAdvancedSurgeon",
|
|
57
|
+
"PolyglotBuildHealer",
|
|
58
|
+
"SecurityCweRemediator",
|
|
59
|
+
"DeadCodeEliminator",
|
|
60
|
+
"AsyncIoModernizer",
|
|
61
|
+
"PCFixerMcpServer",
|
|
62
|
+
"FixerOrchestrator",
|
|
63
|
+
]
|