tzero-mcp 12.2.1 → 12.3.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 (55) hide show
  1. package/README.md +6 -30
  2. package/bin/tzero-mcp.js +2 -2
  3. package/bin/tzero.js +11 -6
  4. package/package.json +1 -2
  5. package/src/addmcp.py +10 -5
  6. package/src/app.py +3 -9
  7. package/src/tzero/__init__.py +1 -1
  8. package/src/tzero/anti_rea/__init__.py +16 -2
  9. package/src/tzero/anti_rea/algebraic_mutator.py +65 -44
  10. package/src/tzero/anti_rea/anti_debugger.py +51 -18
  11. package/src/tzero/anti_rea/asar_shield.py +24 -1
  12. package/src/tzero/anti_rea/auditor.py +62 -12
  13. package/src/tzero/anti_rea/canary_beacon.py +56 -76
  14. package/src/tzero/anti_rea/cli.py +37 -5
  15. package/src/tzero/anti_rea/confusables.py +62 -18
  16. package/src/tzero/anti_rea/crypto_loader.py +132 -0
  17. package/src/tzero/anti_rea/engine.py +129 -29
  18. package/src/tzero/anti_rea/extractor_shield.py +91 -13
  19. package/src/tzero/anti_rea/gui.py +1 -4
  20. package/src/tzero/anti_rea/integrity_guard.py +17 -5
  21. package/src/tzero/anti_rea/rdtsc_guard.py +21 -8
  22. package/src/tzero/anti_rea/string_vault.py +10 -7
  23. package/src/tzero/anti_rea/tier_catalog.py +388 -0
  24. package/src/tzero/siber_akademi.ico +0 -0
  25. package/src/tzero/siber_akademi_icon.py +14 -8
  26. package/src/tzero/tzero_armor.py +29 -7
  27. package/src/tzero/tzero_benchmark.py +4 -2
  28. package/src/tzero/tzero_budget.py +14 -5
  29. package/src/tzero/tzero_ci.py +2 -2
  30. package/src/tzero/tzero_contracts.py +7 -5
  31. package/src/tzero/tzero_dashboard.py +28 -9
  32. package/src/tzero/tzero_debt.py +19 -4
  33. package/src/tzero/tzero_deps.py +109 -87
  34. package/src/tzero/tzero_explain.py +1 -1
  35. package/src/tzero/tzero_features.py +43 -29
  36. package/src/tzero/tzero_federation.py +9 -2
  37. package/src/tzero/tzero_fixer/mcp_server.py +10 -0
  38. package/src/tzero/tzero_golden.py +37 -9
  39. package/src/tzero/tzero_growth.py +166 -8
  40. package/src/tzero/tzero_guard.py +147 -46
  41. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1 -1
  42. package/src/tzero/tzero_jarvis/zero_key_router.py +10 -78
  43. package/src/tzero/tzero_lsp.py +1 -1
  44. package/src/tzero/tzero_mcp.py +71 -23
  45. package/src/tzero/tzero_mutation.py +92 -15
  46. package/src/tzero/tzero_promo.py +1 -1
  47. package/src/tzero/tzero_proxy.py +105 -12
  48. package/src/tzero/tzero_scip.py +12 -6
  49. package/src/tzero/tzero_security.py +404 -60
  50. package/src/tzero/tzero_task_benchmark.py +2 -2
  51. package/src/tzero/tzero_traffic.py +35 -10
  52. package/src/tzero/tzero_tui.py +20 -11
  53. package/src/tzero/tzero_v3.py +304 -153
  54. package/src/tzero/tzero_welcome.py +12 -4
  55. package/bin/postinstall.js +0 -30
@@ -109,6 +109,7 @@ class ChangeImpactAnalyzer:
109
109
  self.symbol_locations: Dict[str, List[str]] = collections.defaultdict(list) # symbol -> [defining_files]
110
110
  self.import_graph: Dict[str, Set[str]] = collections.defaultdict(set) # file -> imported_modules
111
111
  self.inbound_graph: Dict[str, Set[str]] = collections.defaultdict(set) # module -> dependent_files
112
+ self._file_ref_cache: Dict[str, Tuple[Dict[str, Set[int]], Dict[str, Set[int]], Dict[str, Set[int]]]] = {}
112
113
  self._build_index()
113
114
 
