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,600 +1,600 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- T-Zero PC Fixer Doctor Classic Facade and Compatibility Layer
4
- ============================================================
5
- Provides backward-compatible PCFixerDoctor class for legacy test suites and APIs.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import ast
11
- import difflib
12
- import json
13
- import os
14
- import re
15
- import shutil
16
- import sys
17
- import time
18
- from dataclasses import asdict
19
- from pathlib import Path
20
- from typing import Any, Dict, List, Optional, Set, Tuple
21
-
22
- from tzero.tzero_fixer.models import (
23
- DiagnosticCategory,
24
- DiagnosticIssue,
25
- DiagnosticReport,
26
- HealAction,
27
- HealReport,
28
- SeverityLevel,
29
- )
30
-
31
- class PCFixerDoctor:
32
- """Enterprise-grade self-healing PC, runtime environment, and codebase doctor."""
33
-
34
- COMMON_STDLIB_SYMBOLS = {
35
- "os": "import os",
36
- "sys": "import sys",
37
- "re": "import re",
38
- "json": "import json",
39
- "math": "import math",
40
- "time": "import time",
41
- "pathlib": "from pathlib import Path",
42
- "Path": "from pathlib import Path",
43
- "ast": "import ast",
44
- "dataclass": "from dataclasses import dataclass",
45
- "field": "from dataclasses import field",
46
- "asdict": "from dataclasses import asdict",
47
- "Dict": "from typing import Dict",
48
- "List": "from typing import List",
49
- "Optional": "from typing import Optional",
50
- "Union": "from typing import Union",
51
- "Tuple": "from typing import Tuple",
52
- "Any": "from typing import Any",
53
- "Callable": "from typing import Callable",
54
- "Set": "from typing import Set",
55
- }
56
-
57
- IGNORE_DIRS = {
58
- ".git", ".svn", ".hg", "__pycache__", ".pytest_cache", ".mypy_cache",
59
- "node_modules", ".venv", "venv", "env", "build", "dist", ".idea", ".vscode"
60
- }
61
-
62
- @classmethod
63
- def check_tools_on_path(cls) -> Dict[str, bool]:
64
- """Check availability of essential development CLI tools on system PATH."""
65
- tools = ["git", "python", "pip", "npm", "npx", "code", "cursor"]
66
- res = {}
67
- for t in tools:
68
- res[t] = shutil.which(t) is not None
69
- return res
70
-
71
- @classmethod
72
- def inspect_virtualenv(cls, target_dir: str = ".") -> Dict[str, Any]:
73
- """Check integrity of local virtual environments (.venv, venv, env)."""
74
- root = Path(target_dir).resolve()
75
- candidates = [root / ".venv", root / "venv", root / "env"]
76
- found = None
77
- for c in candidates:
78
- if c.is_dir() and (c / "pyvenv.cfg").is_file():
79
- found = c
80
- break
81
-
82
- if not found:
83
- return {
84
- "active": hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix),
85
- "detected": False,
86
- "path": None,
87
- "valid": True,
88
- "error": None
89
- }
90
-
91
- cfg_file = found / "pyvenv.cfg"
92
- home_path = None
93
- try:
94
- with open(cfg_file, "r", encoding="utf-8", errors="replace") as f:
95
- for line in f:
96
- if line.strip().startswith("home ="):
97
- home_path = line.split("=", 1)[1].strip()
98
- break
99
- except Exception as e:
100
- return {"active": True, "detected": True, "path": str(found), "valid": False, "error": f"Cannot read pyvenv.cfg: {e}"}
101
-
102
- home_valid = bool(home_path and os.path.isdir(home_path))
103
- return {
104
- "active": True,
105
- "detected": True,
106
- "path": str(found),
107
- "cfg_home": home_path,
108
- "valid": home_valid,
109
- "error": None if home_valid else f"Base python home invalid: '{home_path}'"
110
- }
111
-
112
- @classmethod
113
- def scan_syntax_and_imports(cls, file_path: str) -> List[DiagnosticIssue]:
114
- """Scan a single Python file for syntax flaws, BOM artifacts, and missing imports."""
115
- issues: List[DiagnosticIssue] = []
116
- path = Path(file_path)
117
- if not path.is_file() or path.suffix != ".py":
118
- return issues
119
-
120
- try:
121
- with open(path, "rb") as f:
122
- raw_bytes = f.read()
123
- except Exception as e:
124
- issues.append(DiagnosticIssue(
125
- category="env",
126
- severity="error",
127
- file_path=str(path),
128
- line=None,
129
- message=f"Permission or read error: {e}",
130
- suggested_fix="Check file permissions",
131
- auto_fixable=False
132
- ))
133
- return issues
134
-
135
- # Check BOM / Zero-width characters
136
- if raw_bytes.startswith(b"\xef\xbb\xbf"):
137
- issues.append(DiagnosticIssue(
138
- category="encoding",
139
- severity="warning",
140
- file_path=str(path),
141
- line=1,
142
- message="File contains UTF-8 Byte Order Mark (BOM) which may disrupt interpreters",
143
- suggested_fix="Strip UTF-8 BOM",
144
- auto_fixable=True,
145
- metadata={"action": "strip_bom"}
146
- ))
147
-
148
- try:
149
- content = raw_bytes.decode("utf-8")
150
- except UnicodeDecodeError:
151
- issues.append(DiagnosticIssue(
152
- category="encoding",
153
- severity="error",
154
- file_path=str(path),
155
- line=1,
156
- message="File encoding is not valid UTF-8",
157
- suggested_fix="Transcode to clean UTF-8",
158
- auto_fixable=True,
159
- metadata={"action": "fix_encoding"}
160
- ))
161
- content = raw_bytes.decode("utf-8", errors="replace")
162
-
163
- # Zero-width spaces
164
- if "\u200b" in content or "\ufeff" in content:
165
- issues.append(DiagnosticIssue(
166
- category="encoding",
167
- severity="warning",
168
- file_path=str(path),
169
- line=1,
170
- message="File contains hidden zero-width spaces causing phantom syntax bugs",
171
- suggested_fix="Strip zero-width characters",
172
- auto_fixable=True,
173
- metadata={"action": "strip_zero_width"}
174
- ))
175
-
176
- # Check AST parse
177
- try:
178
- tree = ast.parse(content, filename=str(path))
179
- except SyntaxError as se:
180
- # Analyze syntax error reason
181
- err_line = se.lineno or 1
182
- err_msg = se.msg or "Syntax error"
183
- suggested = "Fix syntax error"
184
- action = "syntax_fix"
185
-
186
- lines = content.splitlines()
187
- if 0 < err_line <= len(lines):
188
- line_str = lines[err_line - 1].strip()
189
- # Check missing colon
190
- block_starters = ("def ", "class ", "if ", "elif ", "else", "try", "except", "finally", "for ", "while ", "with ")
191
- if any(line_str.startswith(b) for b in block_starters) and not line_str.endswith(":"):
192
- suggested = "Append missing colon ':' to block definition"
193
- action = "append_colon"
194
- # Check Python 2 print
195
- elif re.match(r"^print\s+[\"'].*", line_str):
196
- suggested = "Convert Python 2 print statement to print(...) function call"
197
- action = "convert_print2"
198
-
199
- issues.append(DiagnosticIssue(
200
- category="syntax",
201
- severity="error",
202
- file_path=str(path),
203
- line=err_line,
204
- message=f"SyntaxError: {err_msg} on line {err_line}",
205
- suggested_fix=suggested,
206
- auto_fixable=True,
207
- metadata={"action": action, "lineno": err_line}
208
- ))
209
- return issues
210
-
211
- # Check missing top-level standard library imports
212
- imported_symbols: Set[str] = set()
213
- for node in ast.walk(tree):
214
- if isinstance(node, ast.Import):
215
- for alias in node.names:
216
- imported_symbols.add(alias.name.split(".")[0])
217
- imported_symbols.add(alias.asname or alias.name)
218
- elif isinstance(node, ast.ImportFrom):
219
- for alias in node.names:
220
- imported_symbols.add(alias.asname or alias.name)
221
-
222
- referenced_names: Set[str] = set()
223
- for node in ast.walk(tree):
224
- if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
225
- referenced_names.add(node.id)
226
-
227
- # Builtins
228
- builtins_set = set(dir(__builtins__))
229
-
230
- for sym, import_stmt in cls.COMMON_STDLIB_SYMBOLS.items():
231
- if sym in referenced_names and sym not in imported_symbols and sym not in builtins_set:
232
- issues.append(DiagnosticIssue(
233
- category="import",
234
- severity="warning",
235
- file_path=str(path),
236
- line=1,
237
- message=f"Referenced symbol '{sym}' is missing explicit import statement",
238
- suggested_fix=f"Add '{import_stmt}' at top of file",
239
- auto_fixable=True,
240
- metadata={"action": "add_import", "symbol": sym, "stmt": import_stmt}
241
- ))
242
-
243
- return issues
244
-
245
- @classmethod
246
- def scan_cache_and_bloat(cls, target_dir: str = ".") -> List[DiagnosticIssue]:
247
- """Scan for orphaned .pyc files, stale git locks, and bloated caches."""
248
- issues: List[DiagnosticIssue] = []
249
- root = Path(target_dir).resolve()
250
-
251
- # Check stale .git/index.lock
252
- git_lock = root / ".git" / "index.lock"
253
- if git_lock.is_file():
254
- age_sec = time.time() - os.path.getmtime(git_lock)
255
- if age_sec > 300: # older than 5 minutes
256
- issues.append(DiagnosticIssue(
257
- category="cache",
258
- severity="warning",
259
- file_path=str(git_lock),
260
- line=None,
261
- message=f"Stale git lockfile detected ({int(age_sec)}s old) blocking git operations",
262
- suggested_fix="Remove stale .git/index.lock",
263
- auto_fixable=True,
264
- metadata={"action": "remove_file", "path": str(git_lock)}
265
- ))
266
-
267
- # Check orphaned .pyc in __pycache__
268
- for root_dir, dirs, files in os.walk(str(root)):
269
- # skip ignored
270
- dirs[:] = [d for d in dirs if d not in cls.IGNORE_DIRS or d == "__pycache__"]
271
- if os.path.basename(root_dir) == "__pycache__":
272
- parent_dir = Path(root_dir).parent
273
- for f in files:
274
- if f.endswith(".pyc"):
275
- base_name = f.split(".")[0]
276
- py_sibling = parent_dir / f"{base_name}.py"
277
- if not py_sibling.is_file():
278
- pyc_path = os.path.join(root_dir, f)
279
- issues.append(DiagnosticIssue(
280
- category="cache",
281
- severity="info",
282
- file_path=pyc_path,
283
- line=None,
284
- message=f"Orphaned bytecode {f} has no corresponding .py source file",
285
- suggested_fix="Purge orphaned bytecode",
286
- auto_fixable=True,
287
- metadata={"action": "remove_file", "path": pyc_path}
288
- ))
289
-
290
- return issues
291
-
292
- @classmethod
293
- def diagnose(cls, target_dir: str = ".") -> DiagnosticReport:
294
- """Run comprehensive diagnostic inspection across environment, workspace, and files."""
295
- root = Path(target_dir).resolve()
296
- tools_status = cls.check_tools_on_path()
297
- venv_status = cls.inspect_virtualenv(target_dir)
298
-
299
- issues: List[DiagnosticIssue] = []
300
-
301
- # Check Python version
302
- py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
303
- if sys.version_info < (3, 9):
304
- issues.append(DiagnosticIssue(
305
- category="env",
306
- severity="error",
307
- file_path=None,
308
- line=None,
309
- message=f"Python version {py_ver} is below minimum supported 3.9",
310
- suggested_fix="Upgrade Python to 3.9 or higher",
311
- auto_fixable=False
312
- ))
313
-
314
- # Check venv
315
- if venv_status.get("detected") and not venv_status.get("valid"):
316
- issues.append(DiagnosticIssue(
317
- category="env",
318
- severity="error",
319
- file_path=os.path.join(venv_status["path"], "pyvenv.cfg"),
320
- line=None,
321
- message=f"Virtualenv corrupted: {venv_status.get('error')}",
322
- suggested_fix="Re-point pyvenv.cfg home to active python interpreter",
323
- auto_fixable=True,
324
- metadata={"action": "repair_venv_cfg", "path": venv_status["path"]}
325
- ))
326
-
327
- # Scan files
328
- for root_dir, dirs, files in os.walk(str(root)):
329
- dirs[:] = [d for d in dirs if d not in cls.IGNORE_DIRS]
330
- for file in files:
331
- if file.endswith(".py"):
332
- full_path = os.path.join(root_dir, file)
333
- issues.extend(cls.scan_syntax_and_imports(full_path))
334
-
335
- # Scan cache & bloat
336
- issues.extend(cls.scan_cache_and_bloat(target_dir))
337
-
338
- # Tally counts
339
- syntax_errors = sum(1 for i in issues if i.category == "syntax")
340
- missing_imports = sum(1 for i in issues if i.category == "import")
341
- env_issues = sum(1 for i in issues if i.category == "env")
342
- cache_issues = sum(1 for i in issues if i.category in ("cache", "encoding"))
343
-
344
- # Health score calculation
345
- penalty = (syntax_errors * 20) + (missing_imports * 5) + (env_issues * 15) + (cache_issues * 2)
346
- score = max(0, min(100, 100 - penalty))
347
-
348
- return DiagnosticReport(
349
- timestamp=time.time(),
350
- target_dir=str(root),
351
- health_score_pct=score,
352
- total_issues=len(issues),
353
- syntax_errors=syntax_errors,
354
- missing_imports=missing_imports,
355
- env_issues=env_issues,
356
- cache_issues=cache_issues,
357
- issues=issues,
358
- tools_status=tools_status,
359
- python_version=py_ver,
360
- virtualenv_status=venv_status
361
- )
362
-
363
- @classmethod
364
- def auto_heal(cls, target_dir: str = ".", dry_run: bool = False,
365
- fix_syntax: bool = True, add_imports: bool = True,
366
- clean_caches: bool = True, repair_venv: bool = True) -> HealReport:
367
- """Execute autonomous self-healing for detected codebase and environment issues."""
368
- diag_before = cls.diagnose(target_dir)
369
- actions: List[HealAction] = []
370
-
371
- files_to_recheck: Set[str] = set()
372
-
373
- for issue in diag_before.issues:
374
- action_type = issue.metadata.get("action")
375
- if not issue.auto_fixable or not action_type:
376
- continue
377
-
378
- # 1. Clean UTF-8 BOM or Zero-width chars
379
- if action_type in ("strip_bom", "strip_zero_width", "fix_encoding") and issue.file_path:
380
- try:
381
- p = Path(issue.file_path)
382
- with open(p, "rb") as f:
383
- data = f.read()
384
- if action_type == "strip_bom" and data.startswith(b"\xef\xbb\xbf"):
385
- data = data[3:]
386
- text = data.decode("utf-8", errors="replace")
387
- if action_type == "strip_zero_width":
388
- text = text.replace("\u200b", "").replace("\ufeff", "")
389
- if not dry_run:
390
- with open(p, "w", encoding="utf-8", newline="\n") as f:
391
- f.write(text)
392
- actions.append(HealAction(
393
- category="encoding",
394
- file_path=issue.file_path,
395
- description=f"Sanitized encoding/BOM in {p.name}",
396
- success=True
397
- ))
398
- files_to_recheck.add(issue.file_path)
399
- except Exception as e:
400
- actions.append(HealAction(
401
- category="encoding",
402
- file_path=issue.file_path,
403
- description=f"Failed sanitizing encoding: {e}",
404
- success=False
405
- ))
406
-
407
- # 2. Fix syntax errors (missing colon, Python 2 print)
408
- elif action_type in ("append_colon", "convert_print2") and fix_syntax and issue.file_path:
409
- try:
410
- p = Path(issue.file_path)
411
- with open(p, "r", encoding="utf-8", errors="replace") as f:
412
- lines = f.readlines()
413
- lineno = issue.metadata.get("lineno", 1)
414
- if 0 < lineno <= len(lines):
415
- orig_line = lines[lineno - 1]
416
- mod_line = orig_line
417
- if action_type == "append_colon":
418
- mod_line = orig_line.rstrip("\r\n") + ":\n"
419
- elif action_type == "convert_print2":
420
- mod_line = re.sub(r"^(\s*)print\s+(.*)$", r"\1print(\2)", orig_line)
421
-
422
- if orig_line != mod_line:
423
- diff = "".join(difflib.unified_diff(
424
- [orig_line], [mod_line], fromfile="before", tofile="after"
425
- ))
426
- lines[lineno - 1] = mod_line
427
- if not dry_run:
428
- with open(p, "w", encoding="utf-8", newline="\n") as f:
429
- f.writelines(lines)
430
- actions.append(HealAction(
431
- category="syntax",
432
- file_path=issue.file_path,
433
- description=f"Patched {action_type} on line {lineno} of {p.name}",
434
- success=True,
435
- diff=diff
436
- ))
437
- files_to_recheck.add(issue.file_path)
438
- except Exception as e:
439
- actions.append(HealAction(
440
- category="syntax",
441
- file_path=issue.file_path,
442
- description=f"Failed patching syntax: {e}",
443
- success=False
444
- ))
445
-
446
- # 3. Add missing standard library import
447
- elif action_type == "add_import" and add_imports and issue.file_path:
448
- try:
449
- p = Path(issue.file_path)
450
- with open(p, "r", encoding="utf-8", errors="replace") as f:
451
- lines = f.readlines()
452
- stmt = issue.metadata.get("stmt")
453
- if stmt:
454
- # Find safe insert location (after future imports / docstring or line 0)
455
- insert_idx = 0
456
- for idx, l in enumerate(lines[:15]):
457
- if l.startswith("#") or "coding:" in l or l.startswith('"""') or l.startswith("'''"):
458
- insert_idx = idx + 1
459
- elif l.startswith("from __future__"):
460
- insert_idx = idx + 1
461
-
462
- lines.insert(insert_idx, f"{stmt}\n")
463
- diff = f"+ {stmt}\n"
464
- if not dry_run:
465
- with open(p, "w", encoding="utf-8", newline="\n") as f:
466
- f.writelines(lines)
467
- actions.append(HealAction(
468
- category="import",
469
- file_path=issue.file_path,
470
- description=f"Injected missing '{stmt}' into {p.name}",
471
- success=True,
472
- diff=diff
473
- ))
474
- files_to_recheck.add(issue.file_path)
475
- except Exception as e:
476
- actions.append(HealAction(
477
- category="import",
478
- file_path=issue.file_path,
479
- description=f"Failed adding import: {e}",
480
- success=False
481
- ))
482
-
483
- # 4. Remove stale lockfiles or orphaned bytecode
484
- elif action_type == "remove_file" and clean_caches:
485
- target_path = issue.metadata.get("path") or issue.file_path
486
- if target_path and os.path.exists(target_path):
487
- try:
488
- if not dry_run:
489
- os.remove(target_path)
490
- actions.append(HealAction(
491
- category="cache",
492
- file_path=target_path,
493
- description=f"Purged {os.path.basename(target_path)}",
494
- success=True
495
- ))
496
- except Exception as e:
497
- actions.append(HealAction(
498
- category="cache",
499
- file_path=target_path,
500
- description=f"Failed removing {target_path}: {e}",
501
- success=False
502
- ))
503
-
504
- # 5. Repair virtualenv config
505
- elif action_type == "repair_venv_cfg" and repair_venv:
506
- venv_dir = issue.metadata.get("path")
507
- if venv_dir:
508
- cfg_file = os.path.join(venv_dir, "pyvenv.cfg")
509
- curr_py_home = os.path.dirname(sys.executable)
510
- try:
511
- lines = []
512
- if os.path.isfile(cfg_file):
513
- with open(cfg_file, "r", encoding="utf-8", errors="replace") as f:
514
- for line in f:
515
- if line.strip().startswith("home ="):
516
- lines.append(f"home = {curr_py_home}\n")
517
- else:
518
- lines.append(line)
519
- if not dry_run:
520
- with open(cfg_file, "w", encoding="utf-8", newline="\n") as f:
521
- f.writelines(lines)
522
- actions.append(HealAction(
523
- category="env",
524
- file_path=cfg_file,
525
- description=f"Updated pyvenv.cfg home path to '{curr_py_home}'",
526
- success=True
527
- ))
528
- except Exception as e:
529
- actions.append(HealAction(
530
- category="env",
531
- file_path=cfg_file,
532
- description=f"Failed updating pyvenv.cfg: {e}",
533
- success=False
534
- ))
535
-
536
- # Re-diagnose to evaluate final score
537
- diag_after = cls.diagnose(target_dir) if not dry_run else diag_before
538
- successful_heals = sum(1 for a in actions if a.success)
539
-
540
- return HealReport(
541
- timestamp=time.time(),
542
- target_dir=str(Path(target_dir).resolve()),
543
- initial_health_score=diag_before.health_score_pct,
544
- final_health_score=diag_after.health_score_pct,
545
- issues_detected=diag_before.total_issues,
546
- issues_healed=successful_heals,
547
- dry_run=dry_run,
548
- actions=actions
549
- )
550
-
551
- @classmethod
552
- def render_cli(cls, report: DiagnosticReport, heal_report: Optional[HealReport] = None):
553
- """Render beautiful, ANSI-colored doctor report to terminal."""
554
- print("=" * 80)
555
- print("\033[1;36m🩺 T-ZERO PC-FIXER & ENVIRONMENT AUTONOMOUS DOCTOR\033[0m")
556
- print("=" * 80)
557
- print(f"Target Directory: \033[33m{report.target_dir}\033[0m")
558
- print(f"Python Runtime: \033[32mv{report.python_version}\033[0m ({sys.executable})")
559
- print(f"Virtualenv: \033[32m{report.virtualenv_status.get('path') or 'Global / System'}\033[0m")
560
-
561
- # Tools status
562
- tools_str = " ".join([
563
- f"\033[32m[OK] {t}\033[0m" if ok else f"\033[31m[--] {t}\033[0m"
564
- for t, ok in report.tools_status.items()
565
- ])
566
- print(f"CLI Tools: {tools_str}")
567
-
568
- score_color = "\033[32m" if report.health_score_pct >= 90 else ("\033[33m" if report.health_score_pct >= 70 else "\033[31m")
569
- print(f"Health Score: {score_color}{report.health_score_pct} / 100\033[0m")
570
- print("-" * 80)
571
-
572
- if report.total_issues == 0:
573
- print("\033[32m✨ Codebase and Environment are in 100% pristine condition! Zero issues found.\033[0m")
574
- else:
575
- print(f"Detected Issues: \033[1;31m{report.total_issues}\033[0m "
576
- f"(Syntax: {report.syntax_errors}, Imports: {report.missing_imports}, "
577
- f"Env: {report.env_issues}, Cache: {report.cache_issues})")
578
- print()
579
- for idx, issue in enumerate(report.issues[:15], start=1):
580
- loc = f"{os.path.basename(issue.file_path or 'system')}:{issue.line or '-'}"
581
- icon = "\033[31m[FAIL]\033[0m" if issue.severity == "error" else "\033[33m[WARN]\033[0m"
582
- print(f" {idx:2d}. {icon} \033[1m{loc:<22}\033[0m {issue.message}")
583
- print(f" \033[36mFix:\033[0m {issue.suggested_fix}")
584
-
585
- if len(report.issues) > 15:
586
- print(f" ... and {len(report.issues) - 15} more issues.")
587
-
588
- if heal_report:
589
- print("-" * 80)
590
- print("\033[1;32m💉 AUTONOMOUS SELF-HEALING RESULTS:\033[0m")
591
- print(f" Issues Healed: \033[32m{heal_report.issues_healed} / {heal_report.issues_detected}\033[0m")
592
- print(f" Health Boost: \033[33m{heal_report.initial_health_score}%\033[0m -> \033[1;32m{heal_report.final_health_score}%\033[0m")
593
- for a in heal_report.actions:
594
- status_icon = "\033[32m✔\033[0m" if a.success else "\033[31m✘\033[0m"
595
- print(f" {status_icon} [{a.category.upper()}] {a.description}")
596
- if a.diff:
597
- for dline in a.diff.splitlines()[:3]:
598
- print(f" \033[35m{dline}\033[0m")
599
-
600
- print("=" * 80)
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-Zero PC Fixer Doctor Classic Facade and Compatibility Layer
4
+ ============================================================
5
+ Provides backward-compatible PCFixerDoctor class for legacy test suites and APIs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import difflib
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import sys
17
+ import time
18
+ from dataclasses import asdict
19
+ from pathlib import Path
20
+ from typing import Any, Dict, List, Optional, Set, Tuple
21
+
22
+ from tzero.tzero_fixer.models import (
23
+ DiagnosticCategory,
24
+ DiagnosticIssue,
25
+ DiagnosticReport,
26
+ HealAction,
27
+ HealReport,
28
+ SeverityLevel,
29
+ )
30
+
31
+ class PCFixerDoctor:
32
+ """Enterprise-grade self-healing PC, runtime environment, and codebase doctor."""
33
+
34
+ COMMON_STDLIB_SYMBOLS = {
35
+ "os": "import os",
36
+ "sys": "import sys",
37
+ "re": "import re",
38
+ "json": "import json",
39
+ "math": "import math",
40
+ "time": "import time",
41
+ "pathlib": "from pathlib import Path",
42
+ "Path": "from pathlib import Path",
43
+ "ast": "import ast",
44
+ "dataclass": "from dataclasses import dataclass",
45
+ "field": "from dataclasses import field",
46
+ "asdict": "from dataclasses import asdict",
47
+ "Dict": "from typing import Dict",
48
+ "List": "from typing import List",
49
+ "Optional": "from typing import Optional",
50
+ "Union": "from typing import Union",
51
+ "Tuple": "from typing import Tuple",
52
+ "Any": "from typing import Any",
53
+ "Callable": "from typing import Callable",
54
+ "Set": "from typing import Set",
55
+ }
56
+
57
+ IGNORE_DIRS = {
58
+ ".git", ".svn", ".hg", "__pycache__", ".pytest_cache", ".mypy_cache",
59
+ "node_modules", ".venv", "venv", "env", "build", "dist", ".idea", ".vscode"
60
+ }
61
+
62
+ @classmethod
63
+ def check_tools_on_path(cls) -> Dict[str, bool]:
64
+ """Check availability of essential development CLI tools on system PATH."""
65
+ tools = ["git", "python", "pip", "npm", "npx", "code", "cursor"]
66
+ res = {}
67
+ for t in tools:
68
+ res[t] = shutil.which(t) is not None
69
+ return res
70
+
71
+ @classmethod
72
+ def inspect_virtualenv(cls, target_dir: str = ".") -> Dict[str, Any]:
73
+ """Check integrity of local virtual environments (.venv, venv, env)."""
74
+ root = Path(target_dir).resolve()
75
+ candidates = [root / ".venv", root / "venv", root / "env"]
76
+ found = None
77
+ for c in candidates:
78
+ if c.is_dir() and (c / "pyvenv.cfg").is_file():
79
+ found = c
80
+ break
81
+
82
+ if not found:
83
+ return {
84
+ "active": hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix),
85
+ "detected": False,
86
+ "path": None,
87
+ "valid": True,
88
+ "error": None
89
+ }
90
+
91
+ cfg_file = found / "pyvenv.cfg"
92
+ home_path = None
93
+ try:
94
+ with open(cfg_file, "r", encoding="utf-8", errors="replace") as f:
95
+ for line in f:
96
+ if line.strip().startswith("home ="):
97
+ home_path = line.split("=", 1)[1].strip()
98
+ break
99
+ except Exception as e:
100
+ return {"active": True, "detected": True, "path": str(found), "valid": False, "error": f"Cannot read pyvenv.cfg: {e}"}
101
+
102
+ home_valid = bool(home_path and os.path.isdir(home_path))
103
+ return {
104
+ "active": True,
105
+ "detected": True,
106
+ "path": str(found),
107
+ "cfg_home": home_path,
108
+ "valid": home_valid,
109
+ "error": None if home_valid else f"Base python home invalid: '{home_path}'"
110
+ }
111
+
112
+ @classmethod
113
+ def scan_syntax_and_imports(cls, file_path: str) -> List[DiagnosticIssue]:
114
+ """Scan a single Python file for syntax flaws, BOM artifacts, and missing imports."""
115
+ issues: List[DiagnosticIssue] = []
116
+ path = Path(file_path)
117
+ if not path.is_file() or path.suffix != ".py":
118
+ return issues
119
+
120
+ try:
121
+ with open(path, "rb") as f:
122
+ raw_bytes = f.read()
123
+ except Exception as e:
124
+ issues.append(DiagnosticIssue(
125
+ category="env",
126
+ severity="error",
127
+ file_path=str(path),
128
+ line=None,
129
+ message=f"Permission or read error: {e}",
130
+ suggested_fix="Check file permissions",
131
+ auto_fixable=False
132
+ ))
133
+ return issues
134
+
135
+ # Check BOM / Zero-width characters
136
+ if raw_bytes.startswith(b"\xef\xbb\xbf"):
137
+ issues.append(DiagnosticIssue(
138
+ category="encoding",
139
+ severity="warning",
140
+ file_path=str(path),
141
+ line=1,
142
+ message="File contains UTF-8 Byte Order Mark (BOM) which may disrupt interpreters",
143
+ suggested_fix="Strip UTF-8 BOM",
144
+ auto_fixable=True,
145
+ metadata={"action": "strip_bom"}
146
+ ))
147
+
148
+ try:
149
+ content = raw_bytes.decode("utf-8")
150
+ except UnicodeDecodeError:
151
+ issues.append(DiagnosticIssue(
152
+ category="encoding",
153
+ severity="error",
154
+ file_path=str(path),
155
+ line=1,
156
+ message="File encoding is not valid UTF-8",
157
+ suggested_fix="Transcode to clean UTF-8",
158
+ auto_fixable=True,
159
+ metadata={"action": "fix_encoding"}
160
+ ))
161
+ content = raw_bytes.decode("utf-8", errors="replace")
162
+
163
+ # Zero-width spaces
164
+ if "\u200b" in content or "\ufeff" in content:
165
+ issues.append(DiagnosticIssue(
166
+ category="encoding",
167
+ severity="warning",
168
+ file_path=str(path),
169
+ line=1,
170
+ message="File contains hidden zero-width spaces causing phantom syntax bugs",
171
+ suggested_fix="Strip zero-width characters",
172
+ auto_fixable=True,
173
+ metadata={"action": "strip_zero_width"}
174
+ ))
175
+
176
+ # Check AST parse
177
+ try:
178
+ tree = ast.parse(content, filename=str(path))
179
+ except SyntaxError as se:
180
+ # Analyze syntax error reason
181
+ err_line = se.lineno or 1
182
+ err_msg = se.msg or "Syntax error"
183
+ suggested = "Fix syntax error"
184
+ action = "syntax_fix"
185
+
186
+ lines = content.splitlines()
187
+ if 0 < err_line <= len(lines):
188
+ line_str = lines[err_line - 1].strip()
189
+ # Check missing colon
190
+ block_starters = ("def ", "class ", "if ", "elif ", "else", "try", "except", "finally", "for ", "while ", "with ")
191
+ if any(line_str.startswith(b) for b in block_starters) and not line_str.endswith(":"):
192
+ suggested = "Append missing colon ':' to block definition"
193
+ action = "append_colon"
194
+ # Check Python 2 print
195
+ elif re.match(r"^print\s+[\"'].*", line_str):
196
+ suggested = "Convert Python 2 print statement to print(...) function call"
197
+ action = "convert_print2"
198
+
199
+ issues.append(DiagnosticIssue(
200
+ category="syntax",
201
+ severity="error",
202
+ file_path=str(path),
203
+ line=err_line,
204
+ message=f"SyntaxError: {err_msg} on line {err_line}",
205
+ suggested_fix=suggested,
206
+ auto_fixable=True,
207
+ metadata={"action": action, "lineno": err_line}
208
+ ))
209
+ return issues
210
+
211
+ # Check missing top-level standard library imports
212
+ imported_symbols: Set[str] = set()
213
+ for node in ast.walk(tree):
214
+ if isinstance(node, ast.Import):
215
+ for alias in node.names:
216
+ imported_symbols.add(alias.name.split(".")[0])
217
+ imported_symbols.add(alias.asname or alias.name)
218
+ elif isinstance(node, ast.ImportFrom):
219
+ for alias in node.names:
220
+ imported_symbols.add(alias.asname or alias.name)
221
+
222
+ referenced_names: Set[str] = set()
223
+ for node in ast.walk(tree):
224
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
225
+ referenced_names.add(node.id)
226
+
227
+ # Builtins
228
+ builtins_set = set(dir(__builtins__))
229
+
230
+ for sym, import_stmt in cls.COMMON_STDLIB_SYMBOLS.items():
231
+ if sym in referenced_names and sym not in imported_symbols and sym not in builtins_set:
232
+ issues.append(DiagnosticIssue(
233
+ category="import",
234
+ severity="warning",
235
+ file_path=str(path),
236
+ line=1,
237
+ message=f"Referenced symbol '{sym}' is missing explicit import statement",
238
+ suggested_fix=f"Add '{import_stmt}' at top of file",
239
+ auto_fixable=True,
240
+ metadata={"action": "add_import", "symbol": sym, "stmt": import_stmt}
241
+ ))
242
+
243
+ return issues
244
+
245
+ @classmethod
246
+ def scan_cache_and_bloat(cls, target_dir: str = ".") -> List[DiagnosticIssue]:
247
+ """Scan for orphaned .pyc files, stale git locks, and bloated caches."""
248
+ issues: List[DiagnosticIssue] = []
249
+ root = Path(target_dir).resolve()
250
+
251
+ # Check stale .git/index.lock
252
+ git_lock = root / ".git" / "index.lock"
253
+ if git_lock.is_file():
254
+ age_sec = time.time() - os.path.getmtime(git_lock)
255
+ if age_sec > 300: # older than 5 minutes
256
+ issues.append(DiagnosticIssue(
257
+ category="cache",
258
+ severity="warning",
259
+ file_path=str(git_lock),
260
+ line=None,
261
+ message=f"Stale git lockfile detected ({int(age_sec)}s old) blocking git operations",
262
+ suggested_fix="Remove stale .git/index.lock",
263
+ auto_fixable=True,
264
+ metadata={"action": "remove_file", "path": str(git_lock)}
265
+ ))
266
+
267
+ # Check orphaned .pyc in __pycache__
268
+ for root_dir, dirs, files in os.walk(str(root)):
269
+ # skip ignored
270
+ dirs[:] = [d for d in dirs if d not in cls.IGNORE_DIRS or d == "__pycache__"]
271
+ if os.path.basename(root_dir) == "__pycache__":
272
+ parent_dir = Path(root_dir).parent
273
+ for f in files:
274
+ if f.endswith(".pyc"):
275
+ base_name = f.split(".")[0]
276
+ py_sibling = parent_dir / f"{base_name}.py"
277
+ if not py_sibling.is_file():
278
+ pyc_path = os.path.join(root_dir, f)
279
+ issues.append(DiagnosticIssue(
280
+ category="cache",
281
+ severity="info",
282
+ file_path=pyc_path,
283
+ line=None,
284
+ message=f"Orphaned bytecode {f} has no corresponding .py source file",
285
+ suggested_fix="Purge orphaned bytecode",
286
+ auto_fixable=True,
287
+ metadata={"action": "remove_file", "path": pyc_path}
288
+ ))
289
+
290
+ return issues
291
+
292
+ @classmethod
293
+ def diagnose(cls, target_dir: str = ".") -> DiagnosticReport:
294
+ """Run comprehensive diagnostic inspection across environment, workspace, and files."""
295
+ root = Path(target_dir).resolve()
296
+ tools_status = cls.check_tools_on_path()
297
+ venv_status = cls.inspect_virtualenv(target_dir)
298
+
299
+ issues: List[DiagnosticIssue] = []
300
+
301
+ # Check Python version
302
+ py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
303
+ if sys.version_info < (3, 9):
304
+ issues.append(DiagnosticIssue(
305
+ category="env",
306
+ severity="error",
307
+ file_path=None,
308
+ line=None,
309
+ message=f"Python version {py_ver} is below minimum supported 3.9",
310
+ suggested_fix="Upgrade Python to 3.9 or higher",
311
+ auto_fixable=False
312
+ ))
313
+
314
+ # Check venv
315
+ if venv_status.get("detected") and not venv_status.get("valid"):
316
+ issues.append(DiagnosticIssue(
317
+ category="env",
318
+ severity="error",
319
+ file_path=os.path.join(venv_status["path"], "pyvenv.cfg"),
320
+ line=None,
321
+ message=f"Virtualenv corrupted: {venv_status.get('error')}",
322
+ suggested_fix="Re-point pyvenv.cfg home to active python interpreter",
323
+ auto_fixable=True,
324
+ metadata={"action": "repair_venv_cfg", "path": venv_status["path"]}
325
+ ))
326
+
327
+ # Scan files
328
+ for root_dir, dirs, files in os.walk(str(root)):
329
+ dirs[:] = [d for d in dirs if d not in cls.IGNORE_DIRS]
330
+ for file in files:
331
+ if file.endswith(".py"):
332
+ full_path = os.path.join(root_dir, file)
333
+ issues.extend(cls.scan_syntax_and_imports(full_path))
334
+
335
+ # Scan cache & bloat
336
+ issues.extend(cls.scan_cache_and_bloat(target_dir))
337
+
338
+ # Tally counts
339
+ syntax_errors = sum(1 for i in issues if i.category == "syntax")
340
+ missing_imports = sum(1 for i in issues if i.category == "import")
341
+ env_issues = sum(1 for i in issues if i.category == "env")
342
+ cache_issues = sum(1 for i in issues if i.category in ("cache", "encoding"))
343
+
344
+ # Health score calculation
345
+ penalty = (syntax_errors * 20) + (missing_imports * 5) + (env_issues * 15) + (cache_issues * 2)
346
+ score = max(0, min(100, 100 - penalty))
347
+
348
+ return DiagnosticReport(
349
+ timestamp=time.time(),
350
+ target_dir=str(root),
351
+ health_score_pct=score,
352
+ total_issues=len(issues),
353
+ syntax_errors=syntax_errors,
354
+ missing_imports=missing_imports,
355
+ env_issues=env_issues,
356
+ cache_issues=cache_issues,
357
+ issues=issues,
358
+ tools_status=tools_status,
359
+ python_version=py_ver,
360
+ virtualenv_status=venv_status
361
+ )
362
+
363
+ @classmethod
364
+ def auto_heal(cls, target_dir: str = ".", dry_run: bool = False,
365
+ fix_syntax: bool = True, add_imports: bool = True,
366
+ clean_caches: bool = True, repair_venv: bool = True) -> HealReport:
367
+ """Execute autonomous self-healing for detected codebase and environment issues."""
368
+ diag_before = cls.diagnose(target_dir)
369
+ actions: List[HealAction] = []
370
+
371
+ files_to_recheck: Set[str] = set()
372
+
373
+ for issue in diag_before.issues:
374
+ action_type = issue.metadata.get("action")
375
+ if not issue.auto_fixable or not action_type:
376
+ continue
377
+
378
+ # 1. Clean UTF-8 BOM or Zero-width chars
379
+ if action_type in ("strip_bom", "strip_zero_width", "fix_encoding") and issue.file_path:
380
+ try:
381
+ p = Path(issue.file_path)
382
+ with open(p, "rb") as f:
383
+ data = f.read()
384
+ if action_type == "strip_bom" and data.startswith(b"\xef\xbb\xbf"):
385
+ data = data[3:]
386
+ text = data.decode("utf-8", errors="replace")
387
+ if action_type == "strip_zero_width":
388
+ text = text.replace("\u200b", "").replace("\ufeff", "")
389
+ if not dry_run:
390
+ with open(p, "w", encoding="utf-8", newline="\n") as f:
391
+ f.write(text)
392
+ actions.append(HealAction(
393
+ category="encoding",
394
+ file_path=issue.file_path,
395
+ description=f"Sanitized encoding/BOM in {p.name}",
396
+ success=True
397
+ ))
398
+ files_to_recheck.add(issue.file_path)
399
+ except Exception as e:
400
+ actions.append(HealAction(
401
+ category="encoding",
402
+ file_path=issue.file_path,
403
+ description=f"Failed sanitizing encoding: {e}",
404
+ success=False
405
+ ))
406
+
407
+ # 2. Fix syntax errors (missing colon, Python 2 print)
408
+ elif action_type in ("append_colon", "convert_print2") and fix_syntax and issue.file_path:
409
+ try:
410
+ p = Path(issue.file_path)
411
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
412
+ lines = f.readlines()
413
+ lineno = issue.metadata.get("lineno", 1)
414
+ if 0 < lineno <= len(lines):
415
+ orig_line = lines[lineno - 1]
416
+ mod_line = orig_line
417
+ if action_type == "append_colon":
418
+ mod_line = orig_line.rstrip("\r\n") + ":\n"
419
+ elif action_type == "convert_print2":
420
+ mod_line = re.sub(r"^(\s*)print\s+(.*)$", r"\1print(\2)", orig_line)
421
+
422
+ if orig_line != mod_line:
423
+ diff = "".join(difflib.unified_diff(
424
+ [orig_line], [mod_line], fromfile="before", tofile="after"
425
+ ))
426
+ lines[lineno - 1] = mod_line
427
+ if not dry_run:
428
+ with open(p, "w", encoding="utf-8", newline="\n") as f:
429
+ f.writelines(lines)
430
+ actions.append(HealAction(
431
+ category="syntax",
432
+ file_path=issue.file_path,
433
+ description=f"Patched {action_type} on line {lineno} of {p.name}",
434
+ success=True,
435
+ diff=diff
436
+ ))
437
+ files_to_recheck.add(issue.file_path)
438
+ except Exception as e:
439
+ actions.append(HealAction(
440
+ category="syntax",
441
+ file_path=issue.file_path,
442
+ description=f"Failed patching syntax: {e}",
443
+ success=False
444
+ ))
445
+
446
+ # 3. Add missing standard library import
447
+ elif action_type == "add_import" and add_imports and issue.file_path:
448
+ try:
449
+ p = Path(issue.file_path)
450
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
451
+ lines = f.readlines()
452
+ stmt = issue.metadata.get("stmt")
453
+ if stmt:
454
+ # Find safe insert location (after future imports / docstring or line 0)
455
+ insert_idx = 0
456
+ for idx, l in enumerate(lines[:15]):
457
+ if l.startswith("#") or "coding:" in l or l.startswith('"""') or l.startswith("'''"):
458
+ insert_idx = idx + 1
459
+ elif l.startswith("from __future__"):
460
+ insert_idx = idx + 1
461
+
462
+ lines.insert(insert_idx, f"{stmt}\n")
463
+ diff = f"+ {stmt}\n"
464
+ if not dry_run:
465
+ with open(p, "w", encoding="utf-8", newline="\n") as f:
466
+ f.writelines(lines)
467
+ actions.append(HealAction(
468
+ category="import",
469
+ file_path=issue.file_path,
470
+ description=f"Injected missing '{stmt}' into {p.name}",
471
+ success=True,
472
+ diff=diff
473
+ ))
474
+ files_to_recheck.add(issue.file_path)
475
+ except Exception as e:
476
+ actions.append(HealAction(
477
+ category="import",
478
+ file_path=issue.file_path,
479
+ description=f"Failed adding import: {e}",
480
+ success=False
481
+ ))
482
+
483
+ # 4. Remove stale lockfiles or orphaned bytecode
484
+ elif action_type == "remove_file" and clean_caches:
485
+ target_path = issue.metadata.get("path") or issue.file_path
486
+ if target_path and os.path.exists(target_path):
487
+ try:
488
+ if not dry_run:
489
+ os.remove(target_path)
490
+ actions.append(HealAction(
491
+ category="cache",
492
+ file_path=target_path,
493
+ description=f"Purged {os.path.basename(target_path)}",
494
+ success=True
495
+ ))
496
+ except Exception as e:
497
+ actions.append(HealAction(
498
+ category="cache",
499
+ file_path=target_path,
500
+ description=f"Failed removing {target_path}: {e}",
501
+ success=False
502
+ ))
503
+
504
+ # 5. Repair virtualenv config
505
+ elif action_type == "repair_venv_cfg" and repair_venv:
506
+ venv_dir = issue.metadata.get("path")
507
+ if venv_dir:
508
+ cfg_file = os.path.join(venv_dir, "pyvenv.cfg")
509
+ curr_py_home = os.path.dirname(sys.executable)
510
+ try:
511
+ lines = []
512
+ if os.path.isfile(cfg_file):
513
+ with open(cfg_file, "r", encoding="utf-8", errors="replace") as f:
514
+ for line in f:
515
+ if line.strip().startswith("home ="):
516
+ lines.append(f"home = {curr_py_home}\n")
517
+ else:
518
+ lines.append(line)
519
+ if not dry_run:
520
+ with open(cfg_file, "w", encoding="utf-8", newline="\n") as f:
521
+ f.writelines(lines)
522
+ actions.append(HealAction(
523
+ category="env",
524
+ file_path=cfg_file,
525
+ description=f"Updated pyvenv.cfg home path to '{curr_py_home}'",
526
+ success=True
527
+ ))
528
+ except Exception as e:
529
+ actions.append(HealAction(
530
+ category="env",
531
+ file_path=cfg_file,
532
+ description=f"Failed updating pyvenv.cfg: {e}",
533
+ success=False
534
+ ))
535
+
536
+ # Re-diagnose to evaluate final score
537
+ diag_after = cls.diagnose(target_dir) if not dry_run else diag_before
538
+ successful_heals = sum(1 for a in actions if a.success)
539
+
540
+ return HealReport(
541
+ timestamp=time.time(),
542
+ target_dir=str(Path(target_dir).resolve()),
543
+ initial_health_score=diag_before.health_score_pct,
544
+ final_health_score=diag_after.health_score_pct,
545
+ issues_detected=diag_before.total_issues,
546
+ issues_healed=successful_heals,
547
+ dry_run=dry_run,
548
+ actions=actions
549
+ )
550
+
551
+ @classmethod
552
+ def render_cli(cls, report: DiagnosticReport, heal_report: Optional[HealReport] = None):
553
+ """Render beautiful, ANSI-colored doctor report to terminal."""
554
+ print("=" * 80)
555
+ print("\033[1;36m🩺 T-ZERO PC-FIXER & ENVIRONMENT AUTONOMOUS DOCTOR\033[0m")
556
+ print("=" * 80)
557
+ print(f"Target Directory: \033[33m{report.target_dir}\033[0m")
558
+ print(f"Python Runtime: \033[32mv{report.python_version}\033[0m ({sys.executable})")
559
+ print(f"Virtualenv: \033[32m{report.virtualenv_status.get('path') or 'Global / System'}\033[0m")
560
+
561
+ # Tools status
562
+ tools_str = " ".join([
563
+ f"\033[32m[OK] {t}\033[0m" if ok else f"\033[31m[--] {t}\033[0m"
564
+ for t, ok in report.tools_status.items()
565
+ ])
566
+ print(f"CLI Tools: {tools_str}")
567
+
568
+ score_color = "\033[32m" if report.health_score_pct >= 90 else ("\033[33m" if report.health_score_pct >= 70 else "\033[31m")
569
+ print(f"Health Score: {score_color}{report.health_score_pct} / 100\033[0m")
570
+ print("-" * 80)
571
+
572
+ if report.total_issues == 0:
573
+ print("\033[32m✨ Codebase and Environment are in 100% pristine condition! Zero issues found.\033[0m")
574
+ else:
575
+ print(f"Detected Issues: \033[1;31m{report.total_issues}\033[0m "
576
+ f"(Syntax: {report.syntax_errors}, Imports: {report.missing_imports}, "
577
+ f"Env: {report.env_issues}, Cache: {report.cache_issues})")
578
+ print()
579
+ for idx, issue in enumerate(report.issues[:15], start=1):
580
+ loc = f"{os.path.basename(issue.file_path or 'system')}:{issue.line or '-'}"
581
+ icon = "\033[31m[FAIL]\033[0m" if issue.severity == "error" else "\033[33m[WARN]\033[0m"
582
+ print(f" {idx:2d}. {icon} \033[1m{loc:<22}\033[0m {issue.message}")
583
+ print(f" \033[36mFix:\033[0m {issue.suggested_fix}")
584
+
585
+ if len(report.issues) > 15:
586
+ print(f" ... and {len(report.issues) - 15} more issues.")
587
+
588
+ if heal_report:
589
+ print("-" * 80)
590
+ print("\033[1;32m💉 AUTONOMOUS SELF-HEALING RESULTS:\033[0m")
591
+ print(f" Issues Healed: \033[32m{heal_report.issues_healed} / {heal_report.issues_detected}\033[0m")
592
+ print(f" Health Boost: \033[33m{heal_report.initial_health_score}%\033[0m -> \033[1;32m{heal_report.final_health_score}%\033[0m")
593
+ for a in heal_report.actions:
594
+ status_icon = "\033[32m✔\033[0m" if a.success else "\033[31m✘\033[0m"
595
+ print(f" {status_icon} [{a.category.upper()}] {a.description}")
596
+ if a.diff:
597
+ for dline in a.diff.splitlines()[:3]:
598
+ print(f" \033[35m{dline}\033[0m")
599
+
600
+ print("=" * 80)