tzero-mcp 11.0.0 → 11.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +56 -56
  2. package/CONTRIBUTING.md +71 -71
  3. package/LICENSE +21 -21
  4. package/README.md +64 -64
  5. package/bin/tzero-mcp.js +62 -62
  6. package/bin/tzero.js +61 -61
  7. package/index.d.ts +25 -25
  8. package/index.js +15 -15
  9. package/package.json +89 -88
  10. package/src/addmcp.py +1203 -1197
  11. package/src/app.py +1810 -1810
  12. package/src/main.py +60 -60
  13. package/src/pc_fixer_mcp.py +25 -25
  14. package/src/tzero/__init__.py +54 -54
  15. package/src/tzero/__main__.py +6 -6
  16. package/src/tzero/siber_akademi_icon.py +77 -77
  17. package/src/tzero/tzero_arch_test.py +463 -463
  18. package/src/tzero/tzero_benchmark.py +475 -475
  19. package/src/tzero/tzero_blackboard.py +257 -257
  20. package/src/tzero/tzero_bridge.py +546 -546
  21. package/src/tzero/tzero_budget.py +195 -195
  22. package/src/tzero/tzero_card.py +431 -0
  23. package/src/tzero/tzero_ci.py +153 -153
  24. package/src/tzero/tzero_commit.py +192 -192
  25. package/src/tzero/tzero_contracts.py +1093 -1093
  26. package/src/tzero/tzero_cost.py +166 -166
  27. package/src/tzero/tzero_dashboard.py +1960 -1960
  28. package/src/tzero/tzero_debt.py +461 -461
  29. package/src/tzero/tzero_deps.py +462 -462
  30. package/src/tzero/tzero_drift.py +208 -208
  31. package/src/tzero/tzero_explain.py +306 -306
  32. package/src/tzero/tzero_features.py +3024 -3024
  33. package/src/tzero/tzero_federation.py +299 -299
  34. package/src/tzero/tzero_fix.py +557 -228
  35. package/src/tzero/tzero_fixer/__init__.py +63 -63
  36. package/src/tzero/tzero_fixer/amalgamation.py +334 -334
  37. package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
  38. package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
  39. package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
  40. package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
  41. package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
  42. package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
  43. package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
  44. package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
  45. package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
  46. package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
  47. package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
  48. package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
  49. package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
  50. package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
  51. package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
  52. package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
  53. package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
  54. package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
  55. package/src/tzero/tzero_fixer/mcp_server.py +489 -489
  56. package/src/tzero/tzero_fixer/models.py +385 -385
  57. package/src/tzero/tzero_fixer/orchestrator.py +375 -375
  58. package/src/tzero/tzero_fixer/os_doctor.py +502 -502
  59. package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
  60. package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
  61. package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
  62. package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
  63. package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
  64. package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
  65. package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
  66. package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
  67. package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
  68. package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
  69. package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
  70. package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
  71. package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
  72. package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
  73. package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
  74. package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
  75. package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
  76. package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
  77. package/src/tzero/tzero_golden.py +319 -319
  78. package/src/tzero/tzero_graph_hud.html +338 -338
  79. package/src/tzero/tzero_graph_rag.py +263 -263
  80. package/src/tzero/tzero_growth.py +415 -0
  81. package/src/tzero/tzero_guard.py +251 -243
  82. package/src/tzero/tzero_hooks.py +565 -565
  83. package/src/tzero/tzero_infra.py +274 -274
  84. package/src/tzero/tzero_jarvis/__init__.py +134 -124
  85. package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
  86. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  87. package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
  88. package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
  89. package/src/tzero/tzero_jarvis/latent_press.py +137 -137
  90. package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
  91. package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
  92. package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
  93. package/src/tzero/tzero_jarvis/self_healing.py +308 -308
  94. package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
  95. package/src/tzero/tzero_jarvis/swarm.py +261 -261
  96. package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
  97. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
  98. package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
  99. package/src/tzero/tzero_lsp.py +634 -634
  100. package/src/tzero/tzero_mcp.py +5314 -5237
  101. package/src/tzero/tzero_mutation.py +358 -358
  102. package/src/tzero/tzero_neural_cortex.py +1425 -1425
  103. package/src/tzero/tzero_packer.py +577 -577
  104. package/src/tzero/tzero_patch.py +624 -624
  105. package/src/tzero/tzero_pc_fixer.py +12699 -12699
  106. package/src/tzero/tzero_pipe.py +95 -95
  107. package/src/tzero/tzero_polyglot.py +799 -799
  108. package/src/tzero/tzero_proxy.py +127 -127
  109. package/src/tzero/tzero_reachability.py +272 -272
  110. package/src/tzero/tzero_replay.py +141 -141
  111. package/src/tzero/tzero_rust_bridge.py +198 -198
  112. package/src/tzero/tzero_scip.py +368 -368
  113. package/src/tzero/tzero_security.py +573 -573
  114. package/src/tzero/tzero_semantic_merge.py +189 -189
  115. package/src/tzero/tzero_snapshot.py +471 -471
  116. package/src/tzero/tzero_stubs.py +313 -313
  117. package/src/tzero/tzero_subagent_engine.py +459 -459
  118. package/src/tzero/tzero_superdesign.py +774 -774
  119. package/src/tzero/tzero_sync.py +241 -241
  120. package/src/tzero/tzero_task_benchmark.py +506 -458
  121. package/src/tzero/tzero_tui.py +313 -313
  122. package/src/tzero/tzero_turbo.py +264 -264
  123. package/src/tzero/tzero_v3.py +9997 -9900
  124. package/src/tzero.py +6 -6
  125. package/src/tzero_mcp.py +25 -0
  126. package/test/package.test.js +55 -55
@@ -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 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 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
+