114
115
  def _add_symbol_def(self, symbol: str, rel_path: str):
@@ -139,8 +140,7 @@ class ChangeImpactAnalyzer:
139
140
  try:
140
141
  tree = ast.parse(code)
141
142
  self.ast_trees[rel_path] = tree
142
- stem = os.path.splitext(os.path.basename(rel_path))[0]
143
-
143
+
144
144
  for node in tree.body:
145
145
  if isinstance(node, ast.ClassDef):
146
146
  self._add_symbol_def(node.name, rel_path)
@@ -163,6 +163,34 @@ class ChangeImpactAnalyzer:
163
163
  except Exception:
164
164
  pass
165
165
 
166
+ def _get_file_refs(self, rel_path: str, content: str) -> Tuple[Dict[str, Set[int]], Dict[str, Set[int]], Dict[str, Set[int]]]:
167
+ """Builds and caches a per-file AST reference index in a single traversal."""
168
+ cached = self._file_ref_cache.get(rel_path)
169
+ if cached is not None:
170
+ return cached
171
+ tree = self.ast_trees.get(rel_path)
172
+ if tree is None:
173
+ tree = ast.parse(content)
174
+ self.ast_trees[rel_path] = tree
175
+ name_lines: Dict[str, Set[int]] = collections.defaultdict(set)
176
+ call_attr_lines: Dict[str, Set[int]] = collections.defaultdict(set)
177
+ dotted_lines: Dict[str, Set[int]] = collections.defaultdict(set)
178
+ for node in ast.walk(tree):
179
+ if isinstance(node, ast.Call):
180
+ if isinstance(node.func, ast.Attribute):
181
+ lineno = getattr(node, 'lineno', 1)
182
+ call_attr_lines[node.func.attr].add(lineno)
183
+ if isinstance(node.func.value, ast.Name):
184
+ dotted_lines[f"{node.func.value.id}.{node.func.attr}"].add(lineno)
185
+ elif isinstance(node, ast.Attribute):
186
+ if isinstance(node.value, ast.Name):
187
+ dotted_lines[f"{node.value.id}.{node.attr}"].add(getattr(node, 'lineno', 1))
188
+ elif isinstance(node, ast.Name):
189
+ name_lines[node.id].add(getattr(node, 'lineno', 1))
190
+ entry = (name_lines, call_attr_lines, dotted_lines)
191
+ self._file_ref_cache[rel_path] = entry
192
+ return entry
193
+
166
194
  def analyze_symbol(self, symbol_name: str) -> Dict[str, Any]:
