tzero-mcp 11.0.0 → 11.12.1
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.
- package/CHANGELOG.md +56 -56
- package/CONTRIBUTING.md +71 -71
- package/LICENSE +21 -21
- package/README.md +64 -64
- package/bin/tzero-mcp.js +62 -62
- package/bin/tzero.js +61 -61
- package/index.d.ts +25 -25
- package/index.js +15 -15
- package/package.json +89 -88
- package/src/addmcp.py +1203 -1197
- package/src/app.py +1810 -1810
- package/src/main.py +60 -60
- package/src/pc_fixer_mcp.py +25 -25
- package/src/tzero/__init__.py +54 -54
- package/src/tzero/__main__.py +6 -6
- package/src/tzero/siber_akademi_icon.py +77 -77
- package/src/tzero/tzero_arch_test.py +463 -463
- package/src/tzero/tzero_benchmark.py +475 -475
- package/src/tzero/tzero_blackboard.py +257 -257
- package/src/tzero/tzero_bridge.py +546 -546
- package/src/tzero/tzero_budget.py +195 -195
- package/src/tzero/tzero_card.py +431 -0
- package/src/tzero/tzero_ci.py +153 -153
- package/src/tzero/tzero_commit.py +192 -192
- package/src/tzero/tzero_contracts.py +1093 -1093
- package/src/tzero/tzero_cost.py +166 -166
- package/src/tzero/tzero_dashboard.py +1960 -1960
- package/src/tzero/tzero_debt.py +461 -461
- package/src/tzero/tzero_deps.py +462 -462
- package/src/tzero/tzero_drift.py +208 -208
- package/src/tzero/tzero_explain.py +306 -306
- package/src/tzero/tzero_features.py +3024 -3024
- package/src/tzero/tzero_federation.py +299 -299
- package/src/tzero/tzero_fix.py +557 -228
- package/src/tzero/tzero_fixer/__init__.py +63 -63
- package/src/tzero/tzero_fixer/amalgamation.py +334 -334
- package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
- package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
- package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
- package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
- package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
- package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
- package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
- package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
- package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
- package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
- package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
- package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
- package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
- package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
- package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
- package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
- package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
- package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
- package/src/tzero/tzero_fixer/mcp_server.py +489 -489
- package/src/tzero/tzero_fixer/models.py +385 -385
- package/src/tzero/tzero_fixer/orchestrator.py +375 -375
- package/src/tzero/tzero_fixer/os_doctor.py +502 -502
- package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
- package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
- package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
- package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
- package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
- package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
- package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
- package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
- package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
- package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
- package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
- package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
- package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
- package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
- package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
- package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
- package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
- package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
- package/src/tzero/tzero_golden.py +319 -319
- package/src/tzero/tzero_graph_hud.html +338 -338
- package/src/tzero/tzero_graph_rag.py +263 -263
- package/src/tzero/tzero_growth.py +415 -0
- package/src/tzero/tzero_guard.py +251 -243
- package/src/tzero/tzero_hooks.py +565 -565
- package/src/tzero/tzero_infra.py +274 -274
- package/src/tzero/tzero_jarvis/__init__.py +134 -124
- package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
- package/src/tzero/tzero_jarvis/creative_director.py +333 -0
- package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
- package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
- package/src/tzero/tzero_jarvis/latent_press.py +137 -137
- package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
- package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
- package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
- package/src/tzero/tzero_jarvis/self_healing.py +308 -308
- package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
- package/src/tzero/tzero_jarvis/swarm.py +261 -261
- package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
- package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
- package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
- package/src/tzero/tzero_lsp.py +634 -634
- package/src/tzero/tzero_mcp.py +5314 -5237
- package/src/tzero/tzero_mutation.py +358 -358
- package/src/tzero/tzero_neural_cortex.py +1425 -1425
- package/src/tzero/tzero_packer.py +577 -577
- package/src/tzero/tzero_patch.py +624 -624
- package/src/tzero/tzero_pc_fixer.py +12699 -12699
- package/src/tzero/tzero_pipe.py +95 -95
- package/src/tzero/tzero_polyglot.py +799 -799
- package/src/tzero/tzero_proxy.py +127 -127
- package/src/tzero/tzero_reachability.py +272 -272
- package/src/tzero/tzero_replay.py +141 -141
- package/src/tzero/tzero_rust_bridge.py +198 -198
- package/src/tzero/tzero_scip.py +368 -368
- package/src/tzero/tzero_security.py +573 -573
- package/src/tzero/tzero_semantic_merge.py +189 -189
- package/src/tzero/tzero_snapshot.py +471 -471
- package/src/tzero/tzero_stubs.py +313 -313
- package/src/tzero/tzero_subagent_engine.py +459 -459
- package/src/tzero/tzero_superdesign.py +774 -774
- package/src/tzero/tzero_sync.py +241 -241
- package/src/tzero/tzero_task_benchmark.py +506 -458
- package/src/tzero/tzero_tui.py +313 -313
- package/src/tzero/tzero_turbo.py +264 -264
- package/src/tzero/tzero_v3.py +9997 -9900
- package/src/tzero.py +6 -6
- package/src/tzero_mcp.py +25 -0
- package/test/package.test.js +55 -55
package/src/tzero/tzero_deps.py
CHANGED
|
@@ -1,462 +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_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())
|
|
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())
|