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,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_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
+