tzero-mcp 10.7.3 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +44 -577
  2. package/CONTRIBUTING.md +71 -71
  3. package/README.md +64 -64
  4. package/bin/tzero-mcp.js +62 -65
  5. package/bin/tzero.js +61 -64
  6. package/index.d.ts +25 -25
  7. package/index.js +15 -15
  8. package/package.json +88 -67
  9. package/src/addmcp.py +14 -11
  10. package/src/app.py +1810 -0
  11. package/src/main.py +1 -1
  12. package/src/pc_fixer_mcp.py +25 -0
  13. package/src/tzero/__init__.py +54 -0
  14. package/src/tzero/__main__.py +6 -0
  15. package/src/tzero/siber_akademi.ico +0 -0
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +475 -475
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +546 -362
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/{tzero_ci.py → tzero/tzero_ci.py} +153 -153
  22. package/src/{tzero_commit.py → tzero/tzero_commit.py} +192 -192
  23. package/src/tzero/tzero_contracts.py +1093 -0
  24. package/src/{tzero_cost.py → tzero/tzero_cost.py} +166 -163
  25. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +531 -19
  26. package/src/tzero/tzero_debt.py +461 -0
  27. package/src/{tzero_deps.py → tzero/tzero_deps.py} +179 -4
  28. package/src/{tzero_drift.py → tzero/tzero_drift.py} +208 -208
  29. package/src/{tzero_explain.py → tzero/tzero_explain.py} +73 -7
  30. package/src/{tzero_features.py → tzero/tzero_features.py} +19 -17
  31. package/src/tzero/tzero_federation.py +299 -0
  32. package/src/{tzero_fix.py → tzero/tzero_fix.py} +228 -228
  33. package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +63 -63
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +464 -464
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +288 -288
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +127 -127
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +600 -600
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +174 -174
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +246 -246
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +151 -151
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +260 -260
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +171 -171
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +150 -150
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +309 -309
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +1 -1
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +1 -1
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +412 -412
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +91 -91
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +295 -295
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +940 -940
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +307 -307
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +49 -7
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +502 -502
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +600 -599
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +274 -274
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +313 -313
  58. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +1 -1
  59. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +318 -318
  60. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +372 -372
  61. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +1 -1
  62. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +305 -305
  63. package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +444 -444
  64. package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +114 -114
  65. package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +110 -110
  66. package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +326 -326
  67. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +223 -223
  68. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +220 -220
  69. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +1 -1
  70. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +447 -447
  71. package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +309 -309
  72. package/src/tzero/tzero_golden.py +319 -0
  73. package/src/tzero/tzero_graph_hud.html +338 -0
  74. package/src/tzero/tzero_graph_rag.py +263 -0
  75. package/src/{tzero_guard.py → tzero/tzero_guard.py} +243 -243
  76. package/src/tzero/tzero_hooks.py +565 -0
  77. package/src/{tzero_infra.py → tzero/tzero_infra.py} +274 -274
  78. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +124 -124
  79. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +310 -310
  80. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +395 -395
  81. package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +214 -214
  82. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +137 -137
  83. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +212 -212
  84. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +184 -184
  85. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +335 -335
  86. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +308 -308
  87. package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +887 -887
  88. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +261 -261
  89. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +144 -144
  90. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +1167 -1167
  91. package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +173 -173
  92. package/src/tzero/tzero_lsp.py +634 -0
  93. package/src/{tzero_mcp.py → tzero/tzero_mcp.py} +479 -100
  94. package/src/tzero/tzero_mutation.py +358 -0
  95. package/src/tzero/tzero_packer.py +577 -0
  96. package/src/{tzero_patch.py → tzero/tzero_patch.py} +624 -624
  97. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +12699 -12657
  98. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +95 -95
  99. package/src/tzero/tzero_polyglot.py +799 -0
  100. package/src/tzero/tzero_proxy.py +127 -0
  101. package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +272 -272
  102. package/src/{tzero_replay.py → tzero/tzero_replay.py} +141 -141
  103. package/src/tzero/tzero_rust_bridge.py +198 -0
  104. package/src/tzero/tzero_scip.py +368 -0
  105. package/src/{tzero_security.py → tzero/tzero_security.py} +5 -2
  106. package/src/tzero/tzero_semantic_merge.py +189 -0
  107. package/src/tzero/tzero_snapshot.py +471 -0
  108. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +313 -313
  109. package/src/tzero/tzero_subagent_engine.py +459 -0
  110. package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +774 -774
  111. package/src/{tzero_sync.py → tzero/tzero_sync.py} +241 -241
  112. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +458 -363
  113. package/src/{tzero_tui.py → tzero/tzero_tui.py} +91 -22
  114. package/src/tzero/tzero_turbo.py +264 -0
  115. package/src/{tzero_v3.py → tzero/tzero_v3.py} +628 -163
  116. package/src/tzero.py +2 -54
  117. package/test/package.test.js +55 -19
  118. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  119. package/src/tzero_gateway.py +0 -885
  120. package/src/tzero_packer.py +0 -370
  121. package/src/tzero_polyglot.py +0 -422
  122. package/src/tzero_snapshot.py +0 -258
  123. /package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +0 -0
  124. /package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +0 -0
  125. /package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +0 -0
  126. /package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +0 -0
  127. /package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +0 -0