167
195
  """Calculates the blast radius for modifying a specific symbol (class/function).
168
196
 
@@ -176,44 +204,30 @@ class ChangeImpactAnalyzer:
176
204
 
177
205
  target_attr = symbol_name.split('.')[-1]
178
206
  target_class = symbol_name.split('.')[0] if '.' in symbol_name else ""
207
+ dotted_key = f"{target_class}.{target_attr}" if target_class else ""
179
208
 
180
209
  for f, content in self.snippets.items():
181
210
  if f in defining_locations or target_attr not in content:
182
211
  continue
183
212
 
184
- matches_lines: List[int] = []
213
+ matches_set: Set[int] = set()
185
214
  try:
186
- tree = self.ast_trees.get(f)
187
- if tree is None:
188
- tree = ast.parse(content)
189
- self.ast_trees[f] = tree
190
- for node in ast.walk(tree):
191
- if isinstance(node, ast.Call):
192
- matched = False
193
- if isinstance(node.func, ast.Name) and node.func.id == target_attr:
194
- matched = True
195
- elif isinstance(node.func, ast.Attribute) and node.func.attr == target_attr:
196
- if target_class:
197
- if isinstance(node.func.value, ast.Name) and node.func.value.id == target_class:
198
- matched = True
199
- else:
200
- matched = True
201
- if matched:
202
- matches_lines.append(getattr(node, 'lineno', 1))
203
- elif isinstance(node, ast.Attribute) and node.attr == target_attr:
204
- if target_class and isinstance(node.value, ast.Name) and node.value.id == target_class:
205
- matches_lines.append(getattr(node, 'lineno', 1))
206
- elif isinstance(node, ast.Name) and node.id == target_attr:
207
- # Direct symbol reference as argument, type annotation, or value
208
- matches_lines.append(getattr(node, 'lineno', 1))
215
+ name_lines, call_attr_lines, dotted_lines = self._get_file_refs(f, content)
216
+ if target_attr in name_lines:
217
+ matches_set.update(name_lines[target_attr])
218
+ if target_class:
219
+ if dotted_key in dotted_lines:
220
+ matches_set.update(dotted_lines[dotted_key])
221
+ else:
222
+ if target_attr in call_attr_lines:
223
+ matches_set.update(call_attr_lines[target_attr])
209
224
  except Exception:
210
225
  # Fallback for non-python files or invalid syntax
211
226
  pattern = rf"\b{re.escape(target_attr)}\b"
212
227
  for m in re.finditer(pattern, content):
213
- line_no = content[:m.start()].count('\n') + 1
214
- matches_lines.append(line_no)
228
+ matches_set.add(content[:m.start()].count('\n') + 1)
215
229
 
216
- unique_lines = sorted(list(set(matches_lines)))
230
+ unique_lines = sorted(matches_set)
217
231
  if unique_lines:
218
232
  direct_callers.append({
219
233
  "file": f,
@@ -239,8 +239,15 @@ class FederationSyncEngine:
239
239
  import tempfile
240
240
  ws_root = os.path.realpath(".")
241
241
  tmp_root = os.path.realpath(tempfile.gettempdir())
242
- safe_scip = os.path.normpath(os.path.realpath(os.path.abspath(scip_path)))
243
- if (safe_scip.startswith(ws_root + os.sep) or safe_scip.startswith(tmp_root + os.sep)) and os.path.isfile(safe_scip):
242
+ cand_scip = os.path.realpath(os.path.abspath(scip_path))
243
+ base_root = tmp_root if (cand_scip == tmp_root or cand_scip.startswith(tmp_root + os.sep)) else ws_root
244
+ rel_scip = os.path.relpath(cand_scip, base_root)
245
+ safe_scip = os.path.normpath(os.path.join(base_root, rel_scip))
246
+ if rel_scip == ".." or rel_scip.startswith(".." + os.sep) or os.path.isabs(rel_scip):
247
+ safe_scip = ""
248
+ elif not safe_scip.startswith(base_root):
249
+ safe_scip = ""
250
+ if safe_scip and os.path.isfile(safe_scip):
244
251
  try:
245
252
  from tzero.tzero_scip import ScipIndexImporter
246
253
  scip_trace = ScipIndexImporter.load(safe_scip).trace_symbol(sym)
@@ -481,6 +481,16 @@ class PCFixerMcpServer:
481
481
 
482
482
  def main():
483
483
  """Main CLI entrypoint for PC-Fixer MCP Server."""
484
+ import argparse
485
+ from tzero import __version__ as tzero_version
486
+
487
+ parser = argparse.ArgumentParser(
488
+ prog="pc-fixer-mcp",
489
+ description="T-Zero PC-Fixer & Codebase Doctor Standalone JSON-RPC 2.0 MCP Server (stdio)",
490
+ )
491
+ parser.add_argument("--version", action="version", version=f"pc-fixer-mcp {tzero_version}")
492
+ parser.parse_args()
493
+
484
494
  server = PCFixerMcpServer()
485
495
  server.run()
486
496
 
@@ -11,7 +11,7 @@ Capabilities:
11
11
  - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
12
12
 
13
13
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
14
- Part of T-Zero Context Architect v12.2.1 Master Edition.
14
+ Part of T-Zero Context Architect v12.3.2 Master Edition.
15
15
  """
16
16
 
17
17
  import ast
@@ -160,7 +160,17 @@ class ASTGoldenRegressionEngine:
160
160
  @classmethod
161
161
  def generate_baseline(cls, workspace_root: str = ".", max_files: int = 300) -> GoldenBaseline:
162
162
  """Scans workspace and generates the golden contract baseline."""
