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,385 +1,385 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Autonomous PC-Fixer & Codebase Doctor: Core Models and Enums.
3
-
4
- Defines all diagnostic entities, severity tiers, platform descriptors,
5
- diff structures, transactional rollback manifests, and reporting schemas.
6
-
7
- Author: Toprak Ahmet Aydogmus (Siber Akademi)
8
- Version: 10.5.0
9
- Master Edition / Security Certified Zero-Leak
10
- """
11
-
12
- import enum
13
- import json
14
- import os
15
- import sys
16
- import time
17
- from dataclasses import asdict, dataclass, field
18
- from pathlib import Path
19
- from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
20
-
21
-
22
- class SeverityLevel(enum.Enum):
23
- """Severity classification for diagnostic issues."""
24
- CRITICAL = "critical" # Code fails to parse, interpreter won't start, secrets leaked
25
- ERROR = "error" # Runtime crash, missing import, broken virtualenv
26
- WARNING = "warning" # Anti-pattern, circular import, deprecated API, stale lock
27
- INFO = "info" # Orphaned bytecode, optimization advice, code smell
28
- CLEAN = "clean" # Perfectly healthy check
29
-
30
- @property
31
- def ansi_color(self) -> str:
32
- if self == SeverityLevel.CRITICAL:
33
- return "\033[1;31m" # Bold Red
34
- elif self == SeverityLevel.ERROR:
35
- return "\033[31m" # Red
36
- elif self == SeverityLevel.WARNING:
37
- return "\033[33m" # Yellow
38
- elif self == SeverityLevel.INFO:
39
- return "\033[36m" # Cyan
40
- return "\033[32m" # Green
41
-
42
- @property
43
- def badge(self) -> str:
44
- if self == SeverityLevel.CRITICAL:
45
- return "[CRIT]"
46
- elif self == SeverityLevel.ERROR:
47
- return "[FAIL]"
48
- elif self == SeverityLevel.WARNING:
49
- return "[WARN]"
50
- elif self == SeverityLevel.INFO:
51
- return "[INFO]"
52
- return "[PASS]"
53
-
54
-
55
- class DiagnosticCategory(enum.Enum):
56
- """Category classification for doctor checks."""
57
- SYNTAX = "syntax" # AST syntax, indentation, unclosed strings, delimiters
58
- IMPORTS = "imports" # Missing imports, dead imports, circular dependency cycles
59
- ENVIRONMENT = "environment" # Python runtime, virtualenvs, PATH tools, shims
60
- SECURITY = "security" # Hardcoded secrets, insecure deserialization, SQL injection
61
- SMELLS = "smells" # Mutable defaults, bare except, unclosed file handles
62
- ENCODING = "encoding" # UTF-8 BOM, zero-width characters, non-ascii noise
63
- CACHE = "cache" # Orphaned .pyc files, stale .git locks, temp bloat
64
- POLYGLOT = "polyglot" # Node, Rust, Go, Git, Docker system diagnostics
65
- TYPE_HINTS = "type_hints" # PEP-484 / 585 / 604 type annotation modernizations
66
- PERFORMANCE = "performance" # Quadratic string concatenations, memory leaks
67
- WORKSPACE = "workspace" # Workspace layout, git, VCS, locks, editorconfig
68
- DEPENDENCY = "dependency" # PEP 517 build, virtualenv packages, ABI drift
69
-
70
-
71
- # Backward & forward compatibility alias bindings
72
- DiagnosticCategory.PYTHON_SYNTAX = DiagnosticCategory.SYNTAX # type: ignore
73
- DiagnosticCategory.CODE_SMELLS = DiagnosticCategory.SMELLS # type: ignore
74
- DiagnosticCategory.SECURITY_CREDENTIAL = DiagnosticCategory.SECURITY # type: ignore
75
- DiagnosticCategory.POLYGLOT_CONFIG = DiagnosticCategory.POLYGLOT # type: ignore
76
- DiagnosticCategory.SYSTEM_ENVIRONMENT = DiagnosticCategory.ENVIRONMENT # type: ignore
77
-
78
-
79
- class SystemPlatform(enum.Enum):
80
- """Host operating system platform."""
81
- WINDOWS = "windows"
82
- LINUX = "linux"
83
- MACOS = "macos"
84
- UNKNOWN = "unknown"
85
-
86
- @classmethod
87
- def current(cls) -> "SystemPlatform":
88
- if sys.platform.startswith("win"):
89
- return cls.WINDOWS
90
- elif sys.platform.startswith("linux"):
91
- return cls.LINUX
92
- elif sys.platform.startswith("darwin"):
93
- return cls.MACOS
94
- return cls.UNKNOWN
95
-
96
-
97
- @dataclass
98
- class DiffHunk:
99
- """Represents a unified diff modification hunk."""
100
- file_path: str
101
- old_start_line: int
102
- old_line_count: int
103
- new_start_line: int
104
- new_line_count: int
105
- header: str
106
- lines: List[str] = field(default_factory=list)
107
-
108
- def to_unified_string(self) -> str:
109
- res = [f"@@ -{self.old_start_line},{self.old_line_count} +{self.new_start_line},{self.new_line_count} @@ {self.header}"]
110
- res.extend(self.lines)
111
- return "\n".join(res)
112
-
113
-
114
- @dataclass
115
- class DiagnosticIssue:
116
- """Represents a single detected diagnostic defect in codebase or environment."""
117
- category: str # Value of DiagnosticCategory
118
- severity: str # Value of SeverityLevel
119
- file_path: Optional[str] = None # Path to source file or system config
120
- line: Optional[int] = None # Line number (1-based), None for workspace/env
121
- column: Optional[int] = None # Column offset (0-based)
122
- error_code: str = "" # e.g., 'TZ-SYN-001', 'TZ-SEC-042', 'TZ-ENV-003'
123
- message: str = "" # Human readable problem statement
124
- suggested_fix: str = "" # Proposed solution or remedy
125
- auto_fixable: bool = True # Can T-Zero auto-heal this defect?
126
- confidence_score: float = 1.0 # 0.0 to 1.0 confidence in auto-heal safety
127
- metadata: Dict[str, Any] = field(default_factory=dict)
128
-
129
- def __init__(
130
- self,
131
- category: Union[str, DiagnosticCategory] = "syntax",
132
- severity: Union[str, SeverityLevel] = "warning",
133
- file_path: Optional[str] = None,
134
- line: Optional[int] = None,
135
- column: Optional[int] = None,
136
- error_code: str = "",
137
- message: str = "",
138
- suggested_fix: str = "",
139
- auto_fixable: bool = True,
140
- confidence_score: float = 1.0,
141
- metadata: Optional[Dict[str, Any]] = None,
142
- # Tolerant alias kwargs:
143
- code: Optional[str] = None,
144
- remediation: Optional[str] = None,
145
- line_number: Optional[int] = None,
146
- suggested_action: Any = None,
147
- **extra: Any,
148
- ):
149
- self.category = category.value if isinstance(category, enum.Enum) else str(category)
150
- self.severity = severity.value if isinstance(severity, enum.Enum) else str(severity)
151
- self.file_path = file_path
152
- self.line = line if line is not None else line_number
153
- self.column = column
154
- self.error_code = error_code or code or ""
155
- self.message = message
156
- self.suggested_fix = suggested_fix or remediation or ""
157
- self.auto_fixable = auto_fixable
158
- self.confidence_score = confidence_score
159
- self.metadata = metadata or {}
160
- if suggested_action:
161
- self.metadata["suggested_action"] = str(suggested_action)
162
- if extra:
163
- self.metadata.update(extra)
164
-
165
- @property
166
- def code(self) -> str:
167
- return self.error_code
168
-
169
- @property
170
- def remediation(self) -> str:
171
- return self.suggested_fix
172
-
173
- @property
174
- def line_number(self) -> Optional[int]:
175
- return self.line
176
-
177
- def to_dict(self) -> Dict[str, Any]:
178
- return asdict(self)
179
-
180
- @property
181
- def formatted_location(self) -> str:
182
- if not self.file_path:
183
- return "system"
184
- bname = os.path.basename(self.file_path)
185
- if self.line is not None:
186
- if self.column is not None:
187
- return f"{bname}:{self.line}:{self.column}"
188
- return f"{bname}:{self.line}"
189
- return bname
190
-
191
-
192
- @dataclass
193
- class HealAction:
194
- """Record of a surgical repair action executed on disk or in memory."""
195
- category: str = "workspace" # Value of DiagnosticCategory
196
- file_path: Optional[str] = None # Target file modified
197
- description: str = "" # Summary of action
198
- success: bool = True # Did the patch succeed?
199
- diff: Optional[str] = None # Unified diff preview
200
- action_type: str = "patch" # e.g., 'append_colon', 'inject_import', 'strip_bom'
201
- backup_path: Optional[str] = None # Path to original file snapshot in rollback buffer
202
- duration_ms: float = 0.0 # Execution latency in milliseconds
203
- metadata: Dict[str, Any] = field(default_factory=dict)
204
-
205
- def __init__(
206
- self,
207
- category: Optional[Any] = None,
208
- file_path: Optional[str] = None,
209
- description: str = "",
210
- success: bool = True,
211
- diff: Optional[str] = None,
212
- action_type: str = "patch",
213
- backup_path: Optional[str] = None,
214
- duration_ms: float = 0.0,
215
- metadata: Optional[Dict[str, Any]] = None,
216
- # Tolerant alias kwargs:
217
- issue: Optional[Any] = None,
218
- details: Optional[str] = None,
219
- **extra: Any,
220
- ):
221
- if issue is not None:
222
- cat_val = getattr(issue, "category", "workspace")
223
- self.category = cat_val.value if hasattr(cat_val, "value") else str(cat_val)
224
- self.file_path = getattr(issue, "file_path", file_path)
225
- else:
226
- cat_val = category or "workspace"
227
- self.category = cat_val.value if hasattr(cat_val, "value") else str(cat_val)
228
- self.file_path = file_path
229
-
230
- self.description = details if details is not None else description
231
- self.success = success
232
- self.diff = diff
233
- self.action_type = action_type
234
- self.backup_path = backup_path
235
- self.duration_ms = duration_ms
236
- self.metadata = metadata or {}
237
- if extra:
238
- self.metadata.update(extra)
239
-
240
- @property
241
- def details(self) -> str:
242
- return self.description
243
-
244
- def to_dict(self) -> Dict[str, Any]:
245
- return asdict(self)
246
-
247
-
248
- @dataclass
249
- class ToolStatus:
250
- """Status of an external development tool on system PATH."""
251
- name: str # 'git', 'python', 'npm', etc.
252
- available: bool # Found on PATH?
253
- executable_path: Optional[str] # Absolute path to binary
254
- version_str: Optional[str] # Reported version string
255
- is_compatible: bool = True # Compatible with minimum requirements?
256
- notes: Optional[str] = None # Warnings or recommendation notes
257
-
258
-
259
- @dataclass
260
- class EnvironmentSnapshot:
261
- """Detailed health matrix of the host operating system and execution runtime."""
262
- platform: str # 'windows', 'linux', 'macos'
263
- os_release: str # OS version / kernel details
264
- python_version: str # Active interpreter version
265
- python_executable: str # Active sys.executable
266
- python_architecture: str # '64bit' or '32bit'
267
- is_virtualenv_active: bool # Is active interpreter in a venv?
268
- virtualenv_root: Optional[str] # Root directory of virtualenv
269
- virtualenv_valid: bool # Is venv properly linked and uncorrupted?
270
- virtualenv_error: Optional[str] # Diagnostic message if venv broken
271
- cpu_cores: int # Total CPU core count
272
- total_ram_gb: float # Total system memory in Gigabytes
273
- available_ram_gb: float # Available free memory in Gigabytes
274
- temp_dir_path: str # System temporary folder
275
- tools: Dict[str, ToolStatus] = field(default_factory=dict)
276
- env_vars_healthy: bool = True # PATH and critical variables properly formatted?
277
-
278
-
279
- @dataclass
280
- class DiagnosticReport:
281
- """Complete diagnostic audit result across all categories."""
282
- timestamp: float # Epoch seconds
283
- target_dir: str # Workspace scanned
284
- health_score_pct: int # 0 to 100 overall health rating
285
- total_issues: int # Count of all issues detected
286
- syntax_errors: int = 0 # Issues in SYNTAX category
287
- missing_imports: int = 0 # Issues in IMPORTS category
288
- env_issues: int = 0 # Issues in ENVIRONMENT category
289
- cache_issues: int = 0 # Issues in CACHE / ENCODING categories
290
- issues: List[DiagnosticIssue] = field(default_factory=list) # Complete list of issues
291
- critical_count: int = 0 # Count of critical severity issues
292
- error_count: int = 0 # Count of error severity issues
293
- warning_count: int = 0 # Count of warning severity issues
294
- info_count: int = 0 # Count of info/advisory issues
295
- security_leaks: int = 0 # Issues in SECURITY category
296
- code_smells: int = 0 # Issues in SMELLS category
297
- tools_status: Dict[str, bool] = field(default_factory=dict)
298
- python_version: str = ""
299
- virtualenv_status: Dict[str, Any] = field(default_factory=dict)
300
- environment: Optional[EnvironmentSnapshot] = None # Host system environment metrics
301
- scan_duration_ms: float = 0.0 # Time taken to scan in milliseconds
302
- scanned_file_count: int = 0 # Total source files inspected
303
-
304
- def to_dict(self) -> Dict[str, Any]:
305
- return asdict(self)
306
-
307
- def to_sarif(self) -> Dict[str, Any]:
308
- """Convert diagnostic issues to standard OASIS SARIF v2.1.0 format."""
309
- results = []
310
- for issue in self.issues:
311
- level = "error" if issue.severity in ("critical", "error") else ("warning" if issue.severity == "warning" else "note")
312
- loc = {
313
- "physicalLocation": {
314
- "artifactLocation": {"uri": issue.file_path or "system"},
315
- "region": {
316
- "startLine": issue.line or 1,
317
- "startColumn": (issue.column or 0) + 1
318
- }
319
- }
320
- }
321
- results.append({
322
- "ruleId": issue.error_code,
323
- "level": level,
324
- "message": {"text": f"{issue.message}. Suggestion: {issue.suggested_fix}"},
325
- "locations": [loc],
326
- "properties": {"category": issue.category, "autoFixable": issue.auto_fixable}
327
- })
328
-
329
- return {
330
- "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
331
- "version": "2.1.0",
332
- "runs": [{
333
- "tool": {
334
- "driver": {
335
- "name": "T-Zero PC-Fixer Doctor",
336
- "version": "10.5.0",
337
- "informationUri": "https://tzero-indol.vercel.app"
338
- }
339
- },
340
- "results": results
341
- }]
342
- }
343
-
344
-
345
- @dataclass
346
- class RollbackManifest:
347
- """Manifest of files backed up before autonomous healing for atomic rollback."""
348
- transaction_id: str
349
- timestamp: float
350
- target_dir: str
351
- backup_dir: str
352
- backed_up_files: Dict[str, str] = field(default_factory=dict) # original_path -> backup_path
353
-
354
- def save(self, manifest_file: str):
355
- with open(manifest_file, "w", encoding="utf-8") as f:
356
- json.dump(asdict(self), f, indent=2)
357
-
358
- @classmethod
359
- def load(cls, manifest_file: str) -> "RollbackManifest":
360
- with open(manifest_file, "r", encoding="utf-8") as f:
361
- data = json.load(f)
362
- return cls(**data)
363
-
364
-
365
- @dataclass
366
- class HealReport:
367
- """Comprehensive outcome report of autonomous self-healing execution."""
368
- timestamp: float # Execution completion timestamp
369
- target_dir: str # Workspace path
370
- initial_health_score: int # Health score before repair (0-100)
371
- final_health_score: int # Health score after repair (0-100)
372
- issues_detected: int # Total issues initially found
373
- issues_healed: int # Total issues successfully repaired
374
- dry_run: bool # True if preview mode without writing
375
- actions: List[HealAction] # List of individual repair operations
376
- transaction_id: str = "" # Unique ID for rollback tracking
377
- backup_manifest: Optional[RollbackManifest] = None
378
- execution_duration_ms: float = 0.0 # Total time taken in milliseconds
379
-
380
- def to_dict(self) -> Dict[str, Any]:
381
- return asdict(self)
382
-
383
- @property
384
- def is_fully_healthy(self) -> bool:
385
- return self.final_health_score >= 95
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Autonomous PC-Fixer & Codebase Doctor: Core Models and Enums.
3
+
4
+ Defines all diagnostic entities, severity tiers, platform descriptors,
5
+ diff structures, transactional rollback manifests, and reporting schemas.
6
+
7
+ Author: Toprak Ahmet Aydogmus (Siber Akademi)
8
+ Version: 10.5.0
9
+ Master Edition / Security Certified Zero-Leak
10
+ """
11
+
12
+ import enum
13
+ import json
14
+ import os
15
+ import sys
16
+ import time
17
+ from dataclasses import asdict, dataclass, field
18
+ from pathlib import Path
19
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
20
+
21
+
22
+ class SeverityLevel(enum.Enum):
23
+ """Severity classification for diagnostic issues."""
24
+ CRITICAL = "critical" # Code fails to parse, interpreter won't start, secrets leaked
25
+ ERROR = "error" # Runtime crash, missing import, broken virtualenv
26
+ WARNING = "warning" # Anti-pattern, circular import, deprecated API, stale lock
27
+ INFO = "info" # Orphaned bytecode, optimization advice, code smell
28
+ CLEAN = "clean" # Perfectly healthy check
29
+
30
+ @property
31
+ def ansi_color(self) -> str:
32
+ if self == SeverityLevel.CRITICAL:
33
+ return "\033[1;31m" # Bold Red
34
+ elif self == SeverityLevel.ERROR:
35
+ return "\033[31m" # Red
36
+ elif self == SeverityLevel.WARNING:
37
+ return "\033[33m" # Yellow
38
+ elif self == SeverityLevel.INFO:
39
+ return "\033[36m" # Cyan
40
+ return "\033[32m" # Green
41
+
42
+ @property
43
+ def badge(self) -> str:
44
+ if self == SeverityLevel.CRITICAL:
45
+ return "[CRIT]"
46
+ elif self == SeverityLevel.ERROR:
47
+ return "[FAIL]"
48
+ elif self == SeverityLevel.WARNING:
49
+ return "[WARN]"
50
+ elif self == SeverityLevel.INFO:
51
+ return "[INFO]"
52
+ return "[PASS]"
53
+
54
+
55
+ class DiagnosticCategory(enum.Enum):
56
+ """Category classification for doctor checks."""
57
+ SYNTAX = "syntax" # AST syntax, indentation, unclosed strings, delimiters
58
+ IMPORTS = "imports" # Missing imports, dead imports, circular dependency cycles
59
+ ENVIRONMENT = "environment" # Python runtime, virtualenvs, PATH tools, shims
60
+ SECURITY = "security" # Hardcoded secrets, insecure deserialization, SQL injection
61
+ SMELLS = "smells" # Mutable defaults, bare except, unclosed file handles
62
+ ENCODING = "encoding" # UTF-8 BOM, zero-width characters, non-ascii noise
63
+ CACHE = "cache" # Orphaned .pyc files, stale .git locks, temp bloat
64
+ POLYGLOT = "polyglot" # Node, Rust, Go, Git, Docker system diagnostics
65
+ TYPE_HINTS = "type_hints" # PEP-484 / 585 / 604 type annotation modernizations
66
+ PERFORMANCE = "performance" # Quadratic string concatenations, memory leaks
67
+ WORKSPACE = "workspace" # Workspace layout, git, VCS, locks, editorconfig
68
+ DEPENDENCY = "dependency" # PEP 517 build, virtualenv packages, ABI drift
69
+
70
+
71
+ # Backward & forward compatibility alias bindings
72
+ DiagnosticCategory.PYTHON_SYNTAX = DiagnosticCategory.SYNTAX # type: ignore
73
+ DiagnosticCategory.CODE_SMELLS = DiagnosticCategory.SMELLS # type: ignore
74
+ DiagnosticCategory.SECURITY_CREDENTIAL = DiagnosticCategory.SECURITY # type: ignore
75
+ DiagnosticCategory.POLYGLOT_CONFIG = DiagnosticCategory.POLYGLOT # type: ignore
76
+ DiagnosticCategory.SYSTEM_ENVIRONMENT = DiagnosticCategory.ENVIRONMENT # type: ignore
77
+
78
+
79
+ class SystemPlatform(enum.Enum):
80
+ """Host operating system platform."""
81
+ WINDOWS = "windows"
82
+ LINUX = "linux"
83
+ MACOS = "macos"
84
+ UNKNOWN = "unknown"
85
+
86
+ @classmethod
87
+ def current(cls) -> "SystemPlatform":
88
+ if sys.platform.startswith("win"):
89
+ return cls.WINDOWS
90
+ elif sys.platform.startswith("linux"):
91
+ return cls.LINUX
92
+ elif sys.platform.startswith("darwin"):
93
+ return cls.MACOS
94
+ return cls.UNKNOWN
95
+
96
+
97
+ @dataclass
98
+ class DiffHunk:
99
+ """Represents a unified diff modification hunk."""
100
+ file_path: str
101
+ old_start_line: int
102
+ old_line_count: int
103
+ new_start_line: int
104
+ new_line_count: int
105
+ header: str
106
+ lines: List[str] = field(default_factory=list)
107
+
108
+ def to_unified_string(self) -> str:
109
+ res = [f"@@ -{self.old_start_line},{self.old_line_count} +{self.new_start_line},{self.new_line_count} @@ {self.header}"]
110
+ res.extend(self.lines)
111
+ return "\n".join(res)
112
+
113
+
114
+ @dataclass
115
+ class DiagnosticIssue:
116
+ """Represents a single detected diagnostic defect in codebase or environment."""
117
+ category: str # Value of DiagnosticCategory
118
+ severity: str # Value of SeverityLevel
119
+ file_path: Optional[str] = None # Path to source file or system config
120
+ line: Optional[int] = None # Line number (1-based), None for workspace/env
121
+ column: Optional[int] = None # Column offset (0-based)
122
+ error_code: str = "" # e.g., 'TZ-SYN-001', 'TZ-SEC-042', 'TZ-ENV-003'
123
+ message: str = "" # Human readable problem statement
124
+ suggested_fix: str = "" # Proposed solution or remedy
125
+ auto_fixable: bool = True # Can T-Zero auto-heal this defect?
126
+ confidence_score: float = 1.0 # 0.0 to 1.0 confidence in auto-heal safety
127
+ metadata: Dict[str, Any] = field(default_factory=dict)
128
+
129
+ def __init__(
130
+ self,
131
+ category: Union[str, DiagnosticCategory] = "syntax",
132
+ severity: Union[str, SeverityLevel] = "warning",
133
+ file_path: Optional[str] = None,
134
+ line: Optional[int] = None,
135
+ column: Optional[int] = None,
136
+ error_code: str = "",
137
+ message: str = "",
138
+ suggested_fix: str = "",
139
+ auto_fixable: bool = True,
140
+ confidence_score: float = 1.0,
141
+ metadata: Optional[Dict[str, Any]] = None,
142
+ # Tolerant alias kwargs:
143
+ code: Optional[str] = None,
144
+ remediation: Optional[str] = None,
145
+ line_number: Optional[int] = None,
146
+ suggested_action: Any = None,
147
+ **extra: Any,
148
+ ):
149
+ self.category = category.value if isinstance(category, enum.Enum) else str(category)
150
+ self.severity = severity.value if isinstance(severity, enum.Enum) else str(severity)
151
+ self.file_path = file_path
152
+ self.line = line if line is not None else line_number
153
+ self.column = column
154
+ self.error_code = error_code or code or ""
155
+ self.message = message
156
+ self.suggested_fix = suggested_fix or remediation or ""
157
+ self.auto_fixable = auto_fixable
158
+ self.confidence_score = confidence_score
159
+ self.metadata = metadata or {}
160
+ if suggested_action:
161
+ self.metadata["suggested_action"] = str(suggested_action)
162
+ if extra:
163
+ self.metadata.update(extra)
164
+
165
+ @property
166
+ def code(self) -> str:
167
+ return self.error_code
168
+
169
+ @property
170
+ def remediation(self) -> str:
171
+ return self.suggested_fix
172
+
173
+ @property
174
+ def line_number(self) -> Optional[int]:
175
+ return self.line
176
+
177
+ def to_dict(self) -> Dict[str, Any]:
178
+ return asdict(self)
179
+
180
+ @property
181
+ def formatted_location(self) -> str:
182
+ if not self.file_path:
183
+ return "system"
184
+ bname = os.path.basename(self.file_path)
185
+ if self.line is not None:
186
+ if self.column is not None:
187
+ return f"{bname}:{self.line}:{self.column}"
188
+ return f"{bname}:{self.line}"
189
+ return bname
190
+
191
+
192
+ @dataclass
193
+ class HealAction:
194
+ """Record of a surgical repair action executed on disk or in memory."""
195
+ category: str = "workspace" # Value of DiagnosticCategory
196
+ file_path: Optional[str] = None # Target file modified
197
+ description: str = "" # Summary of action
198
+ success: bool = True # Did the patch succeed?
199
+ diff: Optional[str] = None # Unified diff preview
200
+ action_type: str = "patch" # e.g., 'append_colon', 'inject_import', 'strip_bom'
201
+ backup_path: Optional[str] = None # Path to original file snapshot in rollback buffer
202
+ duration_ms: float = 0.0 # Execution latency in milliseconds
203
+ metadata: Dict[str, Any] = field(default_factory=dict)
204
+
205
+ def __init__(
206
+ self,
207
+ category: Optional[Any] = None,
208
+ file_path: Optional[str] = None,
209
+ description: str = "",
210
+ success: bool = True,
211
+ diff: Optional[str] = None,
212
+ action_type: str = "patch",
213
+ backup_path: Optional[str] = None,
214
+ duration_ms: float = 0.0,
215
+ metadata: Optional[Dict[str, Any]] = None,
216
+ # Tolerant alias kwargs:
217
+ issue: Optional[Any] = None,
218
+ details: Optional[str] = None,
219
+ **extra: Any,
220
+ ):
221
+ if issue is not None:
222
+ cat_val = getattr(issue, "category", "workspace")
223
+ self.category = cat_val.value if hasattr(cat_val, "value") else str(cat_val)
224
+ self.file_path = getattr(issue, "file_path", file_path)
225
+ else:
226
+ cat_val = category or "workspace"
227
+ self.category = cat_val.value if hasattr(cat_val, "value") else str(cat_val)
228
+ self.file_path = file_path
229
+
230
+ self.description = details if details is not None else description
231
+ self.success = success
232
+ self.diff = diff
233
+ self.action_type = action_type
234
+ self.backup_path = backup_path
235
+ self.duration_ms = duration_ms
236
+ self.metadata = metadata or {}
237
+ if extra:
238
+ self.metadata.update(extra)
239
+
240
+ @property
241
+ def details(self) -> str:
242
+ return self.description
243
+
244
+ def to_dict(self) -> Dict[str, Any]:
245
+ return asdict(self)
246
+
247
+
248
+ @dataclass
249
+ class ToolStatus:
250
+ """Status of an external development tool on system PATH."""
251
+ name: str # 'git', 'python', 'npm', etc.
252
+ available: bool # Found on PATH?
253
+ executable_path: Optional[str] # Absolute path to binary
254
+ version_str: Optional[str] # Reported version string
255
+ is_compatible: bool = True # Compatible with minimum requirements?
256
+ notes: Optional[str] = None # Warnings or recommendation notes
257
+
258
+
259
+ @dataclass
260
+ class EnvironmentSnapshot:
261
+ """Detailed health matrix of the host operating system and execution runtime."""
262
+ platform: str # 'windows', 'linux', 'macos'
263
+ os_release: str # OS version / kernel details
264
+ python_version: str # Active interpreter version
265
+ python_executable: str # Active sys.executable
266
+ python_architecture: str # '64bit' or '32bit'
267
+ is_virtualenv_active: bool # Is active interpreter in a venv?
268
+ virtualenv_root: Optional[str] # Root directory of virtualenv
269
+ virtualenv_valid: bool # Is venv properly linked and uncorrupted?
270
+ virtualenv_error: Optional[str] # Diagnostic message if venv broken
271
+ cpu_cores: int # Total CPU core count
272
+ total_ram_gb: float # Total system memory in Gigabytes
273
+ available_ram_gb: float # Available free memory in Gigabytes
274
+ temp_dir_path: str # System temporary folder
275
+ tools: Dict[str, ToolStatus] = field(default_factory=dict)
276
+ env_vars_healthy: bool = True # PATH and critical variables properly formatted?
277
+
278
+
279
+ @dataclass
280
+ class DiagnosticReport:
281
+ """Complete diagnostic audit result across all categories."""
282
+ timestamp: float # Epoch seconds
283
+ target_dir: str # Workspace scanned
284
+ health_score_pct: int # 0 to 100 overall health rating
285
+ total_issues: int # Count of all issues detected
286
+ syntax_errors: int = 0 # Issues in SYNTAX category
287
+ missing_imports: int = 0 # Issues in IMPORTS category
288
+ env_issues: int = 0 # Issues in ENVIRONMENT category
289
+ cache_issues: int = 0 # Issues in CACHE / ENCODING categories
290
+ issues: List[DiagnosticIssue] = field(default_factory=list) # Complete list of issues
291
+ critical_count: int = 0 # Count of critical severity issues
292
+ error_count: int = 0 # Count of error severity issues
293
+ warning_count: int = 0 # Count of warning severity issues
294
+ info_count: int = 0 # Count of info/advisory issues
295
+ security_leaks: int = 0 # Issues in SECURITY category
296
+ code_smells: int = 0 # Issues in SMELLS category
297
+ tools_status: Dict[str, bool] = field(default_factory=dict)
298
+ python_version: str = ""
299
+ virtualenv_status: Dict[str, Any] = field(default_factory=dict)
300
+ environment: Optional[EnvironmentSnapshot] = None # Host system environment metrics
301
+ scan_duration_ms: float = 0.0 # Time taken to scan in milliseconds
302
+ scanned_file_count: int = 0 # Total source files inspected
303
+
304
+ def to_dict(self) -> Dict[str, Any]:
305
+ return asdict(self)
306
+
307
+ def to_sarif(self) -> Dict[str, Any]:
308
+ """Convert diagnostic issues to standard OASIS SARIF v2.1.0 format."""
309
+ results = []
310
+ for issue in self.issues:
311
+ level = "error" if issue.severity in ("critical", "error") else ("warning" if issue.severity == "warning" else "note")
312
+ loc = {
313
+ "physicalLocation": {
314
+ "artifactLocation": {"uri": issue.file_path or "system"},
315
+ "region": {
316
+ "startLine": issue.line or 1,
317
+ "startColumn": (issue.column or 0) + 1
318
+ }
319
+ }
320
+ }
321
+ results.append({
322
+ "ruleId": issue.error_code,
323
+ "level": level,
324
+ "message": {"text": f"{issue.message}. Suggestion: {issue.suggested_fix}"},
325
+ "locations": [loc],
326
+ "properties": {"category": issue.category, "autoFixable": issue.auto_fixable}
327
+ })
328
+
329
+ return {
330
+ "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
331
+ "version": "2.1.0",
332
+ "runs": [{
333
+ "tool": {
334
+ "driver": {
335
+ "name": "T-Zero PC-Fixer Doctor",
336
+ "version": "10.5.0",
337
+ "informationUri": "https://tzero-indol.vercel.app"
338
+ }
339
+ },
340
+ "results": results
341
+ }]
342
+ }
343
+
344
+
345
+ @dataclass
346
+ class RollbackManifest:
347
+ """Manifest of files backed up before autonomous healing for atomic rollback."""
348
+ transaction_id: str
349
+ timestamp: float
350
+ target_dir: str
351
+ backup_dir: str
352
+ backed_up_files: Dict[str, str] = field(default_factory=dict) # original_path -> backup_path
353
+
354
+ def save(self, manifest_file: str):
355
+ with open(manifest_file, "w", encoding="utf-8") as f:
356
+ json.dump(asdict(self), f, indent=2)
357
+
358
+ @classmethod
359
+ def load(cls, manifest_file: str) -> "RollbackManifest":
360
+ with open(manifest_file, "r", encoding="utf-8") as f:
361
+ data = json.load(f)
362
+ return cls(**data)
363
+
364
+
365
+ @dataclass
366
+ class HealReport:
367
+ """Comprehensive outcome report of autonomous self-healing execution."""
368
+ timestamp: float # Execution completion timestamp
369
+ target_dir: str # Workspace path
370
+ initial_health_score: int # Health score before repair (0-100)
371
+ final_health_score: int # Health score after repair (0-100)
372
+ issues_detected: int # Total issues initially found
373
+ issues_healed: int # Total issues successfully repaired
374
+ dry_run: bool # True if preview mode without writing
375
+ actions: List[HealAction] # List of individual repair operations
376
+ transaction_id: str = "" # Unique ID for rollback tracking
377
+ backup_manifest: Optional[RollbackManifest] = None
378
+ execution_duration_ms: float = 0.0 # Total time taken in milliseconds
379
+
380
+ def to_dict(self) -> Dict[str, Any]:
381
+ return asdict(self)
382
+
383
+ @property
384
+ def is_fully_healthy(self) -> bool:
385
+ return self.final_health_score >= 95