tzero-mcp 10.7.4 → 11.11.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 (131) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -21
  3. package/README.md +3 -3
  4. package/bin/tzero-mcp.js +7 -11
  5. package/bin/tzero.js +7 -11
  6. package/index.js +3 -3
  7. package/package.json +3 -2
  8. package/src/addmcp.py +1203 -1194
  9. package/src/app.py +1810 -0
  10. package/src/main.py +60 -60
  11. package/src/pc_fixer_mcp.py +25 -0
  12. package/src/tzero/__init__.py +54 -0
  13. package/src/tzero/__main__.py +6 -0
  14. package/src/tzero/siber_akademi.ico +0 -0
  15. package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +77 -77
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +2 -2
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +184 -0
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/tzero/tzero_card.py +431 -0
  22. package/src/{tzero_ci.py → tzero/tzero_ci.py} +7 -7
  23. package/src/{tzero_commit.py → tzero/tzero_commit.py} +1 -1
  24. package/src/tzero/tzero_contracts.py +1093 -0
  25. package/src/{tzero_cost.py → tzero/tzero_cost.py} +4 -1
  26. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +1960 -1448
  27. package/src/tzero/tzero_debt.py +461 -0
  28. package/src/{tzero_deps.py → tzero/tzero_deps.py} +462 -287
  29. package/src/{tzero_drift.py → tzero/tzero_drift.py} +1 -1
  30. package/src/{tzero_explain.py → tzero/tzero_explain.py} +306 -240
  31. package/src/{tzero_features.py → tzero/tzero_features.py} +3024 -3022
  32. package/src/tzero/tzero_federation.py +299 -0
  33. package/src/tzero/tzero_fix.py +557 -0
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +334 -334
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +1 -1
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +8 -8
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +1 -1
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +1 -1
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +1 -1
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +1 -1
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +1 -1
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +280 -280
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +325 -325
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +489 -447
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +385 -385
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +375 -375
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +323 -323
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +2 -1
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +1 -1
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +1 -1
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +364 -364
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +619 -619
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +1 -1
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +2 -2
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +493 -493
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +1 -1
  58. package/src/tzero/tzero_golden.py +319 -0
  59. package/src/tzero/tzero_graph_hud.html +338 -0
  60. package/src/tzero/tzero_graph_rag.py +263 -0
  61. package/src/tzero/tzero_growth.py +415 -0
  62. package/src/{tzero_guard.py → tzero/tzero_guard.py} +11 -3
  63. package/src/tzero/tzero_hooks.py +565 -0
  64. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +11 -1
  65. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +1 -1
  66. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  67. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +1 -1
  68. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +2 -2
  69. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +1 -1
  70. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +1 -1
  71. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +2 -2
  72. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +1 -1
  73. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +3 -3
  74. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +1 -1
  75. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +6 -6
  76. package/src/tzero/tzero_lsp.py +634 -0
  77. package/src/tzero/tzero_mcp.py +5314 -0
  78. package/src/tzero/tzero_mutation.py +358 -0
  79. package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +1425 -1425
  80. package/src/tzero/tzero_packer.py +577 -0
  81. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +42 -0
  82. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +1 -1
  83. package/src/tzero/tzero_polyglot.py +799 -0
  84. package/src/tzero/tzero_proxy.py +127 -0
  85. package/src/tzero/tzero_rust_bridge.py +198 -0
  86. package/src/tzero/tzero_scip.py +368 -0
  87. package/src/{tzero_security.py → tzero/tzero_security.py} +573 -570
  88. package/src/tzero/tzero_semantic_merge.py +189 -0
  89. package/src/tzero/tzero_snapshot.py +471 -0
  90. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +1 -1
  91. package/src/tzero/tzero_subagent_engine.py +459 -0
  92. package/src/{tzero_sync.py → tzero/tzero_sync.py} +2 -2
  93. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +174 -31
  94. package/src/{tzero_tui.py → tzero/tzero_tui.py} +313 -244
  95. package/src/tzero/tzero_turbo.py +264 -0
  96. package/src/{tzero_v3.py → tzero/tzero_v3.py} +9997 -9435
  97. package/src/tzero.py +6 -58
  98. package/src/tzero_mcp.py +25 -4858
  99. package/test/package.test.js +14 -2
  100. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  101. package/src/tzero_fix.py +0 -228
  102. package/src/tzero_gateway.py +0 -885
  103. package/src/tzero_packer.py +0 -370
  104. package/src/tzero_polyglot.py +0 -422
  105. package/src/tzero_snapshot.py +0 -258
  106. /package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +0 -0
  107. /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +0 -0
  108. /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +0 -0
  109. /package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +0 -0
  110. /package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +0 -0
  111. /package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +0 -0
  112. /package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +0 -0
  113. /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +0 -0
  114. /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +0 -0
  115. /package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +0 -0
  116. /package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +0 -0
  117. /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +0 -0
  118. /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +0 -0
  119. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +0 -0
  120. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +0 -0
  121. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +0 -0
  122. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +0 -0
  123. /package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +0 -0
  124. /package/src/{tzero_infra.py → tzero/tzero_infra.py} +0 -0
  125. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +0 -0
  126. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +0 -0
  127. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +0 -0
  128. /package/src/{tzero_patch.py → tzero/tzero_patch.py} +0 -0
  129. /package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +0 -0
  130. /package/src/{tzero_replay.py → tzero/tzero_replay.py} +0 -0
  131. /package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +0 -0
