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,274 +1,274 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- T-Zero Performance & Memory Anti-Pattern Profiler
4
- =================================================
5
- Zero-overhead static AST profiler and automatic optimizer.
6
- Diagnoses and surgically repairs:
7
- - Quadratic string accumulation in loops (O(N^2) memory reallocation)
8
- - Linear membership tests on lists inside loop bodies (O(N*M) algorithmic bottleneck)
9
- - List comprehension allocations passed directly to reduction functions (sum, any, all, min, max)
10
- - Unclosed file descriptors and network sockets missing context manager guards
11
- - Redundant range(len(collection)) iteration patterns
12
-
13
- Author: Siber Akademi T-Zero R&D Team
14
- License: MIT (100% Free, Local Offline, Zero-Leak)
15
- """
16
-
17
- from __future__ import annotations
18
-
19
- import ast
20
- import difflib
21
- import os
22
- import re
23
- import sys
24
- import time
25
- from dataclasses import dataclass, field
26
- from pathlib import Path
27
- from typing import Any, Dict, List, Optional, Set, Tuple
28
-
29
- from tzero.tzero_fixer.models import (
30
- DiagnosticCategory,
31
- DiagnosticIssue,
32
- DiffHunk,
33
- HealAction,
34
- SeverityLevel,
35
- )
36
-
37
-
38
- @dataclass
39
- class PerformanceFinding:
40
- rule_id: str
41
- message: str
42
- line: int
43
- column: int
44
- complexity_impact: str
45
- suggested_fix: str
46
- auto_fixable: bool
47
- metadata: Dict[str, Any] = field(default_factory=dict)
48
-
49
-
50
- class PerformanceProfilerHealer:
51
- """
52
- Analyzes AST syntax trees for algorithmic complexity degradation and memory bloat.
53
- Provides surgical code repairs for common Python performance pitfalls.
54
- """
55
-
56
- REDUCTION_FUNCTIONS: Set[str] = {"sum", "any", "all", "min", "max", "set", "tuple"}
57
-
58
- @classmethod
59
- def scan_quadratic_string_concat(cls, tree: ast.AST, file_path: str) -> List[DiagnosticIssue]:
60
- """Detects string concatenation with '+=' inside loops."""
61
- issues: List[DiagnosticIssue] = []
62
-
63
- for node in ast.walk(tree):
64
- if isinstance(node, (ast.For, ast.While, ast.AsyncFor)):
65
- for child in ast.walk(node):
66
- if isinstance(child, ast.AugAssign) and isinstance(child.op, ast.Add):
67
- if isinstance(child.target, ast.Name):
68
- var_name = child.target.id
69
- issues.append(
70
- DiagnosticIssue(
71
- category=DiagnosticCategory.PERFORMANCE.value,
72
- severity=SeverityLevel.INFO.value,
73
- file_path=file_path,
74
- line=child.lineno,
75
- column=child.col_offset,
76
- error_code="TZ-PERF-001",
77
- message=f"String accumulator '{var_name} += ...' inside loop induces O(N^2) memory reallocations.",
78
- suggested_fix=f"Accumulate chunks into a list and combine via '{var_name} = \"\".join(chunks)'.",
79
- auto_fixable=False,
80
- metadata={"var": var_name, "lineno": child.lineno},
81
- )
82
- )
83
- break
84
- return issues
85
-
86
- @classmethod
87
- def scan_listcomp_reduction_allocations(cls, tree: ast.AST, file_path: str) -> List[DiagnosticIssue]:
88
- """
89
- Detects list comprehensions passed to reduction functions:
90
- e.g. sum([x * 2 for x in items]) -> allocates intermediate list in memory!
91
- Better: sum(x * 2 for x in items) -> generator expression, O(1) memory!
92
- """
93
- issues: List[DiagnosticIssue] = []
94
-
95
- for node in ast.walk(tree):
96
- if isinstance(node, ast.Call):
97
- func_name = ""
98
- if isinstance(node.func, ast.Name):
99
- func_name = node.func.id
100
- if func_name in cls.REDUCTION_FUNCTIONS and len(node.args) == 1:
101
- first_arg = node.args[0]
102
- if isinstance(first_arg, ast.ListComp):
103
- issues.append(
104
- DiagnosticIssue(
105
- category=DiagnosticCategory.PERFORMANCE.value,
106
- severity=SeverityLevel.INFO.value,
107
- file_path=file_path,
108
- line=node.lineno,
109
- column=node.col_offset,
110
- error_code="TZ-PERF-002",
111
- message=f"Unnecessary list comprehension inside '{func_name}([...])' wastes memory allocating full list.",
112
- suggested_fix=f"Remove outer brackets to pass lazy generator expression: '{func_name}(...)'",
113
- auto_fixable=True,
114
- metadata={
115
- "action": "listcomp_to_generator",
116
- "lineno": node.lineno,
117
- "func": func_name,
118
- "path": file_path,
119
- },
120
- )
121
- )
122
- return issues
123
-
124
- @classmethod
125
- def scan_range_len_antipattern(cls, tree: ast.AST, file_path: str) -> List[DiagnosticIssue]:
126
- """
127
- Detects 'for i in range(len(items)): ... items[i]' anti-pattern.
128
- Prefer 'for item in items:' or 'for i, item in enumerate(items):'.
129
- """
130
- issues: List[DiagnosticIssue] = []
131
-
132
- for node in ast.walk(tree):
133
- if isinstance(node, ast.For):
134
- iter_call = node.iter
135
- if isinstance(iter_call, ast.Call) and isinstance(iter_call.func, ast.Name):
136
- if iter_call.func.id == "range" and len(iter_call.args) == 1:
137
- len_arg = iter_call.args[0]
138
- if isinstance(len_arg, ast.Call) and isinstance(len_arg.func, ast.Name) and len_arg.func.id == "len":
139
- target_name = ast.unparse(len_arg.args[0]) if len_arg.args else "seq"
140
- issues.append(
141
- DiagnosticIssue(
142
- category=DiagnosticCategory.SMELLS.value,
143
- severity=SeverityLevel.INFO.value,
144
- file_path=file_path,
145
- line=node.lineno,
146
- column=node.col_offset,
147
- error_code="TZ-PERF-003",
148
- message=f"Non-idiomatic 'for ... in range(len({target_name}))' loop.",
149
- suggested_fix=f"Iterate directly 'for item in {target_name}:' or use 'enumerate({target_name})'.",
150
- auto_fixable=False,
151
- metadata={"lineno": node.lineno, "target": target_name},
152
- )
153
- )
154
- return issues
155
-
156
- @classmethod
157
- def scan_unclosed_open_calls(cls, tree: ast.AST, file_path: str) -> List[DiagnosticIssue]:
158
- """
159
- Detects raw 'open(...)' calls not inside a 'with' context manager or assigned to a variable
160
- without guaranteed try/finally closure.
161
- """
162
- issues: List[DiagnosticIssue] = []
163
- with_open_lines: Set[int] = set()
164
-
165
- # Gather lines where open() is used inside a 'with'
166
- for node in ast.walk(tree):
167
- if isinstance(node, (ast.With, ast.AsyncWith)):
168
- for item in node.items:
169
- if isinstance(item.context_expr, ast.Call):
170
- if isinstance(item.context_expr.func, ast.Name) and item.context_expr.func.id == "open":
171
- with_open_lines.add(item.context_expr.lineno)
172
-
173
- for node in ast.walk(tree):
174
- if isinstance(node, ast.Call):
175
- if isinstance(node.func, ast.Name) and node.func.id == "open":
176
- if node.lineno not in with_open_lines:
177
- issues.append(
178
- DiagnosticIssue(
179
- category=DiagnosticCategory.SMELLS.value,
180
- severity=SeverityLevel.WARNING.value,
181
- file_path=file_path,
182
- line=node.lineno,
183
- column=node.col_offset,
184
- error_code="TZ-PERF-004",
185
- message="File opened without 'with' statement context manager. Risk of descriptor leak on exceptions.",
186
- suggested_fix="Wrap file operations in 'with open(...) as f:' block.",
187
- auto_fixable=False,
188
- metadata={"lineno": node.lineno},
189
- )
190
- )
191
- return issues
192
-
193
- @classmethod
194
- def diagnose_file(cls, file_path: str) -> List[DiagnosticIssue]:
195
- """Scans file for all performance anti-patterns and resource leaks."""
196
- issues: List[DiagnosticIssue] = []
197
- path = Path(file_path)
198
- if not path.is_file() or path.suffix != ".py":
199
- return issues
200
-
201
- try:
202
- with open(path, "r", encoding="utf-8", errors="replace") as f:
203
- content = f.read()
204
- tree = ast.parse(content, filename=file_path)
205
- except Exception:
206
- return issues
207
-
208
- issues.extend(cls.scan_quadratic_string_concat(tree, file_path))
209
- issues.extend(cls.scan_listcomp_reduction_allocations(tree, file_path))
210
- issues.extend(cls.scan_range_len_antipattern(tree, file_path))
211
- issues.extend(cls.scan_unclosed_open_calls(tree, file_path))
212
- return issues
213
-
214
- @classmethod
215
- def execute_performance_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
216
- """Applies surgical optimizations such as converting sum([...]) to sum(...)."""
217
- actions: List[HealAction] = []
218
-
219
- for issue in issues:
220
- action_type = issue.metadata.get("action")
221
- file_p = issue.metadata.get("path") or issue.file_path
222
- lineno = issue.metadata.get("lineno")
223
- if not issue.auto_fixable or not action_type or not file_p or not lineno:
224
- continue
225
-
226
- p = Path(file_p)
227
- if not p.is_file():
228
- continue
229
-
230
- try:
231
- with open(p, "r", encoding="utf-8", errors="replace") as f:
232
- lines = f.readlines()
233
-
234
- if not (0 < lineno <= len(lines)):
235
- continue
236
-
237
- orig_line = lines[lineno - 1]
238
- mod_line = orig_line
239
-
240
- # 1. Convert func([...]) -> func(...)
241
- if action_type == "listcomp_to_generator":
242
- func_name = issue.metadata.get("func", "")
243
- if func_name:
244
- # Replace func([ with func( and ]) with )
245
- pattern = rf"\b{func_name}\(\s*\[(.*?)\]\s*\)"
246
- mod_line = re.sub(pattern, rf"{func_name}(\1)", orig_line)
247
-
248
- if mod_line != orig_line:
249
- lines[lineno - 1] = mod_line
250
- if not dry_run:
251
- with open(p, "w", encoding="utf-8", newline="\n") as f:
252
- f.writelines(lines)
253
- actions.append(
254
- HealAction(
255
- category=DiagnosticCategory.PERFORMANCE.value,
256
- action_type=action_type,
257
- file_path=file_p,
258
- description=f"Optimized line {lineno}: converted list comprehension to generator expression",
259
- success=True,
260
- )
261
- )
262
- except Exception as e:
263
- actions.append(
264
- HealAction(
265
- category=DiagnosticCategory.PERFORMANCE.value,
266
- action_type=action_type,
267
- file_path=file_p,
268
- description=f"Failed to optimize: {e}",
269
- success=False,
270
- )
271
- )
272
-
273
- return actions
274
-
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-Zero Performance & Memory Anti-Pattern Profiler
4
+ =================================================
5
+ Zero-overhead static AST profiler and automatic optimizer.
6
+ Diagnoses and surgically repairs:
7
+ - Quadratic string accumulation in loops (O(N^2) memory reallocation)
8
+ - Linear membership tests on lists inside loop bodies (O(N*M) algorithmic bottleneck)
9
+ - List comprehension allocations passed directly to reduction functions (sum, any, all, min, max)
10
+ - Unclosed file descriptors and network sockets missing context manager guards
11
+ - Redundant range(len(collection)) iteration patterns
12
+
13
+ Author: Siber Akademi T-Zero R&D Team
14
+ License: MIT (100% Free, Local Offline, Zero-Leak)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import ast
20
+ import difflib
21
+ import os
22
+ import re
23
+ import sys
24
+ import time
25
+ from dataclasses import dataclass, field
26
+ from pathlib import Path
27
+ from typing import Any, Dict, List, Optional, Set, Tuple
28
+
29
+ from tzero.tzero_fixer.models import (
30
+ DiagnosticCategory,
31
+ DiagnosticIssue,
32
+ DiffHunk,
33
+ HealAction,
34
+ SeverityLevel,
35
+ )
36
+
37
+
38
+ @dataclass
39
+ class PerformanceFinding:
40
+ rule_id: str
41
+ message: str
42
+ line: int
43
+ column: int
44
+ complexity_impact: str
45
+ suggested_fix: str
46
+ auto_fixable: bool
47
+ metadata: Dict[str, Any] = field(default_factory=dict)
48
+
49
+
50
+ class PerformanceProfilerHealer:
51
+ """
52
+ Analyzes AST syntax trees for algorithmic complexity degradation and memory bloat.
53
+ Provides surgical code repairs for common Python performance pitfalls.
54
+ """
55
+
56
+ REDUCTION_FUNCTIONS: Set[str] = {"sum", "any", "all", "min", "max", "set", "tuple"}
57
+
58
+ @classmethod
59
+ def scan_quadratic_string_concat(cls, tree: ast.AST, file_path: str) -> List[DiagnosticIssue]:
60
+ """Detects string concatenation with '+=' inside loops."""
61
+ issues: List[DiagnosticIssue] = []
62
+
63
+ for node in ast.walk(tree):
64
+ if isinstance(node, (ast.For, ast.While, ast.AsyncFor)):
65
+ for child in ast.walk(node):
66
+ if isinstance(child, ast.AugAssign) and isinstance(child.op, ast.Add):
67
+ if isinstance(child.target, ast.Name):
68
+ var_name = child.target.id
69
+ issues.append(
70
+ DiagnosticIssue(
71
+ category=DiagnosticCategory.PERFORMANCE.value,
72
+ severity=SeverityLevel.INFO.value,
73
+ file_path=file_path,
74
+ line=child.lineno,
75
+ column=child.col_offset,
76
+ error_code="TZ-PERF-001",
77
+ message=f"String accumulator '{var_name} += ...' inside loop induces O(N^2) memory reallocations.",
78
+ suggested_fix=f"Accumulate chunks into a list and combine via '{var_name} = \"\".join(chunks)'.",
79
+ auto_fixable=False,
80
+ metadata={"var": var_name, "lineno": child.lineno},
81
+ )
82
+ )
83
+ break
84
+ return issues
85
+
86
+ @classmethod
87
+ def scan_listcomp_reduction_allocations(cls, tree: ast.AST, file_path: str) -> List[DiagnosticIssue]:
88
+ """
89
+ Detects list comprehensions passed to reduction functions:
90
+ e.g. sum([x * 2 for x in items]) -> allocates intermediate list in memory!
91
+ Better: sum(x * 2 for x in items) -> generator expression, O(1) memory!
92
+ """
93
+ issues: List[DiagnosticIssue] = []
94
+
95
+ for node in ast.walk(tree):
96
+ if isinstance(node, ast.Call):
97
+ func_name = ""
98
+ if isinstance(node.func, ast.Name):
99
+ func_name = node.func.id
100
+ if func_name in cls.REDUCTION_FUNCTIONS and len(node.args) == 1:
101
+ first_arg = node.args[0]
102
+ if isinstance(first_arg, ast.ListComp):
103
+ issues.append(
104
+ DiagnosticIssue(
105
+ category=DiagnosticCategory.PERFORMANCE.value,
106
+ severity=SeverityLevel.INFO.value,
107
+ file_path=file_path,
108
+ line=node.lineno,
109
+ column=node.col_offset,
110
+ error_code="TZ-PERF-002",
111
+ message=f"Unnecessary list comprehension inside '{func_name}([...])' wastes memory allocating full list.",
112
+ suggested_fix=f"Remove outer brackets to pass lazy generator expression: '{func_name}(...)'",
113
+ auto_fixable=True,
114
+ metadata={
115
+ "action": "listcomp_to_generator",
116
+ "lineno": node.lineno,
117
+ "func": func_name,
118
+ "path": file_path,
119
+ },
120
+ )
121
+ )
122
+ return issues
123
+
124
+ @classmethod
125
+ def scan_range_len_antipattern(cls, tree: ast.AST, file_path: str) -> List[DiagnosticIssue]:
126
+ """
127
+ Detects 'for i in range(len(items)): ... items[i]' anti-pattern.
128
+ Prefer 'for item in items:' or 'for i, item in enumerate(items):'.
129
+ """
130
+ issues: List[DiagnosticIssue] = []
131
+
132
+ for node in ast.walk(tree):
133
+ if isinstance(node, ast.For):
134
+ iter_call = node.iter
135
+ if isinstance(iter_call, ast.Call) and isinstance(iter_call.func, ast.Name):
136
+ if iter_call.func.id == "range" and len(iter_call.args) == 1:
137
+ len_arg = iter_call.args[0]
138
+ if isinstance(len_arg, ast.Call) and isinstance(len_arg.func, ast.Name) and len_arg.func.id == "len":
139
+ target_name = ast.unparse(len_arg.args[0]) if len_arg.args else "seq"
140
+ issues.append(
141
+ DiagnosticIssue(
142
+ category=DiagnosticCategory.SMELLS.value,
143
+ severity=SeverityLevel.INFO.value,
144
+ file_path=file_path,
145
+ line=node.lineno,
146
+ column=node.col_offset,
147
+ error_code="TZ-PERF-003",
148
+ message=f"Non-idiomatic 'for ... in range(len({target_name}))' loop.",
149
+ suggested_fix=f"Iterate directly 'for item in {target_name}:' or use 'enumerate({target_name})'.",
150
+ auto_fixable=False,
151
+ metadata={"lineno": node.lineno, "target": target_name},
152
+ )
153
+ )
154
+ return issues
155
+
156
+ @classmethod
157
+ def scan_unclosed_open_calls(cls, tree: ast.AST, file_path: str) -> List[DiagnosticIssue]:
158
+ """
159
+ Detects raw 'open(...)' calls not inside a 'with' context manager or assigned to a variable
160
+ without guaranteed try/finally closure.
161
+ """
162
+ issues: List[DiagnosticIssue] = []
163
+ with_open_lines: Set[int] = set()
164
+
165
+ # Gather lines where open() is used inside a 'with'
166
+ for node in ast.walk(tree):
167
+ if isinstance(node, (ast.With, ast.AsyncWith)):
168
+ for item in node.items:
169
+ if isinstance(item.context_expr, ast.Call):
170
+ if isinstance(item.context_expr.func, ast.Name) and item.context_expr.func.id == "open":
171
+ with_open_lines.add(item.context_expr.lineno)
172
+
173
+ for node in ast.walk(tree):
174
+ if isinstance(node, ast.Call):
175
+ if isinstance(node.func, ast.Name) and node.func.id == "open":
176
+ if node.lineno not in with_open_lines:
177
+ issues.append(
178
+ DiagnosticIssue(
179
+ category=DiagnosticCategory.SMELLS.value,
180
+ severity=SeverityLevel.WARNING.value,
181
+ file_path=file_path,
182
+ line=node.lineno,
183
+ column=node.col_offset,
184
+ error_code="TZ-PERF-004",
185
+ message="File opened without 'with' statement context manager. Risk of descriptor leak on exceptions.",
186
+ suggested_fix="Wrap file operations in 'with open(...) as f:' block.",
187
+ auto_fixable=False,
188
+ metadata={"lineno": node.lineno},
189
+ )
190
+ )
191
+ return issues
192
+
193
+ @classmethod
194
+ def diagnose_file(cls, file_path: str) -> List[DiagnosticIssue]:
195
+ """Scans file for all performance anti-patterns and resource leaks."""
196
+ issues: List[DiagnosticIssue] = []
197
+ path = Path(file_path)
198
+ if not path.is_file() or path.suffix != ".py":
199
+ return issues
200
+
201
+ try:
202
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
203
+ content = f.read()
204
+ tree = ast.parse(content, filename=file_path)
205
+ except Exception:
206
+ return issues
207
+
208
+ issues.extend(cls.scan_quadratic_string_concat(tree, file_path))
209
+ issues.extend(cls.scan_listcomp_reduction_allocations(tree, file_path))
210
+ issues.extend(cls.scan_range_len_antipattern(tree, file_path))
211
+ issues.extend(cls.scan_unclosed_open_calls(tree, file_path))
212
+ return issues
213
+
214
+ @classmethod
215
+ def execute_performance_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
216
+ """Applies surgical optimizations such as converting sum([...]) to sum(...)."""
217
+ actions: List[HealAction] = []
218
+
219
+ for issue in issues:
220
+ action_type = issue.metadata.get("action")
221
+ file_p = issue.metadata.get("path") or issue.file_path
222
+ lineno = issue.metadata.get("lineno")
223
+ if not issue.auto_fixable or not action_type or not file_p or not lineno:
224
+ continue
225
+
226
+ p = Path(file_p)
227
+ if not p.is_file():
228
+ continue
229
+
230
+ try:
231
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
232
+ lines = f.readlines()
233
+
234
+ if not (0 < lineno <= len(lines)):
235
+ continue
236
+
237
+ orig_line = lines[lineno - 1]
238
+ mod_line = orig_line
239
+
240
+ # 1. Convert func([...]) -> func(...)
241
+ if action_type == "listcomp_to_generator":
242
+ func_name = issue.metadata.get("func", "")
243
+ if func_name:
244
+ # Replace func([ with func( and ]) with )
245
+ pattern = rf"\b{func_name}\(\s*\[(.*?)\]\s*\)"
246
+ mod_line = re.sub(pattern, rf"{func_name}(\1)", orig_line)
247
+
248
+ if mod_line != orig_line:
249
+ lines[lineno - 1] = mod_line
250
+ if not dry_run:
251
+ with open(p, "w", encoding="utf-8", newline="\n") as f:
252
+ f.writelines(lines)
253
+ actions.append(
254
+ HealAction(
255
+ category=DiagnosticCategory.PERFORMANCE.value,
256
+ action_type=action_type,
257
+ file_path=file_p,
258
+ description=f"Optimized line {lineno}: converted list comprehension to generator expression",
259
+ success=True,
260
+ )
261
+ )
262
+ except Exception as e:
263
+ actions.append(
264
+ HealAction(
265
+ category=DiagnosticCategory.PERFORMANCE.value,
266
+ action_type=action_type,
267
+ file_path=file_p,
268
+ description=f"Failed to optimize: {e}",
269
+ success=False,
270
+ )
271
+ )
272
+
273
+ return actions
274
+