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
@@ -1,14 +1,14 @@
1
1
  # -*- coding: utf-8 -*-
2
- """Siber Akademi T-Zero — Anti-REA Defense & Armor Engine.
2
+ """Siber Akademi T-Zero — 180-Tier Ultra Anti-REA Defense & Armor Engine.
3
3
 
4
4
  Military-grade defense engine protecting codebases and executables
5
5
  against AI-driven automated reverse engineering (e.g. morluto/rea,
6
6
  Ghidra MCP bridge, IDA Pro LLM plugins, pyinstxtractor) and uncensored/jailbroken LLMs.
7
7
  Includes native Ring-3 anti-debugging against x64dbg, IDA Pro, WinDbg, and Cheat Engine,
8
- stealth canary beacon telemetry, in-flight string vault, and Electron asar shielding.
8
+ opt-in tamper alert webhook, in-flight string vault, and Electron asar shielding.
9
9
 
10
10
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
11
- Part of Siber Akademi T-Zero Context Architect v12.2.0 Master Edition.
11
+ Part of Siber Akademi T-Zero Context Architect v12.3.2 Master Edition.
12
12
  License: MIT
13
13
  """
14
14
 
@@ -98,22 +98,44 @@ def protect_path_with_armor(
98
98
  if p.is_file():
99
99
  return AntiREAEngine.protect_file(str(p), output_path=output_path, seed=seed, **options)
100
100
 
101
- # If directory, protect all .py files within
101
+ out_root: Optional[Path] = None
102
+ if output_path:
103
+ out_root = Path(output_path)
104
+ if out_root.exists() and not out_root.is_dir():
105
+ return {
106
+ "success": False,
107
+ "error": f"Output target for directory protection must be a directory, got file: {output_path}",
108
+ }
109
+ if out_root.resolve() == p.resolve():
110
+ out_root = None
111
+
102
112
  results = []
113
+ failures = []
103
114
  count = 0
104
115
  for py_file in p.rglob("*.py"):
105
116
  if "__pycache__" in str(py_file) or ".venv" in str(py_file):
106
117
  continue
107
- res = AntiREAEngine.protect_file(str(py_file), seed=seed, **options)
118
+ dst_path: Optional[str] = None
119
+ if out_root is not None:
120
+ rel = py_file.relative_to(p)
121
+ dst_file = out_root / rel
122
+ dst_file.parent.mkdir(parents=True, exist_ok=True)
123
+ dst_path = str(dst_file)
124
+ res = AntiREAEngine.protect_file(str(py_file), output_path=dst_path, seed=seed, **options)
108
125
  if res.get("success"):
109
126
  count += 1
110
127
  results.append(res)
128
+ else:
129
+ failures.append({"file": str(py_file), "error": res.get("error", "Unknown protection failure")})
111
130
 
112
131
  return {
113
- "success": count > 0,
132
+ "success": len(failures) == 0 and count > 0,
114
133
  "directory": str(p),
134
+ "output_directory": str(out_root) if out_root is not None else str(p),
115
135
  "files_protected": count,
116
- "details": results
136
+ "files_failed": len(failures),
137
+ "failures": failures,
138
+ "details": results,
117
139
  }
118
140
 
119
141
 
@@ -2,7 +2,7 @@
2
2
  """
3
3
  Siber Akademi — T-Zero Autonomous Benchmark & Performance Optimization Engine.
4
4
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
5
- Version: 11.15.2
5
+ Version: 12.3.2
6
6
  License: MIT
7
7
 
8
8
  Performs quantitative multi-model benchmarks comparing raw codebase context
@@ -154,9 +154,11 @@ class TZeroBenchmarkEngine:
154
154
  speedup_factor=speedup
155
155
  ))
156
156
 