@@ -1,318 +1,318 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Polyglot Configuration & Environment Files Healer.
3
-
4
- Performs forensic repair and hygiene checks on configuration files:
5
- - JSON repair engine (strips trailing commas, single quotes, unquoted keys, and JS comments).
6
- - Gitignore & Security hygiene (verifies .env, *.pem, *.key are in .gitignore).
7
- - Gitattributes LF/CRLF normalizer (* text=auto eol=lf).
8
- - EditorConfig generator and validator.
9
-
10
- Author: Toprak Ahmet Aydogmus (Siber Akademi)
11
- Version: 10.4.0
12
- """
13
-
14
- import difflib
15
- import json
16
- import os
17
- import re
18
- import time
19
- from dataclasses import dataclass
20
- from pathlib import Path
21
- from typing import Any, Dict, List, Optional, Set, Tuple
22
-
23
- from .models import (
24
- DiagnosticCategory,
25
- DiagnosticIssue,
26
- HealAction,
27
- SeverityLevel,
28
- )
29
-
30
-
31
- class PolyglotConfigHealer:
32
- """Specialized repair engine for JSON, YAML, Gitignore, and Gitattributes files."""
33
-
34
- SENSITIVE_GITIGNORE_ENTRIES = [
35
- ".env",
36
- ".env.local",
37
- "*.pem",
38
- "*.key",
39
- "*.pfx",
40
- "*.p12",
41
- "id_rsa",
42
- "id_ed25519",
43
- ".tzero/fixer_backups/",
44
- ]
45
-
46
- # -------------------------------------------------------------------------
47
- # 1. JSON SURGICAL REPAIR ENGINE
48
- # -------------------------------------------------------------------------
49
- @classmethod
50
- def heal_json_string(cls, content: str) -> Any:
51
- """Helper to repair trailing commas and single quotes in JSON strings."""
52
- @dataclass
53
- class JsonHealResult:
54
- original_content: str
55
- repaired_content: str
56
- changed: bool
57
-
58
- changed, repaired = cls.repair_json_text(content)
59
- return JsonHealResult(
60
- original_content=content,
61
- repaired_content=repaired,
62
- changed=changed,
63
- )
64
-
65
- @classmethod
66
- def repair_json_text(cls, text: str) -> Tuple[bool, str]:
67
- """Surgically repair trailing commas, single quotes, and comments in JSON."""
68
- repaired = text
69
-
70
- # Strip line comments // ...
71
- repaired = re.sub(r"^\s*//.*$", "", repaired, flags=re.MULTILINE)
72
- # Strip block comments /* ... */
73
- repaired = re.sub(r"/\*.*?\*/", "", repaired, flags=re.DOTALL)
74
-
75
- # Convert single quotes to double quotes (around keys/values)
76
- repaired = re.sub(r"\'([^\'\\]*)\'", r'"\1"', repaired)
77
-
78
- # Strip trailing commas in objects: , } -> }
79
- repaired = re.sub(r",\s*(\})", r"\1", repaired)
80
- # Strip trailing commas in arrays: , ] -> ]
81
- repaired = re.sub(r",\s*(\])", r"\1", repaired)
82
-
83
- try:
84
- json.loads(repaired)
85
- return True, repaired
86
- except Exception:
87
- return False, text
88
-
89
- @classmethod
90
- def check_json_files(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
91
- """Inspect all JSON files in workspace for syntax errors and trailing commas."""
92
- issues: List[DiagnosticIssue] = []
93
- root = Path(workspace_dir).resolve()
94
-
95
- for jf in root.glob("**/*.json"):
96
- if not jf.is_file() or any(p in jf.parts for p in (".git", "node_modules", ".venv", "venv", "dist", "build")):
97
- continue
98
-
99
- try:
100
- with open(jf, "r", encoding="utf-8") as f:
101
- content = f.read()
102
- json.loads(content)
103
- except json.JSONDecodeError as jde:
104
- can_heal, _ = cls.repair_json_text(content)
105
- issues.append(DiagnosticIssue(
106
- category=DiagnosticCategory.POLYGLOT.value,
107
- severity=SeverityLevel.ERROR.value,
108
- file_path=str(jf),
109
- line=jde.lineno,
110
- column=jde.colno,
111
- error_code="TZ-JSON-SYNTAX-ERROR",
112
- message=f"JSON syntax error in {jf.name}: {jde.msg}",
113
- suggested_fix="Surgically heal trailing commas, comments, and quotes" if can_heal else "Fix JSON structure",
114
- auto_fixable=can_heal,
115
- metadata={"action": "repair_json_file", "path": str(jf)}
116
- ))
117
- except Exception:
118
- continue
119
-
120
- return issues
121
-
122
- # -------------------------------------------------------------------------
123
- # 2. GITIGNORE HYGIENE DOCTOR
124
- # -------------------------------------------------------------------------
125
- @classmethod
126
- def check_gitignore_hygiene(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
127
- """Verify .gitignore exists and contains critical secret patterns (.env, *.key)."""
128
- issues: List[DiagnosticIssue] = []
129
- root = Path(workspace_dir).resolve()
130
- gi_file = root / ".gitignore"
131
-
132
- if not gi_file.is_file():
133
- issues.append(DiagnosticIssue(
134
- category=DiagnosticCategory.SECURITY.value,
135
- severity=SeverityLevel.ERROR.value,
136
- file_path=str(root),
137
- line=None,
138
- column=None,
139
- error_code="TZ-GIT-MISSING-GITIGNORE",
140
- message="No '.gitignore' file found in workspace root (risk of committing secrets)",
141
- suggested_fix="Generate comprehensive .gitignore with .env and secret patterns",
142
- auto_fixable=True,
143
- metadata={"action": "create_gitignore", "path": str(gi_file)}
144
- ))
145
- return issues
146
-
147
- try:
148
- with open(gi_file, "r", encoding="utf-8", errors="replace") as f:
149
- content = f.read()
150
- lines = set(line.strip() for line in content.splitlines() if line.strip())
151
-
152
- missing_entries = []
153
- for entry in cls.SENSITIVE_GITIGNORE_ENTRIES:
154
- if entry not in lines and not any(l.startswith(entry) for l in lines):
155
- missing_entries.append(entry)
156
-
157
- if missing_entries:
158
- issues.append(DiagnosticIssue(
159
- category=DiagnosticCategory.SECURITY.value,
160
- severity=SeverityLevel.WARNING.value,
161
- file_path=str(gi_file),
162
- line=1,
163
- column=0,
164
- error_code="TZ-GIT-UNPROTECTED-SECRETS",
165
- message=f".gitignore is missing critical secret patterns: {', '.join(missing_entries[:4])}",
166
- suggested_fix=f"Append {', '.join(missing_entries)} to .gitignore",
167
- auto_fixable=True,
168
- metadata={"action": "append_gitignore_entries", "entries": missing_entries, "path": str(gi_file)}
169
- ))
170
- except Exception:
171
- pass
172
-
173
- return issues
174
-
175
- # -------------------------------------------------------------------------
176
- # 3. GITATTRIBUTES LF/CRLF NORMALIZER
177
- # -------------------------------------------------------------------------
178
- @classmethod
179
- def check_gitattributes(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
180
- """Verify .gitattributes exists to prevent cross-platform CRLF/LF chaos."""
181
- issues: List[DiagnosticIssue] = []
182
- root = Path(workspace_dir).resolve()
183
- ga_file = root / ".gitattributes"
184
-
185
- if not ga_file.is_file():
186
- issues.append(DiagnosticIssue(
187
- category=DiagnosticCategory.ENVIRONMENT.value,
188
- severity=SeverityLevel.INFO.value,
189
- file_path=str(ga_file),
190
- line=None,
191
- column=None,
192
- error_code="TZ-GIT-MISSING-GITATTRIBUTES",
193
- message="No '.gitattributes' found; cross-platform line endings (CRLF vs LF) may drift",
194
- suggested_fix="Generate standard .gitattributes ('* text=auto eol=lf')",
195
- auto_fixable=True,
196
- metadata={"action": "create_gitattributes", "path": str(ga_file)}
197
- ))
198
-
199
- return issues
200
-
201
- @classmethod
202
- def diagnose_workspace(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
203
- """Run all polyglot configuration and git hygiene audits."""
204
- issues: List[DiagnosticIssue] = []
205
- issues.extend(cls.check_json_files(workspace_dir))
206
- issues.extend(cls.check_gitignore_hygiene(workspace_dir))
207
- issues.extend(cls.check_gitattributes(workspace_dir))
208
- return issues
209
-
210
- @classmethod
211
- def execute_config_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
212
- """Execute repairs for JSON files, .gitignore, and .gitattributes."""
213
- actions: List[HealAction] = []
214
-
215
- for issue in issues:
216
- action_type = issue.metadata.get("action")
217
- file_p = issue.metadata.get("path")
218
- if not issue.auto_fixable or not action_type or not file_p:
219
- continue
220
-
221
- t0 = time.time()
222
- p = Path(file_p)
223
-
224
- try:
225
- # 1. Repair JSON file
226
- if action_type == "repair_json_file" and p.is_file():
227
- with open(p, "r", encoding="utf-8", errors="replace") as f:
228
- content = f.read()
229
- success, rep = cls.repair_json_text(content)
230
- if success and rep != content:
231
- diff = "".join(difflib.unified_diff(
232
- content.splitlines(keepends=True),
233
- rep.splitlines(keepends=True),
234
- fromfile="before.json",
235
- tofile="after.json"
236
- ))
237
- if not dry_run:
238
- with open(p, "w", encoding="utf-8", newline="\n") as f:
239
- f.write(rep)
240
- actions.append(HealAction(
241
- category=DiagnosticCategory.POLYGLOT.value,
242
- action_type=action_type,
243
- file_path=file_p,
244
- description=f"Surgically repaired JSON syntax in {p.name}",
245
- success=True,
246
- diff=diff,
247
- duration_ms=round((time.time() - t0) * 1000, 2)
248
- ))
249
-
250
- # 2. Create .gitignore
251
- elif action_type == "create_gitignore":
252
- entries = ["# T-Zero Autonomous Security Gitignore", "__pycache__/", "*.pyc", ".venv/", "venv/", "node_modules/", "dist/", "build/"] + cls.SENSITIVE_GITIGNORE_ENTRIES
253
- content = "\n".join(entries) + "\n"
254
- if not dry_run:
255
- with open(p, "w", encoding="utf-8", newline="\n") as f:
256
- f.write(content)
257
- actions.append(HealAction(
258
- category=DiagnosticCategory.SECURITY.value,
259
- action_type=action_type,
260
- file_path=file_p,
261
- description="Generated secure .gitignore protecting .env and key files",
262
- success=True,
263
- duration_ms=round((time.time() - t0) * 1000, 2)
264
- ))
265
-
266
- # 3. Append to .gitignore
267
- elif action_type == "append_gitignore_entries":
268
- missing = issue.metadata.get("entries", [])
269
- if missing:
270
- append_str = "\n# T-Zero Security Guard Protections\n" + "\n".join(missing) + "\n"
271
- if not dry_run:
272
- with open(p, "a", encoding="utf-8") as f:
273
- f.write(append_str)
274
- actions.append(HealAction(
275
- category=DiagnosticCategory.SECURITY.value,
276
- action_type=action_type,
277
- file_path=file_p,
278
- description=f"Appended {len(missing)} security patterns ({', '.join(missing[:3])}) to .gitignore",
279
- success=True,
280
- duration_ms=round((time.time() - t0) * 1000, 2)
281
- ))
282
-
283
- # 4. Create .gitattributes
284
- elif action_type == "create_gitattributes":
285
- content = (
286
- "# T-Zero Standard Gitattributes - Normalize LF Line Endings\n"
287
- "* text=auto eol=lf\n"
288
- "*.py text eol=lf\n"
289
- "*.json text eol=lf\n"
290
- "*.md text eol=lf\n"
291
- "*.yml text eol=lf\n"
292
- "*.yaml text eol=lf\n"
293
- "*.sh text eol=lf\n"
294
- "*.bat text eol=crlf\n"
295
- "*.ps1 text eol=crlf\n"
296
- )
297
- if not dry_run:
298
- with open(p, "w", encoding="utf-8", newline="\n") as f:
299
- f.write(content)
300
- actions.append(HealAction(
301
- category=DiagnosticCategory.ENVIRONMENT.value,
302
- action_type=action_type,
303
- file_path=file_p,
304
- description="Created .gitattributes to ensure cross-platform LF line ending consistency",
305
- success=True,
306
- duration_ms=round((time.time() - t0) * 1000, 2)
307
- ))
308
- except Exception as e:
309
- actions.append(HealAction(
310
- category=DiagnosticCategory.POLYGLOT.value,
311
- action_type=action_type,
312
- file_path=file_p,
313
- description=f"Failed configuration remediation: {e}",
314
- success=False,
315
- duration_ms=round((time.time() - t0) * 1000, 2)
316
- ))
317
-
318
- return actions
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Polyglot Configuration & Environment Files Healer.
3
+
4
+ Performs forensic repair and hygiene checks on configuration files:
5
+ - JSON repair engine (strips trailing commas, single quotes, unquoted keys, and JS comments).
6
+ - Gitignore & Security hygiene (verifies .env, *.pem, *.key are in .gitignore).
7
+ - Gitattributes LF/CRLF normalizer (* text=auto eol=lf).
8
+ - EditorConfig generator and validator.
9
+
10
+ Author: Toprak Ahmet Aydogmus (Siber Akademi)
11
+ Version: 10.4.0
12
+ """
13
+
14
+ import difflib
15
+ import json
16
+ import os
17
+ import re
18
+ import time
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Any, Dict, List, Optional, Set, Tuple
22
+
23
+ from .models import (
24
+ DiagnosticCategory,
25
+ DiagnosticIssue,
26
+ HealAction,
27
+ SeverityLevel,
28
+ )
29
+
30
+
31
+ class PolyglotConfigHealer:
32
+ """Specialized repair engine for JSON, YAML, Gitignore, and Gitattributes files."""
33
+
34
+ SENSITIVE_GITIGNORE_ENTRIES = [
35
+ ".env",
36
+ ".env.local",
37
+ "*.pem",
38
+ "*.key",
39
+ "*.pfx",
40
+ "*.p12",
41
+ "id_rsa",
42
+ "id_ed25519",
43
+ ".tzero/fixer_backups/",
44
+ ]
45
+
46
+ # -------------------------------------------------------------------------
47
+ # 1. JSON SURGICAL REPAIR ENGINE
48
+ # -------------------------------------------------------------------------
49
+ @classmethod
50
+ def heal_json_string(cls, content: str) -> Any:
51
+ """Helper to repair trailing commas and single quotes in JSON strings."""
52
+ @dataclass
53
+ class JsonHealResult:
54
+ original_content: str
55
+ repaired_content: str
56
+ changed: bool
57
+
58
+ changed, repaired = cls.repair_json_text(content)
59
+ return JsonHealResult(
60
+ original_content=content,
61
+ repaired_content=repaired,
62
+ changed=changed,
63
+ )
64
+
65
+ @classmethod
66
+ def repair_json_text(cls, text: str) -> Tuple[bool, str]:
67
+ """Surgically repair trailing commas, single quotes, and comments in JSON."""
68
+ repaired = text
69
+
70
+ # Strip line comments // ...
71
+ repaired = re.sub(r"^\s*//.*$", "", repaired, flags=re.MULTILINE)
72
+ # Strip block comments /* ... */
73
+ repaired = re.sub(r"/\*.*?\*/", "", repaired, flags=re.DOTALL)
74
+
75
+ # Convert single quotes to double quotes (around keys/values)
76
+ repaired = re.sub(r"\'([^\'\\]*)\'", r'"\1"', repaired)
77
+
78
+ # Strip trailing commas in objects: , } -> }
79
+ repaired = re.sub(r",\s*(\})", r"\1", repaired)
80
+ # Strip trailing commas in arrays: , ] -> ]
81
+ repaired = re.sub(r",\s*(\])", r"\1", repaired)
82
+
83
+ try:
84
+ json.loads(repaired)
85
+ return True, repaired
86
+ except Exception:
87
+ return False, text
88
+
89
+ @classmethod
90
+ def check_json_files(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
91
+ """Inspect all JSON files in workspace for syntax errors and trailing commas."""
92
+ issues: List[DiagnosticIssue] = []
93
+ root = Path(workspace_dir).resolve()
94
+
95
+ for jf in root.glob("**/*.json"):
96
+ if not jf.is_file() or any(p in jf.parts for p in (".git", "node_modules", ".venv", "venv", "dist", "build")):
97
+ continue
98
+
99
+ try:
100
+ with open(jf, "r", encoding="utf-8") as f:
101
+ content = f.read()
102
+ json.loads(content)
103
+ except json.JSONDecodeError as jde:
104
+ can_heal, _ = cls.repair_json_text(content)
105
+ issues.append(DiagnosticIssue(
106
+ category=DiagnosticCategory.POLYGLOT.value,
107
+ severity=SeverityLevel.ERROR.value,
108
+ file_path=str(jf),
109
+ line=jde.lineno,
110
+ column=jde.colno,
111
+ error_code="TZ-JSON-SYNTAX-ERROR",
112
+ message=f"JSON syntax error in {jf.name}: {jde.msg}",
113
+ suggested_fix="Surgically heal trailing commas, comments, and quotes" if can_heal else "Fix JSON structure",
114
+ auto_fixable=can_heal,
115
+ metadata={"action": "repair_json_file", "path": str(jf)}
116
+ ))
117
+ except Exception:
118
+ continue
119
+
120
+ return issues
121
+
122
+ # -------------------------------------------------------------------------
123
+ # 2. GITIGNORE HYGIENE DOCTOR
124
+ # -------------------------------------------------------------------------
125
+ @classmethod
126
+ def check_gitignore_hygiene(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
127
+ """Verify .gitignore exists and contains critical secret patterns (.env, *.key)."""
128
+ issues: List[DiagnosticIssue] = []
129
+ root = Path(workspace_dir).resolve()
130
+ gi_file = root / ".gitignore"
131
+
132
+ if not gi_file.is_file():
133
+ issues.append(DiagnosticIssue(
134
+ category=DiagnosticCategory.SECURITY.value,
135
+ severity=SeverityLevel.ERROR.value,
136
+ file_path=str(root),
137
+ line=None,
138
+ column=None,
139
+ error_code="TZ-GIT-MISSING-GITIGNORE",
140
+ message="No '.gitignore' file found in workspace root (risk of committing secrets)",
141
+ suggested_fix="Generate comprehensive .gitignore with .env and secret patterns",
142
+ auto_fixable=True,
143
+ metadata={"action": "create_gitignore", "path": str(gi_file)}
144
+ ))
145
+ return issues
146
+
147
+ try:
148
+ with open(gi_file, "r", encoding="utf-8", errors="replace") as f:
149
+ content = f.read()
150
+ lines = set(line.strip() for line in content.splitlines() if line.strip())
151
+
152
+ missing_entries = []
153
+ for entry in cls.SENSITIVE_GITIGNORE_ENTRIES:
154
+ if entry not in lines and not any(l.startswith(entry) for l in lines):
155
+ missing_entries.append(entry)
156
+
157
+ if missing_entries:
158
+ issues.append(DiagnosticIssue(
159
+ category=DiagnosticCategory.SECURITY.value,
160
+ severity=SeverityLevel.WARNING.value,
161
+ file_path=str(gi_file),
162
+ line=1,
163
+ column=0,
164
+ error_code="TZ-GIT-UNPROTECTED-SECRETS",
165
+ message=f".gitignore is missing critical secret patterns: {', '.join(missing_entries[:4])}",
166
+ suggested_fix=f"Append {', '.join(missing_entries)} to .gitignore",
167
+ auto_fixable=True,
168
+ metadata={"action": "append_gitignore_entries", "entries": missing_entries, "path": str(gi_file)}
169
+ ))
170
+ except Exception:
171
+ pass
172
+
173
+ return issues
174
+
175
+ # -------------------------------------------------------------------------
176
+ # 3. GITATTRIBUTES LF/CRLF NORMALIZER
177
+ # -------------------------------------------------------------------------
178
+ @classmethod
179
+ def check_gitattributes(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
180
+ """Verify .gitattributes exists to prevent cross-platform CRLF/LF chaos."""
181
+ issues: List[DiagnosticIssue] = []
182
+ root = Path(workspace_dir).resolve()
183
+ ga_file = root / ".gitattributes"
184
+
185
+ if not ga_file.is_file():
186
+ issues.append(DiagnosticIssue(
187
+ category=DiagnosticCategory.ENVIRONMENT.value,
188
+ severity=SeverityLevel.INFO.value,
189
+ file_path=str(ga_file),
190
+ line=None,
191
+ column=None,
192
+ error_code="TZ-GIT-MISSING-GITATTRIBUTES",
193
+ message="No '.gitattributes' found; cross-platform line endings (CRLF vs LF) may drift",
194
+ suggested_fix="Generate standard .gitattributes ('* text=auto eol=lf')",
195
+ auto_fixable=True,
196
+ metadata={"action": "create_gitattributes", "path": str(ga_file)}
197
+ ))
198
+
199
+ return issues
200
+
201
+ @classmethod
202
+ def diagnose_workspace(cls, workspace_dir: str = ".") -> List[DiagnosticIssue]:
203
+ """Run all polyglot configuration and git hygiene audits."""
204
+ issues: List[DiagnosticIssue] = []
205
+ issues.extend(cls.check_json_files(workspace_dir))
206
+ issues.extend(cls.check_gitignore_hygiene(workspace_dir))
207
+ issues.extend(cls.check_gitattributes(workspace_dir))
208
+ return issues
209
+
210
+ @classmethod
211
+ def execute_config_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
212
+ """Execute repairs for JSON files, .gitignore, and .gitattributes."""
213
+ actions: List[HealAction] = []
214
+
215
+ for issue in issues:
216
+ action_type = issue.metadata.get("action")
217
+ file_p = issue.metadata.get("path")
218
+ if not issue.auto_fixable or not action_type or not file_p:
219
+ continue
220
+
221
+ t0 = time.time()
222
+ p = Path(file_p)
223
+
224
+ try:
225
+ # 1. Repair JSON file
226
+ if action_type == "repair_json_file" and p.is_file():
227
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
228
+ content = f.read()
229
+ success, rep = cls.repair_json_text(content)
230
+ if success and rep != content:
231
+ diff = "".join(difflib.unified_diff(
232
+ content.splitlines(keepends=True),
233
+ rep.splitlines(keepends=True),
234
+ fromfile="before.json",
235
+ tofile="after.json"
236
+ ))
237
+ if not dry_run:
238
+ with open(p, "w", encoding="utf-8", newline="\n") as f:
239
+ f.write(rep)
240
+ actions.append(HealAction(
241
+ category=DiagnosticCategory.POLYGLOT.value,
242
+ action_type=action_type,
243
+ file_path=file_p,
244
+ description=f"Surgically repaired JSON syntax in {p.name}",
245
+ success=True,
246
+ diff=diff,
247
+ duration_ms=round((time.time() - t0) * 1000, 2)
248
+ ))
249
+
250
+ # 2. Create .gitignore
251
+ elif action_type == "create_gitignore":
252
+ entries = ["# T-Zero Autonomous Security Gitignore", "__pycache__/", "*.pyc", ".venv/", "venv/", "node_modules/", "dist/", "build/"] + cls.SENSITIVE_GITIGNORE_ENTRIES
253
+ content = "\n".join(entries) + "\n"
254
+ if not dry_run:
255
+ with open(p, "w", encoding="utf-8", newline="\n") as f:
256
+ f.write(content)
257
+ actions.append(HealAction(
258
+ category=DiagnosticCategory.SECURITY.value,
259
+ action_type=action_type,
260
+ file_path=file_p,
261
+ description="Generated secure .gitignore protecting .env and key files",
262
+ success=True,
263
+ duration_ms=round((time.time() - t0) * 1000, 2)
264
+ ))
265
+
266
+ # 3. Append to .gitignore
267
+ elif action_type == "append_gitignore_entries":
268
+ missing = issue.metadata.get("entries", [])
269
+ if missing:
270
+ append_str = "\n# T-Zero Security Guard Protections\n" + "\n".join(missing) + "\n"
271
+ if not dry_run:
272
+ with open(p, "a", encoding="utf-8") as f:
273
+ f.write(append_str)
274
+ actions.append(HealAction(
275
+ category=DiagnosticCategory.SECURITY.value,
276
+ action_type=action_type,
277
+ file_path=file_p,
278
+ description=f"Appended {len(missing)} security patterns ({', '.join(missing[:3])}) to .gitignore",
279
+ success=True,
280
+ duration_ms=round((time.time() - t0) * 1000, 2)
281
+ ))
282
+
283
+ # 4. Create .gitattributes
284
+ elif action_type == "create_gitattributes":
285
+ content = (
286
+ "# T-Zero Standard Gitattributes - Normalize LF Line Endings\n"
287
+ "* text=auto eol=lf\n"
288
+ "*.py text eol=lf\n"
289
+ "*.json text eol=lf\n"
290
+ "*.md text eol=lf\n"
291
+ "*.yml text eol=lf\n"
292
+ "*.yaml text eol=lf\n"
293
+ "*.sh text eol=lf\n"
294
+ "*.bat text eol=crlf\n"
295
+ "*.ps1 text eol=crlf\n"
296
+ )
297
+ if not dry_run:
298
+ with open(p, "w", encoding="utf-8", newline="\n") as f:
299
+ f.write(content)
300
+ actions.append(HealAction(
301
+ category=DiagnosticCategory.ENVIRONMENT.value,
302
+ action_type=action_type,
303
+ file_path=file_p,
304
+ description="Created .gitattributes to ensure cross-platform LF line ending consistency",
305
+ success=True,
306
+ duration_ms=round((time.time() - t0) * 1000, 2)
307
+ ))
308
+ except Exception as e:
309
+ actions.append(HealAction(
310
+ category=DiagnosticCategory.POLYGLOT.value,
311
+ action_type=action_type,
312
+ file_path=file_p,
313
+ description=f"Failed configuration remediation: {e}",
314
+ success=False,
315
+ duration_ms=round((time.time() - t0) * 1000, 2)
316
+ ))
317
+
318
+ return actions