163
- abs_root = os.path.realpath(os.path.abspath(workspace_root))
163
+ import tempfile
164
+ ws_root = os.path.realpath(".")
165
+ tmp_root = os.path.realpath(tempfile.gettempdir())
166
+ candidate_root = os.path.realpath(os.path.abspath(workspace_root))
167
+ base_root = tmp_root if (candidate_root == tmp_root or candidate_root.startswith(tmp_root + os.sep)) else ws_root
168
+ rel_root = os.path.relpath(candidate_root, base_root)
169
+ if rel_root == ".." or rel_root.startswith(".." + os.sep) or os.path.isabs(rel_root):
170
+ raise ValueError(f"Workspace root outside allowed scope: {workspace_root}")
171
+ abs_root = os.path.normpath(os.path.join(base_root, rel_root))
172
+ if not abs_root.startswith(base_root):
173
+ raise ValueError(f"Workspace root outside allowed scope: {workspace_root}")
164
174
  all_sigs: Dict[str, Dict[str, Any]] = {}
165
175
  hasher = hashlib.sha256()
166
176
 
@@ -171,10 +181,14 @@ class ASTGoldenRegressionEngine:
171
181
  dirs[:] = [d for d in dirs if d not in ignore_dirs and not d.startswith(".")]
172
182
  for f in files:
173
183
  if f.endswith(".py"):
174
- full_p = os.path.realpath(os.path.join(root, f))
175
- if not (full_p == abs_root or full_p.startswith(abs_root + os.sep)):
184
+ resolved_p = os.path.realpath(os.path.join(root, f))
185
+ rel_file = os.path.relpath(resolved_p, abs_root)
186
+ if rel_file == ".." or rel_file.startswith(".." + os.sep) or os.path.isabs(rel_file):
176
187
  continue
177
- rel_p = os.path.relpath(full_p, abs_root).replace("\\", "/")
188
+ full_p = os.path.normpath(os.path.join(abs_root, rel_file))
189
+ if not full_p.startswith(abs_root):
190
+ continue
191
+ rel_p = rel_file.replace("\\", "/")
178
192
  try:
179
193
  with open(full_p, "r", encoding="utf-8", errors="replace") as fp:
180
194
  code = fp.read()
@@ -194,7 +208,7 @@ class ASTGoldenRegressionEngine:
194
208
 
195
209
  return GoldenBaseline(
196
210
  workspace_root=abs_root,
197
- version="12.2.1",
211
+ version="12.3.2",
198
212
  created_at=time.time(),
199
213
  symbols=all_sigs,
200
214
  total_symbols=len(all_sigs),
@@ -212,10 +226,24 @@ class ASTGoldenRegressionEngine:
212
226
  @classmethod
213
227
  def verify_against_golden(cls, workspace_root: str = ".", golden_path: Optional[str] = None) -> Dict[str, Any]:
214
228
  """Compares current working tree AST signatures against the golden baseline."""
215
- abs_root = os.path.realpath(os.path.abspath(workspace_root))
229
+ import tempfile
230
+ ws_root = os.path.realpath(".")
231
+ tmp_root = os.path.realpath(tempfile.gettempdir())
232
+ cand_root = os.path.realpath(os.path.abspath(workspace_root))
233
+ base_root = tmp_root if (cand_root == tmp_root or cand_root.startswith(tmp_root + os.sep)) else ws_root
234
+ rel_ws = os.path.relpath(cand_root, base_root)
235
+ if rel_ws == ".." or rel_ws.startswith(".." + os.sep) or os.path.isabs(rel_ws):
236
+ return {"success": False, "error": "Workspace root outside allowed scope."}
237
+ abs_root = os.path.normpath(os.path.join(base_root, rel_ws))
238
+ if not abs_root.startswith(base_root):
239
+ return {"success": False, "error": "Workspace root outside allowed scope."}
216
240
  raw_g_path = golden_path or os.path.join(abs_root, ".tzero", "goldens.json")
217
- g_path = os.path.realpath(os.path.abspath(raw_g_path))
218
- if not (g_path == abs_root or g_path.startswith(abs_root + os.sep)):
241
+ cand_g = os.path.realpath(os.path.abspath(raw_g_path))
242
+ rel_g = os.path.relpath(cand_g, abs_root)
243
+ if rel_g == ".." or rel_g.startswith(".." + os.sep) or os.path.isabs(rel_g):
244
+ return {"success": False, "error": "Golden path outside workspace root."}
245
+ g_path = os.path.normpath(os.path.join(abs_root, rel_g))
246
+ if not g_path.startswith(abs_root):
219
247
  return {"success": False, "error": "Golden path outside workspace root."}
220
248
 
221
249
  if not os.path.isfile(g_path):
@@ -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.3.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: