tzero-mcp 12.2.1 → 12.2.2

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 (43) hide show
  1. package/package.json +1 -1
  2. package/src/addmcp.py +10 -5
  3. package/src/app.py +3 -9
  4. package/src/tzero/__init__.py +1 -1
  5. package/src/tzero/anti_rea/asar_shield.py +3 -1
  6. package/src/tzero/anti_rea/auditor.py +42 -12
  7. package/src/tzero/anti_rea/canary_beacon.py +27 -19
  8. package/src/tzero/anti_rea/cli.py +7 -1
  9. package/src/tzero/anti_rea/confusables.py +62 -18
  10. package/src/tzero/anti_rea/engine.py +79 -10
  11. package/src/tzero/anti_rea/extractor_shield.py +52 -9
  12. package/src/tzero/anti_rea/gui.py +1 -4
  13. package/src/tzero/anti_rea/integrity_guard.py +17 -5
  14. package/src/tzero/anti_rea/rdtsc_guard.py +21 -8
  15. package/src/tzero/anti_rea/string_vault.py +10 -7
  16. package/src/tzero/siber_akademi.ico +0 -0
  17. package/src/tzero/siber_akademi_icon.py +14 -8
  18. package/src/tzero/tzero_armor.py +27 -5
  19. package/src/tzero/tzero_benchmark.py +4 -2
  20. package/src/tzero/tzero_budget.py +14 -5
  21. package/src/tzero/tzero_ci.py +1 -1
  22. package/src/tzero/tzero_contracts.py +7 -5
  23. package/src/tzero/tzero_dashboard.py +28 -9
  24. package/src/tzero/tzero_debt.py +19 -4
  25. package/src/tzero/tzero_explain.py +1 -1
  26. package/src/tzero/tzero_features.py +43 -29
  27. package/src/tzero/tzero_federation.py +9 -2
  28. package/src/tzero/tzero_fixer/mcp_server.py +10 -0
  29. package/src/tzero/tzero_golden.py +37 -9
  30. package/src/tzero/tzero_growth.py +166 -8
  31. package/src/tzero/tzero_guard.py +147 -46
  32. package/src/tzero/tzero_lsp.py +1 -1
  33. package/src/tzero/tzero_mcp.py +64 -16
  34. package/src/tzero/tzero_mutation.py +88 -15
  35. package/src/tzero/tzero_promo.py +1 -1
  36. package/src/tzero/tzero_proxy.py +105 -12
  37. package/src/tzero/tzero_scip.py +12 -6
  38. package/src/tzero/tzero_security.py +375 -60
  39. package/src/tzero/tzero_task_benchmark.py +2 -2
  40. package/src/tzero/tzero_traffic.py +35 -10
  41. package/src/tzero/tzero_tui.py +17 -8
  42. package/src/tzero/tzero_v3.py +268 -88
  43. package/src/tzero/tzero_welcome.py +12 -4
@@ -3,7 +3,7 @@
3
3
  T-ZERO $0.00 BUDGET VIRAL MARKETING & COMMUNITY GROWTH ENGINE
4
4
  -------------------------------------------------------------
5
5
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
6
- License: MIT | Version: 11.11.0
6
+ License: MIT | Version: 12.2.2
7
7
 
8
8
  Strictly $0.00 budget: Zero paid ads, zero paid APIs, zero cloud tokens.
9
9
  Pure organic developer-to-developer growth engine engineered to drive 100+ GitHub stars.
@@ -14,6 +14,7 @@ Twitter/X, LinkedIn, Dev.to, Turkish Tech Hubs, and Awesome-Lists.
14
14
  import sys
15
15
  import os
16
16
  import json
17
+ import time
17
18
  import urllib.request
18
19
  from pathlib import Path
19
20
  from typing import Dict, Any, List
@@ -22,21 +23,178 @@ REPO_URL = "https://github.com/toprakahmetaydogmus/TZeroAlgorithm"
22
23
  WEB_URL = "https://tzero-indol.vercel.app"
23
24
  AUTHOR = "Toprak Ahmet Aydoğmuş"
24
25
  ORGANIZATION = "Siber Akademi"
25
- VERSION = "v11.15.5"
26
+ try:
27
+ from tzero import __version__ as _TZ_VER
28
+ except Exception:
29
+ _TZ_VER = "12.2.1"
30
+ VERSION = f"v{_TZ_VER}"
26
31
  PYPI_PKG = "tzero-mcp"
