tzero-mcp 10.7.4 → 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 +56 -29
  2. package/CONTRIBUTING.md +71 -71
  3. package/README.md +64 -64
  4. package/bin/tzero-mcp.js +62 -66
  5. package/bin/tzero.js +61 -65
  6. package/index.d.ts +25 -25
  7. package/index.js +15 -15
  8. package/package.json +88 -88
  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 -43
  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,313 +1,313 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- T-Zero Polyglot Tokenizers, AST Parsers, & Syntax Diagnostics
4
- =============================================================
5
- Zero-dependency, multi-language lexical analysis and AST inspection engine.
6
- Provides syntax parsers and anti-pattern detectors for:
7
- - JavaScript / TypeScript (ES6+): Unclosed delimiters, var declarations, unhandled Promise rejections
8
- - Rust (Cargo & Source): Edition modernizations, unpinned dependencies, unsafe block audits
9
- - Go (go.mod & Source): Deprecated go directives, unhandled error variables, goroutine leak checks
10
- - Shell Scripts (Bash / POSIX sh): Missing shebang, unquoted variables, pipefail safety flags
11
-
12
- Author: Siber Akademi T-Zero R&D Team
13
- License: MIT (100% Free, Local Offline, Zero-Leak)
14
- """
15
-
16
- from __future__ import annotations
17
-
18
- import os
19
- import re
20
- from dataclasses import dataclass, field
21
- from pathlib import Path
22
- from typing import Any, Dict, List, Optional, Set, Tuple
23
-
24
- from tzero_fixer.models import (
25
- DiagnosticCategory,
26
- DiagnosticIssue,
27
- DiffHunk,
28
- HealAction,
29
- SeverityLevel,
30
- )
31
-
32
-
33
- @dataclass
34
- class TokenMatch:
35
- kind: str
36
- value: str
37
- line: int
38
- column: int
39
-
40
-
41
- class JavaScriptTypeScriptDoctor:
42
- """Lexical analyzer and anti-pattern healer for JS and TS codebases."""
43
-
44
- VAR_DECLARATION_PATTERN = re.compile(r"\bvar\s+([A-Za-z_$][A-Za-z0-9_$]*)", re.MULTILINE)
45
- CONSOLE_LOG_PATTERN = re.compile(r"\bconsole\.(log|debug|info)\s*\(", re.MULTILINE)
46
- ALERT_CALL_PATTERN = re.compile(r"\balert\s*\(", re.MULTILINE)
47
- EVAL_CALL_PATTERN = re.compile(r"\beval\s*\(", re.MULTILINE)
48
- SYNC_FS_PATTERN = re.compile(r"\bfs\.(readFileSync|writeFileSync|existsSync)\b", re.MULTILINE)
49
-
50
- @classmethod
51
- def diagnose_file(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
52
- issues: List[DiagnosticIssue] = []
53
- lines = content.splitlines()
54
-
55
- for idx, line in enumerate(lines, 1):
56
- stripped = line.strip()
57
- if stripped.startswith("//") or stripped.startswith("/*") or stripped.startswith("*"):
58
- continue
59
-
60
- # 1. Flag legacy 'var' keyword
61
- var_match = cls.VAR_DECLARATION_PATTERN.search(line)
62
- if var_match:
63
- issues.append(
64
- DiagnosticIssue(
65
- category=DiagnosticCategory.POLYGLOT.value,
66
- severity=SeverityLevel.WARNING.value,
67
- file_path=file_path,
68
- line=idx,
69
- column=var_match.start(),
70
- error_code="TZ-JS-001",
71
- message=f"Legacy 'var {var_match.group(1)}' declaration has function-scoped hoisting semantics.",
72
- suggested_fix="Replace 'var' with block-scoped 'let' or 'const'.",
73
- auto_fixable=True,
74
- metadata={"action": "heal_var_to_let", "lineno": idx, "path": file_path},
75
- )
76
- )
77
-
78
- # 2. Dangerous eval() call
79
- eval_match = cls.ALERT_CALL_PATTERN.search(line) or cls.EVAL_CALL_PATTERN.search(line)
80
- if eval_match:
81
- issues.append(
82
- DiagnosticIssue(
83
- category=DiagnosticCategory.SECURITY.value,
84
- severity=SeverityLevel.CRITICAL.value,
85
- file_path=file_path,
86
- line=idx,
87
- column=eval_match.start(),
88
- error_code="TZ-JS-002",
89
- message="Arbitrary code execution risk with 'eval()' in JavaScript.",
90
- suggested_fix="Parse data using JSON.parse() or a safe parser.",
91
- auto_fixable=False,
92
- )
93
- )
94
-
95
- # 3. Blocking synchronous filesystem in Node.js
96
- sync_match = cls.SYNC_FS_PATTERN.search(line)
97
- if sync_match:
98
- issues.append(
99
- DiagnosticIssue(
100
- category=DiagnosticCategory.PERFORMANCE.value,
101
- severity=SeverityLevel.INFO.value,
102
- file_path=file_path,
103
- line=idx,
104
- column=sync_match.start(),
105
- error_code="TZ-JS-003",
106
- message=f"Synchronous Node.js method '{sync_match.group(0)}' blocks the V8 event loop.",
107
- suggested_fix="Migrate to async 'fs.promises' with await.",
108
- auto_fixable=False,
109
- )
110
- )
111
-
112
- return issues
113
-
114
- @classmethod
115
- def execute_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
116
- actions: List[HealAction] = []
117
- for issue in issues:
118
- action = issue.metadata.get("action")
119
- file_p = issue.metadata.get("path")
120
- lineno = issue.metadata.get("lineno")
121
- if not issue.auto_fixable or action != "heal_var_to_let" or not file_p or not lineno:
122
- continue
123
-
124
- p = Path(file_p)
125
- if not p.is_file():
126
- continue
127
-
128
- try:
129
- with open(p, "r", encoding="utf-8", errors="replace") as f:
130
- lines = f.readlines()
131
- if 0 < lineno <= len(lines):
132
- orig = lines[lineno - 1]
133
- mod = re.sub(r"\bvar\s+", "let ", orig, count=1)
134
- if mod != orig:
135
- lines[lineno - 1] = mod
136
- if not dry_run:
137
- with open(p, "w", encoding="utf-8", newline="\n") as f:
138
- f.writelines(lines)
139
- actions.append(
140
- HealAction(
141
- category=DiagnosticCategory.POLYGLOT.value,
142
- action_type="heal_var_to_let",
143
- file_path=file_p,
144
- description=f"Replaced legacy 'var' with 'let' at line {lineno}",
145
- success=True,
146
- )
147
- )
148
- except Exception as e:
149
- actions.append(
150
- HealAction(
151
- category=DiagnosticCategory.POLYGLOT.value,
152
- action_type=action,
153
- file_path=file_p,
154
- description=f"Failed heal: {e}",
155
- success=False,
156
- )
157
- )
158
- return actions
159
-
160
-
161
- class RustToolchainDoctor:
162
- """Audits Rust Cargo configurations and source code patterns."""
163
-
164
- UNSAFE_BLOCK_PATTERN = re.compile(r"\bunsafe\s*\{", re.MULTILINE)
165
- UNWRAP_CALL_PATTERN = re.compile(r"\.unwrap\s*\(\)", re.MULTILINE)
166
-
167
- @classmethod
168
- def diagnose_cargo_toml(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
169
- issues: List[DiagnosticIssue] = []
170
- lines = content.splitlines()
171
- has_edition = False
172
-
173
- for idx, line in enumerate(lines, 1):
174
- stripped = line.strip()
175
- if stripped.startswith("edition"):
176
- has_edition = True
177
- if '"2015"' in stripped or "'2015'" in stripped:
178
- issues.append(
179
- DiagnosticIssue(
180
- category=DiagnosticCategory.POLYGLOT.value,
181
- severity=SeverityLevel.WARNING.value,
182
- file_path=file_path,
183
- line=idx,
184
- error_code="TZ-RUST-001",
185
- message="Outdated Rust 2015 edition in Cargo.toml.",
186
- suggested_fix="Upgrade to edition = '2021'.",
187
- auto_fixable=True,
188
- metadata={"action": "upgrade_rust_edition", "lineno": idx, "path": file_path},
189
- )
190
- )
191
-
192
- if not has_edition and "[package]" in content:
193
- issues.append(
194
- DiagnosticIssue(
195
- category=DiagnosticCategory.POLYGLOT.value,
196
- severity=SeverityLevel.WARNING.value,
197
- file_path=file_path,
198
- error_code="TZ-RUST-002",
199
- message="Missing 'edition' in Cargo.toml [package] section.",
200
- suggested_fix="Specify edition = '2021'.",
201
- auto_fixable=False,
202
- )
203
- )
204
-
205
- return issues
206
-
207
- @classmethod
208
- def diagnose_source_file(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
209
- issues: List[DiagnosticIssue] = []
210
- lines = content.splitlines()
211
-
212
- for idx, line in enumerate(lines, 1):
213
- stripped = line.strip()
214
- if stripped.startswith("//"):
215
- continue
216
-
217
- # Check unwrap() calls which cause panics in production
218
- if cls.UNWRAP_CALL_PATTERN.search(line):
219
- issues.append(
220
- DiagnosticIssue(
221
- category=DiagnosticCategory.POLYGLOT.value,
222
- severity=SeverityLevel.INFO.value,
223
- file_path=file_path,
224
- line=idx,
225
- error_code="TZ-RUST-003",
226
- message="Production Rust code uses '.unwrap()', risking unhandled panics on None/Err.",
227
- suggested_fix="Use the '?' operator, 'unwrap_or_default()', or match handling.",
228
- auto_fixable=False,
229
- )
230
- )
231
-
232
- return issues
233
-
234
-
235
- class GoToolchainDoctor:
236
- """Diagnostics for Go go.mod modules and source code."""
237
-
238
- @classmethod
239
- def diagnose_go_mod(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
240
- issues: List[DiagnosticIssue] = []
241
- lines = content.splitlines()
242
-
243
- for idx, line in enumerate(lines, 1):
244
- stripped = line.strip()
245
- if stripped.startswith("go "):
246
- ver_str = stripped.split("go ")[1].strip()
247
- try:
248
- parts = [int(p) for p in ver_str.split(".")[:2]]
249
- if parts[0] == 1 and parts[1] < 18:
250
- issues.append(
251
- DiagnosticIssue(
252
- category=DiagnosticCategory.POLYGLOT.value,
253
- severity=SeverityLevel.WARNING.value,
254
- file_path=file_path,
255
- line=idx,
256
- error_code="TZ-GO-001",
257
- message=f"Deprecated Go version '{ver_str}' in go.mod lacks generics and security fixes.",
258
- suggested_fix="Upgrade to 'go 1.22' or latest stable.",
259
- auto_fixable=True,
260
- metadata={"action": "upgrade_go_version", "lineno": idx, "path": file_path},
261
- )
262
- )
263
- except Exception:
264
- pass
265
-
266
- return issues
267
-
268
-
269
- class ShellScriptDoctor:
270
- """Diagnostics for Bash and POSIX shell scripts (.sh)."""
271
-
272
- @classmethod
273
- def diagnose_file(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
274
- issues: List[DiagnosticIssue] = []
275
- lines = content.splitlines()
276
- if not lines:
277
- return issues
278
-
279
- # 1. Missing shebang
280
- first_line = lines[0].strip()
281
- if not first_line.startswith("#!"):
282
- issues.append(
283
- DiagnosticIssue(
284
- category=DiagnosticCategory.POLYGLOT.value,
285
- severity=SeverityLevel.WARNING.value,
286
- file_path=file_path,
287
- line=1,
288
- error_code="TZ-SH-001",
289
- message="Shell script lacks '#!/usr/bin/env bash' shebang header.",
290
- suggested_fix="Add '#!/usr/bin/env bash' at line 1.",
291
- auto_fixable=True,
292
- metadata={"action": "add_shebang", "lineno": 1, "path": file_path},
293
- )
294
- )
295
-
296
- # 2. Missing 'set -e' or 'set -euo pipefail' safety options
297
- has_safety_flags = any("set -e" in l or "set -o pipefail" in l for l in lines[:10])
298
- if not has_safety_flags and len(lines) > 5:
299
- issues.append(
300
- DiagnosticIssue(
301
- category=DiagnosticCategory.POLYGLOT.value,
302
- severity=SeverityLevel.INFO.value,
303
- file_path=file_path,
304
- error_code="TZ-SH-002",
305
- message="Shell script does not enable fail-fast 'set -euo pipefail'. Errors may silently pass.",
306
- suggested_fix="Insert 'set -euo pipefail' near script top.",
307
- auto_fixable=True,
308
- metadata={"action": "add_pipefail", "lineno": 2, "path": file_path},
309
- )
310
- )
311
-
312
- return issues
313
-
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-Zero Polyglot Tokenizers, AST Parsers, & Syntax Diagnostics
4
+ =============================================================
5
+ Zero-dependency, multi-language lexical analysis and AST inspection engine.
6
+ Provides syntax parsers and anti-pattern detectors for:
7
+ - JavaScript / TypeScript (ES6+): Unclosed delimiters, var declarations, unhandled Promise rejections
8
+ - Rust (Cargo & Source): Edition modernizations, unpinned dependencies, unsafe block audits
9
+ - Go (go.mod & Source): Deprecated go directives, unhandled error variables, goroutine leak checks
10
+ - Shell Scripts (Bash / POSIX sh): Missing shebang, unquoted variables, pipefail safety flags
11
+
12
+ Author: Siber Akademi T-Zero R&D Team
13
+ License: MIT (100% Free, Local Offline, Zero-Leak)
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import re
20
+ from dataclasses import dataclass, field
21
+ from pathlib import Path
22
+ from typing import Any, Dict, List, Optional, Set, Tuple
23
+
24
+ from tzero.tzero_fixer.models import (
25
+ DiagnosticCategory,
26
+ DiagnosticIssue,
27
+ DiffHunk,
28
+ HealAction,
29
+ SeverityLevel,
30
+ )
31
+
32
+
33
+ @dataclass
34
+ class TokenMatch:
35
+ kind: str
36
+ value: str
37
+ line: int
38
+ column: int
39
+
40
+
41
+ class JavaScriptTypeScriptDoctor:
42
+ """Lexical analyzer and anti-pattern healer for JS and TS codebases."""
43
+
44
+ VAR_DECLARATION_PATTERN = re.compile(r"\bvar\s+([A-Za-z_$][A-Za-z0-9_$]*)", re.MULTILINE)
45
+ CONSOLE_LOG_PATTERN = re.compile(r"\bconsole\.(log|debug|info)\s*\(", re.MULTILINE)
46
+ ALERT_CALL_PATTERN = re.compile(r"\balert\s*\(", re.MULTILINE)
47
+ EVAL_CALL_PATTERN = re.compile(r"\beval\s*\(", re.MULTILINE)
48
+ SYNC_FS_PATTERN = re.compile(r"\bfs\.(readFileSync|writeFileSync|existsSync)\b", re.MULTILINE)
49
+
50
+ @classmethod
51
+ def diagnose_file(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
52
+ issues: List[DiagnosticIssue] = []
53
+ lines = content.splitlines()
54
+
55
+ for idx, line in enumerate(lines, 1):
56
+ stripped = line.strip()
57
+ if stripped.startswith("//") or stripped.startswith("/*") or stripped.startswith("*"):
58
+ continue
59
+
60
+ # 1. Flag legacy 'var' keyword
61
+ var_match = cls.VAR_DECLARATION_PATTERN.search(line)
62
+ if var_match:
63
+ issues.append(
64
+ DiagnosticIssue(
65
+ category=DiagnosticCategory.POLYGLOT.value,
66
+ severity=SeverityLevel.WARNING.value,
67
+ file_path=file_path,
68
+ line=idx,
69
+ column=var_match.start(),
70
+ error_code="TZ-JS-001",
71
+ message=f"Legacy 'var {var_match.group(1)}' declaration has function-scoped hoisting semantics.",
72
+ suggested_fix="Replace 'var' with block-scoped 'let' or 'const'.",
73
+ auto_fixable=True,
74
+ metadata={"action": "heal_var_to_let", "lineno": idx, "path": file_path},
75
+ )
76
+ )
77
+
78
+ # 2. Dangerous eval() call
79
+ eval_match = cls.ALERT_CALL_PATTERN.search(line) or cls.EVAL_CALL_PATTERN.search(line)
80
+ if eval_match:
81
+ issues.append(
82
+ DiagnosticIssue(
83
+ category=DiagnosticCategory.SECURITY.value,
84
+ severity=SeverityLevel.CRITICAL.value,
85
+ file_path=file_path,
86
+ line=idx,
87
+ column=eval_match.start(),
88
+ error_code="TZ-JS-002",
89
+ message="Arbitrary code execution risk with 'eval()' in JavaScript.",
90
+ suggested_fix="Parse data using JSON.parse() or a safe parser.",
91
+ auto_fixable=False,
92
+ )
93
+ )
94
+
95
+ # 3. Blocking synchronous filesystem in Node.js
96
+ sync_match = cls.SYNC_FS_PATTERN.search(line)
97
+ if sync_match:
98
+ issues.append(
99
+ DiagnosticIssue(
100
+ category=DiagnosticCategory.PERFORMANCE.value,
101
+ severity=SeverityLevel.INFO.value,
102
+ file_path=file_path,
103
+ line=idx,
104
+ column=sync_match.start(),
105
+ error_code="TZ-JS-003",
106
+ message=f"Synchronous Node.js method '{sync_match.group(0)}' blocks the V8 event loop.",
107
+ suggested_fix="Migrate to async 'fs.promises' with await.",
108
+ auto_fixable=False,
109
+ )
110
+ )
111
+
112
+ return issues
113
+
114
+ @classmethod
115
+ def execute_heals(cls, issues: List[DiagnosticIssue], dry_run: bool = False) -> List[HealAction]:
116
+ actions: List[HealAction] = []
117
+ for issue in issues:
118
+ action = issue.metadata.get("action")
119
+ file_p = issue.metadata.get("path")
120
+ lineno = issue.metadata.get("lineno")
121
+ if not issue.auto_fixable or action != "heal_var_to_let" or not file_p or not lineno:
122
+ continue
123
+
124
+ p = Path(file_p)
125
+ if not p.is_file():
126
+ continue
127
+
128
+ try:
129
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
130
+ lines = f.readlines()
131
+ if 0 < lineno <= len(lines):
132
+ orig = lines[lineno - 1]
133
+ mod = re.sub(r"\bvar\s+", "let ", orig, count=1)
134
+ if mod != orig:
135
+ lines[lineno - 1] = mod
136
+ if not dry_run:
137
+ with open(p, "w", encoding="utf-8", newline="\n") as f:
138
+ f.writelines(lines)
139
+ actions.append(
140
+ HealAction(
141
+ category=DiagnosticCategory.POLYGLOT.value,
142
+ action_type="heal_var_to_let",
143
+ file_path=file_p,
144
+ description=f"Replaced legacy 'var' with 'let' at line {lineno}",
145
+ success=True,
146
+ )
147
+ )
148
+ except Exception as e:
149
+ actions.append(
150
+ HealAction(
151
+ category=DiagnosticCategory.POLYGLOT.value,
152
+ action_type=action,
153
+ file_path=file_p,
154
+ description=f"Failed heal: {e}",
155
+ success=False,
156
+ )
157
+ )
158
+ return actions
159
+
160
+
161
+ class RustToolchainDoctor:
162
+ """Audits Rust Cargo configurations and source code patterns."""
163
+
164
+ UNSAFE_BLOCK_PATTERN = re.compile(r"\bunsafe\s*\{", re.MULTILINE)
165
+ UNWRAP_CALL_PATTERN = re.compile(r"\.unwrap\s*\(\)", re.MULTILINE)
166
+
167
+ @classmethod
168
+ def diagnose_cargo_toml(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
169
+ issues: List[DiagnosticIssue] = []
170
+ lines = content.splitlines()
171
+ has_edition = False
172
+
173
+ for idx, line in enumerate(lines, 1):
174
+ stripped = line.strip()
175
+ if stripped.startswith("edition"):
176
+ has_edition = True
177
+ if '"2015"' in stripped or "'2015'" in stripped:
178
+ issues.append(
179
+ DiagnosticIssue(
180
+ category=DiagnosticCategory.POLYGLOT.value,
181
+ severity=SeverityLevel.WARNING.value,
182
+ file_path=file_path,
183
+ line=idx,
184
+ error_code="TZ-RUST-001",
185
+ message="Outdated Rust 2015 edition in Cargo.toml.",
186
+ suggested_fix="Upgrade to edition = '2021'.",
187
+ auto_fixable=True,
188
+ metadata={"action": "upgrade_rust_edition", "lineno": idx, "path": file_path},
189
+ )
190
+ )
191
+
192
+ if not has_edition and "[package]" in content:
193
+ issues.append(
194
+ DiagnosticIssue(
195
+ category=DiagnosticCategory.POLYGLOT.value,
196
+ severity=SeverityLevel.WARNING.value,
197
+ file_path=file_path,
198
+ error_code="TZ-RUST-002",
199
+ message="Missing 'edition' in Cargo.toml [package] section.",
200
+ suggested_fix="Specify edition = '2021'.",
201
+ auto_fixable=False,
202
+ )
203
+ )
204
+
205
+ return issues
206
+
207
+ @classmethod
208
+ def diagnose_source_file(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
209
+ issues: List[DiagnosticIssue] = []
210
+ lines = content.splitlines()
211
+
212
+ for idx, line in enumerate(lines, 1):
213
+ stripped = line.strip()
214
+ if stripped.startswith("//"):
215
+ continue
216
+
217
+ # Check unwrap() calls which cause panics in production
218
+ if cls.UNWRAP_CALL_PATTERN.search(line):
219
+ issues.append(
220
+ DiagnosticIssue(
221
+ category=DiagnosticCategory.POLYGLOT.value,
222
+ severity=SeverityLevel.INFO.value,
223
+ file_path=file_path,
224
+ line=idx,
225
+ error_code="TZ-RUST-003",
226
+ message="Production Rust code uses '.unwrap()', risking unhandled panics on None/Err.",
227
+ suggested_fix="Use the '?' operator, 'unwrap_or_default()', or match handling.",
228
+ auto_fixable=False,
229
+ )
230
+ )
231
+
232
+ return issues
233
+
234
+
235
+ class GoToolchainDoctor:
236
+ """Diagnostics for Go go.mod modules and source code."""
237
+
238
+ @classmethod
239
+ def diagnose_go_mod(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
240
+ issues: List[DiagnosticIssue] = []
241
+ lines = content.splitlines()
242
+
243
+ for idx, line in enumerate(lines, 1):
244
+ stripped = line.strip()
245
+ if stripped.startswith("go "):
246
+ ver_str = stripped.split("go ")[1].strip()
247
+ try:
248
+ parts = [int(p) for p in ver_str.split(".")[:2]]
249
+ if parts[0] == 1 and parts[1] < 18:
250
+ issues.append(
251
+ DiagnosticIssue(
252
+ category=DiagnosticCategory.POLYGLOT.value,
253
+ severity=SeverityLevel.WARNING.value,
254
+ file_path=file_path,
255
+ line=idx,
256
+ error_code="TZ-GO-001",
257
+ message=f"Deprecated Go version '{ver_str}' in go.mod lacks generics and security fixes.",
258
+ suggested_fix="Upgrade to 'go 1.22' or latest stable.",
259
+ auto_fixable=True,
260
+ metadata={"action": "upgrade_go_version", "lineno": idx, "path": file_path},
261
+ )
262
+ )
263
+ except Exception:
264
+ pass
265
+
266
+ return issues
267
+
268
+
269
+ class ShellScriptDoctor:
270
+ """Diagnostics for Bash and POSIX shell scripts (.sh)."""
271
+
272
+ @classmethod
273
+ def diagnose_file(cls, file_path: str, content: str) -> List[DiagnosticIssue]:
274
+ issues: List[DiagnosticIssue] = []
275
+ lines = content.splitlines()
276
+ if not lines:
277
+ return issues
278
+
279
+ # 1. Missing shebang
280
+ first_line = lines[0].strip()
281
+ if not first_line.startswith("#!"):
282
+ issues.append(
283
+ DiagnosticIssue(
284
+ category=DiagnosticCategory.POLYGLOT.value,
285
+ severity=SeverityLevel.WARNING.value,
286
+ file_path=file_path,
287
+ line=1,
288
+ error_code="TZ-SH-001",
289
+ message="Shell script lacks '#!/usr/bin/env bash' shebang header.",
290
+ suggested_fix="Add '#!/usr/bin/env bash' at line 1.",
291
+ auto_fixable=True,
292
+ metadata={"action": "add_shebang", "lineno": 1, "path": file_path},
293
+ )
294
+ )
295
+
296
+ # 2. Missing 'set -e' or 'set -euo pipefail' safety options
297
+ has_safety_flags = any("set -e" in l or "set -o pipefail" in l for l in lines[:10])
298
+ if not has_safety_flags and len(lines) > 5:
299
+ issues.append(
300
+ DiagnosticIssue(
301
+ category=DiagnosticCategory.POLYGLOT.value,
302
+ severity=SeverityLevel.INFO.value,
303
+ file_path=file_path,
304
+ error_code="TZ-SH-002",
305
+ message="Shell script does not enable fail-fast 'set -euo pipefail'. Errors may silently pass.",
306
+ suggested_fix="Insert 'set -euo pipefail' near script top.",
307
+ auto_fixable=True,
308
+ metadata={"action": "add_pipefail", "lineno": 2, "path": file_path},
309
+ )
310
+ )
311
+
312
+ return issues
313
+
@@ -24,7 +24,7 @@ from dataclasses import dataclass
24
24
  from pathlib import Path
25
25
  from typing import Any, Dict, List, Optional, Tuple
26
26
 
27
- from tzero_fixer.models import (
27
+ from tzero.tzero_fixer.models import (
28
28
  DiagnosticCategory,
29
29
  DiagnosticIssue,
30
30
  HealAction,