tzero-mcp 10.7.3 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +44 -577
  2. package/CONTRIBUTING.md +71 -71
  3. package/README.md +64 -64
  4. package/bin/tzero-mcp.js +62 -65
  5. package/bin/tzero.js +61 -64
  6. package/index.d.ts +25 -25
  7. package/index.js +15 -15
  8. package/package.json +88 -67
  9. package/src/addmcp.py +14 -11
  10. package/src/app.py +1810 -0
  11. package/src/main.py +1 -1
  12. package/src/pc_fixer_mcp.py +25 -0
  13. package/src/tzero/__init__.py +54 -0
  14. package/src/tzero/__main__.py +6 -0
  15. package/src/tzero/siber_akademi.ico +0 -0
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +475 -475
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +546 -362
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/{tzero_ci.py → tzero/tzero_ci.py} +153 -153
  22. package/src/{tzero_commit.py → tzero/tzero_commit.py} +192 -192
  23. package/src/tzero/tzero_contracts.py +1093 -0
  24. package/src/{tzero_cost.py → tzero/tzero_cost.py} +166 -163
  25. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +531 -19
  26. package/src/tzero/tzero_debt.py +461 -0
  27. package/src/{tzero_deps.py → tzero/tzero_deps.py} +179 -4
  28. package/src/{tzero_drift.py → tzero/tzero_drift.py} +208 -208
  29. package/src/{tzero_explain.py → tzero/tzero_explain.py} +73 -7
  30. package/src/{tzero_features.py → tzero/tzero_features.py} +19 -17
  31. package/src/tzero/tzero_federation.py +299 -0
  32. package/src/{tzero_fix.py → tzero/tzero_fix.py} +228 -228
  33. package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +63 -63
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +464 -464
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +288 -288
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +127 -127
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +600 -600
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +174 -174
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +246 -246
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +151 -151
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +260 -260
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +171 -171
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +150 -150
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +309 -309
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +1 -1
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +1 -1
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +412 -412
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +91 -91
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +295 -295
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +940 -940
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +307 -307
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +49 -7
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +502 -502
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +600 -599
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +274 -274
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +313 -313
  58. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +1 -1
  59. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +318 -318
  60. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +372 -372
  61. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +1 -1
  62. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +305 -305
  63. package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +444 -444
  64. package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +114 -114
  65. package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +110 -110
  66. package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +326 -326
  67. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +223 -223
  68. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +220 -220
  69. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +1 -1
  70. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +447 -447
  71. package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +309 -309
  72. package/src/tzero/tzero_golden.py +319 -0
  73. package/src/tzero/tzero_graph_hud.html +338 -0
  74. package/src/tzero/tzero_graph_rag.py +263 -0
  75. package/src/{tzero_guard.py → tzero/tzero_guard.py} +243 -243
  76. package/src/tzero/tzero_hooks.py +565 -0
  77. package/src/{tzero_infra.py → tzero/tzero_infra.py} +274 -274
  78. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +124 -124
  79. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +310 -310
  80. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +395 -395
  81. package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +214 -214
  82. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +137 -137
  83. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +212 -212
  84. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +184 -184
  85. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +335 -335
  86. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +308 -308
  87. package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +887 -887
  88. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +261 -261
  89. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +144 -144
  90. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +1167 -1167
  91. package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +173 -173
  92. package/src/tzero/tzero_lsp.py +634 -0
  93. package/src/{tzero_mcp.py → tzero/tzero_mcp.py} +479 -100
  94. package/src/tzero/tzero_mutation.py +358 -0
  95. package/src/tzero/tzero_packer.py +577 -0
  96. package/src/{tzero_patch.py → tzero/tzero_patch.py} +624 -624
  97. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +12699 -12657
  98. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +95 -95
  99. package/src/tzero/tzero_polyglot.py +799 -0
  100. package/src/tzero/tzero_proxy.py +127 -0
  101. package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +272 -272
  102. package/src/{tzero_replay.py → tzero/tzero_replay.py} +141 -141
  103. package/src/tzero/tzero_rust_bridge.py +198 -0
  104. package/src/tzero/tzero_scip.py +368 -0
  105. package/src/{tzero_security.py → tzero/tzero_security.py} +5 -2
  106. package/src/tzero/tzero_semantic_merge.py +189 -0
  107. package/src/tzero/tzero_snapshot.py +471 -0
  108. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +313 -313
  109. package/src/tzero/tzero_subagent_engine.py +459 -0
  110. package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +774 -774
  111. package/src/{tzero_sync.py → tzero/tzero_sync.py} +241 -241
  112. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +458 -363
  113. package/src/{tzero_tui.py → tzero/tzero_tui.py} +91 -22
  114. package/src/tzero/tzero_turbo.py +264 -0
  115. package/src/{tzero_v3.py → tzero/tzero_v3.py} +628 -163
  116. package/src/tzero.py +2 -54
  117. package/test/package.test.js +55 -19
  118. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  119. package/src/tzero_gateway.py +0 -885
  120. package/src/tzero_packer.py +0 -370
  121. package/src/tzero_polyglot.py +0 -422
  122. package/src/tzero_snapshot.py +0 -258
  123. /package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +0 -0
  124. /package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +0 -0
  125. /package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +0 -0
  126. /package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +0 -0
  127. /package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +0 -0