27
32
  NPM_PKG = "tzero-mcp"
28
33
 
34
+ DEFAULT_STAR_BASELINE = 111
35
+ DEFAULT_DOWNLOADS_BASELINE = 22900
36
+ DEFAULT_SAVED_TOKENS_LABEL = "1,120,000+"
37
+ STAR_MILESTONES = (100, 250, 500, 1000, 2500, 5000, 10000)
38
+ COMMUNITY_CACHE_TTL_SEC = 900
39
+
40
+
41
+ def _community_cache_path() -> Path:
42
+ return Path.home() / ".tzero" / "community_stats_cache.json"
43
+
44
+
45
+ def next_star_milestone(stars: int) -> int:
46
+ """Return the next community star milestone strictly above current count."""
47
+ count = max(0, int(stars))
48
+ for milestone in STAR_MILESTONES:
49
+ if count < milestone:
50
+ return milestone
51
+ return ((count // 5000) + 1) * 5000
52
+
53
+
54
+ def format_downloads_label(count: int) -> str:
55
+ """Format package download totals concisely (e.g., 22914 -> '22,900+')."""
56
+ val = max(0, int(count))
57
+ if val >= 1000:
58
+ val = (val // 100) * 100
59
+ return f"{val:,d}+"
60
+
61
+
62
+ def _read_community_cache() -> Dict[str, Any]:
63
+ try:
64
+ cache_file = _community_cache_path()
65
+ if cache_file.is_file():
66
+ data = json.loads(cache_file.read_text(encoding="utf-8"))
67
+ if isinstance(data, dict):
68
+ return data
69
+ except Exception:
70
+ pass
71
+ return {}
72
+
73
+
74
+ def _write_community_cache(stars: int, downloads: int) -> None:
75
+ try:
76
+ cache_file = _community_cache_path()
77
+ cache_file.parent.mkdir(parents=True, exist_ok=True)
78
+ payload = {
79
+ "stars": int(stars),
80
+ "downloads": int(downloads),
81
+ "updated_at": time.time(),
82
+ }
83
+ cache_file.write_text(json.dumps(payload), encoding="utf-8")
84
+ except Exception:
85
+ pass
86
+
87
+
88
+ def _build_community_stats(stars: int, downloads: int, source: str) -> Dict[str, Any]:
89
+ target = next_star_milestone(stars)
90
+ pct = min(100.0, round((stars / max(1, target)) * 100.0, 1))
91
+ return {
92
+ "stars": int(stars),
93
+ "target_stars": target,
94
+ "progress_pct": pct,
95
+ "downloads": int(downloads),
96
+ "downloads_label": format_downloads_label(downloads),
97
+ "saved_tokens_label": DEFAULT_SAVED_TOKENS_LABEL,
98
+ "source": source,
99
+ }
100
+
101
+
102
+ def get_cached_community_stats(max_age_sec: int = COMMUNITY_CACHE_TTL_SEC) -> Dict[str, Any]:
103
+ """Return instantaneous cached (or baseline) community stats without blocking on network."""
104
+ cached = _read_community_cache()
105
+ stars = int(cached.get("stars", DEFAULT_STAR_BASELINE) or DEFAULT_STAR_BASELINE)
106
+ downloads = int(cached.get("downloads", DEFAULT_DOWNLOADS_BASELINE) or DEFAULT_DOWNLOADS_BASELINE)
107
+ stars = max(DEFAULT_STAR_BASELINE, stars) if cached.get("source") != "test" else stars
108
+ downloads = max(DEFAULT_DOWNLOADS_BASELINE, downloads)
109
+ updated_at = float(cached.get("updated_at", 0.0) or 0.0)
110
+ is_fresh = bool(cached) and (time.time() - updated_at) < max_age_sec
111
+ return _build_community_stats(stars, downloads, "cache" if is_fresh else "fallback")
112
+
113
+
114
+ def _fetch_live_downloads(timeout: float = 2.0) -> int:
115
+ total = 0
116
+ try:
117
+ req = urllib.request.Request(
118
+ f"https://pypistats.org/api/packages/{PYPI_PKG}/overall",
119
+ headers={"User-Agent": "T-Zero-Growth-Engine"},
120
+ )
121
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
122
+ data = json.loads(resp.read().decode("utf-8"))
123
+ total += sum(
124
+ int(row.get("downloads", 0))
125
+ for row in data.get("data", [])
126
+ if row.get("category") == "with_mirrors"
127
+ )
128
+ except Exception:
129
+ pass
130
+ try:
131
+ req = urllib.request.Request(
132
+ f"https://api.npmjs.org/downloads/point/last-year/{NPM_PKG}",
133
+ headers={"User-Agent": "T-Zero-Growth-Engine"},
134
+ )
135
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
136
+ data = json.loads(resp.read().decode("utf-8"))
137
+ total += int(data.get("downloads", 0))
138
+ except Exception:
139
+ pass
140
+ return total
141
+
142
+
143
+ def get_live_github_stars(timeout: float = 2.0, force_refresh: bool = False) -> int:
144
+ """Fetch current GitHub stargazers count with local TTL cache and resilient fallback."""
145
+ cached = _read_community_cache()
146
+ updated_at = float(cached.get("updated_at", 0.0) or 0.0)
147
+ if not force_refresh and cached and (time.time() - updated_at) < COMMUNITY_CACHE_TTL_SEC:
148
+ if "stars" in cached:
149
+ return int(cached["stars"])
29
150
 
30
- def get_live_github_stars() -> int:
31
- """Fetch current GitHub stargazers count."""
32
151
  try:
33
152
  url = "https://api.github.com/repos/toprakahmetaydogmus/TZeroAlgorithm"
34
- req = urllib.request.Request(url, headers={"User-Agent": "T-Zero-Growth-Engine"})
35
- with urllib.request.urlopen(req, timeout=5) as resp:
153
+ req = urllib.request.Request(
154
+ url,
155
+ headers={
156
+ "User-Agent": "T-Zero-Growth-Engine",
157
+ "Accept": "application/vnd.github.v3+json",
158
+ },
159
+ )
160
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
36
161
  data = json.loads(resp.read().decode("utf-8"))
37
- return int(data.get("stargazers_count", 45))
162
+ if isinstance(data, dict) and "stargazers_count" in data:
163
+ stars = int(data["stargazers_count"])
164
+ downloads = max(DEFAULT_DOWNLOADS_BASELINE, int(cached.get("downloads", DEFAULT_DOWNLOADS_BASELINE) or DEFAULT_DOWNLOADS_BASELINE))
165
+ _write_community_cache(stars, downloads)
166
+ return stars
38
167
  except Exception:
39
- return 45
168
+ pass
169
+
170
+ if cached and "stars" in cached:
171
+ return int(cached["stars"])
172
+ return DEFAULT_STAR_BASELINE
173
+
174
+
175
+ def get_live_community_stats(
176
+ timeout: float = 2.0,
177
+ force_refresh: bool = False,
178
+ include_downloads: bool = False,
179
+ ) -> Dict[str, Any]:
180
+ """Fetch live GitHub star count and registry downloads with TTL cache + offline fallback."""
181
+ cached = _read_community_cache()
182
+ updated_at = float(cached.get("updated_at", 0.0) or 0.0)
183
+ is_fresh = bool(cached) and (time.time() - updated_at) < COMMUNITY_CACHE_TTL_SEC
184
+ if not force_refresh and is_fresh and "stars" in cached:
185
+ stars = int(cached["stars"])
186
+ downloads = max(DEFAULT_DOWNLOADS_BASELINE, int(cached.get("downloads", DEFAULT_DOWNLOADS_BASELINE) or DEFAULT_DOWNLOADS_BASELINE))
187
+ return _build_community_stats(stars, downloads, "cache")
188
+
189
+ stars = get_live_github_stars(timeout=timeout, force_refresh=force_refresh)
190
+ downloads = max(DEFAULT_DOWNLOADS_BASELINE, int(cached.get("downloads", DEFAULT_DOWNLOADS_BASELINE) or DEFAULT_DOWNLOADS_BASELINE))
191
+ if include_downloads:
192
+ fetched_dl = _fetch_live_downloads(timeout=timeout)
193
+ if fetched_dl > 0:
194
+ downloads = max(DEFAULT_DOWNLOADS_BASELINE, fetched_dl)
195
+ _write_community_cache(stars, downloads)
196
+ source = "live" if _read_community_cache().get("stars") == stars else "fallback"
197
+ return _build_community_stats(stars, downloads, source)
40
198
 
41
199
 
42
200
  def render_progress_bar(current: int, target: int = 100, length: int = 30) -> str:
@@ -41,9 +41,11 @@ TOKEN_WARN_THRESHOLD = 8000 # Tokens (~32,000 characters)
41
41
  class GitSecurityGuard:
42
42
  """Enterprise pre-commit guard ensuring zero secret leaks and optimal prompt tokens."""
43
43
 
44
+ _TZERO_MARKER = "T-Zero Git Pre-Commit"
45
+
44
46
  @classmethod
45
47
  def install_hook(cls, repo_dir: str = ".") -> Dict[str, Any]:
46
- """Installs pre-commit hook into target repository's .git/hooks directory."""
48
+ """Installs pre-commit hook into target repository while preserving existing hooks."""
47
49
  abs_repo = os.path.abspath(repo_dir)
48
50
  git_dir = os.path.join(abs_repo, ".git")
49
51
 
@@ -57,9 +59,43 @@ class GitSecurityGuard:
57
59
  os.makedirs(hooks_dir, exist_ok=True)
58
60
 
59
61
  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
+ backup_path = os.path.join(hooks_dir, "pre-commit.user-backup")
63
+ bat_path = os.path.join(hooks_dir, "pre-commit.bat")
64
+ bat_backup = os.path.join(hooks_dir, "pre-commit.bat.user-backup")
65
+
66
+ try:
67
+ # Preserve pre-existing non-T-Zero Unix pre-commit hook cleanly
68
+ if os.path.isfile(hook_path):
69
+ with open(hook_path, "r", encoding="utf-8", errors="ignore") as f:
70
+ existing = f.read()
71
+ if cls._TZERO_MARKER not in existing and not os.path.exists(backup_path):
72
+ with open(backup_path, "w", encoding="utf-8", newline="\n") as bf:
73
+ bf.write(existing)
74
+ try:
75
+ st_b = os.stat(hook_path)
76
+ os.chmod(backup_path, st_b.st_mode | stat.S_IEXEC)
77
+ except Exception:
78
+ pass
79
+
80
+ # Preserve pre-existing non-T-Zero Windows batch hook cleanly
81
+ if os.path.isfile(bat_path):
82
+ with open(bat_path, "r", encoding="utf-8", errors="ignore") as f:
83
+ existing_bat = f.read()
84
+ if cls._TZERO_MARKER not in existing_bat and not os.path.exists(bat_backup):
85
+ with open(bat_backup, "w", encoding="utf-8") as bf:
86
+ bf.write(existing_bat)
87
+
88
+ hook_script = f"""#!/bin/sh
89
+ # {cls._TZERO_MARKER} & Token Guard
62
90
  # Auto-generated by Siber Akademi T-Zero Context Architect
91
+ HOOK_DIR="$(dirname "$0")"
92
+ if [ -f "$HOOK_DIR/pre-commit.user-backup" ]; then
93
+ sh "$HOOK_DIR/pre-commit.user-backup" "$@"
94
+ USER_EXIT=$?
95
+ if [ $USER_EXIT -ne 0 ]; then
96
+ exit $USER_EXIT
97
+ fi
98
+ fi
63
99
 
64
100
  python -c "try:
65
101
  from tzero.tzero_guard import GitSecurityGuard
@@ -69,35 +105,34 @@ import sys; sys.exit(GitSecurityGuard.run_cli_check('.'))"
69
105
  EXIT_CODE=$?
70
106
 
71
107
  if [ $EXIT_CODE -ne 0 ]; then
72
- echo "\\033[31m[T-ZERO GUARD BLOCKED COMMIT] Commit aborted due to secret leaks or policy violations.\\033[0m"
108
+ echo "\\033[31m[T-ZERO GUARD BLOCKED COMMIT] Commit aborted due to secret leaks or scan errors.\\033[0m"
73
109
  exit 1
74
110
  fi
75
111
 
76
112
  exit 0
77
113
  """
78
-
79
- try:
80
114
  with open(hook_path, "w", encoding="utf-8", newline="\n") as f:
81
115
  f.write(hook_script)
82
116
 
83
- # Mark executable on Unix/Mac
84
117
  try:
85
118
  st = os.stat(hook_path)
86
119
  os.chmod(hook_path, st.st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
87
120
  except Exception:
88
121
  pass
89
122
 
90
- # Also create pre-commit.bat for native Windows cmd / powershell hooks
91
- bat_path = os.path.join(hooks_dir, "pre-commit.bat")
92
123
  bat_script = f"""@echo off
93
- REM T-Zero Git Pre-Commit Guard for Windows
124
+ REM {cls._TZERO_MARKER} for Windows
125
+ if exist "%~dp0pre-commit.bat.user-backup" (
126
+ call "%~dp0pre-commit.bat.user-backup" %*
127
+ if %ERRORLEVEL% NEQ 0 exit /b %ERRORLEVEL%
128
+ )
94
129
  python -c "try:^
95
130
  from tzero.tzero_guard import GitSecurityGuard^
96
131
  except ImportError:^
97
132
  import tzero_guard; GitSecurityGuard = tzero_guard.GitSecurityGuard^
98
133
  import sys; sys.exit(GitSecurityGuard.run_cli_check('.'))"
99
134
  if %ERRORLEVEL% NEQ 0 (
100
- echo [T-ZERO GUARD BLOCKED COMMIT] Commit aborted due to secret leaks.
135
+ echo [T-ZERO GUARD BLOCKED COMMIT] Commit aborted due to secret leaks or scan errors.
101
136
  exit /b 1
102
137
  )
103
138
  exit /b 0
@@ -109,6 +144,7 @@ exit /b 0
109
144
  "success": True,
110
145
  "hook_path": hook_path,
111
146
  "bat_path": bat_path,
147
+ "preserved_existing": os.path.isfile(backup_path) or os.path.isfile(bat_backup),
112
148
  "message": f"Successfully installed T-Zero Pre-Commit Guard in {hook_path}"
113
149
  }
114
150
  except Exception as e:
@@ -118,10 +154,37 @@ exit /b 0
118
154
  }
119
155
 
120
156
  @classmethod
121
- def scan_staged_content(cls, files_map: Dict[str, str]) -> Dict[str, Any]:
157
+ def uninstall_hook(cls, repo_dir: str = ".") -> Dict[str, Any]:
158
+ """Uninstalls T-Zero pre-commit hook and restores any backed-up user hook cleanly."""
159
+ hooks_dir = os.path.join(os.path.abspath(repo_dir), ".git", "hooks")
160
+ if not os.path.isdir(hooks_dir):
161
+ return {"success": False, "message": "Missing .git/hooks directory."}
162
+ for main_name, bak_name in (("pre-commit", "pre-commit.user-backup"), ("pre-commit.bat", "pre-commit.bat.user-backup")):
163
+ main_p = os.path.join(hooks_dir, main_name)
164
+ bak_p = os.path.join(hooks_dir, bak_name)
165
+ is_tzero_hook = False
166
+ if os.path.isfile(main_p):
167
+ with open(main_p, "r", encoding="utf-8", errors="ignore") as f:
168
+ is_tzero_hook = cls._TZERO_MARKER in f.read()
169
+ if is_tzero_hook:
170
+ os.remove(main_p)
171
+ if os.path.isfile(bak_p):
172
+ os.replace(bak_p, main_p)
173
+ return {"success": True, "message": "Uninstalled T-Zero Pre-Commit Guard and restored prior hooks."}
174
+
175
+ @classmethod
176
+ def scan_staged_content(
177
+ cls,
178
+ files_map: Dict[str, str],
179
+ total_input: Optional[int] = None,
180
+ skipped_files: Optional[List[str]] = None,
181
+ errored_files: Optional[List[str]] = None,
182
+ ) -> Dict[str, Any]:
122
183
  """Scans in-memory staged files map {filename: content} for secrets and token bloat."""
123
184
  violations = []
124
185
  warnings = []
186
+ err_list = list(errored_files or [])
187
+ skip_list = list(skipped_files or [])
125
188
 
126
189
  for filename, content in files_map.items():
127
190
  findings = ZeroLeakEngine.scan_text(content, check_entropy=True)
@@ -135,19 +198,23 @@ exit /b 0
135
198
  "entropy": f.entropy
136
199
  })
137
200
 
138
- # Check token bloat
139
201
  approx_tokens = max(1, len(content) // 4)
140
202
  if approx_tokens > TOKEN_WARN_THRESHOLD:
141
203
  warnings.append(
142
204
  f"File '{filename}' has {approx_tokens:,} tokens. Consider compressing with T-Zero before committing."
143
205
  )
144
206
 
145
- clean = (len(violations) == 0)
207
+ clean = (len(violations) == 0 and len(err_list) == 0)
146
208
  return {
147
209
  "clean": clean,
148
210
  "violations": violations,
149
211
  "warnings": warnings,
150
- "files_scanned": len(files_map)
212
+ "errors": err_list,
213
+ "skipped": skip_list,
214
+ "files_input": total_input if total_input is not None else len(files_map) + len(skip_list) + len(err_list),
215
+ "files_scanned": len(files_map),
216
+ "files_skipped": len(skip_list),
217
+ "files_errored": len(err_list),
151
218
  }
152
219
 
153
220
  @classmethod
@@ -155,12 +222,15 @@ exit /b 0
155
222
  """Scans all repository files for hardcoded secrets, keys, and credentials."""
156
223
  abs_repo = os.path.abspath(repo_dir)
157
224
  files_map: Dict[str, str] = {}
225
+ skipped_files: List[str] = []
226
+ errored_files: List[str] = []
158
227
  skip_dirs = {".git", "__pycache__", ".pytest_cache", "target", "dist", "build", ".venv", "venv", ".egg-info", "node_modules"}
159
228
  skip_files = {
160
229
  "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "Cargo.lock",
161
230
  "poetry.lock", "composer.lock", "Gemfile.lock", "Pipfile.lock"
162
231
  }
163
- code_exts = {".py", ".rs", ".js", ".ts", ".jsx", ".tsx", ".go", ".java", ".json", ".toml", ".yaml", ".yml", ".env"}
232
+ code_exts = {".py", ".rs", ".js", ".ts", ".jsx", ".tsx", ".go", ".java", ".json", ".toml", ".yaml", ".yml", ".env", ".sh", ".ps1", ".cfg", ".ini"}
233
+ total_seen = 0
164
234
 
165
235
  for root, dirs, files in os.walk(abs_repo):
166
236
  dirs[:] = [d for d in dirs if d not in skip_dirs]
@@ -169,66 +239,97 @@ exit /b 0
169
239
  continue
170
240
  _, ext = os.path.splitext(f)
171
241
  if ext.lower() in code_exts or f.startswith(".env"):
242
+ total_seen += 1
172
243
  fpath = os.path.join(root, f)
173
244
  rel_path = os.path.relpath(fpath, abs_repo).replace("\\", "/")
174
- if "test" in rel_path.lower():
175
- continue
176
245
  if f.startswith(".env") and f != ".env.example":
177
- # Skip local gitignored environment files
178
246
  try:
179
247
  check = subprocess.run(["git", "-C", abs_repo, "check-ignore", fpath], capture_output=True)
180
248
  if check.returncode == 0:
249
+ skipped_files.append(rel_path)
181
250
  continue
182
251
  except Exception:
183
252
  pass
184
253
  try:
185
- with open(fpath, "r", encoding="utf-8", errors="replace") as fp:
254
+ with open(fpath, "r", encoding="utf-8", errors="strict") as fp:
186
255
  files_map[rel_path] = fp.read()
187
- except Exception:
188
- pass
189
- return cls.scan_staged_content(files_map)
256
+ except UnicodeDecodeError:
257
+ try:
258
+ with open(fpath, "r", encoding="utf-8", errors="replace") as fp:
259
+ files_map[rel_path] = fp.read()
260
+ except Exception as exc:
261
+ errored_files.append(f"{rel_path}: {exc}")
262
+ except Exception as exc:
263
+ errored_files.append(f"{rel_path}: {exc}")
264
+ return cls.scan_staged_content(
265
+ files_map, total_input=total_seen, skipped_files=skipped_files, errored_files=errored_files
266
+ )
190
267
 
191
268
  @classmethod
192
269
  def run_cli_check(cls, repo_dir: str = ".") -> int:
193
270
  """Executes pre-commit check on currently staged git files."""
194
271
  abs_repo = os.path.abspath(repo_dir)
272
+ git_dir = os.path.join(abs_repo, ".git")
195
273
  try:
196
- # Get list of staged files
197
- cmd = ["git", "-C", abs_repo, "diff", "--cached", "--name-only"]
198
- output = subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL)
199
- staged_names = [line.strip() for line in output.splitlines() if line.strip()]
200
- except Exception:
201
- return 0 # Not in a git repo or no git binary
274
+ proc = subprocess.run(
275
+ ["git", "-C", abs_repo, "diff", "--cached", "--name-only"],
276
+ capture_output=True, text=True, check=False,
277
+ )
278
+ except Exception as exc:
279
+ print(f"[T-ZERO GUARD ERROR] Unable to execute git diff: {exc}", file=sys.stderr)
280
+ return 1
202
281
 
282
+ if proc.returncode != 0:
283
+ err_msg = (proc.stderr or proc.stdout or "git diff --cached failed").strip()
284
+ print(f"[T-ZERO GUARD ERROR] Staged file listing failed ({git_dir}): {err_msg}", file=sys.stderr)
285
+ return 1
286
+
287
+ staged_names = [line.strip() for line in proc.stdout.splitlines() if line.strip()]
203
288
  if not staged_names:
204
289
  return 0
205
290
 
206
- # Read content of staged files from git index
207
291
  files_map: Dict[str, str] = {}
292
+ skipped_files: List[str] = []
293
+ errored_files: List[str] = []
208
294
  for fname in staged_names:
209
- if "test" in fname.lower() or fname.startswith(".agents") or fname in ("app.py",):
295
+ if fname.startswith(".agents/"):
296
+ skipped_files.append(fname)
210
297
  continue
211
- try:
212
- content = subprocess.check_output(
213
- ["git", "-C", abs_repo, "show", f":{fname}"],
214
- text=True,
215
- errors="replace",
216
- stderr=subprocess.DEVNULL
217
- )
218
- files_map[fname] = content
219
- except Exception:
298
+ show_proc = subprocess.run(
299
+ ["git", "-C", abs_repo, "show", f":{fname}"],
300
+ capture_output=True,
301
+ check=False,
302
+ )
303
+ if show_proc.returncode != 0:
304
+ err_txt = show_proc.stderr.decode("utf-8", errors="replace").strip()
305
+ errored_files.append(f"{fname}: git show failed ({err_txt})")
306
+ continue
307
+ raw_bytes = show_proc.stdout
308
+ if b"\x00" in raw_bytes[:4096]:
309
+ skipped_files.append(fname)
220
310
  continue
311
+ files_map[fname] = raw_bytes.decode("utf-8", errors="replace")
221
312
 
222
- res = cls.scan_staged_content(files_map)
313
+ res = cls.scan_staged_content(
314
+ files_map,
315
+ total_input=len(staged_names),
316
+ skipped_files=skipped_files,
317
+ errored_files=errored_files,
318
+ )
223
319
 
224
320
  if not res["clean"]:
225
321
  print("\n" + "=" * 70)
226
322
  print("🚨 \033[31mT-ZERO ZERO-LEAK SECURITY GUARD: COMMIT BLOCKED!\033[0m")
227
323
  print("=" * 70)
228
- print("Found prohibited credentials / hardcoded secrets in staged files:")
229
- for v in res["violations"]:
230
- print(f" ❌ \033[33m{v['file']}\033[0m: Detected {v['type']}")
231
- print("\nRemove all secrets and credentials before committing.")
324
+ if res["errors"]:
325
+ print("Unreadable or failed staged files:")
326
+ for err in res["errors"]:
327
+ print(f" ❌ {err}")
328
+ if res["violations"]:
329
+ print("Found prohibited credentials / hardcoded secrets in staged files:")
330
+ for v in res["violations"]:
331
+ print(f" ❌ \033[33m{v['file']}\033[0m (Line {v['line']}): Detected {v['type']}")
332
+ print(f"\nCounts: input={res['files_input']} scanned={res['files_scanned']} skipped={res['files_skipped']} errored={res['files_errored']}")
232
333
  print("=" * 70 + "\n")
233
334
  return 1
234
335
 
@@ -237,7 +338,7 @@ exit /b 0
237
338
  for w in res["warnings"]:
238
339
  print(f" • {w}")
239
340
 
240
- print("⚡ \033[32m[T-Zero Pre-Commit Guard] All staged files clean & safe.\033[0m")
341
+ print(f"⚡ \033[32m[T-Zero Pre-Commit Guard] Scanned {res['files_scanned']}/{res['files_input']} staged files cleanly.\033[0m")
241
342
  return 0
242
343
 
243
344
 
@@ -513,7 +513,7 @@ class TZeroLSPServer:
513
513
  "hoverProvider": True,
514
514
  "codeActionProvider": True,
515
515
  },
516
- "serverInfo": {"name": "tzero-lsp", "version": "12.2.1"},
516
+ "serverInfo": {"name": "tzero-lsp", "version": "12.2.2"},
517
517
  },
518
518
  }]
519
519