157
+ from tzero import __version__ as tz_ver
158
+
157
159
  return BenchmarkReport(
158
160
  workspace_dir=abs_root,
159
- version="11.15.2",
161
+ version=tz_ver,
160
162
  total_files=total_files,
161
163
  total_loc=total_loc,
162
164
  raw_tokens=raw_tokens,
@@ -12,7 +12,7 @@ Capabilities:
12
12
  - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
13
13
 
14
14
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
15
- Part of T-Zero Context Architect v12.2.1 Master Edition.
15
+ Part of T-Zero Context Architect v12.3.2 Master Edition.
16
16
  """
17
17
 
18
18
  import hashlib
@@ -68,8 +68,13 @@ class ASTTokenBudgetOptimizer:
68
68
  import tempfile
69
69
  ws_root = os.path.realpath(".")
70
70
  tmp_root = os.path.realpath(tempfile.gettempdir())
71
- abs_root = os.path.normpath(os.path.realpath(os.path.abspath(workspace_root)))
72
- if abs_root != ws_root and not abs_root.startswith(ws_root + os.sep) and not abs_root.startswith(tmp_root + os.sep):
71
+ candidate = os.path.realpath(os.path.abspath(workspace_root))
72
+ base_root = tmp_root if (candidate == tmp_root or candidate.startswith(tmp_root + os.sep)) else ws_root
73
+ rel_ws = os.path.relpath(candidate, base_root)
74
+ if rel_ws == ".." or rel_ws.startswith(".." + os.sep) or os.path.isabs(rel_ws):
75
+ raise ValueError(f"Workspace path outside allowed scope: {workspace_root}")
76
+ abs_root = os.path.normpath(os.path.join(base_root, rel_ws))
77
+ if not abs_root.startswith(base_root):
73
78
  raise ValueError(f"Workspace path outside allowed scope: {workspace_root}")
74
79
  total_chars = 0
75
80
  file_count = 0
@@ -92,8 +97,12 @@ class ASTTokenBudgetOptimizer:
92
97
  dirs[:] = [d for d in dirs if d not in ignore_dirs and not d.startswith(".")]
93
98
  for f in files:
94
99
  if f.endswith((".py", ".ts", ".js", ".rs", ".go", ".cpp", ".c", ".h", ".swift", ".kt", ".dart")):
95
- full_p = os.path.realpath(os.path.join(root, f))
96
- if not (full_p == abs_root or full_p.startswith(abs_root + os.sep)):
100
+ resolved_f = os.path.realpath(os.path.join(root, f))
101
+ rel_f = os.path.relpath(resolved_f, abs_root)
102
+ if rel_f == ".." or rel_f.startswith(".." + os.sep) or os.path.isabs(rel_f):
103
+ continue
104
+ full_p = os.path.normpath(os.path.join(abs_root, rel_f))
105
+ if not full_p.startswith(abs_root):
97
106
  continue
98
107
  try:
99
108
  with open(full_p, "rb") as fp:
@@ -712,7 +712,7 @@ exit 0
712
712
  lines = []
713
713
  lines.append("\033[36m┌────────────────────────────────────────────────────────────────────────┐\033[0m")
714
714
  lines.append("\033[36m│\033[0m \033[1;37m⚡ T-ZERO LOCAL CI & PRE-PUSH VERIFICATION RUNNER\033[0m \033[36m│\033[0m")
715
- lines.append("\033[36m│\033[0m \033[32mZero Quota Burn\033[0m • \033[33m100% Offline\033[0m • \033[35mZero-Leak Guaranteed\033[0m \033[36m│\033[0m")
715
+ lines.append("\033[36m│\033[0m \033[32mLocal AST Analysis\033[0m • \033[33mToken Estimates\033[0m \033[36m│\033[0m")
716
716
  lines.append("\033[36m└────────────────────────────────────────────────────────────────────────┘\033[0m")
717
717
  lines.append("")
718
718
 
@@ -755,7 +755,7 @@ def main():
755
755
  prog="tzero-ci",
756
756
  description="Siber Akademi T-Zero Local CI Pipeline & Pre-Push Verification Shield"
757
757
  )
758
- parser.add_argument("--version", "-v", action="version", version="%(prog)s 12.2.1")
758
+ parser.add_argument("--version", "-v", action="version", version="%(prog)s 12.3.2")
759
759
  parser.add_argument("--quick", "-q", action="store_true", help="Run fast verification battery (seconds)")
760
760
  parser.add_argument("--all", "-a", action="store_true", help="Run full matrix verification battery")
761
761
  parser.add_argument("--fix", action="store_true", help="Attempt auto-repair for auto-fixable gates (metadata sync)")
@@ -13,7 +13,7 @@ Capabilities:
13
13
  - 100% Offline, $0 cost, zero external dependencies (pure Python standard library).
14
14
 
15
15
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
16
- Part of T-Zero Context Architect v12.2.1 Master Edition.
16
+ Part of T-Zero Context Architect v12.3.2 Master Edition.
17
17
  """
18
18
 
19
19
  import ast
@@ -471,9 +471,11 @@ class ASTContractExtractor:
471
471
  if "\n" in header_tail and "extends" not in header_tail:
472
472
  continue
473
473
  bases: List[str] = []
474
- ext_m = re.search(r'\bextends\s+(.+)$', header_tail, re.DOTALL)
475
- if ext_m:
476
- bases = [b.strip() for b in ext_m.group(1).split(",") if b.strip()]
474
+ ext_idx = header_tail.find("extends")
475
+ if ext_idx != -1 and (ext_idx == 0 or not (header_tail[ext_idx - 1].isalnum() or header_tail[ext_idx - 1] == "_")):
476
+ after_ext = header_tail[ext_idx + 7:]
477
+ if after_ext and after_ext[0].isspace():
478
+ bases = [b.strip() for b in after_ext.strip().split(",") if b.strip()]
477
479
  end_brace = cls._find_matching_brace(clean_code, brace_idx)
478
480
  if end_brace == -1:
479
481
  end_brace = len(clean_code) - 1
@@ -1054,7 +1056,7 @@ class ASTContractComparator:
1054
1056
  "tool": {
1055
1057
  "driver": {
1056
1058
  "name": "T-Zero Contract Guardian",
1057
- "version": "12.2.1",
1059
+ "version": "12.3.2",
1058
1060
  "rules": rules_list
1059
1061
  }
1060
1062
  },
@@ -457,7 +457,7 @@ HTML_PAGE = """<!DOCTYPE html>
457
457
  <div class="brand-logo">T0</div>
458
458
  <div>
459
459
  <div class="brand-title">T-Zero Developer Console</div>
460
- <div class="brand-sub" id="headerBrandSub">Enterprise AST Context Architect &bull; v12.2.1</div>
460
+ <div class="brand-sub" id="headerBrandSub">Enterprise AST Context Architect &bull; v12.3.2</div>
461
461
  </div>
462
462
  </div>
463
463
  <div class="header-actions">
@@ -850,7 +850,7 @@ x = 2
850
850
  </main>
851
851
 
852
852
  <footer>
853
- <span id="footerBrand">T-Zero Context Architect v12.2.1</span> &bull; Developer: Toprak Ahmet Aydoğmuş &bull; Siber Akademi
853
+ <span id="footerBrand">T-Zero Context Architect v12.3.2</span> &bull; Developer: Toprak Ahmet Aydoğmuş &bull; Siber Akademi
854
854
  </footer>
855
855
 
856
856
  <script>
@@ -1481,7 +1481,7 @@ def compute_live_dashboard_stats(workspace_dir: str = ".") -> Dict[str, Any]:
1481
1481
  if cached is not None and (now - _DASHBOARD_STATS_CACHE["ts"]) < 60.0:
1482
1482
  return cached
1483
1483
 
1484
- version = "12.2.1"
1484
+ version = "12.3.2"
1485
1485
  tools_count = 57
1486
1486
  try:
1487
1487
  from tzero import tzero_mcp
@@ -1572,10 +1572,13 @@ class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
1572
1572
  raise ValueError("Invalid null byte in path.")
1573
1573
  ws_root = os.path.realpath(".")
1574
1574
  tmp_root = os.path.realpath(tempfile.gettempdir())
1575
- real_target = os.path.normpath(os.path.realpath(os.path.abspath(candidate)))
1576
- in_ws = (real_target == ws_root) or real_target.startswith(ws_root + os.sep)
1577
- in_tmp = (real_target == tmp_root) or real_target.startswith(tmp_root + os.sep)
1578
- if not in_ws and not in_tmp:
1575
+ resolved = os.path.realpath(os.path.abspath(candidate))
1576
+ base_root = tmp_root if (resolved == tmp_root or resolved.startswith(tmp_root + os.sep)) else ws_root
1577
+ rel = os.path.relpath(resolved, base_root)
1578
+ if rel == ".." or rel.startswith(".." + os.sep) or os.path.isabs(rel):
1579
+ raise ValueError(f"Access denied: path outside allowed workspace or temp scope ({candidate})")
1580
+ real_target = os.path.normpath(os.path.join(base_root, rel))
1581
+ if not real_target.startswith(base_root):
1579
1582
  raise ValueError(f"Access denied: path outside allowed workspace or temp scope ({candidate})")
1580
1583
  return real_target
1581
1584
  """Handles static UI and JSON-RPC API endpoints for T-Zero Dashboard."""
@@ -1832,8 +1835,16 @@ class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
1832
1835
  content_length = int(self.headers.get("Content-Length", 0))
1833
1836
  body = self.rfile.read(content_length).decode("utf-8")
1834
1837
  try:
1838
+ import tempfile
1835
1839
  payload = json.loads(body) if body.strip() else {}
1836
- target_p = self._resolve_safe_api_path(payload.get("path", "."))
1840
+ raw_debt = self._resolve_safe_api_path(payload.get("path", "."))
1841
+ ws_root = os.path.realpath(".")
1842
+ tmp_root = os.path.realpath(tempfile.gettempdir())
1843
+ base_root = tmp_root if (raw_debt == tmp_root or raw_debt.startswith(tmp_root + os.sep)) else ws_root
1844
+ rel_debt = os.path.relpath(raw_debt, base_root)
1845
+ target_p = os.path.normpath(os.path.join(base_root, rel_debt))
1846
+ if not target_p.startswith(base_root):
1847
+ raise ValueError("Access denied: debt path outside allowed root")
1837
1848
  from tzero.tzero_debt import CodeHealthAnalyzer
1838
1849
  if os.path.isfile(target_p):
1839
1850
  rep = CodeHealthAnalyzer.analyze_file(target_p)
@@ -1931,12 +1942,20 @@ class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
1931
1942
  self._send_json(resp)
1932
1943
  elif parsed.path == "/api/scip/summary":
1933
1944
  try:
1945
+ import tempfile
1934
1946
  payload = self._read_json_body()
1935
1947
  raw_scip = str(payload.get("path") or "").strip()
1936
1948
  if not raw_scip:
1937
1949
  resp = {"success": False, "error": "SCIP/LSIF index file not found: (empty)"}
1938
1950
  else:
1939
- scip_path = self._resolve_safe_api_path(raw_scip)
1951
+ resolved_scip = self._resolve_safe_api_path(raw_scip)
1952
+ ws_root = os.path.realpath(".")
1953
+ tmp_root = os.path.realpath(tempfile.gettempdir())
1954
+ base_root = tmp_root if (resolved_scip == tmp_root or resolved_scip.startswith(tmp_root + os.sep)) else ws_root
1955
+ rel_scip = os.path.relpath(resolved_scip, base_root)
1956
+ scip_path = os.path.normpath(os.path.join(base_root, rel_scip))
1957
+ if not scip_path.startswith(base_root):
1958
+ raise ValueError("Access denied: SCIP path outside allowed root")
1940
1959
  if not os.path.isfile(scip_path):
1941
1960
  resp = {"success": False, "error": f"SCIP/LSIF index file not found: {raw_scip}"}
1942
1961
  else:
@@ -13,7 +13,7 @@ Capabilities:
13
13
  - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
14
14
 
15
15
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
16
- Part of T-Zero Context Architect v12.2.1 Master Edition.
16
+ Part of T-Zero Context Architect v12.3.2 Master Edition.
17
17
  """
18
18
 
19
19
  import ast
@@ -214,8 +214,13 @@ class CodeHealthAnalyzer:
214
214
  import tempfile
215
215
  ws_root = os.path.realpath(".")
216
216
  tmp_root = os.path.realpath(tempfile.gettempdir())
217
- real_fp = os.path.normpath(os.path.realpath(os.path.abspath(file_path)))
218
- if not real_fp.startswith(ws_root + os.sep) and not real_fp.startswith(tmp_root + os.sep):
217
+ cand_fp = os.path.realpath(os.path.abspath(file_path))
218
+ base_root = tmp_root if (cand_fp == tmp_root or cand_fp.startswith(tmp_root + os.sep)) else ws_root
219
+ rel_fp = os.path.relpath(cand_fp, base_root)
220
+ if rel_fp == ".." or rel_fp.startswith(".." + os.sep) or os.path.isabs(rel_fp):
221
+ raise ValueError(f"Path outside allowed workspace/temp root: {file_path}")
222
+ real_fp = os.path.normpath(os.path.join(base_root, rel_fp))
223
+ if not real_fp.startswith(base_root):
219
224
  raise ValueError(f"Path outside allowed workspace/temp root: {file_path}")
220
225
  try:
221
226
  with open(real_fp, "r", encoding="utf-8", errors="replace") as f:
@@ -341,7 +346,17 @@ class CodeHealthAnalyzer:
341
346
 
342
347
  @classmethod
343
348
  def analyze_workspace(cls, workspace_root: str = ".", max_files: int = 250) -> WorkspaceHealthReport:
344
- abs_root = os.path.realpath(os.path.abspath(workspace_root))
349
+ import tempfile
350
+ ws_root = os.path.realpath(".")
351
+ tmp_root = os.path.realpath(tempfile.gettempdir())
352
+ cand_root = os.path.realpath(os.path.abspath(workspace_root))
353
+ base_root = tmp_root if (cand_root == tmp_root or cand_root.startswith(tmp_root + os.sep)) else ws_root
354
+ rel_root = os.path.relpath(cand_root, base_root)
355
+ if rel_root == ".." or rel_root.startswith(".." + os.sep) or os.path.isabs(rel_root):
356
+ raise ValueError(f"Workspace path outside allowed scope: {workspace_root}")
357
+ abs_root = os.path.normpath(os.path.join(base_root, rel_root))
358
+ if not abs_root.startswith(base_root):
359
+ raise ValueError(f"Workspace path outside allowed scope: {workspace_root}")
345
360
  reports: List[FileHealthReport] = []
346
361
 
347
362
  ignore_dirs = {".git", ".venv", "venv", "__pycache__", "node_modules", "dist", "build", ".pytest_cache"}
@@ -1,14 +1,9 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  """T-Zero dependency bootstrap and environment doctor (standard library only).
3
3
 
4
- * ``ensure_dependencies()`` runs before anything else is imported. If a required package is
5
- missing or older than the minimum version, it is installed with pip (quietly, to stderr only,
6
- so the MCP stdio protocol on stdout is never disturbed).
7
- * ``run_doctor()`` powers ``python main.py --doctor``: it checks Python, packages, tkinter, git
8
- and the OS keyring and prints an easy-to-read report.
9
-
10
- Set ``TZERO_NO_AUTO_INSTALL=1`` to disable automatic installation (the tool then only tells you
11
- what is missing). Frozen builds (the .exe) never install anything.
4
+ * ``ensure_dependencies()`` checks installed package versions and prints a manual
5
+ installation command when something is missing.
6
+ * ``run_doctor()`` reports the state of Python, packages, tkinter, Git and keyring.
12
7
 
13
8
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
14
9
  """
@@ -17,9 +12,12 @@ import importlib
17
12
  import importlib.util
18
13
  import os
19
14
  import re
15
+ import shlex
20
16
  import shutil
21
17
  import subprocess
22
18
  import sys
19
+ import sysconfig
20
+ from pathlib import Path
23
21
  from typing import List, NamedTuple, Optional, Tuple
24
22
 
25
23
  OPT_OUT_ENV = "TZERO_NO_AUTO_INSTALL"
@@ -89,8 +87,8 @@ def _err(message: str) -> None:
89
87
  pass
90
88
 
91
89
 
92
- def ensure_dependencies(include_mcp: bool = False) -> bool:
93
- """Makes sure required packages are present, installing them when allowed.
90
+ def ensure_dependencies(include_mcp: bool = False, *, install: bool = False) -> bool:
91
+ """Check dependencies, with installation available to explicit callers.
94
92
 
95
93
  Returns True when everything needed is available afterwards.
96
94
  """
@@ -101,7 +99,6 @@ def ensure_dependencies(include_mcp: bool = False) -> bool:
101
99
  if getattr(sys, "frozen", False): # PyInstaller build: dependencies are bundled
102
100
  return True
103
101
 
104
- ensure_scripts_in_path(quiet=True)
105
102
  deps = list(REQUIRED) + ([MCP_DEPENDENCY] if include_mcp else [])
106
103
  problems = [d for d in deps if check_dependency(d)[0] != "ok"]
107
104
  if not problems:
@@ -109,9 +106,9 @@ def ensure_dependencies(include_mcp: bool = False) -> bool:
109
106
 
110
107
  specs = [d.spec for d in problems]
111
108
  manual = f'"{sys.executable}" -m pip install ' + " ".join(f'"{s}"' for s in specs)
112
- if os.environ.get(OPT_OUT_ENV) == "1":
109
+ if not install or os.environ.get(OPT_OUT_ENV) == "1":
113
110
  _err("[T-Zero] Missing or outdated packages: " + ", ".join(specs))
114
- _err(f"[T-Zero] Automatic install is disabled ({OPT_OUT_ENV}=1). Run:\n {manual}")
111
+ _err(f"[T-Zero] Install manually:\n {manual}")
115
112
  return False
116
113
 
117
114
  _err("[T-Zero] Installing missing or outdated packages: " + ", ".join(specs))
@@ -135,7 +132,6 @@ def ensure_dependencies(include_mcp: bool = False) -> bool:
135
132
  _err(f" Install manually:\n {manual}")
136
133
  return False
137
134
 
138
- ensure_scripts_in_path(quiet=True)
139
135
  still_bad = [d.spec for d in problems if check_dependency(d)[0] != "ok"]
140
136
  if still_bad:
141
137
  _err("[T-Zero] Still unavailable after install: " + ", ".join(still_bad))
@@ -144,77 +140,107 @@ def ensure_dependencies(include_mcp: bool = False) -> bool:
144
140
  return True
145
141
 
146
142
 
147
- def ensure_scripts_in_path(quiet: bool = True) -> bool:
148
- """Ensures Python's Scripts/bin directory is in the user's PATH environment variable.
149
-
150
- Automatically fixes Windows and Unix PATH when installing via pip so commands
151
- like `tzero`, `tzero-gui`, `tzero-mcp`, `tzero-add-mcp` work everywhere immediately.
152
- """
153
- import site
154
- candidates = []
143
+ def _line(level: str, text: str) -> str:
144
+ return f" [{level:^4}] {text}"
145
+
146
+
147
+ def _tzero_scripts_directory() -> Path:
148
+ executable = "tzero.exe" if os.name == "nt" else "tzero"
149
+ for scheme in (sysconfig.get_default_scheme(), sysconfig.get_preferred_scheme("user")):
150
+ scripts = Path(sysconfig.get_path("scripts", scheme)).resolve()
151
+ if (scripts / executable).is_file():
152
+ return scripts
153
+ raise ValueError("No T-Zero executable was found for this Python installation.")
154
+
155
+
156
+ def _append_windows_user_path(scripts: Path) -> bool:
157
+ import ntpath
158
+ import winreg
159
+
160
+ directory = str(scripts)
161
+
162
+ def normalize(value: str) -> str:
163
+ return ntpath.normcase(ntpath.normpath(winreg.ExpandEnvironmentStrings(value)))
164
+
165
+ access = winreg.KEY_READ | winreg.KEY_SET_VALUE
166
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, "Environment", 0, access) as key:
167
+ try:
168
+ current, kind = winreg.QueryValueEx(key, "Path")
169
+ except FileNotFoundError:
170
+ current, kind = "", winreg.REG_EXPAND_SZ
171
+ if kind not in (winreg.REG_SZ, winreg.REG_EXPAND_SZ):
172
+ raise ValueError("The Windows user PATH is not a string.")
173
+ if any(normalize(entry) == normalize(directory) for entry in current.split(";") if entry):
174
+ return False
175
+ separator = ";" if current and not current.endswith(";") else ""
176
+ winreg.SetValueEx(key, "Path", 0, kind, current + separator + directory)
177
+ return True
178
+
155
179
 
156
- if os.name == "nt":
157
- sys_scripts = os.path.join(sys.prefix, "Scripts")
158
- user_scripts = os.path.join(site.USER_BASE, "Scripts")
180
+ def _append_shell_path(scripts: Path, config: Path) -> bool:
181
+ import fcntl
182
+
183
+ directory = shlex.quote(str(scripts))
184
+ entry = f'case ":$PATH:" in *:{directory}:*) ;; *) export PATH="${{PATH:+$PATH:}}"{directory} ;; esac'
185
+ with config.open("a+", encoding="utf-8", errors="surrogateescape", newline="") as handle:
186
+ fcntl.flock(handle, fcntl.LOCK_EX)
187
+ handle.seek(0)
188
+ current = handle.read()
189
+ if entry in current.splitlines():
190
+ return False
191
+ if current and not current.endswith("\n"):
192
+ handle.write("\n")
193
+ handle.write(f"# Added by T-Zero\n{entry}\n")
194
+ return True
195
+
196
+
197
+ def add_to_user_path(shell: Optional[str] = None) -> int:
198
+ """Add an installed T-Zero launcher to the user's PATH on explicit request."""
199
+ try:
200
+ scripts = _tzero_scripts_directory()
201
+ separator = ";" if os.name == "nt" else ":"
202
+ if any(char in str(scripts) for char in (separator, "\r", "\n")):
203
+ raise ValueError("The T-Zero executable directory contains a PATH separator or newline.")
204
+ if os.name == "nt":
205
+ if shell:
206
+ raise ValueError("--shell applies to Bash and Zsh on Unix.")
207
+ changed = _append_windows_user_path(scripts)
208
+ target = "the Windows user PATH"
209
+ else:
210
+ shell = shell or Path(os.environ.get("SHELL", "")).name
211
+ if shell not in ("bash", "zsh"):
212
+ raise ValueError("Select Bash or Zsh with --shell bash or --shell zsh.")
213
+ config_dir = Path.home()
214
+ if shell == "zsh" and os.environ.get("ZDOTDIR"):
215
+ config_dir = Path(os.environ["ZDOTDIR"]).expanduser()
216
+ config = config_dir / f".{shell}rc"
217
+ changed = _append_shell_path(scripts, config)
218
+ target = str(config)
219
+ except (OSError, ValueError) as exc:
220
+ _err(f"[T-Zero] Could not update PATH: {exc}")
221
+ return 1
222
+
223
+ if changed:
224
+ print(f"Added {scripts} to {target}. Open a new shell to use the updated PATH.")
159
225
  else:
160
- sys_scripts = os.path.join(sys.prefix, "bin")
161
- user_scripts = os.path.join(site.USER_BASE, "bin")
162
-
163
- for p in [sys_scripts, user_scripts]:
164
- if p and os.path.isdir(p) and p not in candidates:
165
- candidates.append(p)
166
-
167
- current_path_dirs = [os.path.normcase(os.path.abspath(x)) for x in os.environ.get("PATH", "").split(os.pathsep) if x]
168
-
169
- added_any = False
170
- for candidate in candidates:
171
- norm_cand = os.path.normcase(os.path.abspath(candidate))
172
- if norm_cand not in current_path_dirs:
173
- # Update current process
174
- os.environ["PATH"] = candidate + os.pathsep + os.environ.get("PATH", "")
175
- current_path_dirs.insert(0, norm_cand)
176
- added_any = True
177
-
178
- # Permanently update user PATH
179
- if os.name == "nt":
180
- try:
181
- import winreg
182
- with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Environment", 0, winreg.KEY_READ | winreg.KEY_WRITE) as key:
183
- try:
184
- user_path, _ = winreg.QueryValueEx(key, "Path")
185
- except FileNotFoundError:
186
- user_path = ""
187
- parts = [x.strip() for x in user_path.split(";") if x.strip()]
188
- if candidate not in parts:
189
- parts.append(candidate)
190
- new_path = ";".join(parts)
191
- winreg.SetValueEx(key, "Path", 0, winreg.REG_EXPAND_SZ, new_path)
192
- if not quiet:
193
- sys.stderr.write(f"[T-Zero] Added {candidate} to User PATH in Windows Registry.\n")
194
- except Exception:
195
- pass
196
- else:
197
- try:
198
- home = os.path.expanduser("~")
199
- for rc_name in [".bashrc", ".zshrc"]:
200
- rc_path = os.path.join(home, rc_name)
201
- if os.path.exists(rc_path):
202
- with open(rc_path, "r", encoding="utf-8", errors="ignore") as f:
203
- rc_content = f.read()
204
- export_line = f'export PATH="{candidate}:$PATH"'
205
- if candidate not in rc_content:
206
- with open(rc_path, "a", encoding="utf-8") as f:
207
- f.write(f"\n# Added by T-Zero Context Architect\n{export_line}\n")
208
- if not quiet:
209
- sys.stderr.write(f"[T-Zero] Added {candidate} to {rc_name}\n")
210
- except Exception:
211
- pass
212
-
213
- return added_any
226
+ print(f"{scripts} is already configured in {target}.")
227
+ return 0
214
228
 
215
229
 
216
- def _line(level: str, text: str) -> str:
217
- return f" [{level:^4}] {text}"
230
+ def main() -> int:
231
+ import argparse
232
+
233
+ parser = argparse.ArgumentParser(description="Check Python dependencies and configure T-Zero's user PATH.")
234
+ parser.add_argument(
235
+ "--add-to-path", action="store_true", help="Persist T-Zero's executable directory in your user PATH."
236
+ )
237
+ parser.add_argument("--shell", choices=("bash", "zsh"), help="Select the shell configuration file to update on Unix.")
238
+ args = parser.parse_args()
239
+ if args.add_to_path:
240
+ return add_to_user_path(args.shell)
241
+ if args.shell:
242
+ parser.error("--shell requires --add-to-path")
243
+ return run_doctor()
218
244
 
219
245
 
220
246
  def _run_deep_subsystem_check() -> int:
@@ -382,7 +408,7 @@ def _run_deep_subsystem_check() -> int:
382
408
 
383
409
 
384
410
  def run_doctor(deep: bool = False) -> int:
385
- """Checks the environment, fixing missing packages when allowed. Returns a process exit code."""
411
+ """Checks the environment and returns a process exit code."""
386
412
  print("T-Zero Doctor: environment check\n")
387
413
  failures = 0
388
414
 
@@ -437,10 +463,6 @@ def run_doctor(deep: bool = False) -> int:
437
463
  except Exception as exc:
438
464
  print(_line("WARN", f"keyring could not be checked: {exc}"))
439
465
 
440
- if not deep:
441
- ensure_scripts_in_path(quiet=True)
442
- print(_line("OK", "Python Scripts PATH verified (tzero, tzero-gui, tzero-mcp accessible)"))
443
-
444
466
  if deep:
445
467
  from tzero.tzero_polyglot import _ALLOW_BPE_DOWNLOAD
446
468
 
@@ -459,4 +481,4 @@ def run_doctor(deep: bool = False) -> int:
459
481
 
460
482
 
461
483
  if __name__ == "__main__":
462
- sys.exit(run_doctor())
484
+ sys.exit(main())
@@ -6,7 +6,7 @@ delivering maximum semantic grounding to LLMs (Claude, GPT, Gemini, DeepSeek) wi
6
6
  up to 95% token savings compared to raw file ingestion.
7
7
 
8
8
  Author: Toprak Ahmet Aydogmus (Siber Akademi)
9
- Version: 11.15.1
9
+ Version: 12.3.2
10
10
  """
11
11
 
12
12
  import ast