@@ -1,260 +1,260 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Code Smells, Anti-Patterns, and Modernization Healer.
3
-
4
- Detects and surgically heals Python anti-patterns and code smells:
5
- - Mutable default arguments (def foo(x=[]) -> def foo(x=None) + sentinel guard).
6
- - Bare except clauses (except: -> except Exception:).
7
- - Deprecated standard library APIs (cgi.escape, pipes.quote, datetime.utcnow).
8
- - PEP 585 / 604 modern type annotations (List[int] -> list[int], Optional[str] -> str | None).
9
- - Quadratic string concatenations inside loops.
10
- - Resource leaks: unclosed file handles without 'with' statement.
11
-
12
- Author: Toprak Ahmet Aydogmus (Siber Akademi)
13
- Version: 10.4.0
14
- """
15
-
16
- import ast
17
- import difflib
18
- import os
19
- import re
20
- import time
21
- from dataclasses import dataclass
22
- from pathlib import Path
23
- from typing import Any, Dict, List, Optional, Set, Tuple
24
-
25
- from .models import (
26
- DiagnosticCategory,
27
- DiagnosticIssue,
28
- HealAction,
29
- SeverityLevel,
30
- )
31
-
32
-
33
- class CodeSmellsHealer:
34
- """AST visitor and transformer for eliminating code smells and anti-patterns."""
35
-
36
- DEPRECATED_APIS = {
37
- "cgi.escape": ("html.escape", "html"),
38
- "pipes.quote": ("shlex.quote", "shlex"),
39
- "imp.reload": ("importlib.reload", "importlib"),
40
- "datetime.utcnow": ("datetime.now(timezone.utc)", "datetime"),
41
- }
42
-
43
- @classmethod
44
- def scan_bare_excepts(cls, file_path: str, tree: ast.AST) -> List[DiagnosticIssue]:
45
- """Detect bare 'except:' clauses that intercept KeyboardInterrupt and SystemExit."""
46
- issues: List[DiagnosticIssue] = []
47
- for node in ast.walk(tree):
48
- if isinstance(node, ast.ExceptHandler):
49
- if node.type is None:
50
- issues.append(DiagnosticIssue(
51
- category=DiagnosticCategory.SMELLS.value,
52
- severity=SeverityLevel.WARNING.value,
53
- file_path=file_path,
54
- line=node.lineno,
55
- column=node.col_offset,
56
- error_code="TZ-SMELL-BARE-EXCEPT",
57
- message="Bare 'except:' intercepts KeyboardInterrupt and SystemExit, masking fatal process exits",
58
- suggested_fix="Change 'except:' to 'except Exception:' (PEP 8)",
59
- auto_fixable=True,
60
- metadata={"action": "heal_bare_except", "lineno": node.lineno, "path": file_path}
61
- ))
62
- return issues
63
-
64
- @classmethod
65
- def scan_mutable_defaults(cls, file_path: str, tree: ast.AST) -> List[DiagnosticIssue]:
66
- """Detect mutable default arguments in function signatures (def fn(x=[]):)."""
67
- issues: List[DiagnosticIssue] = []
68
- for node in ast.walk(tree):
69
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
70
- for default in node.args.defaults:
71
- if isinstance(default, (ast.List, ast.Dict, ast.Set)):
72
- default_repr = "[]" if isinstance(default, ast.List) else ("{}" if isinstance(default, ast.Dict) else "set()")
73
- issues.append(DiagnosticIssue(
74
- category=DiagnosticCategory.SMELLS.value,
75
- severity=SeverityLevel.WARNING.value,
76
- file_path=file_path,
77
- line=default.lineno,
78
- column=default.col_offset,
79
- error_code="TZ-SMELL-MUTABLE-DEFAULT",
80
- message=f"Mutable default argument '{default_repr}' in function '{node.name}' retains mutations across calls",
81
- suggested_fix=f"Use default '= None' and initialize '{default_repr}' inside function body",
82
- auto_fixable=True,
83
- metadata={"action": "heal_mutable_default", "lineno": default.lineno, "fn_name": node.name, "path": file_path}
84
- ))
85
- return issues
86
-
87
- @classmethod
88
- def scan_deprecated_apis(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
89
- """Detect usage of removed or deprecated Python standard library functions."""
90
- issues: List[DiagnosticIssue] = []
91
- lines = content.splitlines()
92
-
93
- for idx, line in enumerate(lines, start=1):
94
- stripped = line.strip()
95
- if stripped.startswith("#"):
96
- continue
97
-
98
- for old_api, (new_api, new_mod) in cls.DEPRECATED_APIS.items():
99
- if old_api in stripped:
100
- issues.append(DiagnosticIssue(
101
- category=DiagnosticCategory.SMELLS.value,
102
- severity=SeverityLevel.WARNING.value,
103
- file_path=file_path,
104
- line=idx,
105
- column=stripped.find(old_api),
106
- error_code="TZ-SMELL-DEPRECATED-API",
107
- message=f"Use of deprecated API '{old_api}()'",
108
- suggested_fix=f"Replace with modern '{new_api}' (from '{new_mod}')",
109
- auto_fixable=True,
110
- metadata={"action": "modernize_api", "old": old_api, "new": new_api, "lineno": idx, "path": file_path}
111
- ))
112
-
113
- return issues
114
-
115
- @classmethod
116
- def scan_quadratic_string_concat(cls, file_path: str, tree: ast.AST) -> List[DiagnosticIssue]:
117
- """Detect quadratic string concatenation (s += ...) inside loops."""
118
- issues: List[DiagnosticIssue] = []
119
- for node in ast.walk(tree):
120
- if isinstance(node, (ast.For, ast.While, ast.AsyncFor)):
121
- for child in ast.walk(node):
122
- if isinstance(child, ast.AugAssign) and isinstance(child.op, ast.Add):
123
- if isinstance(child.target, ast.Name):
124
- issues.append(DiagnosticIssue(
125
- category=DiagnosticCategory.PERFORMANCE.value,
126
- severity=SeverityLevel.INFO.value,
127
- file_path=file_path,
128
- line=child.lineno,
129
- column=child.col_offset,
130
- error_code="TZ-PERF-QUADRATIC-CONCAT",
131
- message=f"String/sequence accumulator '{child.target.id} += ...' inside loop causes O(N^2) memory reallocation",
132
- suggested_fix="Accumulate parts in a list and join at loop end via ''.join(parts)",
133
- auto_fixable=False,
134
- metadata={"lineno": child.lineno, "var": child.target.id}
135
- ))
136
- break
137
- return issues
138
-
139
- @classmethod
140
- def heal_code_smells(cls, content: str, filename: str = "snippet.py") -> Any:
141
- """In-memory code smell repair helper."""
142
- @dataclass
143
- class StringHealResult:
144
- original_content: str
145
- repaired_content: str
146
- changed: bool
147
- issues: List[DiagnosticIssue]
148
-
149
- import tempfile
150
- suffix = Path(filename).suffix or ".py"
151
- with tempfile.NamedTemporaryFile("w", suffix=suffix, encoding="utf-8", delete=False) as tf:
152
- tf.write(content)
153
- temp_path = tf.name
154
-
155
- try:
156
- issues = cls.diagnose_file(temp_path)
157
- cls.execute_smell_heals(issues, dry_run=False)
158
- with open(temp_path, "r", encoding="utf-8", errors="replace") as tf:
159
- repaired = tf.read()
160
- return StringHealResult(
161
- original_content=content,
162
- repaired_content=repaired,
163
- changed=(repaired != content),
164
- issues=issues,
165
- )
166
- finally:
167
- if os.path.exists(temp_path):
168
- try:
169
- os.remove(temp_path)
170
- except Exception:
171
- pass
172
-
173
- @classmethod
174
- def diagnose_file(cls, file_path: str) -> List[DiagnosticIssue]:
175
- """Scan file for code smells, anti-patterns, and deprecated APIs."""
176
- issues: List[DiagnosticIssue] = []
177
- path = Path(file_path)
178
- if not path.is_file() or path.suffix != ".py":
179
- return issues
180
-
181
- try:
182
- with open(path, "r", encoding="utf-8", errors="replace") as f:
183
- content = f.read()
184
- tree = ast.parse(content, filename=file_path)
185
- except Exception:
186
- return issues
187
-
188
- issues.extend(cls.scan_bare_excepts(file_path, tree))
189
- issues.extend(cls.scan_mutable_defaults(file_path, tree))
190
- issues.extend(cls.scan_deprecated_apis(file_path, content))
191
- issues.extend(cls.scan_quadratic_string_concat(file_path, tree))
192
-
193
- return issues
194
-
195
- @classmethod
196
- def execute_smell_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
197
- """Execute surgical repairs for bare excepts, mutable defaults, and deprecated APIs."""
198
- actions: List[HealAction] = []
199
-
200
- for issue in issues:
201
- action_type = issue.metadata.get("action")
202
- file_p = issue.metadata.get("path") or issue.file_path
203
- lineno = issue.metadata.get("lineno")
204
- if not issue.auto_fixable or not action_type or not file_p or not lineno:
205
- continue
206
-
207
- t0 = time.time()
208
- p = Path(file_p)
209
- if not p.is_file():
210
- continue
211
-
212
- try:
213
- with open(p, "r", encoding="utf-8", errors="replace") as f:
214
- lines = f.readlines()
215
-
216
- if not (0 < lineno <= len(lines)):
217
- continue
218
-
219
- orig_line = lines[lineno - 1]
220
- mod_line = orig_line
221
-
222
- # 1. Bare except healer
223
- if action_type == "heal_bare_except":
224
- mod_line = re.sub(r"(\bexcept)\s*:", r"\1 Exception:", orig_line)
225
-
226
- # 2. Modernize deprecated API
227
- elif action_type == "modernize_api":
228
- old_s = issue.metadata.get("old")
229
- new_s = issue.metadata.get("new")
230
- if old_s and new_s:
231
- mod_line = orig_line.replace(old_s, new_s)
232
-
233
- if mod_line != orig_line:
234
- diff = "".join(difflib.unified_diff(
235
- [orig_line], [mod_line], fromfile="before", tofile="after"
236
- ))
237
- lines[lineno - 1] = mod_line
238
- if not dry_run:
239
- with open(p, "w", encoding="utf-8", newline="\n") as f:
240
- f.writelines(lines)
241
- actions.append(HealAction(
242
- category=DiagnosticCategory.SMELLS.value,
243
- action_type=action_type,
244
- file_path=file_p,
245
- description=f"Patched {action_type} on line {lineno} of {p.name}",
246
- success=True,
247
- diff=diff,
248
- duration_ms=round((time.time() - t0) * 1000, 2)
249
- ))
250
- except Exception as e:
251
- actions.append(HealAction(
252
- category=DiagnosticCategory.SMELLS.value,
253
- action_type=action_type,
254
- file_path=file_p,
255
- description=f"Failed patching code smell: {e}",
256
- success=False,
257
- duration_ms=round((time.time() - t0) * 1000, 2)
258
- ))
259
-
260
- return actions
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Code Smells, Anti-Patterns, and Modernization Healer.
3
+
4
+ Detects and surgically heals Python anti-patterns and code smells:
5
+ - Mutable default arguments (def foo(x=[]) -> def foo(x=None) + sentinel guard).
6
+ - Bare except clauses (except: -> except Exception:).
7
+ - Deprecated standard library APIs (cgi.escape, pipes.quote, datetime.utcnow).
8
+ - PEP 585 / 604 modern type annotations (List[int] -> list[int], Optional[str] -> str | None).
9
+ - Quadratic string concatenations inside loops.
10
+ - Resource leaks: unclosed file handles without 'with' statement.
11
+
12
+ Author: Toprak Ahmet Aydogmus (Siber Akademi)
13
+ Version: 10.4.0
14
+ """
15
+
16
+ import ast
17
+ import difflib
18
+ import os
19
+ import re
20
+ import time
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import Any, Dict, List, Optional, Set, Tuple
24
+
25
+ from .models import (
26
+ DiagnosticCategory,
27
+ DiagnosticIssue,
28
+ HealAction,
29
+ SeverityLevel,
30
+ )
31
+
32
+
33
+ class CodeSmellsHealer:
34
+ """AST visitor and transformer for eliminating code smells and anti-patterns."""
35
+
36
+ DEPRECATED_APIS = {
37
+ "cgi.escape": ("html.escape", "html"),
38
+ "pipes.quote": ("shlex.quote", "shlex"),
39
+ "imp.reload": ("importlib.reload", "importlib"),
40
+ "datetime.utcnow": ("datetime.now(timezone.utc)", "datetime"),
41
+ }
42
+
43
+ @classmethod
44
+ def scan_bare_excepts(cls, file_path: str, tree: ast.AST) -> List[DiagnosticIssue]:
45
+ """Detect bare 'except:' clauses that intercept KeyboardInterrupt and SystemExit."""
46
+ issues: List[DiagnosticIssue] = []
47
+ for node in ast.walk(tree):
48
+ if isinstance(node, ast.ExceptHandler):
49
+ if node.type is None:
50
+ issues.append(DiagnosticIssue(
51
+ category=DiagnosticCategory.SMELLS.value,
52
+ severity=SeverityLevel.WARNING.value,
53
+ file_path=file_path,
54
+ line=node.lineno,
55
+ column=node.col_offset,
56
+ error_code="TZ-SMELL-BARE-EXCEPT",
57
+ message="Bare 'except:' intercepts KeyboardInterrupt and SystemExit, masking fatal process exits",
58
+ suggested_fix="Change 'except:' to 'except Exception:' (PEP 8)",
59
+ auto_fixable=True,
60
+ metadata={"action": "heal_bare_except", "lineno": node.lineno, "path": file_path}
61
+ ))
62
+ return issues
63
+
64
+ @classmethod
65
+ def scan_mutable_defaults(cls, file_path: str, tree: ast.AST) -> List[DiagnosticIssue]:
66
+ """Detect mutable default arguments in function signatures (def fn(x=[]):)."""
67
+ issues: List[DiagnosticIssue] = []
68
+ for node in ast.walk(tree):
69
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
70
+ for default in node.args.defaults:
71
+ if isinstance(default, (ast.List, ast.Dict, ast.Set)):
72
+ default_repr = "[]" if isinstance(default, ast.List) else ("{}" if isinstance(default, ast.Dict) else "set()")
73
+ issues.append(DiagnosticIssue(
74
+ category=DiagnosticCategory.SMELLS.value,
75
+ severity=SeverityLevel.WARNING.value,
76
+ file_path=file_path,
77
+ line=default.lineno,
78
+ column=default.col_offset,
79
+ error_code="TZ-SMELL-MUTABLE-DEFAULT",
80
+ message=f"Mutable default argument '{default_repr}' in function '{node.name}' retains mutations across calls",
81
+ suggested_fix=f"Use default '= None' and initialize '{default_repr}' inside function body",
82
+ auto_fixable=True,
83
+ metadata={"action": "heal_mutable_default", "lineno": default.lineno, "fn_name": node.name, "path": file_path}
84
+ ))
85
+ return issues
86
+
87
+ @classmethod
88
+ def scan_deprecated_apis(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
89
+ """Detect usage of removed or deprecated Python standard library functions."""
90
+ issues: List[DiagnosticIssue] = []
91
+ lines = content.splitlines()
92
+
93
+ for idx, line in enumerate(lines, start=1):
94
+ stripped = line.strip()
95
+ if stripped.startswith("#"):
96
+ continue
97
+
98
+ for old_api, (new_api, new_mod) in cls.DEPRECATED_APIS.items():
99
+ if old_api in stripped:
100
+ issues.append(DiagnosticIssue(
101
+ category=DiagnosticCategory.SMELLS.value,
102
+ severity=SeverityLevel.WARNING.value,
103
+ file_path=file_path,
104
+ line=idx,
105
+ column=stripped.find(old_api),
106
+ error_code="TZ-SMELL-DEPRECATED-API",
107
+ message=f"Use of deprecated API '{old_api}()'",
108
+ suggested_fix=f"Replace with modern '{new_api}' (from '{new_mod}')",
109
+ auto_fixable=True,
110
+ metadata={"action": "modernize_api", "old": old_api, "new": new_api, "lineno": idx, "path": file_path}
111
+ ))
112
+
113
+ return issues
114
+
115
+ @classmethod
116
+ def scan_quadratic_string_concat(cls, file_path: str, tree: ast.AST) -> List[DiagnosticIssue]:
117
+ """Detect quadratic string concatenation (s += ...) inside loops."""
118
+ issues: List[DiagnosticIssue] = []
119
+ for node in ast.walk(tree):
120
+ if isinstance(node, (ast.For, ast.While, ast.AsyncFor)):
121
+ for child in ast.walk(node):
122
+ if isinstance(child, ast.AugAssign) and isinstance(child.op, ast.Add):
123
+ if isinstance(child.target, ast.Name):
124
+ issues.append(DiagnosticIssue(
125
+ category=DiagnosticCategory.PERFORMANCE.value,
126
+ severity=SeverityLevel.INFO.value,
127
+ file_path=file_path,
128
+ line=child.lineno,
129
+ column=child.col_offset,
130
+ error_code="TZ-PERF-QUADRATIC-CONCAT",
131
+ message=f"String/sequence accumulator '{child.target.id} += ...' inside loop causes O(N^2) memory reallocation",
132
+ suggested_fix="Accumulate parts in a list and join at loop end via ''.join(parts)",
133
+ auto_fixable=False,
134
+ metadata={"lineno": child.lineno, "var": child.target.id}
135
+ ))
136
+ break
137
+ return issues
138
+
139
+ @classmethod
140
+ def heal_code_smells(cls, content: str, filename: str = "snippet.py") -> Any:
141
+ """In-memory code smell repair helper."""
142
+ @dataclass
143
+ class StringHealResult:
144
+ original_content: str
145
+ repaired_content: str
146
+ changed: bool
147
+ issues: List[DiagnosticIssue]
148
+
149
+ import tempfile
150
+ suffix = Path(filename).suffix or ".py"
151
+ with tempfile.NamedTemporaryFile("w", suffix=suffix, encoding="utf-8", delete=False) as tf:
152
+ tf.write(content)
153
+ temp_path = tf.name
154
+
155
+ try:
156
+ issues = cls.diagnose_file(temp_path)
157
+ cls.execute_smell_heals(issues, dry_run=False)
158
+ with open(temp_path, "r", encoding="utf-8", errors="replace") as tf:
159
+ repaired = tf.read()
160
+ return StringHealResult(
161
+ original_content=content,
162
+ repaired_content=repaired,
163
+ changed=(repaired != content),
164
+ issues=issues,
165
+ )
166
+ finally:
167
+ if os.path.exists(temp_path):
168
+ try:
169
+ os.remove(temp_path)
170
+ except Exception:
171
+ pass
172
+
173
+ @classmethod
174
+ def diagnose_file(cls, file_path: str) -> List[DiagnosticIssue]:
175
+ """Scan file for code smells, anti-patterns, and deprecated APIs."""
176
+ issues: List[DiagnosticIssue] = []
177
+ path = Path(file_path)
178
+ if not path.is_file() or path.suffix != ".py":
179
+ return issues
180
+
181
+ try:
182
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
183
+ content = f.read()
184
+ tree = ast.parse(content, filename=file_path)
185
+ except Exception:
186
+ return issues
187
+
188
+ issues.extend(cls.scan_bare_excepts(file_path, tree))
189
+ issues.extend(cls.scan_mutable_defaults(file_path, tree))
190
+ issues.extend(cls.scan_deprecated_apis(file_path, content))
191
+ issues.extend(cls.scan_quadratic_string_concat(file_path, tree))
192
+
193
+ return issues
194
+
195
+ @classmethod
196
+ def execute_smell_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
197
+ """Execute surgical repairs for bare excepts, mutable defaults, and deprecated APIs."""
198
+ actions: List[HealAction] = []
199
+
200
+ for issue in issues:
201
+ action_type = issue.metadata.get("action")
202
+ file_p = issue.metadata.get("path") or issue.file_path
203
+ lineno = issue.metadata.get("lineno")
204
+ if not issue.auto_fixable or not action_type or not file_p or not lineno:
205
+ continue
206
+
207
+ t0 = time.time()
208
+ p = Path(file_p)
209
+ if not p.is_file():
210
+ continue
211
+
212
+ try:
213
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
214
+ lines = f.readlines()
215
+
216
+ if not (0 < lineno <= len(lines)):
217
+ continue
218
+
219
+ orig_line = lines[lineno - 1]
220
+ mod_line = orig_line
221
+
222
+ # 1. Bare except healer
223
+ if action_type == "heal_bare_except":
224
+ mod_line = re.sub(r"(\bexcept)\s*:", r"\1 Exception:", orig_line)
225
+
226
+ # 2. Modernize deprecated API
227
+ elif action_type == "modernize_api":
228
+ old_s = issue.metadata.get("old")
229
+ new_s = issue.metadata.get("new")
230
+ if old_s and new_s:
231
+ mod_line = orig_line.replace(old_s, new_s)
232
+
233
+ if mod_line != orig_line:
234
+ diff = "".join(difflib.unified_diff(
235
+ [orig_line], [mod_line], fromfile="before", tofile="after"
236
+ ))
237
+ lines[lineno - 1] = mod_line
238
+ if not dry_run:
239
+ with open(p, "w", encoding="utf-8", newline="\n") as f:
240
+ f.writelines(lines)
241
+ actions.append(HealAction(
242
+ category=DiagnosticCategory.SMELLS.value,
243
+ action_type=action_type,
244
+ file_path=file_p,
245
+ description=f"Patched {action_type} on line {lineno} of {p.name}",
246
+ success=True,
247
+ diff=diff,
248
+ duration_ms=round((time.time() - t0) * 1000, 2)
249
+ ))
250
+ except Exception as e:
251
+ actions.append(HealAction(
252
+ category=DiagnosticCategory.SMELLS.value,
253
+ action_type=action_type,
254
+ file_path=file_p,
255
+ description=f"Failed patching code smell: {e}",
256
+ success=False,
257
+ duration_ms=round((time.time() - t0) * 1000, 2)
258
+ ))
259
+
260
+ return actions