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,364 +1,364 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- T-Zero Polyglot Build, Container, & Infrastructure Healer
4
- ========================================================
5
- Specialized AST & syntax healer for cross-language build tools, Dockerfiles,
6
- Makefiles, container configurations, web server rules, and multi-ecosystem manifests.
7
-
8
- Key Capabilities:
9
- - Dockerfile best-practice auditor & .dockerignore generator
10
- - Makefile tab-vs-space indentation healer (eliminates 'missing separator' errors)
11
- - Makefile .PHONY target generator
12
- - Nginx / Caddy reverse proxy syntax and semicolon validator
13
- - Rust Cargo.toml & Go go.mod basic syntax integrity checkers
14
-
15
- Author: Siber Akademi T-Zero R&D Team
16
- Version: 10.5.0 | 100% Free & Local Offline | Zero-Leak Certified
17
- """
18
-
19
- from __future__ import annotations
20
-
21
- import os
22
- import re
23
- from dataclasses import dataclass
24
- from pathlib import Path
25
- from typing import Any, Dict, List, Optional, Tuple
26
-
27
- from tzero.tzero_fixer.models import (
28
- DiagnosticCategory,
29
- DiagnosticIssue,
30
- HealAction,
31
- SeverityLevel,
32
- )
33
-
34
-
35
- class PolyglotBuildHealer:
36
- """Surgeon for polyglot build scripts, container files, and infrastructure recipes."""
37
-
38
- @classmethod
39
- def diagnose_workspace(cls, workspace_path: str) -> List[DiagnosticIssue]:
40
- """Audit build and container files across the workspace."""
41
- issues: List[DiagnosticIssue] = []
42
- root = Path(workspace_path).resolve()
43
-
44
- # 1. Dockerfile check
45
- for dockerfile in root.glob("**/Dockerfile*"):
46
- if dockerfile.is_file() and not cls._is_ignored(dockerfile):
47
- issues.extend(cls._audit_dockerfile(dockerfile, root))
48
-
49
- # 2. Makefile check
50
- for makefile in root.glob("**/Makefile*"):
51
- if makefile.is_file() and not cls._is_ignored(makefile):
52
- issues.extend(cls._audit_makefile(makefile))
53
-
54
- # 3. Nginx / Caddy conf check
55
- for conf in root.glob("**/*.conf"):
56
- if conf.is_file() and not cls._is_ignored(conf):
57
- issues.extend(cls._audit_webserver_conf(conf))
58
-
59
- # 4. Cargo.toml check
60
- for cargo in root.glob("**/Cargo.toml"):
61
- if cargo.is_file() and not cls._is_ignored(cargo):
62
- issues.extend(cls._audit_cargo_toml(cargo))
63
-
64
- # 5. go.mod check
65
- for gopkg in root.glob("**/go.mod"):
66
- if gopkg.is_file() and not cls._is_ignored(gopkg):
67
- issues.extend(cls._audit_go_mod(gopkg))
68
-
69
- return issues
70
-
71
- @classmethod
72
- def _is_ignored(cls, p: Path) -> bool:
73
- """Check if path is inside ignored VCS, venv, or build folders."""
74
- parts = p.parts
75
- ignored_names = {".git", ".venv", "venv", "node_modules", "dist", "build", ".tox", "__pycache__"}
76
- return any(part in ignored_names for part in parts)
77
-
78
- @classmethod
79
- def _audit_dockerfile(cls, dockerfile: Path, root: Path) -> List[DiagnosticIssue]:
80
- """Audit Dockerfile for best practices and check for .dockerignore."""
81
- issues: List[DiagnosticIssue] = []
82
- try:
83
- content = dockerfile.read_text(encoding="utf-8", errors="replace")
84
- lines = content.splitlines()
85
- except Exception:
86
- return issues
87
-
88
- # Check for missing .dockerignore in directory
89
- dockerignore = dockerfile.parent / ".dockerignore"
90
- if not dockerignore.is_file():
91
- issues.append(DiagnosticIssue(
92
- category=DiagnosticCategory.WORKSPACE,
93
- severity=SeverityLevel.WARNING,
94
- description=f"Dockerfile in '{dockerfile.parent.name}' lacks a '.dockerignore' file (unnecessary files like .git or .venv will bloat context)",
95
- file_path=str(dockerfile),
96
- suggested_fix="Generate optimized .dockerignore to exclude git, venv, cache, and build artifacts",
97
- metadata={"issue_type": "missing_dockerignore", "target_dir": str(dockerfile.parent)},
98
- ))
99
-
100
- for idx, line in enumerate(lines, start=1):
101
- stripped = line.strip()
102
-
103
- # FROM :latest warning
104
- if stripped.startswith("FROM ") and ":latest" in stripped:
105
- issues.append(DiagnosticIssue(
106
- category=DiagnosticCategory.WORKSPACE,
107
- severity=SeverityLevel.INFO,
108
- description=f"Dockerfile uses unpinned ':latest' base image: '{stripped}'",
109
- file_path=str(dockerfile),
110
- line_number=idx,
111
- suggested_fix="Pin base image to specific digest or version tag for deterministic builds",
112
- metadata={"issue_type": "unpinned_docker_image"},
113
- ))
114
-
115
- # ADD instead of COPY
116
- if stripped.startswith("ADD ") and not ("://" in stripped or stripped.endswith(".tar.gz") or stripped.endswith(".tgz")):
117
- issues.append(DiagnosticIssue(
118
- category=DiagnosticCategory.WORKSPACE,
119
- severity=SeverityLevel.INFO,
120
- description=f"Using 'ADD' instead of 'COPY' for simple local file copy: '{stripped}'",
121
- file_path=str(dockerfile),
122
- line_number=idx,
123
- suggested_fix="Replace 'ADD' with 'COPY' for local files as per Dockerfile best practices",
124
- metadata={"issue_type": "docker_add_to_copy", "line_num": idx},
125
- ))
126
-
127
- # apt-get install without cleanup
128
- if "apt-get install" in stripped and "rm -rf /var/lib/apt/lists" not in stripped and not stripped.endswith("\\"):
129
- issues.append(DiagnosticIssue(
130
- category=DiagnosticCategory.WORKSPACE,
131
- severity=SeverityLevel.WARNING,
132
- description=f"apt-get install without cache cleanup in same RUN layer: '{stripped}'",
133
- file_path=str(dockerfile),
134
- line_number=idx,
135
- suggested_fix="Append '&& rm -rf /var/lib/apt/lists/*' to reduce container image footprint",
136
- metadata={"issue_type": "docker_apt_cleanup"},
137
- ))
138
-
139
- return issues
140
-
141
- @classmethod
142
- def _audit_makefile(cls, makefile: Path) -> List[DiagnosticIssue]:
143
- """Audit Makefile for space vs tab indentation and missing .PHONY declarations."""
144
- issues: List[DiagnosticIssue] = []
145
- try:
146
- content = makefile.read_text(encoding="utf-8", errors="replace")
147
- lines = content.splitlines()
148
- except Exception:
149
- return issues
150
-
151
- in_rule = False
152
- space_indented_lines: List[int] = []
153
- targets: List[str] = []
154
-
155
- for idx, line in enumerate(lines, start=1):
156
- if not line.strip() or line.strip().startswith("#"):
157
- continue
158
-
159
- # Detect target rule
160
- target_match = re.match(r"^([a-zA-Z0-9_\-\.]+)\s*:\s*(.*)$", line)
161
- if target_match:
162
- in_rule = True
163
- tgt = target_match.group(1)
164
- if not tgt.startswith("."):
165
- targets.append(tgt)
166
- continue
167
-
168
- # Recipe lines must start with TAB, not spaces
169
- if in_rule:
170
- if line.startswith(" ") or (line.startswith(" ") and not line.startswith("\t")):
171
- space_indented_lines.append(idx)
172
-
173
- if space_indented_lines:
174
- issues.append(DiagnosticIssue(
175
- category=DiagnosticCategory.SYNTAX,
176
- severity=SeverityLevel.ERROR,
177
- description=f"Makefile contains {len(space_indented_lines)} recipe line(s) indented with spaces instead of tabs (causes '*** missing separator' error)",
178
- file_path=str(makefile),
179
- line_number=space_indented_lines[0],
180
- suggested_fix="Convert leading spaces on recipe lines to real tab (\\t) characters",
181
- metadata={"issue_type": "makefile_spaces_to_tabs", "lines": space_indented_lines},
182
- ))
183
-
184
- if targets and ".PHONY:" not in content:
185
- issues.append(DiagnosticIssue(
186
- category=DiagnosticCategory.WORKSPACE,
187
- severity=SeverityLevel.INFO,
188
- description="Makefile declares targets without '.PHONY' directive (can conflict with files named after targets)",
189
- file_path=str(makefile),
190
- suggested_fix=f"Declare targets as .PHONY: {', '.join(targets[:5])}",
191
- metadata={"issue_type": "makefile_missing_phony", "targets": targets},
192
- ))
193
-
194
- return issues
195
-
196
- @classmethod
197
- def _audit_webserver_conf(cls, conf_file: Path) -> List[DiagnosticIssue]:
198
- """Audit Nginx / reverse proxy config files for missing semicolons."""
199
- issues: List[DiagnosticIssue] = []
200
- try:
201
- content = conf_file.read_text(encoding="utf-8", errors="replace")
202
- lines = content.splitlines()
203
- except Exception:
204
- return issues
205
-
206
- # Only audit if it looks like an nginx/caddy configuration
207
- if "server {" not in content and "http {" not in content and "location " not in content:
208
- return issues
209
-
210
- for idx, line in enumerate(lines, start=1):
211
- stripped = line.strip()
212
- if not stripped or stripped.startswith("#") or stripped.endswith("{") or stripped.endswith("}"):
213
- continue
214
- if not stripped.endswith(";"):
215
- issues.append(DiagnosticIssue(
216
- category=DiagnosticCategory.SYNTAX,
217
- severity=SeverityLevel.ERROR,
218
- description=f"Missing terminating semicolon in Nginx directive: '{stripped}'",
219
- file_path=str(conf_file),
220
- line_number=idx,
221
- suggested_fix="Append ';' to directive line",
222
- metadata={"issue_type": "nginx_missing_semicolon", "line_num": idx},
223
- ))
224
-
225
- return issues
226
-
227
- @classmethod
228
- def _audit_cargo_toml(cls, cargo_file: Path) -> List[DiagnosticIssue]:
229
- """Audit Rust Cargo.toml for basic sections."""
230
- issues: List[DiagnosticIssue] = []
231
- try:
232
- content = cargo_file.read_text(encoding="utf-8", errors="replace")
233
- except Exception:
234
- return issues
235
-
236
- if "[package]" not in content and "[workspace]" not in content:
237
- issues.append(DiagnosticIssue(
238
- category=DiagnosticCategory.DEPENDENCY,
239
- severity=SeverityLevel.ERROR,
240
- description="Cargo.toml is missing mandatory '[package]' or '[workspace]' header",
241
- file_path=str(cargo_file),
242
- suggested_fix="Add '[package]' table with name, version, and edition = '2021'",
243
- metadata={"issue_type": "cargo_missing_package"},
244
- ))
245
-
246
- return issues
247
-
248
- @classmethod
249
- def _audit_go_mod(cls, go_mod_file: Path) -> List[DiagnosticIssue]:
250
- """Audit Go go.mod for module declaration."""
251
- issues: List[DiagnosticIssue] = []
252
- try:
253
- content = go_mod_file.read_text(encoding="utf-8", errors="replace")
254
- except Exception:
255
- return issues
256
-
257
- if not re.search(r"^module\s+\S+", content, re.MULTILINE):
258
- issues.append(DiagnosticIssue(
259
- category=DiagnosticCategory.DEPENDENCY,
260
- severity=SeverityLevel.ERROR,
261
- description="go.mod is missing mandatory 'module <path>' declaration",
262
- file_path=str(go_mod_file),
263
- suggested_fix="Declare module path on first line of go.mod",
264
- metadata={"issue_type": "go_missing_module"},
265
- ))
266
-
267
- return issues
268
-
269
- @classmethod
270
- def heal_issue(cls, issue: DiagnosticIssue, dry_run: bool = False) -> HealAction:
271
- """Autonomously heal polyglot build and container issues."""
272
- itype = issue.metadata.get("issue_type")
273
- file_path = issue.file_path
274
-
275
- if itype == "missing_dockerignore":
276
- target_dir = Path(issue.metadata.get("target_dir", "."))
277
- dignore = target_dir / ".dockerignore"
278
- if dry_run:
279
- return HealAction(issue=issue, success=True, details=f"[Dry-Run] Would create .dockerignore in {target_dir}")
280
-
281
- ignore_content = (
282
- "# T-Zero Autonomous Dockerignore\n"
283
- ".git\n"
284
- ".gitignore\n"
285
- ".venv\n"
286
- "venv/\n"
287
- "env/\n"
288
- "node_modules/\n"
289
- "__pycache__/\n"
290
- "*.pyc\n"
291
- "*.pyo\n"
292
- "dist/\n"
293
- "build/\n"
294
- "*.egg-info/\n"
295
- ".DS_Store\n"
296
- "Thumbs.db\n"
297
- ".env\n"
298
- ".env.local\n"
299
- "coverage/\n"
300
- ".pytest_cache/\n"
301
- )
302
- dignore.write_text(ignore_content, encoding="utf-8")
303
- return HealAction(issue=issue, success=True, details=f"Generated high-performance .dockerignore in '{target_dir.name}'")
304
-
305
- if itype == "makefile_spaces_to_tabs" and file_path:
306
- p = Path(file_path)
307
- if dry_run:
308
- return HealAction(issue=issue, success=True, details="[Dry-Run] Would convert recipe spaces to tabs in Makefile")
309
-
310
- lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
311
- new_lines = []
312
- converted = 0
313
- in_rule = False
314
-
315
- for line in lines:
316
- if not line.strip() or line.strip().startswith("#"):
317
- new_lines.append(line)
318
- continue
319
-
320
- if re.match(r"^[a-zA-Z0-9_\-\.]+\s*:\s*.*$", line):
321
- in_rule = True
322
- new_lines.append(line)
323
- continue
324
-
325
- if in_rule:
326
- if line.startswith(" "):
327
- new_lines.append("\t" + line[4:])
328
- converted += 1
329
- continue
330
- elif line.startswith(" "):
331
- new_lines.append("\t" + line.lstrip(" "))
332
- converted += 1
333
- continue
334
-
335
- new_lines.append(line)
336
-
337
- p.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
338
- return HealAction(issue=issue, success=True, details=f"Converted {converted} recipe lines from spaces to real tabs in Makefile")
339
-
340
- if itype == "makefile_missing_phony" and file_path:
341
- p = Path(file_path)
342
- targets = issue.metadata.get("targets", [])
343
- if dry_run:
344
- return HealAction(issue=issue, success=True, details=f"[Dry-Run] Would prepend .PHONY: {' '.join(targets)} to Makefile")
345
-
346
- content = p.read_text(encoding="utf-8", errors="replace")
347
- phony_line = f".PHONY: {' '.join(targets)}\n\n"
348
- p.write_text(phony_line + content, encoding="utf-8")
349
- return HealAction(issue=issue, success=True, details=f"Injected .PHONY target declarations into Makefile")
350
-
351
- if itype == "docker_add_to_copy" and file_path:
352
- p = Path(file_path)
353
- line_num = issue.metadata.get("line_num")
354
- if dry_run:
355
- return HealAction(issue=issue, success=True, details=f"[Dry-Run] Would replace ADD with COPY on line {line_num}")
356
-
357
- lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
358
- if line_num and 1 <= line_num <= len(lines):
359
- lines[line_num - 1] = re.sub(r"^ADD\s+", "COPY ", lines[line_num - 1])
360
- p.write_text("\n".join(lines) + "\n", encoding="utf-8")
361
- return HealAction(issue=issue, success=True, details=f"Replaced 'ADD' with 'COPY' on line {line_num} of Dockerfile")
362
-
363
- return HealAction(issue=issue, success=False, details=f"No automated repair for issue type '{itype}'")
364
-
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-Zero Polyglot Build, Container, & Infrastructure Healer
4
+ ========================================================
5
+ Specialized AST & syntax healer for cross-language build tools, Dockerfiles,
6
+ Makefiles, container configurations, web server rules, and multi-ecosystem manifests.
7
+
8
+ Key Capabilities:
9
+ - Dockerfile best-practice auditor & .dockerignore generator
10
+ - Makefile tab-vs-space indentation healer (eliminates 'missing separator' errors)
11
+ - Makefile .PHONY target generator
12
+ - Nginx / Caddy reverse proxy syntax and semicolon validator
13
+ - Rust Cargo.toml & Go go.mod basic syntax integrity checkers
14
+
15
+ Author: Siber Akademi T-Zero R&D Team
16
+ Version: 10.5.0 | 100% Free & Local Offline | Zero-Leak Certified
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import re
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Any, Dict, List, Optional, Tuple
26
+
27
+ from tzero.tzero_fixer.models import (
28
+ DiagnosticCategory,
29
+ DiagnosticIssue,
30
+ HealAction,
31
+ SeverityLevel,
32
+ )
33
+
34
+
35
+ class PolyglotBuildHealer:
36
+ """Surgeon for polyglot build scripts, container files, and infrastructure recipes."""
37
+
38
+ @classmethod
39
+ def diagnose_workspace(cls, workspace_path: str) -> List[DiagnosticIssue]:
40
+ """Audit build and container files across the workspace."""
41
+ issues: List[DiagnosticIssue] = []
42
+ root = Path(workspace_path).resolve()
43
+
44
+ # 1. Dockerfile check
45
+ for dockerfile in root.glob("**/Dockerfile*"):
46
+ if dockerfile.is_file() and not cls._is_ignored(dockerfile):
47
+ issues.extend(cls._audit_dockerfile(dockerfile, root))
48
+
49
+ # 2. Makefile check
50
+ for makefile in root.glob("**/Makefile*"):
51
+ if makefile.is_file() and not cls._is_ignored(makefile):
52
+ issues.extend(cls._audit_makefile(makefile))
53
+
54
+ # 3. Nginx / Caddy conf check
55
+ for conf in root.glob("**/*.conf"):
56
+ if conf.is_file() and not cls._is_ignored(conf):
57
+ issues.extend(cls._audit_webserver_conf(conf))
58
+
59
+ # 4. Cargo.toml check
60
+ for cargo in root.glob("**/Cargo.toml"):
61
+ if cargo.is_file() and not cls._is_ignored(cargo):
62
+ issues.extend(cls._audit_cargo_toml(cargo))
63
+
64
+ # 5. go.mod check
65
+ for gopkg in root.glob("**/go.mod"):
66
+ if gopkg.is_file() and not cls._is_ignored(gopkg):
67
+ issues.extend(cls._audit_go_mod(gopkg))
68
+
69
+ return issues
70
+
71
+ @classmethod
72
+ def _is_ignored(cls, p: Path) -> bool:
73
+ """Check if path is inside ignored VCS, venv, or build folders."""
74
+ parts = p.parts
75
+ ignored_names = {".git", ".venv", "venv", "node_modules", "dist", "build", ".tox", "__pycache__"}
76
+ return any(part in ignored_names for part in parts)
77
+
78
+ @classmethod
79
+ def _audit_dockerfile(cls, dockerfile: Path, root: Path) -> List[DiagnosticIssue]:
80
+ """Audit Dockerfile for best practices and check for .dockerignore."""
81
+ issues: List[DiagnosticIssue] = []
82
+ try:
83
+ content = dockerfile.read_text(encoding="utf-8", errors="replace")
84
+ lines = content.splitlines()
85
+ except Exception:
86
+ return issues
87
+
88
+ # Check for missing .dockerignore in directory
89
+ dockerignore = dockerfile.parent / ".dockerignore"
90
+ if not dockerignore.is_file():
91
+ issues.append(DiagnosticIssue(
92
+ category=DiagnosticCategory.WORKSPACE,
93
+ severity=SeverityLevel.WARNING,
94
+ description=f"Dockerfile in '{dockerfile.parent.name}' lacks a '.dockerignore' file (unnecessary files like .git or .venv will bloat context)",
95
+ file_path=str(dockerfile),
96
+ suggested_fix="Generate optimized .dockerignore to exclude git, venv, cache, and build artifacts",
97
+ metadata={"issue_type": "missing_dockerignore", "target_dir": str(dockerfile.parent)},
98
+ ))
99
+
100
+ for idx, line in enumerate(lines, start=1):
101
+ stripped = line.strip()
102
+
103
+ # FROM :latest warning
104
+ if stripped.startswith("FROM ") and ":latest" in stripped:
105
+ issues.append(DiagnosticIssue(
106
+ category=DiagnosticCategory.WORKSPACE,
107
+ severity=SeverityLevel.INFO,
108
+ description=f"Dockerfile uses unpinned ':latest' base image: '{stripped}'",
109
+ file_path=str(dockerfile),
110
+ line_number=idx,
111
+ suggested_fix="Pin base image to specific digest or version tag for deterministic builds",
112
+ metadata={"issue_type": "unpinned_docker_image"},
113
+ ))
114
+
115
+ # ADD instead of COPY
116
+ if stripped.startswith("ADD ") and not ("://" in stripped or stripped.endswith(".tar.gz") or stripped.endswith(".tgz")):
117
+ issues.append(DiagnosticIssue(
118
+ category=DiagnosticCategory.WORKSPACE,
119
+ severity=SeverityLevel.INFO,
120
+ description=f"Using 'ADD' instead of 'COPY' for simple local file copy: '{stripped}'",
121
+ file_path=str(dockerfile),
122
+ line_number=idx,
123
+ suggested_fix="Replace 'ADD' with 'COPY' for local files as per Dockerfile best practices",
124
+ metadata={"issue_type": "docker_add_to_copy", "line_num": idx},
125
+ ))
126
+
127
+ # apt-get install without cleanup
128
+ if "apt-get install" in stripped and "rm -rf /var/lib/apt/lists" not in stripped and not stripped.endswith("\\"):
129
+ issues.append(DiagnosticIssue(
130
+ category=DiagnosticCategory.WORKSPACE,
131
+ severity=SeverityLevel.WARNING,
132
+ description=f"apt-get install without cache cleanup in same RUN layer: '{stripped}'",
133
+ file_path=str(dockerfile),
134
+ line_number=idx,
135
+ suggested_fix="Append '&& rm -rf /var/lib/apt/lists/*' to reduce container image footprint",
136
+ metadata={"issue_type": "docker_apt_cleanup"},
137
+ ))
138
+
139
+ return issues
140
+
141
+ @classmethod
142
+ def _audit_makefile(cls, makefile: Path) -> List[DiagnosticIssue]:
143
+ """Audit Makefile for space vs tab indentation and missing .PHONY declarations."""
144
+ issues: List[DiagnosticIssue] = []
145
+ try:
146
+ content = makefile.read_text(encoding="utf-8", errors="replace")
147
+ lines = content.splitlines()
148
+ except Exception:
149
+ return issues
150
+
151
+ in_rule = False
152
+ space_indented_lines: List[int] = []
153
+ targets: List[str] = []
154
+
155
+ for idx, line in enumerate(lines, start=1):
156
+ if not line.strip() or line.strip().startswith("#"):
157
+ continue
158
+
159
+ # Detect target rule
160
+ target_match = re.match(r"^([a-zA-Z0-9_\-\.]+)\s*:\s*(.*)$", line)
161
+ if target_match:
162
+ in_rule = True
163
+ tgt = target_match.group(1)
164
+ if not tgt.startswith("."):
165
+ targets.append(tgt)
166
+ continue
167
+
168
+ # Recipe lines must start with TAB, not spaces
169
+ if in_rule:
170
+ if line.startswith(" ") or (line.startswith(" ") and not line.startswith("\t")):
171
+ space_indented_lines.append(idx)
172
+
173
+ if space_indented_lines:
174
+ issues.append(DiagnosticIssue(
175
+ category=DiagnosticCategory.SYNTAX,
176
+ severity=SeverityLevel.ERROR,
177
+ description=f"Makefile contains {len(space_indented_lines)} recipe line(s) indented with spaces instead of tabs (causes '*** missing separator' error)",
178
+ file_path=str(makefile),
179
+ line_number=space_indented_lines[0],
180
+ suggested_fix="Convert leading spaces on recipe lines to real tab (\\t) characters",
181
+ metadata={"issue_type": "makefile_spaces_to_tabs", "lines": space_indented_lines},
182
+ ))
183
+
184
+ if targets and ".PHONY:" not in content:
185
+ issues.append(DiagnosticIssue(
186
+ category=DiagnosticCategory.WORKSPACE,
187
+ severity=SeverityLevel.INFO,
188
+ description="Makefile declares targets without '.PHONY' directive (can conflict with files named after targets)",
189
+ file_path=str(makefile),
190
+ suggested_fix=f"Declare targets as .PHONY: {', '.join(targets[:5])}",
191
+ metadata={"issue_type": "makefile_missing_phony", "targets": targets},
192
+ ))
193
+
194
+ return issues
195
+
196
+ @classmethod
197
+ def _audit_webserver_conf(cls, conf_file: Path) -> List[DiagnosticIssue]:
198
+ """Audit Nginx / reverse proxy config files for missing semicolons."""
199
+ issues: List[DiagnosticIssue] = []
200
+ try:
201
+ content = conf_file.read_text(encoding="utf-8", errors="replace")
202
+ lines = content.splitlines()
203
+ except Exception:
204
+ return issues
205
+
206
+ # Only audit if it looks like an nginx/caddy configuration
207
+ if "server {" not in content and "http {" not in content and "location " not in content:
208
+ return issues
209
+
210
+ for idx, line in enumerate(lines, start=1):
211
+ stripped = line.strip()
212
+ if not stripped or stripped.startswith("#") or stripped.endswith("{") or stripped.endswith("}"):
213
+ continue
214
+ if not stripped.endswith(";"):
215
+ issues.append(DiagnosticIssue(
216
+ category=DiagnosticCategory.SYNTAX,
217
+ severity=SeverityLevel.ERROR,
218
+ description=f"Missing terminating semicolon in Nginx directive: '{stripped}'",
219
+ file_path=str(conf_file),
220
+ line_number=idx,
221
+ suggested_fix="Append ';' to directive line",
222
+ metadata={"issue_type": "nginx_missing_semicolon", "line_num": idx},
223
+ ))
224
+
225
+ return issues
226
+
227
+ @classmethod
228
+ def _audit_cargo_toml(cls, cargo_file: Path) -> List[DiagnosticIssue]:
229
+ """Audit Rust Cargo.toml for basic sections."""
230
+ issues: List[DiagnosticIssue] = []
231
+ try:
232
+ content = cargo_file.read_text(encoding="utf-8", errors="replace")
233
+ except Exception:
234
+ return issues
235
+
236
+ if "[package]" not in content and "[workspace]" not in content:
237
+ issues.append(DiagnosticIssue(
238
+ category=DiagnosticCategory.DEPENDENCY,
239
+ severity=SeverityLevel.ERROR,
240
+ description="Cargo.toml is missing mandatory '[package]' or '[workspace]' header",
241
+ file_path=str(cargo_file),
242
+ suggested_fix="Add '[package]' table with name, version, and edition = '2021'",
243
+ metadata={"issue_type": "cargo_missing_package"},
244
+ ))
245
+
246
+ return issues
247
+
248
+ @classmethod
249
+ def _audit_go_mod(cls, go_mod_file: Path) -> List[DiagnosticIssue]:
250
+ """Audit Go go.mod for module declaration."""
251
+ issues: List[DiagnosticIssue] = []
252
+ try:
253
+ content = go_mod_file.read_text(encoding="utf-8", errors="replace")
254
+ except Exception:
255
+ return issues
256
+
257
+ if not re.search(r"^module\s+\S+", content, re.MULTILINE):
258
+ issues.append(DiagnosticIssue(
259
+ category=DiagnosticCategory.DEPENDENCY,
260
+ severity=SeverityLevel.ERROR,
261
+ description="go.mod is missing mandatory 'module <path>' declaration",
262
+ file_path=str(go_mod_file),
263
+ suggested_fix="Declare module path on first line of go.mod",
264
+ metadata={"issue_type": "go_missing_module"},
265
+ ))
266
+
267
+ return issues
268
+
269
+ @classmethod
270
+ def heal_issue(cls, issue: DiagnosticIssue, dry_run: bool = False) -> HealAction:
271
+ """Autonomously heal polyglot build and container issues."""
272
+ itype = issue.metadata.get("issue_type")
273
+ file_path = issue.file_path
274
+
275
+ if itype == "missing_dockerignore":
276
+ target_dir = Path(issue.metadata.get("target_dir", "."))
277
+ dignore = target_dir / ".dockerignore"
278
+ if dry_run:
279
+ return HealAction(issue=issue, success=True, details=f"[Dry-Run] Would create .dockerignore in {target_dir}")
280
+
281
+ ignore_content = (
282
+ "# T-Zero Autonomous Dockerignore\n"
283
+ ".git\n"
284
+ ".gitignore\n"
285
+ ".venv\n"
286
+ "venv/\n"
287
+ "env/\n"
288
+ "node_modules/\n"
289
+ "__pycache__/\n"
290
+ "*.pyc\n"
291
+ "*.pyo\n"
292
+ "dist/\n"
293
+ "build/\n"
294
+ "*.egg-info/\n"
295
+ ".DS_Store\n"
296
+ "Thumbs.db\n"
297
+ ".env\n"
298
+ ".env.local\n"
299
+ "coverage/\n"
300
+ ".pytest_cache/\n"
301
+ )
302
+ dignore.write_text(ignore_content, encoding="utf-8")
303
+ return HealAction(issue=issue, success=True, details=f"Generated high-performance .dockerignore in '{target_dir.name}'")
304
+
305
+ if itype == "makefile_spaces_to_tabs" and file_path:
306
+ p = Path(file_path)
307
+ if dry_run:
308
+ return HealAction(issue=issue, success=True, details="[Dry-Run] Would convert recipe spaces to tabs in Makefile")
309
+
310
+ lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
311
+ new_lines = []
312
+ converted = 0
313
+ in_rule = False
314
+
315
+ for line in lines:
316
+ if not line.strip() or line.strip().startswith("#"):
317
+ new_lines.append(line)
318
+ continue
319
+
320
+ if re.match(r"^[a-zA-Z0-9_\-\.]+\s*:\s*.*$", line):
321
+ in_rule = True
322
+ new_lines.append(line)
323
+ continue
324
+
325
+ if in_rule:
326
+ if line.startswith(" "):
327
+ new_lines.append("\t" + line[4:])
328
+ converted += 1
329
+ continue
330
+ elif line.startswith(" "):
331
+ new_lines.append("\t" + line.lstrip(" "))
332
+ converted += 1
333
+ continue
334
+
335
+ new_lines.append(line)
336
+
337
+ p.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
338
+ return HealAction(issue=issue, success=True, details=f"Converted {converted} recipe lines from spaces to real tabs in Makefile")
339
+
340
+ if itype == "makefile_missing_phony" and file_path:
341
+ p = Path(file_path)
342
+ targets = issue.metadata.get("targets", [])
343
+ if dry_run:
344
+ return HealAction(issue=issue, success=True, details=f"[Dry-Run] Would prepend .PHONY: {' '.join(targets)} to Makefile")
345
+
346
+ content = p.read_text(encoding="utf-8", errors="replace")
347
+ phony_line = f".PHONY: {' '.join(targets)}\n\n"
348
+ p.write_text(phony_line + content, encoding="utf-8")
349
+ return HealAction(issue=issue, success=True, details=f"Injected .PHONY target declarations into Makefile")
350
+
351
+ if itype == "docker_add_to_copy" and file_path:
352
+ p = Path(file_path)
353
+ line_num = issue.metadata.get("line_num")
354
+ if dry_run:
355
+ return HealAction(issue=issue, success=True, details=f"[Dry-Run] Would replace ADD with COPY on line {line_num}")
356
+
357
+ lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
358
+ if line_num and 1 <= line_num <= len(lines):
359
+ lines[line_num - 1] = re.sub(r"^ADD\s+", "COPY ", lines[line_num - 1])
360
+ p.write_text("\n".join(lines) + "\n", encoding="utf-8")
361
+ return HealAction(issue=issue, success=True, details=f"Replaced 'ADD' with 'COPY' on line {line_num} of Dockerfile")
362
+
363
+ return HealAction(issue=issue, success=False, details=f"No automated repair for issue type '{itype}'")
364
+