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,309 +1,309 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Virtualenv, Python Runtime, and Dependency Drift Doctor.
3
-
4
- Performs forensic diagnosis and autonomous healing on:
5
- - Virtual environment structures (.venv, venv, env, poetry, conda, pipenv).
6
- - pyvenv.cfg integrity, broken base python home paths, and invalid symlinks.
7
- - Missing packages defined in requirements.txt / pyproject.toml.
8
- - Corrupted site-packages, dangling .dist-info / .egg-info directories.
9
- - Package version conflicts and Python minor version drift.
10
-
11
- Author: Toprak Ahmet Aydogmus (Siber Akademi)
12
- Version: 10.4.0
13
- """
14
-
15
- import importlib.metadata
16
- import os
17
- import re
18
- import sys
19
- import time
20
- from pathlib import Path
21
- from typing import Any, Dict, List, Optional, Set, Tuple
22
-
23
- from .models import (
24
- DiagnosticCategory,
25
- DiagnosticIssue,
26
- HealAction,
27
- SeverityLevel,
28
- SystemPlatform,
29
- )
30
-
31
-
32
- class VenvDoctor:
33
- """Specialized doctor for Python virtual environments and dependency topologies."""
34
-
35
- CANDIDATE_VENV_NAMES = [".venv", "venv", "env", ".env", "virtualenv"]
36
-
37
- @classmethod
38
- def detect_workspace_venvs(cls, workspace_dir: str = ".") -> List[Path]:
39
- """Locate all local virtualenv directories in workspace root."""
40
- root = Path(workspace_dir).resolve()
41
- found: List[Path] = []
42
- for name in cls.CANDIDATE_VENV_NAMES:
43
- cand = root / name
44
- if cand.is_dir() and (cand / "pyvenv.cfg").is_file():
45
- found.append(cand)
46
- return found
47
-
48
- @classmethod
49
- def parse_pyvenv_cfg(cls, cfg_path: Path) -> Dict[str, str]:
50
- """Parse key-value pairs from a pyvenv.cfg file."""
51
- res: Dict[str, str] = {}
52
- if not cfg_path.is_file():
53
- return res
54
- try:
55
- with open(cfg_path, "r", encoding="utf-8", errors="replace") as f:
56
- for line in f:
57
- line = line.strip()
58
- if line and not line.startswith("#") and "=" in line:
59
- k, v = line.split("=", 1)
60
- res[k.strip().lower()] = v.strip()
61
- except Exception:
62
- pass
63
- return res
64
-
65
- @classmethod
66
- def inspect_virtualenv(cls, venv_dir: Path) -> Tuple[bool, Optional[str], Dict[str, Any]]:
67
- """Validate virtualenv structure, pyvenv.cfg, and interpreter binary."""
68
- cfg_file = venv_dir / "pyvenv.cfg"
69
- if not cfg_file.is_file():
70
- return False, f"Missing 'pyvenv.cfg' in {venv_dir.name}", {}
71
-
72
- cfg_data = cls.parse_pyvenv_cfg(cfg_file)
73
- home_path = cfg_data.get("home")
74
-
75
- if not home_path:
76
- return False, "Missing 'home' directive in pyvenv.cfg", cfg_data
77
-
78
- if not os.path.isdir(home_path):
79
- return False, f"Base python home directory does not exist: '{home_path}'", cfg_data
80
-
81
- # Check binary presence
82
- is_windows = sys.platform.startswith("win")
83
- bin_dir = venv_dir / ("Scripts" if is_windows else "bin")
84
- py_binary = bin_dir / ("python.exe" if is_windows else "python")
85
-
86
- if not bin_dir.is_dir():
87
- return False, f"Missing '{bin_dir.name}' folder in virtualenv", cfg_data
88
-
89
- if not py_binary.is_file():
90
- return False, f"Missing python interpreter '{py_binary.name}' in {bin_dir.name}", cfg_data
91
-
92
- return True, None, cfg_data
93
-
94
- @classmethod
95
- def parse_requirements_file(cls, req_file: Path) -> List[Tuple[str, Optional[str]]]:
96
- """Extract package names and version specifiers from requirements.txt."""
97
- packages: List[Tuple[str, Optional[str]]] = []
98
- if not req_file.is_file():
99
- return packages
100
-
101
- try:
102
- with open(req_file, "r", encoding="utf-8", errors="replace") as f:
103
- for line in f:
104
- line = line.strip()
105
- if not line or line.startswith(("#", "-", "git+", "http")):
106
- continue
107
- # Match name and optional specifier
108
- match = re.match(r"^([A-Za-z0-9_\-\.]+)(.*)$", line)
109
- if match:
110
- name = match.group(1).replace("-", "_").lower()
111
- spec = match.group(2).strip() or None
112
- packages.append((name, spec))
113
- except Exception:
114
- pass
115
- return packages
116
-
117
- @classmethod
118
- def check_dependency_drift(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
119
- """Cross-reference requirements against currently installed packages."""
120
- issues: List[DiagnosticIssue] = []
121
- root = Path(workspace_dir).resolve()
122
-
123
- req_candidates = [root / "requirements.txt", root / "requirements-dev.txt"]
124
- for req_f in req_candidates:
125
- if not req_f.is_file():
126
- continue
127
-
128
- packages = cls.parse_requirements_file(req_f)
129
- for pkg_name, spec in packages:
130
- try:
131
- installed_ver = importlib.metadata.version(pkg_name)
132
- except importlib.metadata.PackageNotFoundError:
133
- # Also try dash version
134
- try:
135
- installed_ver = importlib.metadata.version(pkg_name.replace("_", "-"))
136
- except importlib.metadata.PackageNotFoundError:
137
- issues.append(DiagnosticIssue(
138
- category=DiagnosticCategory.ENVIRONMENT.value,
139
- severity=SeverityLevel.ERROR.value,
140
- file_path=str(req_f),
141
- line=None,
142
- column=None,
143
- error_code="TZ-ENV-PKG-MISSING",
144
- message=f"Declared dependency '{pkg_name}' ({spec or 'any'}) is not installed in the active environment",
145
- suggested_fix=f"Run 'pip install {pkg_name}{spec or ''}' to satisfy workspace requirements",
146
- auto_fixable=False,
147
- metadata={"package": pkg_name, "spec": spec}
148
- ))
149
-
150
- return issues
151
-
152
- @classmethod
153
- def check_corrupted_site_packages(cls, venv_dir: Path) -> List[DiagnosticIssue]:
154
- """Scan site-packages for empty or corrupted .dist-info / .egg-info remnants."""
155
- issues: List[DiagnosticIssue] = []
156
- is_windows = sys.platform.startswith("win")
157
- lib_dir = venv_dir / "Lib" / "site-packages" if is_windows else venv_dir / "lib"
158
-
159
- # On POSIX it might be lib/python3.X/site-packages
160
- if not is_windows and lib_dir.is_dir():
161
- py_dirs = list(lib_dir.glob("python3.*"))
162
- if py_dirs:
163
- lib_dir = py_dirs[0] / "site-packages"
164
-
165
- if not lib_dir.is_dir():
166
- return issues
167
-
168
- try:
169
- for item in lib_dir.iterdir():
170
- if item.is_dir() and item.name.endswith((".dist-info", ".egg-info")):
171
- # Check if empty or missing METADATA / PKG-INFO
172
- meta = item / "METADATA"
173
- pkg_info = item / "PKG-INFO"
174
- if not meta.is_file() and not pkg_info.is_file():
175
- issues.append(DiagnosticIssue(
176
- category=DiagnosticCategory.ENVIRONMENT.value,
177
- severity=SeverityLevel.WARNING.value,
178
- file_path=str(item),
179
- line=None,
180
- column=None,
181
- error_code="TZ-ENV-CORRUPT-DISTINFO",
182
- message=f"Corrupted distribution metadata folder: '{item.name}' (missing METADATA)",
183
- suggested_fix="Purge orphaned metadata folder and reinstall package",
184
- auto_fixable=True,
185
- metadata={"action": "purge_corrupt_distinfo", "path": str(item)}
186
- ))
187
- except Exception:
188
- pass
189
-
190
- return issues
191
-
192
- @classmethod
193
- def diagnose(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
194
- """Run complete virtualenv diagnostic suite."""
195
- issues: List[DiagnosticIssue] = []
196
- venvs = cls.detect_workspace_venvs(workspace_dir)
197
-
198
- if not venvs:
199
- # Check if active Python is a virtualenv
200
- is_venv = hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix)
201
- if not is_venv:
202
- issues.append(DiagnosticIssue(
203
- category=DiagnosticCategory.ENVIRONMENT.value,
204
- severity=SeverityLevel.INFO.value,
205
- file_path=None,
206
- line=None,
207
- column=None,
208
- error_code="TZ-ENV-NO-VENV",
209
- message="No local virtual environment detected (.venv); running in global / system Python",
210
- suggested_fix="Create isolated virtualenv via 'python -m venv .venv'",
211
- auto_fixable=False
212
- ))
213
- return issues
214
-
215
- for venv in venvs:
216
- valid, err_msg, cfg = cls.inspect_virtualenv(venv)
217
- if not valid:
218
- issues.append(DiagnosticIssue(
219
- category=DiagnosticCategory.ENVIRONMENT.value,
220
- severity=SeverityLevel.ERROR.value,
221
- file_path=str(venv / "pyvenv.cfg"),
222
- line=None,
223
- column=None,
224
- error_code="TZ-ENV-VENV-BROKEN",
225
- message=f"Corrupted virtualenv '{venv.name}': {err_msg}",
226
- suggested_fix="Re-point 'home' in pyvenv.cfg to the active system Python directory",
227
- auto_fixable=True,
228
- metadata={"action": "repair_pyvenv_cfg", "path": str(venv)}
229
- ))
230
- else:
231
- # Check site-packages inside valid venv
232
- issues.extend(cls.check_corrupted_site_packages(venv))
233
-
234
- # Check dependency drift against requirements.txt
235
- issues.extend(cls.check_dependency_drift(workspace_dir))
236
- return issues
237
-
238
- @classmethod
239
- def execute_venv_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
240
- """Execute autonomous healing on virtualenv configurations and corruptions."""
241
- actions: List[HealAction] = []
242
-
243
- for issue in issues:
244
- action_type = issue.metadata.get("action")
245
- if not issue.auto_fixable or not action_type:
246
- continue
247
-
248
- t0 = time.time()
249
- if action_type == "repair_pyvenv_cfg":
250
- venv_p = issue.metadata.get("path")
251
- if venv_p:
252
- cfg_file = Path(venv_p) / "pyvenv.cfg"
253
- current_py_home = os.path.dirname(sys.executable)
254
- try:
255
- lines = []
256
- if cfg_file.is_file():
257
- with open(cfg_file, "r", encoding="utf-8", errors="replace") as f:
258
- for line in f:
259
- if line.strip().startswith("home ="):
260
- lines.append(f"home = {current_py_home}\n")
261
- else:
262
- lines.append(line)
263
- if not dry_run:
264
- with open(cfg_file, "w", encoding="utf-8", newline="\n") as f:
265
- f.writelines(lines)
266
- actions.append(HealAction(
267
- category=DiagnosticCategory.ENVIRONMENT.value,
268
- action_type=action_type,
269
- file_path=str(cfg_file),
270
- description=f"Updated pyvenv.cfg home path to '{current_py_home}' in {Path(venv_p).name}",
271
- success=True,
272
- duration_ms=round((time.time() - t0) * 1000, 2)
273
- ))
274
- except Exception as e:
275
- actions.append(HealAction(
276
- category=DiagnosticCategory.ENVIRONMENT.value,
277
- action_type=action_type,
278
- file_path=str(cfg_file),
279
- description=f"Failed updating pyvenv.cfg: {e}",
280
- success=False,
281
- duration_ms=round((time.time() - t0) * 1000, 2)
282
- ))
283
-
284
- elif action_type == "purge_corrupt_distinfo":
285
- target_p = issue.metadata.get("path")
286
- if target_p and os.path.isdir(target_p):
287
- try:
288
- if not dry_run:
289
- import shutil
290
- shutil.rmtree(target_p, ignore_errors=True)
291
- actions.append(HealAction(
292
- category=DiagnosticCategory.ENVIRONMENT.value,
293
- action_type=action_type,
294
- file_path=target_p,
295
- description=f"Purged corrupted metadata directory {os.path.basename(target_p)}",
296
- success=True,
297
- duration_ms=round((time.time() - t0) * 1000, 2)
298
- ))
299
- except Exception as e:
300
- actions.append(HealAction(
301
- category=DiagnosticCategory.ENVIRONMENT.value,
302
- action_type=action_type,
303
- file_path=target_p,
304
- description=f"Failed purging corrupt distinfo: {e}",
305
- success=False,
306
- duration_ms=round((time.time() - t0) * 1000, 2)
307
- ))
308
-
309
- return actions
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Virtualenv, Python Runtime, and Dependency Drift Doctor.
3
+
4
+ Performs forensic diagnosis and autonomous healing on:
5
+ - Virtual environment structures (.venv, venv, env, poetry, conda, pipenv).
6
+ - pyvenv.cfg integrity, broken base python home paths, and invalid symlinks.
7
+ - Missing packages defined in requirements.txt / pyproject.toml.
8
+ - Corrupted site-packages, dangling .dist-info / .egg-info directories.
9
+ - Package version conflicts and Python minor version drift.
10
+
11
+ Author: Toprak Ahmet Aydogmus (Siber Akademi)
12
+ Version: 10.4.0
13
+ """
14
+
15
+ import importlib.metadata
16
+ import os
17
+ import re
18
+ import sys
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Any, Dict, List, Optional, Set, Tuple
22
+
23
+ from .models import (
24
+ DiagnosticCategory,
25
+ DiagnosticIssue,
26
+ HealAction,
27
+ SeverityLevel,
28
+ SystemPlatform,
29
+ )
30
+
31
+
32
+ class VenvDoctor:
33
+ """Specialized doctor for Python virtual environments and dependency topologies."""
34
+
35
+ CANDIDATE_VENV_NAMES = [".venv", "venv", "env", ".env", "virtualenv"]
36
+
37
+ @classmethod
38
+ def detect_workspace_venvs(cls, workspace_dir: str = ".") -> List[Path]:
39
+ """Locate all local virtualenv directories in workspace root."""
40
+ root = Path(workspace_dir).resolve()
41
+ found: List[Path] = []
42
+ for name in cls.CANDIDATE_VENV_NAMES:
43
+ cand = root / name
44
+ if cand.is_dir() and (cand / "pyvenv.cfg").is_file():
45
+ found.append(cand)
46
+ return found
47
+
48
+ @classmethod
49
+ def parse_pyvenv_cfg(cls, cfg_path: Path) -> Dict[str, str]:
50
+ """Parse key-value pairs from a pyvenv.cfg file."""
51
+ res: Dict[str, str] = {}
52
+ if not cfg_path.is_file():
53
+ return res
54
+ try:
55
+ with open(cfg_path, "r", encoding="utf-8", errors="replace") as f:
56
+ for line in f:
57
+ line = line.strip()
58
+ if line and not line.startswith("#") and "=" in line:
59
+ k, v = line.split("=", 1)
60
+ res[k.strip().lower()] = v.strip()
61
+ except Exception:
62
+ pass
63
+ return res
64
+
65
+ @classmethod
66
+ def inspect_virtualenv(cls, venv_dir: Path) -> Tuple[bool, Optional[str], Dict[str, Any]]:
67
+ """Validate virtualenv structure, pyvenv.cfg, and interpreter binary."""
68
+ cfg_file = venv_dir / "pyvenv.cfg"
69
+ if not cfg_file.is_file():
70
+ return False, f"Missing 'pyvenv.cfg' in {venv_dir.name}", {}
71
+
72
+ cfg_data = cls.parse_pyvenv_cfg(cfg_file)
73
+ home_path = cfg_data.get("home")
74
+
75
+ if not home_path:
76
+ return False, "Missing 'home' directive in pyvenv.cfg", cfg_data
77
+
78
+ if not os.path.isdir(home_path):
79
+ return False, f"Base python home directory does not exist: '{home_path}'", cfg_data
80
+
81
+ # Check binary presence
82
+ is_windows = sys.platform.startswith("win")
83
+ bin_dir = venv_dir / ("Scripts" if is_windows else "bin")
84
+ py_binary = bin_dir / ("python.exe" if is_windows else "python")
85
+
86
+ if not bin_dir.is_dir():
87
+ return False, f"Missing '{bin_dir.name}' folder in virtualenv", cfg_data
88
+
89
+ if not py_binary.is_file():
90
+ return False, f"Missing python interpreter '{py_binary.name}' in {bin_dir.name}", cfg_data
91
+
92
+ return True, None, cfg_data
93
+
94
+ @classmethod
95
+ def parse_requirements_file(cls, req_file: Path) -> List[Tuple[str, Optional[str]]]:
96
+ """Extract package names and version specifiers from requirements.txt."""
97
+ packages: List[Tuple[str, Optional[str]]] = []
98
+ if not req_file.is_file():
99
+ return packages
100
+
101
+ try:
102
+ with open(req_file, "r", encoding="utf-8", errors="replace") as f:
103
+ for line in f:
104
+ line = line.strip()
105
+ if not line or line.startswith(("#", "-", "git+", "http")):
106
+ continue
107
+ # Match name and optional specifier
108
+ match = re.match(r"^([A-Za-z0-9_\-\.]+)(.*)$", line)
109
+ if match:
110
+ name = match.group(1).replace("-", "_").lower()
111
+ spec = match.group(2).strip() or None
112
+ packages.append((name, spec))
113
+ except Exception:
114
+ pass
115
+ return packages
116
+
117
+ @classmethod
118
+ def check_dependency_drift(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
119
+ """Cross-reference requirements against currently installed packages."""
120
+ issues: List[DiagnosticIssue] = []
121
+ root = Path(workspace_dir).resolve()
122
+
123
+ req_candidates = [root / "requirements.txt", root / "requirements-dev.txt"]
124
+ for req_f in req_candidates:
125
+ if not req_f.is_file():
126
+ continue
127
+
128
+ packages = cls.parse_requirements_file(req_f)
129
+ for pkg_name, spec in packages:
130
+ try:
131
+ installed_ver = importlib.metadata.version(pkg_name)
132
+ except importlib.metadata.PackageNotFoundError:
133
+ # Also try dash version
134
+ try:
135
+ installed_ver = importlib.metadata.version(pkg_name.replace("_", "-"))
136
+ except importlib.metadata.PackageNotFoundError:
137
+ issues.append(DiagnosticIssue(
138
+ category=DiagnosticCategory.ENVIRONMENT.value,
139
+ severity=SeverityLevel.ERROR.value,
140
+ file_path=str(req_f),
141
+ line=None,
142
+ column=None,
143
+ error_code="TZ-ENV-PKG-MISSING",
144
+ message=f"Declared dependency '{pkg_name}' ({spec or 'any'}) is not installed in the active environment",
145
+ suggested_fix=f"Run 'pip install {pkg_name}{spec or ''}' to satisfy workspace requirements",
146
+ auto_fixable=False,
147
+ metadata={"package": pkg_name, "spec": spec}
148
+ ))
149
+
150
+ return issues
151
+
152
+ @classmethod
153
+ def check_corrupted_site_packages(cls, venv_dir: Path) -> List[DiagnosticIssue]:
154
+ """Scan site-packages for empty or corrupted .dist-info / .egg-info remnants."""
155
+ issues: List[DiagnosticIssue] = []
156
+ is_windows = sys.platform.startswith("win")
157
+ lib_dir = venv_dir / "Lib" / "site-packages" if is_windows else venv_dir / "lib"
158
+
159
+ # On POSIX it might be lib/python3.X/site-packages
160
+ if not is_windows and lib_dir.is_dir():
161
+ py_dirs = list(lib_dir.glob("python3.*"))
162
+ if py_dirs:
163
+ lib_dir = py_dirs[0] / "site-packages"
164
+
165
+ if not lib_dir.is_dir():
166
+ return issues
167
+
168
+ try:
169
+ for item in lib_dir.iterdir():
170
+ if item.is_dir() and item.name.endswith((".dist-info", ".egg-info")):
171
+ # Check if empty or missing METADATA / PKG-INFO
172
+ meta = item / "METADATA"
173
+ pkg_info = item / "PKG-INFO"
174
+ if not meta.is_file() and not pkg_info.is_file():
175
+ issues.append(DiagnosticIssue(
176
+ category=DiagnosticCategory.ENVIRONMENT.value,
177
+ severity=SeverityLevel.WARNING.value,
178
+ file_path=str(item),
179
+ line=None,
180
+ column=None,
181
+ error_code="TZ-ENV-CORRUPT-DISTINFO",
182
+ message=f"Corrupted distribution metadata folder: '{item.name}' (missing METADATA)",
183
+ suggested_fix="Purge orphaned metadata folder and reinstall package",
184
+ auto_fixable=True,
185
+ metadata={"action": "purge_corrupt_distinfo", "path": str(item)}
186
+ ))
187
+ except Exception:
188
+ pass
189
+
190
+ return issues
191
+
192
+ @classmethod
193
+ def diagnose(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
194
+ """Run complete virtualenv diagnostic suite."""
195
+ issues: List[DiagnosticIssue] = []
196
+ venvs = cls.detect_workspace_venvs(workspace_dir)
197
+
198
+ if not venvs:
199
+ # Check if active Python is a virtualenv
200
+ is_venv = hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix)
201
+ if not is_venv:
202
+ issues.append(DiagnosticIssue(
203
+ category=DiagnosticCategory.ENVIRONMENT.value,
204
+ severity=SeverityLevel.INFO.value,
205
+ file_path=None,
206
+ line=None,
207
+ column=None,
208
+ error_code="TZ-ENV-NO-VENV",
209
+ message="No local virtual environment detected (.venv); running in global / system Python",
210
+ suggested_fix="Create isolated virtualenv via 'python -m venv .venv'",
211
+ auto_fixable=False
212
+ ))
213
+ return issues
214
+
215
+ for venv in venvs:
216
+ valid, err_msg, cfg = cls.inspect_virtualenv(venv)
217
+ if not valid:
218
+ issues.append(DiagnosticIssue(
219
+ category=DiagnosticCategory.ENVIRONMENT.value,
220
+ severity=SeverityLevel.ERROR.value,
221
+ file_path=str(venv / "pyvenv.cfg"),
222
+ line=None,
223
+ column=None,
224
+ error_code="TZ-ENV-VENV-BROKEN",
225
+ message=f"Corrupted virtualenv '{venv.name}': {err_msg}",
226
+ suggested_fix="Re-point 'home' in pyvenv.cfg to the active system Python directory",
227
+ auto_fixable=True,
228
+ metadata={"action": "repair_pyvenv_cfg", "path": str(venv)}
229
+ ))
230
+ else:
231
+ # Check site-packages inside valid venv
232
+ issues.extend(cls.check_corrupted_site_packages(venv))
233
+
234
+ # Check dependency drift against requirements.txt
235
+ issues.extend(cls.check_dependency_drift(workspace_dir))
236
+ return issues
237
+
238
+ @classmethod
239
+ def execute_venv_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
240
+ """Execute autonomous healing on virtualenv configurations and corruptions."""
241
+ actions: List[HealAction] = []
242
+
243
+ for issue in issues:
244
+ action_type = issue.metadata.get("action")
245
+ if not issue.auto_fixable or not action_type:
246
+ continue
247
+
248
+ t0 = time.time()
249
+ if action_type == "repair_pyvenv_cfg":
250
+ venv_p = issue.metadata.get("path")
251
+ if venv_p:
252
+ cfg_file = Path(venv_p) / "pyvenv.cfg"
253
+ current_py_home = os.path.dirname(sys.executable)
254
+ try:
255
+ lines = []
256
+ if cfg_file.is_file():
257
+ with open(cfg_file, "r", encoding="utf-8", errors="replace") as f:
258
+ for line in f:
259
+ if line.strip().startswith("home ="):
260
+ lines.append(f"home = {current_py_home}\n")
261
+ else:
262
+ lines.append(line)
263
+ if not dry_run:
264
+ with open(cfg_file, "w", encoding="utf-8", newline="\n") as f:
265
+ f.writelines(lines)
266
+ actions.append(HealAction(
267
+ category=DiagnosticCategory.ENVIRONMENT.value,
268
+ action_type=action_type,
269
+ file_path=str(cfg_file),
270
+ description=f"Updated pyvenv.cfg home path to '{current_py_home}' in {Path(venv_p).name}",
271
+ success=True,
272
+ duration_ms=round((time.time() - t0) * 1000, 2)
273
+ ))
274
+ except Exception as e:
275
+ actions.append(HealAction(
276
+ category=DiagnosticCategory.ENVIRONMENT.value,
277
+ action_type=action_type,
278
+ file_path=str(cfg_file),
279
+ description=f"Failed updating pyvenv.cfg: {e}",
280
+ success=False,
281
+ duration_ms=round((time.time() - t0) * 1000, 2)
282
+ ))
283
+
284
+ elif action_type == "purge_corrupt_distinfo":
285
+ target_p = issue.metadata.get("path")
286
+ if target_p and os.path.isdir(target_p):
287
+ try:
288
+ if not dry_run:
289
+ import shutil
290
+ shutil.rmtree(target_p, ignore_errors=True)
291
+ actions.append(HealAction(
292
+ category=DiagnosticCategory.ENVIRONMENT.value,
293
+ action_type=action_type,
294
+ file_path=target_p,
295
+ description=f"Purged corrupted metadata directory {os.path.basename(target_p)}",
296
+ success=True,
297
+ duration_ms=round((time.time() - t0) * 1000, 2)
298
+ ))
299
+ except Exception as e:
300
+ actions.append(HealAction(
301
+ category=DiagnosticCategory.ENVIRONMENT.value,
302
+ action_type=action_type,
303
+ file_path=target_p,
304
+ description=f"Failed purging corrupt distinfo: {e}",
305
+ success=False,
306
+ duration_ms=round((time.time() - t0) * 1000, 2)
307
+ ))
308
+
309
+ return actions