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,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