@@ -1,287 +1,462 @@
1
- # -*- coding: utf-8 -*-
2
- """T-Zero dependency bootstrap and environment doctor (standard library only).
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.
12
-
13
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
14
- """
15
-
16
- import importlib
17
- import importlib.util
18
- import os
19
- import re
20
- import shutil
21
- import subprocess
22
- import sys
23
- from typing import List, NamedTuple, Optional, Tuple
24
-
25
- OPT_OUT_ENV = "TZERO_NO_AUTO_INSTALL"
26
- MIN_PYTHON = (3, 9)
27
-
28
-
29
- class Dependency(NamedTuple):
30
- import_name: str # name used in `import x`
31
- dist_name: str # name on PyPI / importlib.metadata
32
- min_version: str # minimum acceptable version
33
- purpose: str
34
-
35
- @property
36
- def spec(self) -> str:
37
- return f"{self.dist_name}>={self.min_version}"
38
-
39
-
40
- REQUIRED: List[Dependency] = [
41
- Dependency("requests", "requests", "2.28.0", "AI provider HTTP calls"),
42
- Dependency("keyring", "keyring", "23.13.1", "OS credential storage"),
43
- Dependency("darkdetect", "darkdetect", "0.8.0", "OS theme detection"),
44
- Dependency("pygments", "pygments", "2.14.0", "syntax highlighting"),
45
- Dependency("PIL", "Pillow", "9.0.0", "icon and image generation"),
46
- ]
47
- MCP_DEPENDENCY = Dependency("mcp", "mcp", "1.0.0", "Model Context Protocol server")
48
-
49
-
50
- def _version_tuple(version: str) -> Tuple[int, ...]:
51
- parts: List[int] = []
52
- for token in re.split(r"[.\-+]", version):
53
- match = re.match(r"\d+", token)
54
- if not match:
55
- break
56
- parts.append(int(match.group()))
57
- return tuple(parts)
58
-
59
-
60
- def installed_version(dep: Dependency) -> Optional[str]:
61
- """Returns the installed version string, or None when the distribution is unknown."""
62
- try:
63
- from importlib import metadata
64
- return metadata.version(dep.dist_name)
65
- except Exception:
66
- return None
67
-
68
-
69
- def check_dependency(dep: Dependency) -> Tuple[str, Optional[str]]:
70
- """Returns (status, version) where status is 'ok', 'outdated' or 'missing'."""
71
- try:
72
- found = importlib.util.find_spec(dep.import_name) is not None
73
- except (ImportError, ValueError):
74
- found = False
75
- if not found:
76
- return "missing", None
77
- version = installed_version(dep)
78
- if version and _version_tuple(version) < _version_tuple(dep.min_version):
79
- return "outdated", version
80
- return "ok", version
81
-
82
-
83
- def _err(message: str) -> None:
84
- if sys.stderr is not None and hasattr(sys.stderr, "write"):
85
- try:
86
- sys.stderr.write(message + "\n")
87
- sys.stderr.flush()
88
- except Exception:
89
- pass
90
-
91
-
92
- def ensure_dependencies(include_mcp: bool = False) -> bool:
93
- """Makes sure required packages are present, installing them when allowed.
94
-
95
- Returns True when everything needed is available afterwards.
96
- """
97
- if sys.version_info < MIN_PYTHON:
98
- _err(f"[T-Zero] Python {MIN_PYTHON[0]}.{MIN_PYTHON[1]}+ is required "
99
- f"(found {sys.version_info.major}.{sys.version_info.minor}).")
100
- return False
101
- if getattr(sys, "frozen", False): # PyInstaller build: dependencies are bundled
102
- return True
103
-
104
- ensure_scripts_in_path(quiet=True)
105
- deps = list(REQUIRED) + ([MCP_DEPENDENCY] if include_mcp else [])
106
- problems = [d for d in deps if check_dependency(d)[0] != "ok"]
107
- if not problems:
108
- return True
109
-
110
- specs = [d.spec for d in problems]
111
- manual = f'"{sys.executable}" -m pip install ' + " ".join(f'"{s}"' for s in specs)
112
- if os.environ.get(OPT_OUT_ENV) == "1":
113
- _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}")
115
- return False
116
-
117
- _err("[T-Zero] Installing missing or outdated packages: " + ", ".join(specs))
118
- try:
119
- proc = subprocess.run(
120
- [sys.executable, "-m", "pip", "install", "--disable-pip-version-check", "--quiet", *specs],
121
- capture_output=True, text=True, timeout=900,
122
- )
123
- except (OSError, subprocess.SubprocessError) as exc:
124
- _err(f"[T-Zero] Could not run pip: {exc}\n Install manually:\n {manual}")
125
- return False
126
-
127
- importlib.invalidate_caches()
128
- if proc.returncode != 0:
129
- output = (proc.stderr or proc.stdout or "").strip()
130
- _err("[T-Zero] pip failed:\n" + "\n".join(output.splitlines()[-8:]))
131
- if "externally-managed-environment" in output:
132
- _err("[T-Zero] This Python is managed by your OS. Use a virtual environment:\n"
133
- " python -m venv .venv && .venv/bin/pip install -r requirements.txt")
134
- else:
135
- _err(f" Install manually:\n {manual}")
136
- return False
137
-
138
- ensure_scripts_in_path(quiet=True)
139
- still_bad = [d.spec for d in problems if check_dependency(d)[0] != "ok"]
140
- if still_bad:
141
- _err("[T-Zero] Still unavailable after install: " + ", ".join(still_bad))
142
- return False
143
- _err("[T-Zero] Dependencies ready.")
144
- return True
145
-
146
-
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 = []
155
-
156
- if os.name == "nt":
157
- sys_scripts = os.path.join(sys.prefix, "Scripts")
158
- user_scripts = os.path.join(site.USER_BASE, "Scripts")
159
- 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
214
-
215
-
216
- def _line(level: str, text: str) -> str:
217
- return f" [{level:^4}] {text}"
218
-
219
-
220
- def run_doctor() -> int:
221
- """Checks the environment, fixing missing packages when allowed. Returns a process exit code."""
222
- print("T-Zero Doctor: environment check\n")
223
- failures = 0
224
-
225
- py = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
226
- if sys.version_info >= MIN_PYTHON:
227
- print(_line("OK", f"Python {py}"))
228
- else:
229
- failures += 1
230
- print(_line("FAIL", f"Python {py}: version {MIN_PYTHON[0]}.{MIN_PYTHON[1]}+ is required"))
231
-
232
- ensure_dependencies(include_mcp=True)
233
- for dep in REQUIRED + [MCP_DEPENDENCY]:
234
- status, version = check_dependency(dep)
235
- label = f"{dep.dist_name} {version or ''}".strip()
236
- if status == "ok":
237
- print(_line("OK", f"{label} ({dep.purpose})"))
238
- else:
239
- failures += 1
240
- print(_line("FAIL", f"{dep.dist_name}>={dep.min_version} is {status} ({dep.purpose})"))
241
-
242
- if importlib.util.find_spec("mcp") is not None:
243
- try:
244
- if importlib.util.find_spec("mcp.server.mcpserver") is not None:
245
- print(_line("OK", "MCP SDK flavor: MCPServer (mcp 2.x)"))
246
- else:
247
- print(_line("OK", "MCP SDK flavor: FastMCP (mcp 1.x)"))
248
- except (ImportError, ValueError):
249
- print(_line("OK", "MCP SDK flavor: FastMCP (mcp 1.x)"))
250
-
251
- if importlib.util.find_spec("tkinter") is not None:
252
- print(_line("OK", "tkinter (desktop GUI available)"))
253
- else:
254
- print(_line("WARN", "tkinter missing: the GUI is unavailable, the CLI and MCP server still work "
255
- "(Debian/Ubuntu: sudo apt install python3-tk)"))
256
-
257
- if shutil.which("git"):
258
- print(_line("OK", "git found (commit history and diff features)"))
259
- else:
260
- print(_line("WARN", "git not found: git features are disabled"))
261
-
262
- try:
263
- import keyring
264
- backend = keyring.get_keyring()
265
- name = f"{type(backend).__module__}.{type(backend).__name__}"
266
- if "fail" in name.lower() or "null" in name.lower():
267
- print(_line("WARN", "no usable OS keyring backend: saving API keys in the app will not work; "
268
- "set NVIDIA_API_KEY / OPENAI_API_KEY / GEMINI_API_KEY / OPENROUTER_API_KEY / "
269
- "ANTHROPIC_API_KEY instead"))
270
- else:
271
- print(_line("OK", f"keyring backend: {name}"))
272
- except Exception as exc:
273
- print(_line("WARN", f"keyring could not be checked: {exc}"))
274
-
275
- ensure_scripts_in_path(quiet=True)
276
- print(_line("OK", "Python Scripts PATH verified (tzero, tzero-gui, tzero-mcp accessible)"))
277
-
278
- print()
279
- if failures:
280
- print(f"{failures} problem(s) found. See the FAIL lines above.")
281
- return 1
282
- print("All required checks passed.")
283
- return 0
284
-
285
-
286
- if __name__ == "__main__":
287
- sys.exit(run_doctor())
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero dependency bootstrap and environment doctor (standard library only).
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.
12
+
13
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
14
+ """
15
+
16
+ import importlib
17
+ import importlib.util
18
+ import os
19
+ import re
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ from typing import List, NamedTuple, Optional, Tuple
24
+
25
+ OPT_OUT_ENV = "TZERO_NO_AUTO_INSTALL"
26
+ MIN_PYTHON = (3, 9)
27
+
28
+
29
+ class Dependency(NamedTuple):
30
+ import_name: str # name used in `import x`
31
+ dist_name: str # name on PyPI / importlib.metadata
32
+ min_version: str # minimum acceptable version
33
+ purpose: str
34
+
35
+ @property
36
+ def spec(self) -> str:
37
+ return f"{self.dist_name}>={self.min_version}"
38
+
39
+
40
+ REQUIRED: List[Dependency] = [
41
+ Dependency("requests", "requests", "2.28.0", "AI provider HTTP calls"),
42
+ Dependency("keyring", "keyring", "23.13.1", "OS credential storage"),
43
+ Dependency("darkdetect", "darkdetect", "0.8.0", "OS theme detection"),
44
+ Dependency("pygments", "pygments", "2.14.0", "syntax highlighting"),
45
+ Dependency("PIL", "Pillow", "9.0.0", "icon and image generation"),
46
+ ]
47
+ MCP_DEPENDENCY = Dependency("mcp", "mcp", "1.0.0", "Model Context Protocol server")
48
+
49
+
50
+ def _version_tuple(version: str) -> Tuple[int, ...]:
51
+ parts: List[int] = []
52
+ for token in re.split(r"[.\-+]", version):
53
+ match = re.match(r"\d+", token)
54
+ if not match:
55
+ break
56
+ parts.append(int(match.group()))
57
+ return tuple(parts)
58
+
59
+
60
+ def installed_version(dep: Dependency) -> Optional[str]:
61
+ """Returns the installed version string, or None when the distribution is unknown."""
62
+ try:
63
+ from importlib import metadata
64
+ return metadata.version(dep.dist_name)
65
+ except Exception:
66
+ return None
67
+
68
+
69
+ def check_dependency(dep: Dependency) -> Tuple[str, Optional[str]]:
70
+ """Returns (status, version) where status is 'ok', 'outdated' or 'missing'."""
71
+ try:
72
+ found = importlib.util.find_spec(dep.import_name) is not None
73
+ except (ImportError, ValueError):
74
+ found = False
75
+ if not found:
76
+ return "missing", None
77
+ version = installed_version(dep)
78
+ if version and _version_tuple(version) < _version_tuple(dep.min_version):
79
+ return "outdated", version
80
+ return "ok", version
81
+
82
+
83
+ def _err(message: str) -> None:
84
+ if sys.stderr is not None and hasattr(sys.stderr, "write"):
85
+ try:
86
+ sys.stderr.write(message + "\n")
87
+ sys.stderr.flush()
88
+ except Exception:
89
+ pass
90
+
91
+
92
+ def ensure_dependencies(include_mcp: bool = False) -> bool:
93
+ """Makes sure required packages are present, installing them when allowed.
94
+
95
+ Returns True when everything needed is available afterwards.
96
+ """
97
+ if sys.version_info < MIN_PYTHON:
98
+ _err(f"[T-Zero] Python {MIN_PYTHON[0]}.{MIN_PYTHON[1]}+ is required "
99
+ f"(found {sys.version_info.major}.{sys.version_info.minor}).")
100
+ return False
101
+ if getattr(sys, "frozen", False): # PyInstaller build: dependencies are bundled
102
+ return True
103
+
104
+ ensure_scripts_in_path(quiet=True)
105
+ deps = list(REQUIRED) + ([MCP_DEPENDENCY] if include_mcp else [])
106
+ problems = [d for d in deps if check_dependency(d)[0] != "ok"]
107
+ if not problems:
108
+ return True
109
+
110
+ specs = [d.spec for d in problems]
111
+ manual = f'"{sys.executable}" -m pip install ' + " ".join(f'"{s}"' for s in specs)
112
+ if os.environ.get(OPT_OUT_ENV) == "1":
113
+ _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}")
115
+ return False
116
+
117
+ _err("[T-Zero] Installing missing or outdated packages: " + ", ".join(specs))
118
+ try:
119
+ proc = subprocess.run(
120
+ [sys.executable, "-m", "pip", "install", "--disable-pip-version-check", "--quiet", *specs],
121
+ capture_output=True, text=True, timeout=900,
122
+ )
123
+ except (OSError, subprocess.SubprocessError) as exc:
124
+ _err(f"[T-Zero] Could not run pip: {exc}\n Install manually:\n {manual}")
125
+ return False
126
+
127
+ importlib.invalidate_caches()
128
+ if proc.returncode != 0:
129
+ output = (proc.stderr or proc.stdout or "").strip()
130
+ _err("[T-Zero] pip failed:\n" + "\n".join(output.splitlines()[-8:]))
131
+ if "externally-managed-environment" in output:
132
+ _err("[T-Zero] This Python is managed by your OS. Use a virtual environment:\n"
133
+ " python -m venv .venv && .venv/bin/pip install -r requirements.txt")
134
+ else:
135
+ _err(f" Install manually:\n {manual}")
136
+ return False
137
+
138
+ ensure_scripts_in_path(quiet=True)
139
+ still_bad = [d.spec for d in problems if check_dependency(d)[0] != "ok"]
140
+ if still_bad:
141
+ _err("[T-Zero] Still unavailable after install: " + ", ".join(still_bad))
142
+ return False
143
+ _err("[T-Zero] Dependencies ready.")
144
+ return True
145
+
146
+
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 = []
155
+
156
+ if os.name == "nt":
157
+ sys_scripts = os.path.join(sys.prefix, "Scripts")
158
+ user_scripts = os.path.join(site.USER_BASE, "Scripts")
159
+ 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
214
+
215
+
216
+ def _line(level: str, text: str) -> str:
217
+ return f" [{level:^4}] {text}"
218
+
219
+
220
+ def _run_deep_subsystem_check() -> int:
221
+ """Exercise all 9 v11 offline subsystems and report pass/fail. Returns failure count."""
222
+ import tempfile
223
+ from pathlib import Path
224
+
225
+ print("\nDeep Offline Subsystem Self-Check:")
226
+ checks = []
227
+
228
+ with tempfile.TemporaryDirectory() as tmpdir:
229
+ # 1. BPE Tokenizer
230
+ try:
231
+ from tzero.tzero_polyglot import count_bpe_tokens
232
+ tok = count_bpe_tokens("def hello(): pass\n")
233
+ if not (isinstance(tok, int) and tok > 0):
234
+ raise ValueError("unexpected diagnostic result")
235
+ checks.append(("BPE Tokenizer", True, ""))
236
+ except Exception as exc:
237
+ checks.append(("BPE Tokenizer", False, str(exc)))
238
+
239
+ # 2. Polyglot AST Reducer
240
+ try:
241
+ from tzero.tzero_polyglot import PolyglotTokenReducer
242
+ r = PolyglotTokenReducer()
243
+ out = r.reduce_code("def foo(x: int) -> int:\n return x + 1\n", filename="foo.py")
244
+ if not ("def foo" in out):
245
+ raise ValueError("unexpected diagnostic result")
246
+ ts = r.reduce_code("export function greet(name: string): string { return name; }", filename="sample.ts")
247
+ if not ("greet" in ts):
248
+ raise ValueError("unexpected diagnostic result")
249
+ checks.append(("Polyglot AST Reducer", True, ""))
250
+ except Exception as exc:
251
+ checks.append(("Polyglot AST Reducer", False, str(exc)))
252
+
253
+ # 3. Zero-Leak Engine
254
+ try:
255
+ from tzero.tzero_security import ZeroLeakEngine
256
+ fake_key = "sk" + "-" + "a" * 32
257
+ result = ZeroLeakEngine.scan_text(fake_key)
258
+ if not (isinstance(result, list) and len(result) > 0):
259
+ raise ValueError("unexpected diagnostic result")
260
+ checks.append(("Zero-Leak Engine", True, ""))
261
+ except Exception as exc:
262
+ checks.append(("Zero-Leak Engine", False, str(exc)))
263
+
264
+ # 4. LSP Server
265
+ try:
266
+ from tzero.tzero_lsp import TZeroLSPServer
267
+ lsp = TZeroLSPServer(workspace_dir=tmpdir)
268
+ py_path = os.path.join(tmpdir, "sample.py")
269
+ code = f'SERVICE_KEY = "{fake_key}"\n' + "def greet(name: str) -> str:\n return name\n"
270
+ Path(py_path).write_text(code, encoding="utf-8")
271
+ uri = Path(py_path).as_uri()
272
+ opened = lsp.handle_message({
273
+ "jsonrpc": "2.0",
274
+ "method": "textDocument/didOpen",
275
+ "params": {"textDocument": {"uri": uri, "text": code}},
276
+ })
277
+ hover = lsp.compute_hover(uri, code, line=1, character=4)
278
+ if hover is None:
279
+ raise ValueError("unexpected diagnostic result")
280
+ diagnostics = opened[0]["params"]["diagnostics"]
281
+ if not (lsp.compute_code_actions(uri, code, diagnostics)):
282
+ raise ValueError("unexpected diagnostic result")
283
+ checks.append(("LSP Server", True, ""))
284
+ except Exception as exc:
285
+ checks.append(("LSP Server", False, str(exc)))
286
+
287
+ # 5. Lifecycle Hooks
288
+ try:
289
+ from tzero.tzero_hooks import evaluate_pre_tool_use, evaluate_post_tool_use
290
+ blocked = evaluate_pre_tool_use(
291
+ {"tool_name": "Read", "tool_input": {"file_path": ".env"}},
292
+ workspace_dir=tmpdir,
293
+ )
294
+ if not (blocked["decision"] == "block"):
295
+ raise ValueError("unexpected diagnostic result")
296
+ big = "def x(): pass\n" * 20
297
+ pruned = evaluate_post_tool_use(
298
+ {"tool_name": "Read", "tool_input": {"file_path": "f.py"}, "tool_response": big},
299
+ workspace_dir=tmpdir,
300
+ max_chars=50,
301
+ )
302
+ if not (pruned["decision"] == "prune"):
303
+ raise ValueError("unexpected diagnostic result")
304
+ checks.append(("Lifecycle Hooks", True, ""))
305
+ except Exception as exc:
306
+ checks.append(("Lifecycle Hooks", False, str(exc)))
307
+
308
+ # 6. Federation Sync
309
+ try:
310
+ from tzero.tzero_federation import FederationSyncEngine
311
+ peer_ws = os.path.join(tmpdir, "peer")
312
+ os.mkdir(peer_ws)
313
+ peer_py = os.path.join(peer_ws, "ledger.py")
314
+ with open(peer_py, "w", encoding="utf-8") as fh:
315
+ fh.write("class Ledger:\n pass\n")
316
+ manifest_file = os.path.join(peer_ws, "manifest.json")
317
+ exported = FederationSyncEngine.export_manifest(peer_ws, repo_name="deep-peer", out_file=manifest_file)
318
+ if not (FederationSyncEngine.verify_manifest(exported)):
319
+ raise ValueError("unexpected diagnostic result")
320
+ imp = FederationSyncEngine.import_manifest(tmpdir, manifest_file)
321
+ if not (imp["verified"]):
322
+ raise ValueError("unexpected diagnostic result")
323
+ checks.append(("Federation Sync", True, ""))
324
+ except Exception as exc:
325
+ checks.append(("Federation Sync", False, str(exc)))
326
+
327
+ # 7. SCIP Importer
328
+ try:
329
+ from tzero.tzero_scip import ScipIndexImporter
330
+ sample = {"documents": [{"relative_path": "a.py", "occurrences": [
331
+ {"range": [0, 0, 0, 5], "symbol": "MyClass", "symbol_roles": 1},
332
+ ]}]}
333
+ graph = ScipIndexImporter.from_scip_dict(sample)
334
+ if not (graph.format_name in ("scip", "scip-dict")):
335
+ raise ValueError("unexpected diagnostic result")
336
+ checks.append(("SCIP Importer", True, ""))
337
+ except Exception as exc:
338
+ checks.append(("SCIP Importer", False, str(exc)))
339
+
340
+ # 8. Contracts & SARIF
341
+ try:
342
+ from tzero.tzero_contracts import ASTContractComparator
343
+ old = "def foo(x: int) -> int:\n return x\n"
344
+ new = "def foo(x: int, y: int) -> int:\n return x + y\n"
345
+ diff_rep = ASTContractComparator.compare_code(old, new, file_path="f.py")
346
+ if not (diff_rep.is_breaking):
347
+ raise ValueError("unexpected diagnostic result")
348
+ sarif = ASTContractComparator.format_sarif_report([diff_rep])
349
+ if not (sarif.get("version") == "2.1.0"):
350
+ raise ValueError("unexpected diagnostic result")
351
+ checks.append(("Contracts & SARIF", True, ""))
352
+ except Exception as exc:
353
+ checks.append(("Contracts & SARIF", False, str(exc)))
354
+
355
+ # 9. Agent Kernel & Snapshot
356
+ try:
357
+ from tzero.tzero_rust_bridge import AgentKernelSandbox
358
+ from tzero.tzero_snapshot import SnapshotEngine
359
+ kernel = AgentKernelSandbox(workspace_dir=tmpdir)
360
+ if not (kernel.validate_execution_plan({"allow_network": False, "read_paths": [tmpdir]})["allowed"]):
361
+ raise ValueError("unexpected diagnostic result")
362
+ if kernel.validate_execution_plan({"allow_network": True, "read_paths": [tmpdir]})["allowed"]:
363
+ raise ValueError("unexpected diagnostic result")
364
+ snap_py = os.path.join(tmpdir, "snap_test.py")
365
+ with open(snap_py, "w", encoding="utf-8") as fh:
366
+ fh.write("def snap_fn(): pass\n")
367
+ snap = SnapshotEngine.create_snapshot(tmpdir)
368
+ if not (snap.file_count >= 1):
369
+ raise ValueError("unexpected diagnostic result")
370
+ checks.append(("Agent Kernel & Snapshot", True, ""))
371
+ except Exception as exc:
372
+ checks.append(("Agent Kernel & Snapshot", False, str(exc)))
373
+
374
+ failures = 0
375
+ for name, passed, msg in checks:
376
+ if passed:
377
+ print(_line("OK", name))
378
+ else:
379
+ failures += 1
380
+ print(_line("FAIL", f"{name}: {msg}"))
381
+ return failures
382
+
383
+
384
+ def run_doctor(deep: bool = False) -> int:
385
+ """Checks the environment, fixing missing packages when allowed. Returns a process exit code."""
386
+ print("T-Zero Doctor: environment check\n")
387
+ failures = 0
388
+
389
+ py = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
390
+ if sys.version_info >= MIN_PYTHON:
391
+ print(_line("OK", f"Python {py}"))
392
+ else:
393
+ failures += 1
394
+ print(_line("FAIL", f"Python {py}: version {MIN_PYTHON[0]}.{MIN_PYTHON[1]}+ is required"))
395
+
396
+ if not deep:
397
+ ensure_dependencies(include_mcp=True)
398
+ for dep in REQUIRED + [MCP_DEPENDENCY]:
399
+ status, version = check_dependency(dep)
400
+ label = f"{dep.dist_name} {version or ''}".strip()
401
+ if status == "ok":
402
+ print(_line("OK", f"{label} ({dep.purpose})"))
403
+ else:
404
+ failures += 1
405
+ print(_line("FAIL", f"{dep.dist_name}>={dep.min_version} is {status} ({dep.purpose})"))
406
+
407
+ if importlib.util.find_spec("mcp") is not None:
408
+ try:
409
+ if importlib.util.find_spec("mcp.server.mcpserver") is not None:
410
+ print(_line("OK", "MCP SDK flavor: MCPServer (mcp 2.x)"))
411
+ else:
412
+ print(_line("OK", "MCP SDK flavor: FastMCP (mcp 1.x)"))
413
+ except (ImportError, ValueError):
414
+ print(_line("OK", "MCP SDK flavor: FastMCP (mcp 1.x)"))
415
+
416
+ if importlib.util.find_spec("tkinter") is not None:
417
+ print(_line("OK", "tkinter (desktop GUI available)"))
418
+ else:
419
+ print(_line("WARN", "tkinter missing: the GUI is unavailable, the CLI and MCP server still work "
420
+ "(Debian/Ubuntu: sudo apt install python3-tk)"))
421
+
422
+ if shutil.which("git"):
423
+ print(_line("OK", "git found (commit history and diff features)"))
424
+ else:
425
+ print(_line("WARN", "git not found: git features are disabled"))
426
+
427
+ try:
428
+ import keyring
429
+ backend = keyring.get_keyring()
430
+ name = f"{type(backend).__module__}.{type(backend).__name__}"
431
+ if "fail" in name.lower() or "null" in name.lower():
432
+ print(_line("WARN", "no usable OS keyring backend: saving API keys in the app will not work; "
433
+ "set NVIDIA_API_KEY / OPENAI_API_KEY / GEMINI_API_KEY / OPENROUTER_API_KEY / "
434
+ "ANTHROPIC_API_KEY instead"))
435
+ else:
436
+ print(_line("OK", f"keyring backend: {name}"))
437
+ except Exception as exc:
438
+ print(_line("WARN", f"keyring could not be checked: {exc}"))
439
+
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
+ if deep:
445
+ from tzero.tzero_polyglot import _ALLOW_BPE_DOWNLOAD
446
+
447
+ token = _ALLOW_BPE_DOWNLOAD.set(False)
448
+ try:
449
+ failures += _run_deep_subsystem_check()
450
+ finally:
451
+ _ALLOW_BPE_DOWNLOAD.reset(token)
452
+
453
+ print()
454
+ if failures:
455
+ print(f"{failures} problem(s) found. See the FAIL lines above.")
456
+ return 1
457
+ print("All required checks passed.")
458
+ return 0
459
+
460
+
461
+ if __name__ == "__main__":
462
+ sys.exit(run_doctor())