tzero-mcp 11.0.0 → 11.11.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 +56 -56
- package/CONTRIBUTING.md +71 -71
- package/LICENSE +21 -21
- package/README.md +64 -64
- package/bin/tzero-mcp.js +62 -62
- package/bin/tzero.js +61 -61
- package/index.d.ts +25 -25
- package/index.js +15 -15
- package/package.json +89 -88
- package/src/addmcp.py +1203 -1197
- package/src/app.py +1810 -1810
- package/src/main.py +60 -60
- package/src/pc_fixer_mcp.py +25 -25
- package/src/tzero/__init__.py +54 -54
- package/src/tzero/__main__.py +6 -6
- package/src/tzero/siber_akademi_icon.py +77 -77
- package/src/tzero/tzero_arch_test.py +463 -463
- package/src/tzero/tzero_benchmark.py +475 -475
- package/src/tzero/tzero_blackboard.py +257 -257
- package/src/tzero/tzero_bridge.py +546 -546
- package/src/tzero/tzero_budget.py +195 -195
- package/src/tzero/tzero_card.py +431 -0
- package/src/tzero/tzero_ci.py +153 -153
- package/src/tzero/tzero_commit.py +192 -192
- package/src/tzero/tzero_contracts.py +1093 -1093
- package/src/tzero/tzero_cost.py +166 -166
- package/src/tzero/tzero_dashboard.py +1960 -1960
- package/src/tzero/tzero_debt.py +461 -461
- package/src/tzero/tzero_deps.py +462 -462
- package/src/tzero/tzero_drift.py +208 -208
- package/src/tzero/tzero_explain.py +306 -306
- package/src/tzero/tzero_features.py +3024 -3024
- package/src/tzero/tzero_federation.py +299 -299
- package/src/tzero/tzero_fix.py +557 -228
- package/src/tzero/tzero_fixer/__init__.py +63 -63
- package/src/tzero/tzero_fixer/amalgamation.py +334 -334
- package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
- package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
- package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
- package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
- package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
- package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
- package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
- package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
- package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
- package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
- package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
- package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
- package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
- package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
- package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
- package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
- package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
- package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
- package/src/tzero/tzero_fixer/mcp_server.py +489 -489
- package/src/tzero/tzero_fixer/models.py +385 -385
- package/src/tzero/tzero_fixer/orchestrator.py +375 -375
- package/src/tzero/tzero_fixer/os_doctor.py +502 -502
- package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
- package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
- package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
- package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
- package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
- package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
- package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
- package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
- package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
- package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
- package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
- package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
- package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
- package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
- package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
- package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
- package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
- package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
- package/src/tzero/tzero_golden.py +319 -319
- package/src/tzero/tzero_graph_hud.html +338 -338
- package/src/tzero/tzero_graph_rag.py +263 -263
- package/src/tzero/tzero_growth.py +415 -0
- package/src/tzero/tzero_guard.py +251 -243
- package/src/tzero/tzero_hooks.py +565 -565
- package/src/tzero/tzero_infra.py +274 -274
- package/src/tzero/tzero_jarvis/__init__.py +134 -124
- package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
- package/src/tzero/tzero_jarvis/creative_director.py +333 -0
- package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
- package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
- package/src/tzero/tzero_jarvis/latent_press.py +137 -137
- package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
- package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
- package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
- package/src/tzero/tzero_jarvis/self_healing.py +308 -308
- package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
- package/src/tzero/tzero_jarvis/swarm.py +261 -261
- package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
- package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
- package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
- package/src/tzero/tzero_lsp.py +634 -634
- package/src/tzero/tzero_mcp.py +5314 -5237
- package/src/tzero/tzero_mutation.py +358 -358
- package/src/tzero/tzero_neural_cortex.py +1425 -1425
- package/src/tzero/tzero_packer.py +577 -577
- package/src/tzero/tzero_patch.py +624 -624
- package/src/tzero/tzero_pc_fixer.py +12699 -12699
- package/src/tzero/tzero_pipe.py +95 -95
- package/src/tzero/tzero_polyglot.py +799 -799
- package/src/tzero/tzero_proxy.py +127 -127
- package/src/tzero/tzero_reachability.py +272 -272
- package/src/tzero/tzero_replay.py +141 -141
- package/src/tzero/tzero_rust_bridge.py +198 -198
- package/src/tzero/tzero_scip.py +368 -368
- package/src/tzero/tzero_security.py +573 -573
- package/src/tzero/tzero_semantic_merge.py +189 -189
- package/src/tzero/tzero_snapshot.py +471 -471
- package/src/tzero/tzero_stubs.py +313 -313
- package/src/tzero/tzero_subagent_engine.py +459 -459
- package/src/tzero/tzero_superdesign.py +774 -774
- package/src/tzero/tzero_sync.py +241 -241
- package/src/tzero/tzero_task_benchmark.py +506 -458
- package/src/tzero/tzero_tui.py +313 -313
- package/src/tzero/tzero_turbo.py +264 -264
- package/src/tzero/tzero_v3.py +9997 -9900
- package/src/tzero.py +6 -6
- package/src/tzero_mcp.py +25 -0
- package/test/package.test.js +55 -55
package/src/tzero/tzero_fix.py
CHANGED
|
@@ -1,228 +1,557 @@
|
|
|
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
|
|
15
|
-
import
|
|
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
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
)
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
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 re
|
|
15
|
+
import ast
|
|
16
|
+
import builtins
|
|
17
|
+
import difflib
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Dict, List, Set, Any, Optional, Tuple
|
|
20
|
+
|
|
21
|
+
STD_LIB_ROOT_MODULES = {
|
|
22
|
+
"os", "sys", "json", "time", "re", "math", "hashlib", "uuid", "datetime",
|
|
23
|
+
"asyncio", "subprocess", "tempfile", "platform", "shutil", "urllib", "random",
|
|
24
|
+
"logging", "collections", "functools", "itertools", "pathlib", "difflib",
|
|
25
|
+
"typing", "dataclasses", "unittest", "tomllib", "argparse", "io", "copy"
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
TYPING_NAMES = {
|
|
29
|
+
"Optional", "List", "Dict", "Tuple", "Set", "Any", "Union", "Callable",
|
|
30
|
+
"Sequence", "Iterable", "NamedTuple", "TypeVar", "Generic", "Annotated"
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
PATHLIB_NAMES = {"Path"}
|
|
34
|
+
|
|
35
|
+
PYTHON_BUILTIN_FUNCTIONS = set(dir(builtins))
|
|
36
|
+
|
|
37
|
+
BUILTIN_COMMON_METHODS = {
|
|
38
|
+
# unittest / testing
|
|
39
|
+
"assert", "assertequal", "assertnotequal", "asserttrue", "assertfalse",
|
|
40
|
+
"assertis", "assertisnot", "assertisnone", "assertisnotnone",
|
|
41
|
+
"assertin", "assertnotin", "assertisinstance", "assertnotisinstance",
|
|
42
|
+
"assertgreater", "assertgreaterequal", "assertless", "assertlessequal",
|
|
43
|
+
"assertalmostequal", "assertnotalmostequal", "assertraises", "assertwarns",
|
|
44
|
+
"assertlogs", "assertcount", "assertsequenceequal", "assertdictequal",
|
|
45
|
+
"setup", "teardown", "setupclass", "teardownclass",
|
|
46
|
+
# pathlib & fs methods
|
|
47
|
+
"write_text", "read_text", "write_bytes", "read_bytes", "mkdir", "unlink",
|
|
48
|
+
"rmdir", "rename", "replace", "stat", "chmod", "touch", "iterdir", "glob",
|
|
49
|
+
"rglob", "is_dir", "is_file", "is_symlink", "samefile", "expanduser",
|
|
50
|
+
# dict / list / set / str / io / process methods
|
|
51
|
+
"append", "extend", "insert", "remove", "pop", "clear", "index", "count",
|
|
52
|
+
"sort", "reverse", "copy", "get", "setdefault", "update", "values",
|
|
53
|
+
"keys", "items", "split", "rsplit", "splitlines", "join", "strip",
|
|
54
|
+
"lstrip", "rstrip", "lower", "upper", "capitalize", "title", "startswith",
|
|
55
|
+
"endswith", "replace", "find", "rfind", "encode", "decode", "format",
|
|
56
|
+
"read", "readline", "readlines", "write", "writelines", "close", "seek",
|
|
57
|
+
"tell", "flush", "seekable", "readable", "writable", "fileno", "isatty",
|
|
58
|
+
"communicate", "poll", "wait", "terminate", "kill", "send_signal",
|
|
59
|
+
"dump", "dumps", "load", "loads", "run", "call", "check_call", "check_output",
|
|
60
|
+
"exists", "is_file", "is_dir", "resolve", "parent", "parents", "stem",
|
|
61
|
+
"suffix", "suffixes", "name", "as_posix", "match", "search", "findall",
|
|
62
|
+
"finditer", "sub", "subn", "group", "groups", "groupdict", "start", "end",
|
|
63
|
+
"span", "sleep", "time", "monotonic", "now", "utcnow", "isoformat",
|
|
64
|
+
"strftime", "strptime", "timestamp", "date", "year", "month", "day",
|
|
65
|
+
"hour", "minute", "second", "microsecond", "total_seconds", "days",
|
|
66
|
+
"parse", "unparse", "walk", "visit", "generic_visit"
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
IGNORED_WORKSPACE_FILES = {
|
|
70
|
+
"tzero_gateway.py", "auto_outreach.py", "auto_onprem_outreach.py",
|
|
71
|
+
"test_gateway_client.py", "siber_akademi_icon.py"
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def find_best_symbol_match(target: str, candidates: Set[str], cutoff: float = 0.50) -> Tuple[Optional[str], float]:
|
|
76
|
+
"""Hybrid symbol matcher combining token-level Jaccard overlap, prefix boost, and SequenceMatcher."""
|
|
77
|
+
if not candidates or not target:
|
|
78
|
+
return None, 0.0
|
|
79
|
+
t_lower = target.lower()
|
|
80
|
+
for c in candidates:
|
|
81
|
+
if c.lower() == t_lower:
|
|
82
|
+
return c, 0.99
|
|
83
|
+
|
|
84
|
+
best_cand: Optional[str] = None
|
|
85
|
+
best_score: float = 0.0
|
|
86
|
+
t_words = set(re.findall(r'[A-Z]?[a-z]+|[A-Z]+(?=[A-Z][a-z]|\d|\W|$)|\d+', target))
|
|
87
|
+
t_words = {w.lower() for w in t_words}
|
|
88
|
+
|
|
89
|
+
for c in candidates:
|
|
90
|
+
c_words = set(re.findall(r'[A-Z]?[a-z]+|[A-Z]+(?=[A-Z][a-z]|\d|\W|$)|\d+', c))
|
|
91
|
+
c_words = {w.lower() for w in c_words}
|
|
92
|
+
word_overlap = len(t_words & c_words) / max(1, len(t_words | c_words)) if (t_words or c_words) else 0.0
|
|
93
|
+
seq_ratio = difflib.SequenceMatcher(None, target, c).ratio()
|
|
94
|
+
prefix_boost = 0.15 if (c.lower().startswith(target[:4].lower()) and len(target) >= 4) else 0.0
|
|
95
|
+
score = (0.5 * seq_ratio) + (0.5 * word_overlap) + prefix_boost
|
|
96
|
+
if score > best_score and score >= cutoff:
|
|
97
|
+
best_score = score
|
|
98
|
+
best_cand = c
|
|
99
|
+
|
|
100
|
+
return best_cand, round(best_score, 2)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass
|
|
104
|
+
class HealingAction:
|
|
105
|
+
original_symbol: str
|
|
106
|
+
healed_symbol: str
|
|
107
|
+
symbol_type: str # "import", "method_call", "function_call"
|
|
108
|
+
line_number: int
|
|
109
|
+
confidence: float
|
|
110
|
+
context_hint: str = ""
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class HealingReport:
|
|
115
|
+
success: bool
|
|
116
|
+
original_code: str
|
|
117
|
+
healed_code: str
|
|
118
|
+
total_fixes: int
|
|
119
|
+
actions: List[HealingAction] = field(default_factory=list)
|
|
120
|
+
diff: str = ""
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class _ASTHealerTransformer(ast.NodeTransformer):
|
|
124
|
+
def __init__(
|
|
125
|
+
self,
|
|
126
|
+
known_functions: Set[str],
|
|
127
|
+
known_imports: Set[str],
|
|
128
|
+
known_methods: Set[str],
|
|
129
|
+
module_symbol_map: Optional[Dict[str, Set[str]]] = None
|
|
130
|
+
):
|
|
131
|
+
super().__init__()
|
|
132
|
+
self.known_functions = known_functions
|
|
133
|
+
self.known_imports = known_imports
|
|
134
|
+
self.known_methods = known_methods
|
|
135
|
+
self.module_symbol_map = module_symbol_map or {}
|
|
136
|
+
self.actions: List[HealingAction] = []
|
|
137
|
+
self.renamed_imports: Dict[str, str] = {}
|
|
138
|
+
|
|
139
|
+
def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.AST:
|
|
140
|
+
# Never alter imports from Python standard library or popular runtime libraries
|
|
141
|
+
if node.module:
|
|
142
|
+
root_mod = node.module.split(".")[0]
|
|
143
|
+
if (
|
|
144
|
+
root_mod in STD_LIB_ROOT_MODULES
|
|
145
|
+
or root_mod in getattr(sys, "stdlib_module_names", set())
|
|
146
|
+
or root_mod in ("requests", "keyring", "PIL", "pygments", "pytest", "mcp", "pydantic", "tiktoken")
|
|
147
|
+
):
|
|
148
|
+
return node
|
|
149
|
+
|
|
150
|
+
# Check imported names against known symbols
|
|
151
|
+
new_names = []
|
|
152
|
+
target_candidates = self.known_imports
|
|
153
|
+
if node.module and self.module_symbol_map:
|
|
154
|
+
mod_key = node.module.split(".")[-1]
|
|
155
|
+
if node.module in self.module_symbol_map and self.module_symbol_map[node.module]:
|
|
156
|
+
target_candidates = self.module_symbol_map[node.module]
|
|
157
|
+
elif mod_key in self.module_symbol_map and self.module_symbol_map[mod_key]:
|
|
158
|
+
target_candidates = self.module_symbol_map[mod_key]
|
|
159
|
+
|
|
160
|
+
for alias in node.names:
|
|
161
|
+
name = alias.name
|
|
162
|
+
if target_candidates and name not in target_candidates:
|
|
163
|
+
best, score = find_best_symbol_match(name, target_candidates, cutoff=0.50)
|
|
164
|
+
if best and best != name:
|
|
165
|
+
self.actions.append(HealingAction(
|
|
166
|
+
original_symbol=name,
|
|
167
|
+
healed_symbol=best,
|
|
168
|
+
symbol_type="import",
|
|
169
|
+
line_number=getattr(node, "lineno", 1),
|
|
170
|
+
confidence=score,
|
|
171
|
+
context_hint=f"Module: {node.module or ''}"
|
|
172
|
+
))
|
|
173
|
+
self.renamed_imports[name] = best
|
|
174
|
+
new_names.append(ast.alias(name=best, asname=alias.asname))
|
|
175
|
+
continue
|
|
176
|
+
new_names.append(alias)
|
|
177
|
+
node.names = new_names
|
|
178
|
+
return node
|
|
179
|
+
|
|
180
|
+
def visit_Name(self, node: ast.Name) -> ast.AST:
|
|
181
|
+
if node.id in self.renamed_imports:
|
|
182
|
+
node.id = self.renamed_imports[node.id]
|
|
183
|
+
return node
|
|
184
|
+
|
|
185
|
+
def visit_Call(self, node: ast.Call) -> ast.AST:
|
|
186
|
+
self.generic_visit(node)
|
|
187
|
+
# Check attribute calls (e.g. obj.calc_cost())
|
|
188
|
+
if isinstance(node.func, ast.Attribute):
|
|
189
|
+
attr_name = node.func.attr
|
|
190
|
+
if (
|
|
191
|
+
attr_name.startswith("_")
|
|
192
|
+
or attr_name.startswith("assert")
|
|
193
|
+
or attr_name.lower() in BUILTIN_COMMON_METHODS
|
|
194
|
+
):
|
|
195
|
+
return node
|
|
196
|
+
if self.known_methods and attr_name not in self.known_methods:
|
|
197
|
+
best, score = find_best_symbol_match(attr_name, self.known_methods, cutoff=0.55)
|
|
198
|
+
if best and best != attr_name:
|
|
199
|
+
self.actions.append(HealingAction(
|
|
200
|
+
original_symbol=attr_name,
|
|
201
|
+
healed_symbol=best,
|
|
202
|
+
symbol_type="method_call",
|
|
203
|
+
line_number=getattr(node, "lineno", 1),
|
|
204
|
+
confidence=score
|
|
205
|
+
))
|
|
206
|
+
node.func.attr = best
|
|
207
|
+
# Check standalone function calls (e.g. calculate_tokens())
|
|
208
|
+
elif isinstance(node.func, ast.Name):
|
|
209
|
+
func_name = node.func.id
|
|
210
|
+
if (
|
|
211
|
+
func_name.startswith("_")
|
|
212
|
+
or func_name in PYTHON_BUILTIN_FUNCTIONS
|
|
213
|
+
):
|
|
214
|
+
return node
|
|
215
|
+
if self.known_functions and func_name not in self.known_functions:
|
|
216
|
+
best, score = find_best_symbol_match(func_name, self.known_functions, cutoff=0.55)
|
|
217
|
+
if best and best != func_name:
|
|
218
|
+
self.actions.append(HealingAction(
|
|
219
|
+
original_symbol=func_name,
|
|
220
|
+
healed_symbol=best,
|
|
221
|
+
symbol_type="function_call",
|
|
222
|
+
line_number=getattr(node, "lineno", 1),
|
|
223
|
+
confidence=score
|
|
224
|
+
))
|
|
225
|
+
node.func.id = best
|
|
226
|
+
return node
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class WorkspaceSymbolsResult:
|
|
230
|
+
"""Container for collected symbols supporting both 3-element unpacking and module map."""
|
|
231
|
+
def __init__(self, funcs: Set[str], imports: Set[str], methods: Set[str], module_map: Optional[Dict[str, Set[str]]] = None):
|
|
232
|
+
self.functions = funcs
|
|
233
|
+
self.imports = imports
|
|
234
|
+
self.methods = methods
|
|
235
|
+
self.module_map = module_map or {}
|
|
236
|
+
|
|
237
|
+
def __iter__(self):
|
|
238
|
+
yield self.functions
|
|
239
|
+
yield self.imports
|
|
240
|
+
yield self.methods
|
|
241
|
+
|
|
242
|
+
def __getitem__(self, idx):
|
|
243
|
+
return (self.functions, self.imports, self.methods, self.module_map)[idx]
|
|
244
|
+
|
|
245
|
+
def __len__(self):
|
|
246
|
+
return 3
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class ASTHallucinationAutoCorrector:
|
|
250
|
+
"""Self-healing engine to detect and repair hallucinated AI symbols."""
|
|
251
|
+
|
|
252
|
+
SKIP_DIRS = {
|
|
253
|
+
".git", "__pycache__", ".pytest_cache", "target", "dist",
|
|
254
|
+
"build", ".venv", "venv", "node_modules", ".superpowers", "bin"
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
@classmethod
|
|
258
|
+
def collect_workspace_symbols(cls, workspace_dir: str) -> WorkspaceSymbolsResult:
|
|
259
|
+
"""Collects all real functions, imports, and methods defined across workspace."""
|
|
260
|
+
functions: Set[str] = set()
|
|
261
|
+
imports: Set[str] = set()
|
|
262
|
+
methods: Set[str] = set()
|
|
263
|
+
module_map: Dict[str, Set[str]] = {}
|
|
264
|
+
|
|
265
|
+
abs_root = os.path.abspath(workspace_dir)
|
|
266
|
+
for root, dirs, fnames in os.walk(abs_root):
|
|
267
|
+
dirs[:] = [d for d in dirs if d not in cls.SKIP_DIRS and not d.startswith(".")]
|
|
268
|
+
for fname in fnames:
|
|
269
|
+
if fname in IGNORED_WORKSPACE_FILES or fname.startswith("."):
|
|
270
|
+
continue
|
|
271
|
+
if fname.endswith(".py"):
|
|
272
|
+
fpath = os.path.join(root, fname)
|
|
273
|
+
mod_name = os.path.splitext(fname)[0]
|
|
274
|
+
imports.add(mod_name)
|
|
275
|
+
rel_dir = os.path.relpath(root, abs_root).replace(os.sep, ".").replace("/", ".")
|
|
276
|
+
if rel_dir != "." and not rel_dir.startswith("."):
|
|
277
|
+
module_map.setdefault(rel_dir, set()).add(mod_name)
|
|
278
|
+
parent_pkg = rel_dir.split(".")[-1]
|
|
279
|
+
module_map.setdefault(parent_pkg, set()).add(mod_name)
|
|
280
|
+
mod_symbols: Set[str] = set()
|
|
281
|
+
try:
|
|
282
|
+
with open(fpath, "r", encoding="utf-8", errors="replace") as f:
|
|
283
|
+
tree = ast.parse(f.read(), filename=fname)
|
|
284
|
+
for node in ast.walk(tree):
|
|
285
|
+
if isinstance(node, ast.ClassDef):
|
|
286
|
+
imports.add(node.name)
|
|
287
|
+
mod_symbols.add(node.name)
|
|
288
|
+
for item in node.body:
|
|
289
|
+
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
290
|
+
methods.add(item.name)
|
|
291
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
292
|
+
functions.add(node.name)
|
|
293
|
+
imports.add(node.name)
|
|
294
|
+
mod_symbols.add(node.name)
|
|
295
|
+
module_map[mod_name] = mod_symbols
|
|
296
|
+
rel = os.path.relpath(fpath, abs_root).replace(os.sep, ".").replace("/", ".")
|
|
297
|
+
if rel.endswith(".py"):
|
|
298
|
+
rel = rel[:-3]
|
|
299
|
+
module_map[rel] = mod_symbols
|
|
300
|
+
except Exception:
|
|
301
|
+
pass
|
|
302
|
+
|
|
303
|
+
return WorkspaceSymbolsResult(functions, imports, methods, module_map)
|
|
304
|
+
|
|
305
|
+
@classmethod
|
|
306
|
+
def heal_code(
|
|
307
|
+
cls,
|
|
308
|
+
code: str,
|
|
309
|
+
workspace_dir: str = ".",
|
|
310
|
+
precomputed_symbols: Optional[Any] = None
|
|
311
|
+
) -> HealingReport:
|
|
312
|
+
"""Parses candidate code, fixes hallucinated symbols, and returns report."""
|
|
313
|
+
try:
|
|
314
|
+
tree = ast.parse(code)
|
|
315
|
+
except SyntaxError as e:
|
|
316
|
+
return HealingReport(
|
|
317
|
+
success=False,
|
|
318
|
+
original_code=code,
|
|
319
|
+
healed_code=code,
|
|
320
|
+
total_fixes=0,
|
|
321
|
+
diff=f"SyntaxError in code: {e}"
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
if precomputed_symbols is not None:
|
|
325
|
+
if hasattr(precomputed_symbols, "module_map"):
|
|
326
|
+
known_funcs = precomputed_symbols.functions
|
|
327
|
+
known_imports = precomputed_symbols.imports
|
|
328
|
+
known_methods = precomputed_symbols.methods
|
|
329
|
+
module_map = precomputed_symbols.module_map
|
|
330
|
+
else:
|
|
331
|
+
known_funcs, known_imports, known_methods = precomputed_symbols[:3]
|
|
332
|
+
module_map = precomputed_symbols[3] if len(precomputed_symbols) > 3 else {}
|
|
333
|
+
else:
|
|
334
|
+
sym_res = cls.collect_workspace_symbols(workspace_dir)
|
|
335
|
+
known_funcs = sym_res.functions
|
|
336
|
+
known_imports = sym_res.imports
|
|
337
|
+
known_methods = sym_res.methods
|
|
338
|
+
module_map = sym_res.module_map
|
|
339
|
+
|
|
340
|
+
transformer = _ASTHealerTransformer(known_funcs, known_imports, known_methods, module_symbol_map=module_map)
|
|
341
|
+
healed_tree = transformer.visit(tree)
|
|
342
|
+
ast.fix_missing_locations(healed_tree)
|
|
343
|
+
|
|
344
|
+
try:
|
|
345
|
+
healed_code = ast.unparse(healed_tree)
|
|
346
|
+
except Exception:
|
|
347
|
+
healed_code = code
|
|
348
|
+
|
|
349
|
+
# Check for unimported standard modules & typing names
|
|
350
|
+
declared_or_imported = set()
|
|
351
|
+
for node in ast.walk(tree):
|
|
352
|
+
if isinstance(node, ast.Import):
|
|
353
|
+
for a in node.names:
|
|
354
|
+
declared_or_imported.add(a.name.split('.')[0])
|
|
355
|
+
elif isinstance(node, ast.ImportFrom):
|
|
356
|
+
for a in node.names:
|
|
357
|
+
declared_or_imported.add(a.name)
|
|
358
|
+
elif isinstance(node, ast.FunctionDef):
|
|
359
|
+
declared_or_imported.add(node.name)
|
|
360
|
+
elif isinstance(node, ast.ClassDef):
|
|
361
|
+
declared_or_imported.add(node.name)
|
|
362
|
+
|
|
363
|
+
used_names = {node.id for node in ast.walk(tree) if isinstance(node, ast.Name)}
|
|
364
|
+
missing_root_modules = sorted(list(STD_LIB_ROOT_MODULES & used_names - declared_or_imported))
|
|
365
|
+
missing_typing = sorted(list(TYPING_NAMES & used_names - declared_or_imported))
|
|
366
|
+
missing_path = sorted(list(PATHLIB_NAMES & used_names - declared_or_imported))
|
|
367
|
+
|
|
368
|
+
injected_headers = []
|
|
369
|
+
for mod in missing_root_modules:
|
|
370
|
+
injected_headers.append(f"import {mod}")
|
|
371
|
+
transformer.actions.append(HealingAction(
|
|
372
|
+
original_symbol=f"<missing import {mod}>",
|
|
373
|
+
healed_symbol=f"import {mod}",
|
|
374
|
+
symbol_type="auto_import",
|
|
375
|
+
line_number=1,
|
|
376
|
+
confidence=1.0,
|
|
377
|
+
context_hint="Auto-injected standard library import"
|
|
378
|
+
))
|
|
379
|
+
if missing_typing:
|
|
380
|
+
injected_headers.append(f"from typing import {', '.join(missing_typing)}")
|
|
381
|
+
for t_name in missing_typing:
|
|
382
|
+
transformer.actions.append(HealingAction(
|
|
383
|
+
original_symbol=f"<missing typing {t_name}>",
|
|
384
|
+
healed_symbol=f"from typing import {t_name}",
|
|
385
|
+
symbol_type="auto_import",
|
|
386
|
+
line_number=1,
|
|
387
|
+
confidence=1.0,
|
|
388
|
+
context_hint="Auto-injected typing annotation import"
|
|
389
|
+
))
|
|
390
|
+
if missing_path:
|
|
391
|
+
injected_headers.append("from pathlib import Path")
|
|
392
|
+
transformer.actions.append(HealingAction(
|
|
393
|
+
original_symbol="<missing pathlib Path>",
|
|
394
|
+
healed_symbol="from pathlib import Path",
|
|
395
|
+
symbol_type="auto_import",
|
|
396
|
+
line_number=1,
|
|
397
|
+
confidence=1.0,
|
|
398
|
+
context_hint="Auto-injected pathlib import"
|
|
399
|
+
))
|
|
400
|
+
|
|
401
|
+
if not transformer.actions and not injected_headers:
|
|
402
|
+
return HealingReport(
|
|
403
|
+
success=True,
|
|
404
|
+
original_code=code,
|
|
405
|
+
healed_code=code,
|
|
406
|
+
total_fixes=0,
|
|
407
|
+
actions=[],
|
|
408
|
+
diff=""
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
if injected_headers:
|
|
412
|
+
header_str = "\n".join(injected_headers) + "\n\n"
|
|
413
|
+
healed_code = header_str + healed_code
|
|
414
|
+
|
|
415
|
+
# Generate diff
|
|
416
|
+
orig_lines = code.splitlines(keepends=True)
|
|
417
|
+
healed_lines = healed_code.splitlines(keepends=True)
|
|
418
|
+
diff_lines = list(difflib.unified_diff(
|
|
419
|
+
orig_lines, healed_lines, fromfile="candidate.py (ai_generated)", tofile="healed.py (ast_corrected)"
|
|
420
|
+
))
|
|
421
|
+
diff_str = "".join(diff_lines)
|
|
422
|
+
|
|
423
|
+
return HealingReport(
|
|
424
|
+
success=True,
|
|
425
|
+
original_code=code,
|
|
426
|
+
healed_code=healed_code,
|
|
427
|
+
total_fixes=len(transformer.actions),
|
|
428
|
+
actions=transformer.actions,
|
|
429
|
+
diff=diff_str
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
@classmethod
|
|
433
|
+
def heal_file(
|
|
434
|
+
cls,
|
|
435
|
+
file_path: str,
|
|
436
|
+
workspace_dir: str = ".",
|
|
437
|
+
apply_write: bool = False,
|
|
438
|
+
precomputed_symbols: Optional[Tuple[Set[str], Set[str], Set[str]]] = None
|
|
439
|
+
) -> HealingReport:
|
|
440
|
+
"""Reads file, applies healing, optionally overwrites if apply_write is True."""
|
|
441
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
442
|
+
code = f.read()
|
|
443
|
+
|
|
444
|
+
report = cls.heal_code(code, workspace_dir=workspace_dir, precomputed_symbols=precomputed_symbols)
|
|
445
|
+
if apply_write and report.total_fixes > 0:
|
|
446
|
+
with open(file_path, "w", encoding="utf-8") as f:
|
|
447
|
+
f.write(report.healed_code)
|
|
448
|
+
|
|
449
|
+
return report
|
|
450
|
+
|
|
451
|
+
@classmethod
|
|
452
|
+
def render_cli(cls, rep: HealingReport, target_hint: str = ""):
|
|
453
|
+
print("\n🔧 \033[1mT-ZERO SELF-HEALING AST AUTO-CORRECTOR\033[0m")
|
|
454
|
+
print("=" * 70)
|
|
455
|
+
if target_hint:
|
|
456
|
+
print(f"🎯 Target File: {target_hint}")
|
|
457
|
+
print(f"📊 Auto-Repaired Hallucinations: \033[1m{rep.total_fixes}\033[0m")
|
|
458
|
+
|
|
459
|
+
if rep.actions:
|
|
460
|
+
print("\n📋 Detected & Repaired Symbols:")
|
|
461
|
+
for a in rep.actions:
|
|
462
|
+
conf_pct = int(a.confidence * 100)
|
|
463
|
+
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}%)")
|
|
464
|
+
|
|
465
|
+
if rep.diff:
|
|
466
|
+
print("\n🔍 AST Unified Diff:")
|
|
467
|
+
for line in rep.diff.splitlines()[:20]:
|
|
468
|
+
if line.startswith("+"):
|
|
469
|
+
print(f"\033[32m{line}\033[0m")
|
|
470
|
+
elif line.startswith("-"):
|
|
471
|
+
print(f"\033[31m{line}\033[0m")
|
|
472
|
+
else:
|
|
473
|
+
print(line)
|
|
474
|
+
else:
|
|
475
|
+
print("\033[32m✅ Flawless Code: 0 hallucinated symbols detected! AST matches workspace.\033[0m")
|
|
476
|
+
print("=" * 70)
|
|
477
|
+
|
|
478
|
+
@classmethod
|
|
479
|
+
def heal_workspace(
|
|
480
|
+
cls,
|
|
481
|
+
target_dir: str = ".",
|
|
482
|
+
workspace_dir: Optional[str] = None,
|
|
483
|
+
apply_write: bool = False,
|
|
484
|
+
exclude_dirs: Optional[Set[str]] = None
|
|
485
|
+
) -> Dict[str, Any]:
|
|
486
|
+
"""Recursively scans and self-heals all Python source files across target_dir."""
|
|
487
|
+
if workspace_dir is None:
|
|
488
|
+
workspace_dir = target_dir
|
|
489
|
+
if exclude_dirs is None:
|
|
490
|
+
exclude_dirs = {
|
|
491
|
+
".git", ".venv", "venv", "node_modules", "build", "dist",
|
|
492
|
+
"__pycache__", ".pytest_cache", ".tzero", "tzero-showcase"
|
|
493
|
+
}
|
|
494
|
+
scanned_files = 0
|
|
495
|
+
healed_reports: List[Tuple[str, HealingReport]] = []
|
|
496
|
+
total_fixes = 0
|
|
497
|
+
precomputed_symbols = cls.collect_workspace_symbols(workspace_dir)
|
|
498
|
+
|
|
499
|
+
for root, dirs, files in os.walk(target_dir):
|
|
500
|
+
dirs[:] = [d for d in dirs if d not in exclude_dirs and not d.startswith(".")]
|
|
501
|
+
for f in files:
|
|
502
|
+
if f in IGNORED_WORKSPACE_FILES or f.startswith("."):
|
|
503
|
+
continue
|
|
504
|
+
if f.endswith(".py"):
|
|
505
|
+
scanned_files += 1
|
|
506
|
+
full_path = os.path.join(root, f)
|
|
507
|
+
try:
|
|
508
|
+
rep = cls.heal_file(
|
|
509
|
+
full_path,
|
|
510
|
+
workspace_dir=workspace_dir,
|
|
511
|
+
apply_write=apply_write,
|
|
512
|
+
precomputed_symbols=precomputed_symbols
|
|
513
|
+
)
|
|
514
|
+
if rep.total_fixes > 0:
|
|
515
|
+
healed_reports.append((full_path, rep))
|
|
516
|
+
total_fixes += rep.total_fixes
|
|
517
|
+
except Exception:
|
|
518
|
+
pass
|
|
519
|
+
|
|
520
|
+
return {
|
|
521
|
+
"success": True,
|
|
522
|
+
"workspace_dir": workspace_dir,
|
|
523
|
+
"total_files_scanned": scanned_files,
|
|
524
|
+
"healed_files_count": len(healed_reports),
|
|
525
|
+
"total_fixes": total_fixes,
|
|
526
|
+
"reports": healed_reports,
|
|
527
|
+
"written_to_disk": apply_write
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
@classmethod
|
|
531
|
+
def render_workspace_cli(cls, summary: Dict[str, Any], target_hint: str = ""):
|
|
532
|
+
print("\n🔧 \033[1mT-ZERO WORKSPACE-WIDE OMNI-SUPERVISOR\033[0m")
|
|
533
|
+
print("=" * 70)
|
|
534
|
+
target = target_hint or summary.get("workspace_dir", ".")
|
|
535
|
+
print(f"📁 Workspace Root: \033[1m{target}\033[0m")
|
|
536
|
+
print(f"📂 Total Python Files Scanned: {summary['total_files_scanned']}")
|
|
537
|
+
print(f"✨ Repaired Files: \033[1m{summary['healed_files_count']}\033[0m")
|
|
538
|
+
print(f"📊 Total Repaired Hallucinations: \033[1m{summary['total_fixes']}\033[0m")
|
|
539
|
+
if summary.get("written_to_disk"):
|
|
540
|
+
print("💾 In-place disk write: \033[32mENABLED (Atomic Saved)\033[0m")
|
|
541
|
+
else:
|
|
542
|
+
print("🔍 Mode: \033[33mDRY-RUN (No files modified)\033[0m")
|
|
543
|
+
|
|
544
|
+
reports = summary.get("reports", [])
|
|
545
|
+
if reports:
|
|
546
|
+
print("\n📋 Repaired Files Summary:")
|
|
547
|
+
for path, rep in reports[:15]:
|
|
548
|
+
rel_path = os.path.relpath(path, target) if os.path.isabs(path) else path
|
|
549
|
+
print(f" • \033[1m{rel_path}\033[0m: {rep.total_fixes} fix(es)")
|
|
550
|
+
for a in rep.actions[:3]:
|
|
551
|
+
print(f" [{a.symbol_type}] \033[31m{a.original_symbol}\033[0m ➔ \033[32m{a.healed_symbol}\033[0m")
|
|
552
|
+
if len(reports) > 15:
|
|
553
|
+
print(f" ... and {len(reports) - 15} more files repaired.")
|
|
554
|
+
else:
|
|
555
|
+
print("\n\033[32m✅ Workspace Flawless: 0 hallucinated symbols detected across all files!\033[0m")
|
|
556
|
+
print("=" * 70)
|
|
557
|
+
|