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,243 +1,243 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero Git Pre-Commit Zero-Leak & Token Security Guard.
3
-
4
- Automatically intercepts git commits, scanning staged files for:
5
- 1. Zero-Leak Security: Blocks accidental commits of API keys, tokens, private keys, passwords.
6
- 2. Token Bloat Alert: Warns when uncompressed staged files exceed recommended token thresholds.
7
- 3. Micro-Patch companion suggestion.
8
-
9
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
10
- Part of T-Zero Context Architect v7.0.0 Master Edition.
11
- """
12
-
13
- import os
14
- import re
15
- import sys
16
- import stat
17
- import subprocess
18
- from typing import Dict, List, Any, Optional
19
-
20
- if sys.stdout and hasattr(sys.stdout, "reconfigure"):
21
- try:
22
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
23
- except Exception:
24
- pass
25
- if sys.stderr and hasattr(sys.stderr, "reconfigure"):
26
- try:
27
- sys.stderr.reconfigure(encoding="utf-8", errors="replace")
28
- except Exception:
29
- pass
30
-
31
- from tzero_security import ZeroLeakEngine, calculate_shannon_entropy, SECRET_RULES
32
-
33
- # Backward-compatibility alias for external consumers
34
- SECRET_PATTERNS = [
35
- (rule.description, rule.pattern) for rule in SECRET_RULES
36
- ]
37
-
38
- TOKEN_WARN_THRESHOLD = 8000 # Tokens (~32,000 characters)
39
-
40
-
41
- class GitSecurityGuard:
42
- """Enterprise pre-commit guard ensuring zero secret leaks and optimal prompt tokens."""
43
-
44
- @classmethod
45
- def install_hook(cls, repo_dir: str = ".") -> Dict[str, Any]:
46
- """Installs pre-commit hook into target repository's .git/hooks directory."""
47
- abs_repo = os.path.abspath(repo_dir)
48
- git_dir = os.path.join(abs_repo, ".git")
49
-
50
- if not os.path.isdir(git_dir):
51
- return {
52
- "success": False,
53
- "message": f"Target path '{repo_dir}' is not a git repository (missing .git directory)."
54
- }
55
-
56
- hooks_dir = os.path.join(git_dir, "hooks")
57
- os.makedirs(hooks_dir, exist_ok=True)
58
-
59
- hook_path = os.path.join(hooks_dir, "pre-commit")
60
- hook_script = f"""#!/bin/sh
61
- # T-Zero Git Pre-Commit Zero-Leak & Token Guard
62
- # Auto-generated by Siber Akademi T-Zero Context Architect
63
-
64
- python -c "import tzero_guard; import sys; sys.exit(tzero_guard.GitSecurityGuard.run_cli_check('.'))"
65
- EXIT_CODE=$?
66
-
67
- if [ $EXIT_CODE -ne 0 ]; then
68
- echo "\\033[31m[T-ZERO GUARD BLOCKED COMMIT] Commit aborted due to secret leaks or policy violations.\\033[0m"
69
- exit 1
70
- fi
71
-
72
- exit 0
73
- """
74
-
75
- try:
76
- with open(hook_path, "w", encoding="utf-8", newline="\n") as f:
77
- f.write(hook_script)
78
-
79
- # Mark executable on Unix/Mac
80
- try:
81
- st = os.stat(hook_path)
82
- os.chmod(hook_path, st.st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
83
- except Exception:
84
- pass
85
-
86
- # Also create pre-commit.bat for native Windows cmd / powershell hooks
87
- bat_path = os.path.join(hooks_dir, "pre-commit.bat")
88
- bat_script = f"""@echo off
89
- REM T-Zero Git Pre-Commit Guard for Windows
90
- python -c "import tzero_guard; import sys; sys.exit(tzero_guard.GitSecurityGuard.run_cli_check('.'))"
91
- if %ERRORLEVEL% NEQ 0 (
92
- echo [T-ZERO GUARD BLOCKED COMMIT] Commit aborted due to secret leaks.
93
- exit /b 1
94
- )
95
- exit /b 0
96
- """
97
- with open(bat_path, "w", encoding="utf-8") as f:
98
- f.write(bat_script)
99
-
100
- return {
101
- "success": True,
102
- "hook_path": hook_path,
103
- "bat_path": bat_path,
104
- "message": f"Successfully installed T-Zero Pre-Commit Guard in {hook_path}"
105
- }
106
- except Exception as e:
107
- return {
108
- "success": False,
109
- "message": f"Failed to write hook file: {e}"
110
- }
111
-
112
- @classmethod
113
- def scan_staged_content(cls, files_map: Dict[str, str]) -> Dict[str, Any]:
114
- """Scans in-memory staged files map {filename: content} for secrets and token bloat."""
115
- violations = []
116
- warnings = []
117
-
118
- for filename, content in files_map.items():
119
- findings = ZeroLeakEngine.scan_text(content, check_entropy=True)
120
- for f in findings:
121
- violations.append({
122
- "file": filename,
123
- "type": f"{f.provider}: {f.description}",
124
- "match_count": 1,
125
- "line": f.line_no,
126
- "preview": f.preview,
127
- "entropy": f.entropy
128
- })
129
-
130
- # Check token bloat
131
- approx_tokens = max(1, len(content) // 4)
132
- if approx_tokens > TOKEN_WARN_THRESHOLD:
133
- warnings.append(
134
- f"File '{filename}' has {approx_tokens:,} tokens. Consider compressing with T-Zero before committing."
135
- )
136
-
137
- clean = (len(violations) == 0)
138
- return {
139
- "clean": clean,
140
- "violations": violations,
141
- "warnings": warnings,
142
- "files_scanned": len(files_map)
143
- }
144
-
145
- @classmethod
146
- def scan_directory(cls, repo_dir: str = ".") -> Dict[str, Any]:
147
- """Scans all repository files for hardcoded secrets, keys, and credentials."""
148
- abs_repo = os.path.abspath(repo_dir)
149
- files_map: Dict[str, str] = {}
150
- skip_dirs = {".git", "__pycache__", ".pytest_cache", "target", "dist", "build", ".venv", "venv", ".egg-info", "node_modules"}
151
- skip_files = {
152
- "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "Cargo.lock",
153
- "poetry.lock", "composer.lock", "Gemfile.lock", "Pipfile.lock"
154
- }
155
- code_exts = {".py", ".rs", ".js", ".ts", ".jsx", ".tsx", ".go", ".java", ".json", ".toml", ".yaml", ".yml", ".env"}
156
-
157
- for root, dirs, files in os.walk(abs_repo):
158
- dirs[:] = [d for d in dirs if d not in skip_dirs]
159
- for f in files:
160
- if f in skip_files or f.endswith((".lock", ".min.js", ".min.css", ".map")):
161
- continue
162
- _, ext = os.path.splitext(f)
163
- if ext.lower() in code_exts or f.startswith(".env"):
164
- fpath = os.path.join(root, f)
165
- rel_path = os.path.relpath(fpath, abs_repo).replace("\\", "/")
166
- if "test" in rel_path.lower():
167
- continue
168
- if f.startswith(".env") and f != ".env.example":
169
- # Skip local gitignored environment files
170
- try:
171
- check = subprocess.run(["git", "-C", abs_repo, "check-ignore", fpath], capture_output=True)
172
- if check.returncode == 0:
173
- continue
174
- except Exception:
175
- pass
176
- try:
177
- with open(fpath, "r", encoding="utf-8", errors="replace") as fp:
178
- files_map[rel_path] = fp.read()
179
- except Exception:
180
- pass
181
- return cls.scan_staged_content(files_map)
182
-
183
- @classmethod
184
- def run_cli_check(cls, repo_dir: str = ".") -> int:
185
- """Executes pre-commit check on currently staged git files."""
186
- abs_repo = os.path.abspath(repo_dir)
187
- try:
188
- # Get list of staged files
189
- cmd = ["git", "-C", abs_repo, "diff", "--cached", "--name-only"]
190
- output = subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL)
191
- staged_names = [line.strip() for line in output.splitlines() if line.strip()]
192
- except Exception:
193
- return 0 # Not in a git repo or no git binary
194
-
195
- if not staged_names:
196
- return 0
197
-
198
- # Read content of staged files from git index
199
- files_map: Dict[str, str] = {}
200
- for fname in staged_names:
201
- if "test" in fname.lower() or fname.startswith(".agents") or fname in ("app.py",):
202
- continue
203
- try:
204
- content = subprocess.check_output(
205
- ["git", "-C", abs_repo, "show", f":{fname}"],
206
- text=True,
207
- errors="replace",
208
- stderr=subprocess.DEVNULL
209
- )
210
- files_map[fname] = content
211
- except Exception:
212
- continue
213
-
214
- res = cls.scan_staged_content(files_map)
215
-
216
- if not res["clean"]:
217
- print("\n" + "=" * 70)
218
- print("🚨 \033[31mT-ZERO ZERO-LEAK SECURITY GUARD: COMMIT BLOCKED!\033[0m")
219
- print("=" * 70)
220
- print("Found prohibited credentials / hardcoded secrets in staged files:")
221
- for v in res["violations"]:
222
- print(f" ❌ \033[33m{v['file']}\033[0m: Detected {v['type']}")
223
- print("\nRemove all secrets and credentials before committing.")
224
- print("=" * 70 + "\n")
225
- return 1
226
-
227
- if res["warnings"]:
228
- print("\n⚠️ [T-Zero Token Optimization Notice]")
229
- for w in res["warnings"]:
230
- print(f" • {w}")
231
-
232
- print("⚡ \033[32m[T-Zero Pre-Commit Guard] All staged files clean & safe.\033[0m")
233
- return 0
234
-
235
-
236
- def main():
237
- target = sys.argv[1] if len(sys.argv) > 1 else "."
238
- sys.exit(GitSecurityGuard.run_cli_check(target))
239
-
240
-
241
- if __name__ == "__main__":
242
- main()
243
-
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero Git Pre-Commit Zero-Leak & Token Security Guard.
3
+
4
+ Automatically intercepts git commits, scanning staged files for:
5
+ 1. Zero-Leak Security: Blocks accidental commits of API keys, tokens, private keys, passwords.
6
+ 2. Token Bloat Alert: Warns when uncompressed staged files exceed recommended token thresholds.
7
+ 3. Micro-Patch companion suggestion.
8
+
9
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
10
+ Part of T-Zero Context Architect v7.0.0 Master Edition.
11
+ """
12
+
13
+ import os
14
+ import re
15
+ import sys
16
+ import stat
17
+ import subprocess
18
+ from typing import Dict, List, Any, Optional
19
+
20
+ if sys.stdout and hasattr(sys.stdout, "reconfigure"):
21
+ try:
22
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
23
+ except Exception:
24
+ pass
25
+ if sys.stderr and hasattr(sys.stderr, "reconfigure"):
26
+ try:
27
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
28
+ except Exception:
29
+ pass
30
+
31
+ from tzero.tzero_security import ZeroLeakEngine, calculate_shannon_entropy, SECRET_RULES
32
+
33
+ # Backward-compatibility alias for external consumers
34
+ SECRET_PATTERNS = [
35
+ (rule.description, rule.pattern) for rule in SECRET_RULES
36
+ ]
37
+
38
+ TOKEN_WARN_THRESHOLD = 8000 # Tokens (~32,000 characters)
39
+
40
+
41
+ class GitSecurityGuard:
42
+ """Enterprise pre-commit guard ensuring zero secret leaks and optimal prompt tokens."""
43
+
44
+ @classmethod
45
+ def install_hook(cls, repo_dir: str = ".") -> Dict[str, Any]:
46
+ """Installs pre-commit hook into target repository's .git/hooks directory."""
47
+ abs_repo = os.path.abspath(repo_dir)
48
+ git_dir = os.path.join(abs_repo, ".git")
49
+
50
+ if not os.path.isdir(git_dir):
51
+ return {
52
+ "success": False,
53
+ "message": f"Target path '{repo_dir}' is not a git repository (missing .git directory)."
54
+ }
55
+
56
+ hooks_dir = os.path.join(git_dir, "hooks")
57
+ os.makedirs(hooks_dir, exist_ok=True)
58
+
59
+ hook_path = os.path.join(hooks_dir, "pre-commit")
60
+ hook_script = f"""#!/bin/sh
61
+ # T-Zero Git Pre-Commit Zero-Leak & Token Guard
62
+ # Auto-generated by Siber Akademi T-Zero Context Architect
63
+
64
+ python -c "import tzero_guard; import sys; sys.exit(tzero_guard.GitSecurityGuard.run_cli_check('.'))"
65
+ EXIT_CODE=$?
66
+
67
+ if [ $EXIT_CODE -ne 0 ]; then
68
+ echo "\\033[31m[T-ZERO GUARD BLOCKED COMMIT] Commit aborted due to secret leaks or policy violations.\\033[0m"
69
+ exit 1
70
+ fi
71
+
72
+ exit 0
73
+ """
74
+
75
+ try:
76
+ with open(hook_path, "w", encoding="utf-8", newline="\n") as f:
77
+ f.write(hook_script)
78
+
79
+ # Mark executable on Unix/Mac
80
+ try:
81
+ st = os.stat(hook_path)
82
+ os.chmod(hook_path, st.st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
83
+ except Exception:
84
+ pass
85
+
86
+ # Also create pre-commit.bat for native Windows cmd / powershell hooks
87
+ bat_path = os.path.join(hooks_dir, "pre-commit.bat")
88
+ bat_script = f"""@echo off
89
+ REM T-Zero Git Pre-Commit Guard for Windows
90
+ python -c "import tzero_guard; import sys; sys.exit(tzero_guard.GitSecurityGuard.run_cli_check('.'))"
91
+ if %ERRORLEVEL% NEQ 0 (
92
+ echo [T-ZERO GUARD BLOCKED COMMIT] Commit aborted due to secret leaks.
93
+ exit /b 1
94
+ )
95
+ exit /b 0
96
+ """
97
+ with open(bat_path, "w", encoding="utf-8") as f:
98
+ f.write(bat_script)
99
+
100
+ return {
101
+ "success": True,
102
+ "hook_path": hook_path,
103
+ "bat_path": bat_path,
104
+ "message": f"Successfully installed T-Zero Pre-Commit Guard in {hook_path}"
105
+ }
106
+ except Exception as e:
107
+ return {
108
+ "success": False,
109
+ "message": f"Failed to write hook file: {e}"
110
+ }
111
+
112
+ @classmethod
113
+ def scan_staged_content(cls, files_map: Dict[str, str]) -> Dict[str, Any]:
114
+ """Scans in-memory staged files map {filename: content} for secrets and token bloat."""
115
+ violations = []
116
+ warnings = []
117
+
118
+ for filename, content in files_map.items():
119
+ findings = ZeroLeakEngine.scan_text(content, check_entropy=True)
120
+ for f in findings:
121
+ violations.append({
122
+ "file": filename,
123
+ "type": f"{f.provider}: {f.description}",
124
+ "match_count": 1,
125
+ "line": f.line_no,
126
+ "preview": f.preview,
127
+ "entropy": f.entropy
128
+ })
129
+
130
+ # Check token bloat
131
+ approx_tokens = max(1, len(content) // 4)
132
+ if approx_tokens > TOKEN_WARN_THRESHOLD:
133
+ warnings.append(
134
+ f"File '{filename}' has {approx_tokens:,} tokens. Consider compressing with T-Zero before committing."
135
+ )
136
+
137
+ clean = (len(violations) == 0)
138
+ return {
139
+ "clean": clean,
140
+ "violations": violations,
141
+ "warnings": warnings,
142
+ "files_scanned": len(files_map)
143
+ }
144
+
145
+ @classmethod
146
+ def scan_directory(cls, repo_dir: str = ".") -> Dict[str, Any]:
147
+ """Scans all repository files for hardcoded secrets, keys, and credentials."""
148
+ abs_repo = os.path.abspath(repo_dir)
149
+ files_map: Dict[str, str] = {}
150
+ skip_dirs = {".git", "__pycache__", ".pytest_cache", "target", "dist", "build", ".venv", "venv", ".egg-info", "node_modules"}
151
+ skip_files = {
152
+ "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "Cargo.lock",
153
+ "poetry.lock", "composer.lock", "Gemfile.lock", "Pipfile.lock"
154
+ }
155
+ code_exts = {".py", ".rs", ".js", ".ts", ".jsx", ".tsx", ".go", ".java", ".json", ".toml", ".yaml", ".yml", ".env"}
156
+
157
+ for root, dirs, files in os.walk(abs_repo):
158
+ dirs[:] = [d for d in dirs if d not in skip_dirs]
159
+ for f in files:
160
+ if f in skip_files or f.endswith((".lock", ".min.js", ".min.css", ".map")):
161
+ continue
162
+ _, ext = os.path.splitext(f)
163
+ if ext.lower() in code_exts or f.startswith(".env"):
164
+ fpath = os.path.join(root, f)
165
+ rel_path = os.path.relpath(fpath, abs_repo).replace("\\", "/")
166
+ if "test" in rel_path.lower():
167
+ continue
168
+ if f.startswith(".env") and f != ".env.example":
169
+ # Skip local gitignored environment files
170
+ try:
171
+ check = subprocess.run(["git", "-C", abs_repo, "check-ignore", fpath], capture_output=True)
172
+ if check.returncode == 0:
173
+ continue
174
+ except Exception:
175
+ pass
176
+ try:
177
+ with open(fpath, "r", encoding="utf-8", errors="replace") as fp:
178
+ files_map[rel_path] = fp.read()
179
+ except Exception:
180
+ pass
181
+ return cls.scan_staged_content(files_map)
182
+
183
+ @classmethod
184
+ def run_cli_check(cls, repo_dir: str = ".") -> int:
185
+ """Executes pre-commit check on currently staged git files."""
186
+ abs_repo = os.path.abspath(repo_dir)
187
+ try:
188
+ # Get list of staged files
189
+ cmd = ["git", "-C", abs_repo, "diff", "--cached", "--name-only"]
190
+ output = subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL)
191
+ staged_names = [line.strip() for line in output.splitlines() if line.strip()]
192
+ except Exception:
193
+ return 0 # Not in a git repo or no git binary
194
+
195
+ if not staged_names:
196
+ return 0
197
+
198
+ # Read content of staged files from git index
199
+ files_map: Dict[str, str] = {}
200
+ for fname in staged_names:
201
+ if "test" in fname.lower() or fname.startswith(".agents") or fname in ("app.py",):
202
+ continue
203
+ try:
204
+ content = subprocess.check_output(
205
+ ["git", "-C", abs_repo, "show", f":{fname}"],
206
+ text=True,
207
+ errors="replace",
208
+ stderr=subprocess.DEVNULL
209
+ )
210
+ files_map[fname] = content
211
+ except Exception:
212
+ continue
213
+
214
+ res = cls.scan_staged_content(files_map)
215
+
216
+ if not res["clean"]:
217
+ print("\n" + "=" * 70)
218
+ print("🚨 \033[31mT-ZERO ZERO-LEAK SECURITY GUARD: COMMIT BLOCKED!\033[0m")
219
+ print("=" * 70)
220
+ print("Found prohibited credentials / hardcoded secrets in staged files:")
221
+ for v in res["violations"]:
222
+ print(f" ❌ \033[33m{v['file']}\033[0m: Detected {v['type']}")
223
+ print("\nRemove all secrets and credentials before committing.")
224
+ print("=" * 70 + "\n")
225
+ return 1
226
+
227
+ if res["warnings"]:
228
+ print("\n⚠️ [T-Zero Token Optimization Notice]")
229
+ for w in res["warnings"]:
230
+ print(f" • {w}")
231
+
232
+ print("⚡ \033[32m[T-Zero Pre-Commit Guard] All staged files clean & safe.\033[0m")
233
+ return 0
234
+
235
+
236
+ def main():
237
+ target = sys.argv[1] if len(sys.argv) > 1 else "."
238
+ sys.exit(GitSecurityGuard.run_cli_check(target))
239
+
240
+
241
+ if __name__ == "__main__":
242
+ main()
243
+