tzero-mcp 11.0.0 → 11.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,288 +1,288 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero AST Type Hint Modernizer & PEP 585 / PEP 604 Transformer.
3
-
4
- Performs static AST transforms to modernize Python type annotations:
5
- - PEP 585 Generics: converts typing.List[T] -> list[T], typing.Dict[K, V] -> dict[K, V], typing.Set[T] -> set[T].
6
- - PEP 604 Unions: converts typing.Optional[T] -> T | None, typing.Union[A, B] -> A | B.
7
- - Dataclass field mutable defaults: converts 'field: list = []' -> 'field: list = field(default_factory=list)'.
8
- - PEP 654 Exception Groups validation and modernization.
9
-
10
- Author: Toprak Ahmet Aydogmus (Siber Akademi)
11
- Version: 10.4.0
12
- """
13
-
14
- import ast
15
- import difflib
16
- import os
17
- import re
18
- import sys
19
- import time
20
- from dataclasses import dataclass
21
- from pathlib import Path
22
- from typing import Any, Dict, List, Optional, Set, Tuple
23
-
24
- from .models import (
25
- DiagnosticCategory,
26
- DiagnosticIssue,
27
- HealAction,
28
- SeverityLevel,
29
- )
30
-
31
-
32
- class ASTTypeModernizer:
33
- """AST visitor and transformer for upgrading type hints to modern Python standards."""
34
-
35
- PEP_585_MAP = {
36
- "List": "list",
37
- "Dict": "dict",
38
- "Set": "set",
39
- "Tuple": "tuple",
40
- "FrozenSet": "frozenset",
41
- "Type": "type",
42
- }
43
-
44
- @classmethod
45
- def scan_legacy_typing_generics(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
46
- """Detect legacy typing module collections (typing.List, typing.Dict) eligible for PEP 585."""
47
- issues: List[DiagnosticIssue] = []
48
- if sys.version_info < (3, 9):
49
- return issues # PEP 585 requires Python 3.9+
50
-
51
- lines = content.splitlines()
52
- for idx, line in enumerate(lines, start=1):
53
- stripped = line.strip()
54
- if stripped.startswith("#"):
55
- continue
56
-
57
- for old_typ, new_typ in cls.PEP_585_MAP.items():
58
- pattern = rf"\b(typing\.)?{old_typ}\["
59
- if re.search(pattern, line):
60
- issues.append(DiagnosticIssue(
61
- category=DiagnosticCategory.TYPE_HINTS.value,
62
- severity=SeverityLevel.INFO.value,
63
- file_path=file_path,
64
- line=idx,
65
- column=0,
66
- error_code="TZ-TYPE-PEP585",
67
- message=f"Legacy typing generic '{old_typ}[...]' can be modernized to native '{new_typ}[...]'",
68
- suggested_fix=f"Replace '{old_typ}[...]' with native '{new_typ}[...]' (PEP 585)",
69
- auto_fixable=True,
70
- metadata={"action": "modernize_pep585", "old": old_typ, "new": new_typ, "lineno": idx, "path": file_path}
71
- ))
72
- break
73
-
74
- return issues
75
-
76
- @classmethod
77
- def scan_legacy_optional_and_union(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
78
- """Detect Optional[T] and Union[A, B] eligible for PEP 604 pipe syntax (A | B)."""
79
- issues: List[DiagnosticIssue] = []
80
- if sys.version_info < (3, 10):
81
- return issues # PEP 604 requires Python 3.10+
82
-
83
- lines = content.splitlines()
84
- for idx, line in enumerate(lines, start=1):
85
- stripped = line.strip()
86
- if stripped.startswith("#"):
87
- continue
88
-
89
- # Optional[T] -> T | None
90
- match_opt = re.search(r"\b(typing\.)?Optional\[([A-Za-z0-9_\.]+)\]", line)
91
- if match_opt:
92
- inner_t = match_opt.group(2)
93
- issues.append(DiagnosticIssue(
94
- category=DiagnosticCategory.TYPE_HINTS.value,
95
- severity=SeverityLevel.INFO.value,
96
- file_path=file_path,
97
- line=idx,
98
- column=match_opt.start(),
99
- error_code="TZ-TYPE-PEP604-OPTIONAL",
100
- message=f"Legacy 'Optional[{inner_t}]' can be modernized to '{inner_t} | None'",
101
- suggested_fix=f"Replace with modern pipe syntax: '{inner_t} | None' (PEP 604)",
102
- auto_fixable=True,
103
- metadata={"action": "modernize_optional", "inner": inner_t, "lineno": idx, "path": file_path}
104
- ))
105
-
106
- return issues
107
-
108
- @classmethod
109
- def scan_dataclass_mutable_fields(cls, file_path: str, tree: ast.AST) -> List[DiagnosticIssue]:
110
- """Detect mutable defaults directly assigned to fields in @dataclass definitions."""
111
- issues: List[DiagnosticIssue] = []
112
-
113
- for node in ast.walk(tree):
114
- if isinstance(node, ast.ClassDef):
115
- # Check if decorated with @dataclass
116
- is_dc = any(
117
- (isinstance(d, ast.Name) and d.id == "dataclass") or
118
- (isinstance(d, ast.Call) and isinstance(d.func, ast.Name) and d.func.id == "dataclass")
119
- for d in node.decorator_list
120
- )
121
- if not is_dc:
122
- continue
123
-
124
- for stmt in node.body:
125
- if isinstance(stmt, ast.AnnAssign) and stmt.value:
126
- if isinstance(stmt.value, ast.List):
127
- issues.append(DiagnosticIssue(
128
- category=DiagnosticCategory.SMELLS.value,
129
- severity=SeverityLevel.CRITICAL.value,
130
- file_path=file_path,
131
- line=stmt.lineno,
132
- column=stmt.col_offset,
133
- error_code="TZ-TYPE-DC-MUTABLE-LIST",
134
- message=f"Mutable list default directly assigned to dataclass field '{ast.unparse(stmt.target)}'",
135
- suggested_fix="Use 'field(default_factory=list)' instead of mutable default",
136
- auto_fixable=True,
137
- metadata={"action": "heal_dc_mutable_field", "field_type": "list", "lineno": stmt.lineno, "path": file_path}
138
- ))
139
- elif isinstance(stmt.value, ast.Dict):
140
- issues.append(DiagnosticIssue(
141
- category=DiagnosticCategory.SMELLS.value,
142
- severity=SeverityLevel.CRITICAL.value,
143
- file_path=file_path,
144
- line=stmt.lineno,
145
- column=stmt.col_offset,
146
- error_code="TZ-TYPE-DC-MUTABLE-DICT",
147
- message=f"Mutable dict default directly assigned to dataclass field '{ast.unparse(stmt.target)}'",
148
- suggested_fix="Use 'field(default_factory=dict)' instead of mutable default",
149
- auto_fixable=True,
150
- metadata={"action": "heal_dc_mutable_field", "field_type": "dict", "lineno": stmt.lineno, "path": file_path}
151
- ))
152
-
153
- return issues
154
-
155
- @classmethod
156
- def modernize_code(cls, content: str, filename: str = "snippet.py") -> Any:
157
- """In-memory type modernization helper."""
158
- @dataclass
159
- class StringHealResult:
160
- original_content: str
161
- repaired_content: str
162
- changed: bool
163
- issues: List[DiagnosticIssue]
164
-
165
- import tempfile
166
- suffix = Path(filename).suffix or ".py"
167
- with tempfile.NamedTemporaryFile("w", suffix=suffix, encoding="utf-8", delete=False) as tf:
168
- tf.write(content)
169
- temp_path = tf.name
170
-
171
- try:
172
- issues = cls.diagnose_file(temp_path)
173
- cls.execute_type_heals(issues, dry_run=False)
174
- with open(temp_path, "r", encoding="utf-8", errors="replace") as tf:
175
- repaired = tf.read()
176
- return StringHealResult(
177
- original_content=content,
178
- repaired_content=repaired,
179
- changed=(repaired != content),
180
- issues=issues,
181
- )
182
- finally:
183
- if os.path.exists(temp_path):
184
- try:
185
- os.remove(temp_path)
186
- except Exception:
187
- pass
188
-
189
- @classmethod
190
- def diagnose_file(cls, file_path: str) -> List[DiagnosticIssue]:
191
- """Scan file for all type modernization opportunities and dataclass flaws."""
192
- issues: List[DiagnosticIssue] = []
193
- path = Path(file_path)
194
- if not path.is_file() or path.suffix != ".py":
195
- return issues
196
-
197
- try:
198
- with open(path, "r", encoding="utf-8", errors="replace") as f:
199
- content = f.read()
200
- except Exception:
201
- return issues
202
-
203
- issues.extend(cls.scan_legacy_typing_generics(file_path, content))
204
- issues.extend(cls.scan_legacy_optional_and_union(file_path, content))
205
-
206
- try:
207
- tree = ast.parse(content, filename=file_path)
208
- issues.extend(cls.scan_dataclass_mutable_fields(file_path, tree))
209
- except Exception:
210
- pass
211
-
212
- return issues
213
-
214
- @classmethod
215
- def execute_type_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
216
- """Execute surgical regex/AST transforms for PEP 585/604 and dataclass fields."""
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
- t0 = time.time()
227
- p = Path(file_p)
228
- if not p.is_file():
229
- continue
230
-
231
- try:
232
- with open(p, "r", encoding="utf-8", errors="replace") as f:
233
- lines = f.readlines()
234
-
235
- if not (0 < lineno <= len(lines)):
236
- continue
237
-
238
- orig_line = lines[lineno - 1]
239
- mod_line = orig_line
240
-
241
- # 1. PEP 585 modernizer
242
- if action_type == "modernize_pep585":
243
- old_t = issue.metadata.get("old")
244
- new_t = issue.metadata.get("new")
245
- if old_t and new_t:
246
- mod_line = re.sub(rf"\b(typing\.)?{old_t}\[", f"{new_t}[", orig_line)
247
-
248
- # 2. PEP 604 Optional modernizer
249
- elif action_type == "modernize_optional":
250
- inner_t = issue.metadata.get("inner")
251
- if inner_t:
252
- mod_line = re.sub(rf"\b(typing\.)?Optional\[{re.escape(inner_t)}\]", f"{inner_t} | None", orig_line)
253
-
254
- # 3. Dataclass mutable field healer
255
- elif action_type == "heal_dc_mutable_field":
256
- f_type = issue.metadata.get("field_type")
257
- factory_name = "list" if f_type == "list" else "dict"
258
- mod_line = re.sub(r"=\s*\[\s*\]", f"= field(default_factory={factory_name})", orig_line)
259
- mod_line = re.sub(r"=\s*\{\s*\}", f"= field(default_factory={factory_name})", mod_line)
260
-
261
- if mod_line != orig_line:
262
- diff = "".join(difflib.unified_diff(
263
- [orig_line], [mod_line], fromfile="before", tofile="after"
264
- ))
265
- lines[lineno - 1] = mod_line
266
- if not dry_run:
267
- with open(p, "w", encoding="utf-8", newline="\n") as f:
268
- f.writelines(lines)
269
- actions.append(HealAction(
270
- category=DiagnosticCategory.TYPE_HINTS.value,
271
- action_type=action_type,
272
- file_path=file_p,
273
- description=f"Modernized type hint on line {lineno} of {p.name}",
274
- success=True,
275
- diff=diff,
276
- duration_ms=round((time.time() - t0) * 1000, 2)
277
- ))
278
- except Exception as e:
279
- actions.append(HealAction(
280
- category=DiagnosticCategory.TYPE_HINTS.value,
281
- action_type=action_type,
282
- file_path=file_p,
283
- description=f"Failed modernizing type hint: {e}",
284
- success=False,
285
- duration_ms=round((time.time() - t0) * 1000, 2)
286
- ))
287
-
288
- return actions
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero AST Type Hint Modernizer & PEP 585 / PEP 604 Transformer.
3
+
4
+ Performs static AST transforms to modernize Python type annotations:
5
+ - PEP 585 Generics: converts typing.List[T] -> list[T], typing.Dict[K, V] -> dict[K, V], typing.Set[T] -> set[T].
6
+ - PEP 604 Unions: converts typing.Optional[T] -> T | None, typing.Union[A, B] -> A | B.
7
+ - Dataclass field mutable defaults: converts 'field: list = []' -> 'field: list = field(default_factory=list)'.
8
+ - PEP 654 Exception Groups validation and modernization.
9
+
10
+ Author: Toprak Ahmet Aydogmus (Siber Akademi)
11
+ Version: 10.4.0
12
+ """
13
+
14
+ import ast
15
+ import difflib
16
+ import os
17
+ import re
18
+ import sys
19
+ import time
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import Any, Dict, List, Optional, Set, Tuple
23
+
24
+ from .models import (
25
+ DiagnosticCategory,
26
+ DiagnosticIssue,
27
+ HealAction,
28
+ SeverityLevel,
29
+ )
30
+
31
+
32
+ class ASTTypeModernizer:
33
+ """AST visitor and transformer for upgrading type hints to modern Python standards."""
34
+
35
+ PEP_585_MAP = {
36
+ "List": "list",
37
+ "Dict": "dict",
38
+ "Set": "set",
39
+ "Tuple": "tuple",
40
+ "FrozenSet": "frozenset",
41
+ "Type": "type",
42
+ }
43
+
44
+ @classmethod
45
+ def scan_legacy_typing_generics(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
46
+ """Detect legacy typing module collections (typing.List, typing.Dict) eligible for PEP 585."""
47
+ issues: List[DiagnosticIssue] = []
48
+ if sys.version_info < (3, 9):
49
+ return issues # PEP 585 requires Python 3.9+
50
+
51
+ lines = content.splitlines()
52
+ for idx, line in enumerate(lines, start=1):
53
+ stripped = line.strip()
54
+ if stripped.startswith("#"):
55
+ continue
56
+
57
+ for old_typ, new_typ in cls.PEP_585_MAP.items():
58
+ pattern = rf"\b(typing\.)?{old_typ}\["
59
+ if re.search(pattern, line):
60
+ issues.append(DiagnosticIssue(
61
+ category=DiagnosticCategory.TYPE_HINTS.value,
62
+ severity=SeverityLevel.INFO.value,
63
+ file_path=file_path,
64
+ line=idx,
65
+ column=0,
66
+ error_code="TZ-TYPE-PEP585",
67
+ message=f"Legacy typing generic '{old_typ}[...]' can be modernized to native '{new_typ}[...]'",
68
+ suggested_fix=f"Replace '{old_typ}[...]' with native '{new_typ}[...]' (PEP 585)",
69
+ auto_fixable=True,
70
+ metadata={"action": "modernize_pep585", "old": old_typ, "new": new_typ, "lineno": idx, "path": file_path}
71
+ ))
72
+ break
73
+
74
+ return issues
75
+
76
+ @classmethod
77
+ def scan_legacy_optional_and_union(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
78
+ """Detect Optional[T] and Union[A, B] eligible for PEP 604 pipe syntax (A | B)."""
79
+ issues: List[DiagnosticIssue] = []
80
+ if sys.version_info < (3, 10):
81
+ return issues # PEP 604 requires Python 3.10+
82
+
83
+ lines = content.splitlines()
84
+ for idx, line in enumerate(lines, start=1):
85
+ stripped = line.strip()
86
+ if stripped.startswith("#"):
87
+ continue
88
+
89
+ # Optional[T] -> T | None
90
+ match_opt = re.search(r"\b(typing\.)?Optional\[([A-Za-z0-9_\.]+)\]", line)
91
+ if match_opt:
92
+ inner_t = match_opt.group(2)
93
+ issues.append(DiagnosticIssue(
94
+ category=DiagnosticCategory.TYPE_HINTS.value,
95
+ severity=SeverityLevel.INFO.value,
96
+ file_path=file_path,
97
+ line=idx,
98
+ column=match_opt.start(),
99
+ error_code="TZ-TYPE-PEP604-OPTIONAL",
100
+ message=f"Legacy 'Optional[{inner_t}]' can be modernized to '{inner_t} | None'",
101
+ suggested_fix=f"Replace with modern pipe syntax: '{inner_t} | None' (PEP 604)",
102
+ auto_fixable=True,
103
+ metadata={"action": "modernize_optional", "inner": inner_t, "lineno": idx, "path": file_path}
104
+ ))
105
+
106
+ return issues
107
+
108
+ @classmethod
109
+ def scan_dataclass_mutable_fields(cls, file_path: str, tree: ast.AST) -> List[DiagnosticIssue]:
110
+ """Detect mutable defaults directly assigned to fields in @dataclass definitions."""
111
+ issues: List[DiagnosticIssue] = []
112
+
113
+ for node in ast.walk(tree):
114
+ if isinstance(node, ast.ClassDef):
115
+ # Check if decorated with @dataclass
116
+ is_dc = any(
117
+ (isinstance(d, ast.Name) and d.id == "dataclass") or
118
+ (isinstance(d, ast.Call) and isinstance(d.func, ast.Name) and d.func.id == "dataclass")
119
+ for d in node.decorator_list
120
+ )
121
+ if not is_dc:
122
+ continue
123
+
124
+ for stmt in node.body:
125
+ if isinstance(stmt, ast.AnnAssign) and stmt.value:
126
+ if isinstance(stmt.value, ast.List):
127
+ issues.append(DiagnosticIssue(
128
+ category=DiagnosticCategory.SMELLS.value,
129
+ severity=SeverityLevel.CRITICAL.value,
130
+ file_path=file_path,
131
+ line=stmt.lineno,
132
+ column=stmt.col_offset,
133
+ error_code="TZ-TYPE-DC-MUTABLE-LIST",
134
+ message=f"Mutable list default directly assigned to dataclass field '{ast.unparse(stmt.target)}'",
135
+ suggested_fix="Use 'field(default_factory=list)' instead of mutable default",
136
+ auto_fixable=True,
137
+ metadata={"action": "heal_dc_mutable_field", "field_type": "list", "lineno": stmt.lineno, "path": file_path}
138
+ ))
139
+ elif isinstance(stmt.value, ast.Dict):
140
+ issues.append(DiagnosticIssue(
141
+ category=DiagnosticCategory.SMELLS.value,
142
+ severity=SeverityLevel.CRITICAL.value,
143
+ file_path=file_path,
144
+ line=stmt.lineno,
145
+ column=stmt.col_offset,
146
+ error_code="TZ-TYPE-DC-MUTABLE-DICT",
147
+ message=f"Mutable dict default directly assigned to dataclass field '{ast.unparse(stmt.target)}'",
148
+ suggested_fix="Use 'field(default_factory=dict)' instead of mutable default",
149
+ auto_fixable=True,
150
+ metadata={"action": "heal_dc_mutable_field", "field_type": "dict", "lineno": stmt.lineno, "path": file_path}
151
+ ))
152
+
153
+ return issues
154
+
155
+ @classmethod
156
+ def modernize_code(cls, content: str, filename: str = "snippet.py") -> Any:
157
+ """In-memory type modernization helper."""
158
+ @dataclass
159
+ class StringHealResult:
160
+ original_content: str
161
+ repaired_content: str
162
+ changed: bool
163
+ issues: List[DiagnosticIssue]
164
+
165
+ import tempfile
166
+ suffix = Path(filename).suffix or ".py"
167
+ with tempfile.NamedTemporaryFile("w", suffix=suffix, encoding="utf-8", delete=False) as tf:
168
+ tf.write(content)
169
+ temp_path = tf.name
170
+
171
+ try:
172
+ issues = cls.diagnose_file(temp_path)
173
+ cls.execute_type_heals(issues, dry_run=False)
174
+ with open(temp_path, "r", encoding="utf-8", errors="replace") as tf:
175
+ repaired = tf.read()
176
+ return StringHealResult(
177
+ original_content=content,
178
+ repaired_content=repaired,
179
+ changed=(repaired != content),
180
+ issues=issues,
181
+ )
182
+ finally:
183
+ if os.path.exists(temp_path):
184
+ try:
185
+ os.remove(temp_path)
186
+ except Exception:
187
+ pass
188
+
189
+ @classmethod
190
+ def diagnose_file(cls, file_path: str) -> List[DiagnosticIssue]:
191
+ """Scan file for all type modernization opportunities and dataclass flaws."""
192
+ issues: List[DiagnosticIssue] = []
193
+ path = Path(file_path)
194
+ if not path.is_file() or path.suffix != ".py":
195
+ return issues
196
+
197
+ try:
198
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
199
+ content = f.read()
200
+ except Exception:
201
+ return issues
202
+
203
+ issues.extend(cls.scan_legacy_typing_generics(file_path, content))
204
+ issues.extend(cls.scan_legacy_optional_and_union(file_path, content))
205
+
206
+ try:
207
+ tree = ast.parse(content, filename=file_path)
208
+ issues.extend(cls.scan_dataclass_mutable_fields(file_path, tree))
209
+ except Exception:
210
+ pass
211
+
212
+ return issues
213
+
214
+ @classmethod
215
+ def execute_type_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
216
+ """Execute surgical regex/AST transforms for PEP 585/604 and dataclass fields."""
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
+ t0 = time.time()
227
+ p = Path(file_p)
228
+ if not p.is_file():
229
+ continue
230
+
231
+ try:
232
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
233
+ lines = f.readlines()
234
+
235
+ if not (0 < lineno <= len(lines)):
236
+ continue
237
+
238
+ orig_line = lines[lineno - 1]
239
+ mod_line = orig_line
240
+
241
+ # 1. PEP 585 modernizer
242
+ if action_type == "modernize_pep585":
243
+ old_t = issue.metadata.get("old")
244
+ new_t = issue.metadata.get("new")
245
+ if old_t and new_t:
246
+ mod_line = re.sub(rf"\b(typing\.)?{old_t}\[", f"{new_t}[", orig_line)
247
+
248
+ # 2. PEP 604 Optional modernizer
249
+ elif action_type == "modernize_optional":
250
+ inner_t = issue.metadata.get("inner")
251
+ if inner_t:
252
+ mod_line = re.sub(rf"\b(typing\.)?Optional\[{re.escape(inner_t)}\]", f"{inner_t} | None", orig_line)
253
+
254
+ # 3. Dataclass mutable field healer
255
+ elif action_type == "heal_dc_mutable_field":
256
+ f_type = issue.metadata.get("field_type")
257
+ factory_name = "list" if f_type == "list" else "dict"
258
+ mod_line = re.sub(r"=\s*\[\s*\]", f"= field(default_factory={factory_name})", orig_line)
259
+ mod_line = re.sub(r"=\s*\{\s*\}", f"= field(default_factory={factory_name})", mod_line)
260
+
261
+ if mod_line != orig_line:
262
+ diff = "".join(difflib.unified_diff(
263
+ [orig_line], [mod_line], fromfile="before", tofile="after"
264
+ ))
265
+ lines[lineno - 1] = mod_line
266
+ if not dry_run:
267
+ with open(p, "w", encoding="utf-8", newline="\n") as f:
268
+ f.writelines(lines)
269
+ actions.append(HealAction(
270
+ category=DiagnosticCategory.TYPE_HINTS.value,
271
+ action_type=action_type,
272
+ file_path=file_p,
273
+ description=f"Modernized type hint on line {lineno} of {p.name}",
274
+ success=True,
275
+ diff=diff,
276
+ duration_ms=round((time.time() - t0) * 1000, 2)
277
+ ))
278
+ except Exception as e:
279
+ actions.append(HealAction(
280
+ category=DiagnosticCategory.TYPE_HINTS.value,
281
+ action_type=action_type,
282
+ file_path=file_p,
283
+ description=f"Failed modernizing type hint: {e}",
284
+ success=False,
285
+ duration_ms=round((time.time() - t0) * 1000, 2)
286
+ ))
287
+
288
+ return actions