tzero-mcp 12.2.2 → 12.3.3

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 (44) 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 +2 -2
  6. package/src/app.py +1 -1
  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 +21 -0
  12. package/src/tzero/anti_rea/auditor.py +20 -0
  13. package/src/tzero/anti_rea/canary_beacon.py +33 -61
  14. package/src/tzero/anti_rea/cli.py +30 -4
  15. package/src/tzero/anti_rea/crypto_loader.py +132 -0
  16. package/src/tzero/anti_rea/engine.py +51 -20
  17. package/src/tzero/anti_rea/extractor_shield.py +60 -25
  18. package/src/tzero/anti_rea/tier_catalog.py +388 -0
  19. package/src/tzero/tzero_armor.py +3 -3
  20. package/src/tzero/tzero_benchmark.py +1 -1
  21. package/src/tzero/tzero_budget.py +1 -1
  22. package/src/tzero/tzero_ci.py +2 -2
  23. package/src/tzero/tzero_contracts.py +2 -2
  24. package/src/tzero/tzero_dashboard.py +3 -3
  25. package/src/tzero/tzero_debt.py +85 -7
  26. package/src/tzero/tzero_deps.py +109 -87
  27. package/src/tzero/tzero_explain.py +1 -1
  28. package/src/tzero/tzero_golden.py +2 -2
  29. package/src/tzero/tzero_graph_hud.html +4 -4
  30. package/src/tzero/tzero_growth.py +1 -1
  31. package/src/tzero/tzero_jarvis/swarm.py +23 -2
  32. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1 -1
  33. package/src/tzero/tzero_jarvis/zero_key_router.py +10 -78
  34. package/src/tzero/tzero_lsp.py +1 -1
  35. package/src/tzero/tzero_mcp.py +28 -10
  36. package/src/tzero/tzero_mutation.py +6 -2
  37. package/src/tzero/tzero_promo.py +1 -1
  38. package/src/tzero/tzero_security.py +40 -11
  39. package/src/tzero/tzero_task_benchmark.py +2 -2
  40. package/src/tzero/tzero_traffic.py +1 -1
  41. package/src/tzero/tzero_tui.py +5 -5
  42. package/src/tzero/tzero_v3.py +418 -275
  43. package/src/tzero/tzero_welcome.py +1 -1
  44. package/bin/postinstall.js +0 -30
@@ -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.2 Master Edition.
16
+ Part of T-Zero Context Architect v12.3.3 Master Edition.
17
17
  """
18
18
 
19
19
  import ast
@@ -68,6 +68,7 @@ class FileHealthReport:
68
68
  functions: List[FunctionHealth] = field(default_factory=list)
69
69
  classes: List[ClassHealth] = field(default_factory=list)
70
70
  debt_markers: List[Dict[str, Any]] = field(default_factory=list)
71
+ debt_by_scope: Dict[str, int] = field(default_factory=dict) # "Class.method" -> marker count
71
72
 
72
73
 
73
74
  @dataclass
@@ -193,21 +194,64 @@ class CodeHealthAnalyzer:
193
194
  normalized = max(0.0, min(100.0, (raw_mi * 100.0) / 171.0))
194
195
  return round(normalized, 1)
195
196
 
197
+ # Estimated remediation hours per marker tag (replaces the flat 0.5h per marker).
198
+ TAG_DEBT_HOURS: Dict[str, float] = {
199
+ "TEMP": 0.25,
200
+ "TODO": 0.5,
201
+ "XXX": 0.5,
202
+ "FIXME": 1.0,
203
+ "HACK": 1.5,
204
+ }
205
+
196
206
  @classmethod
197
207
  def extract_debt_markers(cls, code: str) -> List[Dict[str, Any]]:
198
- """Finds TODO, FIXME, HACK, XXX, TEMP debt comments."""
208
+ """Finds TODO, FIXME, HACK, XXX, TEMP debt comments (Python '#' and C-style '//')."""
199
209
  markers = []
200
- pattern = re.compile(r"#\s*(TODO|FIXME|HACK|XXX|TEMP)[:\s]*(.*)", re.IGNORECASE)
210
+ pattern = re.compile(r"(?:#|//)\s*(TODO|FIXME|HACK|XXX|TEMP)\b[:\s]*(.*)", re.IGNORECASE)
201
211
  for idx, line in enumerate(code.splitlines(), start=1):
202
212
  match = pattern.search(line)
203
213
  if match:
214
+ tag = match.group(1).upper()
204
215
  markers.append({
205
216
  "line": idx,
206
- "tag": match.group(1).upper(),
207
- "text": match.group(2).strip()
217
+ "tag": tag,
218
+ "text": match.group(2).strip(),
219
+ "weight_hours": cls.TAG_DEBT_HOURS.get(tag, 0.5),
220
+ "scope": "<module>",
208
221
  })
209
222
  return markers
210
223
 
224
+ @staticmethod
225
+ def attach_marker_scopes(markers: List[Dict[str, Any]], tree: ast.AST) -> Dict[str, int]:
226
+ """Sets each marker's 'scope' to its innermost enclosing class/function.
227
+
228
+ Returns a histogram {scope: marker_count} sorted by count (descending).
229
+ """
230
+ spans: List[Tuple[int, int, str]] = []
231
+
232
+ def walk(node: ast.AST, prefix: str) -> None:
233
+ for child in ast.iter_child_nodes(node):
234
+ if isinstance(child, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
235
+ name = f"{prefix}{child.name}"
236
+ end = getattr(child, "end_lineno", None) or child.lineno
237
+ spans.append((child.lineno, end, name))
238
+ walk(child, name + ".")
239
+ else:
240
+ walk(child, prefix)
241
+
242
+ walk(tree, "")
243
+ counts: Dict[str, int] = {}
244
+ for marker in markers:
245
+ line = marker["line"]
246
+ best: Optional[Tuple[int, int, str]] = None
247
+ for start, end, name in spans:
248
+ if start <= line <= end and (best is None or (end - start) < (best[1] - best[0])):
249
+ best = (start, end, name)
250
+ scope = best[2] if best else "<module>"
251
+ marker["scope"] = scope
252
+ counts[scope] = counts.get(scope, 0) + 1
253
+ return dict(sorted(counts.items(), key=lambda kv: kv[1], reverse=True))
254
+
211
255
  @classmethod
212
256
  def analyze_file(cls, file_path: str, code: Optional[str] = None) -> FileHealthReport:
213
257
  if code is None:
@@ -257,10 +301,12 @@ class CodeHealthAnalyzer:
257
301
  total_cog = cls.compute_cognitive_complexity(tree)
258
302
  mi = cls.compute_maintainability_index(code, total_cc)
259
303
  debt_markers = cls.extract_debt_markers(code)
304
+ debt_by_scope = cls.attach_marker_scopes(debt_markers, tree)
260
305
 
261
306
  fn_reports: List[FunctionHealth] = []
262
307
  cls_reports: List[ClassHealth] = []
263
- total_debt_hours = len(debt_markers) * 0.5 # 30m per TODO/FIXME
308
+ # Tag-weighted marker cost (TODO 0.5h, FIXME 1h, HACK 1.5h, TEMP 0.25h).
309
+ total_debt_hours = sum(m["weight_hours"] for m in debt_markers)
264
310
 
265
311
  for node in ast.walk(tree):
266
312
  if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
@@ -341,7 +387,8 @@ class CodeHealthAnalyzer:
341
387
  todo_count=len(debt_markers),
342
388
  functions=fn_reports,
343
389
  classes=cls_reports,
344
- debt_markers=debt_markers
390
+ debt_markers=debt_markers,
391
+ debt_by_scope=debt_by_scope,
345
392
  )
346
393
 
347
394
  @classmethod
@@ -483,3 +530,34 @@ class CodeHealthAnalyzer:
483
530
 
484
531
  return "\n".join(lines).strip()
485
532
 
533
+
534
+
535
+ def format_debt_markers_markdown(report: WorkspaceHealthReport, limit: int = 50) -> str:
536
+ """Renders every debt marker grouped by file and scope, sorted by weight (heaviest first)."""
537
+ rows: List[Tuple[float, str, Dict[str, Any]]] = []
538
+ for fr in report.file_reports:
539
+ for marker in fr.debt_markers:
540
+ rows.append((marker.get("weight_hours", 0.5), fr.file_path, marker))
541
+ rows.sort(key=lambda r: (-r[0], r[1], r[2]["line"]))
542
+
543
+ lines = [
544
+ "# Technical Debt Markers",
545
+ "",
546
+ f"- **Markers found:** {len(rows)}",
547
+ f"- **Estimated remediation:** {round(sum(r[0] for r in rows), 2)} h",
548
+ "",
549
+ ]
550
+ if not rows:
551
+ lines.append("No TODO / FIXME / HACK / XXX / TEMP markers found.")
552
+ return "\n".join(lines)
553
+
554
+ lines += ["| Tag | Hours | File | Line | Scope | Text |", "|---|---|---|---|---|---|"]
555
+ for weight, path, marker in rows[:limit]:
556
+ text = marker.get("text", "").replace("|", "\\|")[:80]
557
+ lines.append(
558
+ f"| {marker['tag']} | {weight} | `{path}` | {marker['line']} | "
559
+ f"`{marker.get('scope', '<module>')}` | {text} |"
560
+ )
561
+ if len(rows) > limit:
562
+ lines.append(f"\n_…{len(rows) - limit} more markers omitted (limit={limit})._")
563
+ return "\n".join(lines)
@@ -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: 12.2.2
9
+ Version: 12.3.3
10
10
  """
11
11
 
12
12
  import ast
@@ -11,7 +11,7 @@ Capabilities:
11
11
  - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
12
12
 
13
13
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
14
- Part of T-Zero Context Architect v12.2.2 Master Edition.
14
+ Part of T-Zero Context Architect v12.3.3 Master Edition.
15
15
  """
16
16
 
17
17
  import ast
@@ -208,7 +208,7 @@ class ASTGoldenRegressionEngine:
208
208
 
209
209
  return GoldenBaseline(
210
210
  workspace_root=abs_root,
211
- version="12.2.2",
211
+ version="12.3.3",
212
212
  created_at=time.time(),
213
213
  symbols=all_sigs,
214
214
  total_symbols=len(all_sigs),
@@ -95,17 +95,17 @@
95
95
  </div>
96
96
 
97
97
  <div id="controls">
98
- <input type="text" id="searchInput" placeholder="Düğüm / Kod ara (örn: ESP32, #8421)..." oninput="filterGraph()">
98
+ <input type="text" id="searchInput" placeholder="Search node / code (e.g. ESP32, #8421)..." oninput="filterGraph()">
99
99
  </div>
100
100
 
101
101
  <div id="stats-bar">
102
- Düğümler: <span id="nodeCount" style="color:#38bdf8">0</span> |
103
- Bağlar: <span id="edgeCount" style="color:#818cf8">0</span> |
102
+ Nodes: <span id="nodeCount" style="color:#38bdf8">0</span> |
103
+ Edges: <span id="edgeCount" style="color:#818cf8">0</span> |
104
104
  FPS: <span id="fpsCount" style="color:#fbbf24">60</span>
105
105
  </div>
106
106
 
107
107
  <div id="inspector">
108
- <h3 id="insTitle" style="color:#38bdf8; margin-bottom:6px;">Detay</h3>
108
+ <h3 id="insTitle" style="color:#38bdf8; margin-bottom:6px;">Details</h3>
109
109
  <p id="insBody" style="color:#cbd5e1; line-height:1.5;"></p>
110
110
  </div>
111
111
 
@@ -3,7 +3,7 @@
3
3
  T-ZERO $0.00 BUDGET VIRAL MARKETING & COMMUNITY GROWTH ENGINE
4
4
  -------------------------------------------------------------
5
5
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
6
- License: MIT | Version: 12.2.2
6
+ License: MIT | Version: 12.3.3
7
7
 
8
8
  Strictly $0.00 budget: Zero paid ads, zero paid APIs, zero cloud tokens.
9
9
  Pure organic developer-to-developer growth engine engineered to drive 100+ GitHub stars.
@@ -217,9 +217,22 @@ class SwarmCoordinator:
217
217
  all_tokens = []
218
218
  all_triplets = []
219
219
 
220
- # Her uzman ajan hedefe göre rapor üretir
220
+ # Her uzman ajan hedefe göre rapor üretir. Bir ajanın hatası tüm görevi
221
+ # düşürmez: hata, WARNING verdict'li bir rapora dönüştürülür.
221
222
  for agent in self.agents:
222
- rep = agent.evaluate(mission_goal, context)
223
+ t_agent = time.time()
224
+ try:
225
+ rep = agent.evaluate(mission_goal, context)
226
+ except Exception as exc: # isolate per-agent failures
227
+ rep = SwarmAgentReport(
228
+ agent_name=agent.name,
229
+ role=agent.role,
230
+ verdict="WARNING",
231
+ confidence=0.0,
232
+ findings=[f"Ajan hata verdi: {type(exc).__name__}: {exc}"],
233
+ recommendations=["Ajan girdisini ve yapılandırmasını kontrol edin."],
234
+ latency_ms=(time.time() - t_agent) * 1000.0,
235
+ )
223
236
  agent_reports.append(rep)
224
237
  all_tokens.extend(rep.memory_tokens)
225
238
  all_triplets.extend(rep.semantic_triplets)
@@ -248,9 +261,17 @@ class SwarmCoordinator:
248
261
  verdicts = [r.verdict for r in agent_reports]
249
262
  consensus = "APPROVED" if all(v == "APPROVED" for v in verdicts) else "WARNING"
250
263
 
264
+ # Güven ağırlıklı skor: APPROVED ajanların confidence toplamı / toplam confidence.
265
+ total_conf = sum(r.confidence for r in agent_reports)
266
+ approved_conf = sum(r.confidence for r in agent_reports if r.verdict == "APPROVED")
267
+ consensus_score = round(approved_conf / total_conf, 3) if total_conf > 0 else 0.0
268
+ blocking_agents = [r.agent_name for r in agent_reports if r.verdict != "APPROVED"]
269
+
251
270
  return {
252
271
  "mission_goal": mission_goal,
253
272
  "consensus": consensus,
273
+ "consensus_score": consensus_score,
274
+ "blocking_agents": blocking_agents,
254
275
  "orchestrator": "JARVIS Prime",
255
276
  "swarm_agent_count": len(self.agents) + 1,
256
277
  "agent_reports": [r.to_dict() for r in agent_reports],
@@ -1041,7 +1041,7 @@ flowchart LR
1041
1041
 
1042
1042
  return f"""# T-ZERO JARVIS MASTER WORKSPACE ORCHESTRATOR
1043
1043
  *Executive AI Engineering Manager & Autonomous Multi-Agent Coordinator*
1044
- *Version: 5.1.0 | 100% Offline | $0.00 Cost | 100% Zero-Leak Certified*
1044
+ *Version: 5.1.0 | Local AST Core | $0.00 Cost | 100% Zero-Leak Certified*
1045
1045
 
1046
1046
  ---
1047
1047
 
@@ -5,26 +5,13 @@ JARVIS ZERO-KEY INTELLIGENCE ROUTER
5
5
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
6
6
  Version: 4.2.0
7
7
 
8
- Bu modül, kullanıcının tek bir API key girmesine dahi gerek kalmadan,
9
- %100 BEDAVA ve SINIRSIZ olarak çalışan zeka yönlendiricisidir.
10
-
11
- 4 Katmanlı Akıllı Havuz:
12
- 1. Yerel Ollama (Eğer makinede yüklüyse, sıfır internet ve sıfır maliyetle çalışır)
13
- 2. Pollinations AI Ücretsiz Uç Noktası (Kayıt, kredi kartı veya API Key gerektirmez)
14
- 3. OpenRouter Free Whitelist (Sadece ':free' etiketli modeller)
15
- 4. Deterministik AST Tamircisi (Sözdizimi ve import hatalarını LLM olmadan doğrudan onarır)
8
+ Runs keyless inference through a local Ollama API and exposes a separate web
9
+ search helper.
16
10
  """
17
11
 
18
- import os
19
- import sys
20
12
  import json
21
- import logging
22
13
  import urllib.request
23
- import urllib.error
24
- import urllib.parse
25
- from typing import Dict, List, Optional, Any
26
-
27
- logger = logging.getLogger("TZeroJarvisRouter")
14
+ from typing import Any, Dict, Optional
28
15
 
29
16
 
30
17
  class ZeroCostSecurityGuard:
@@ -49,8 +36,6 @@ class ZeroCostSecurityGuard:
49
36
  class ZeroKeyAIRouter:
50
37
  """API Key gerektirmeyen, hatasız ve yedekli yapay zeka motoru."""
51
38
 
52
- POLLINATIONS_URL = "https://text.pollinations.ai/"
53
-
54
39
  @classmethod
55
40
  def check_ollama_available(cls) -> bool:
56
41
  """Yerel makinede Ollama'nın çalışıp çalışmadığını yoklar."""
@@ -71,45 +56,6 @@ class ZeroKeyAIRouter:
71
56
  data = json.loads(resp.read().decode("utf-8"))
72
57
  return data.get("response", "")
73
58
 
74
- @classmethod
75
- def call_pollinations_free(cls, prompt: str, system_prompt: str = "Sen T-Zero Jarvis otonom kodlama asistanısın.") -> str:
76
- """
77
- Pollinations AI ücretsiz REST uç noktasını çağırır.
78
- HİÇBİR API KEY VEYA KAYIT GEREKTİRMEZ.
79
- """
80
- payload = {
81
- "messages": [
82
- {"role": "system", "content": system_prompt},
83
- {"role": "user", "content": prompt}
84
- ],
85
- "model": "openai",
86
- "seed": 42,
87
- "jsonMode": False
88
- }
89
- data = json.dumps(payload).encode("utf-8")
90
- req = urllib.request.Request(
91
- cls.POLLINATIONS_URL,
92
- data=data,
93
- headers={
94
- "Content-Type": "application/json",
95
- "User-Agent": "T-Zero-Jarvis-Autonomous/4.2"
96
- }
97
- )
98
- try:
99
- with urllib.request.urlopen(req, timeout=45) as resp:
100
- return resp.read().decode("utf-8", errors="replace").strip()
101
- except urllib.error.HTTPError as e:
102
- # Yedek GET parametreli ücretsiz çağrı
103
- try:
104
- encoded_prompt = urllib.parse.quote(prompt[:500])
105
- fallback_url = f"{cls.POLLINATIONS_URL}{encoded_prompt}?system={urllib.parse.quote(system_prompt[:200])}"
106
- fallback_req = urllib.request.Request(fallback_url, headers={"User-Agent": "T-Zero-Jarvis"})
107
- with urllib.request.urlopen(fallback_req, timeout=30) as f_resp:
108
- return f_resp.read().decode("utf-8", errors="replace").strip()
109
- except Exception as e2:
110
- logger.error(f"Pollinations fallback failed: {e2}")
111
- raise RuntimeError(f"Ücretsiz genel çıkarım uç noktasına bağlanılamadı: {e}")
112
-
113
59
  @classmethod
114
60
  def search_duckduckgo_free(cls, query: str, max_results: int = 4) -> str:
115
61
  """API anahtarı olmadan canlı internet araması yapar."""
@@ -128,10 +74,7 @@ class ZeroKeyAIRouter:
128
74
 
129
75
  @classmethod
130
76
  def query_intelligence(cls, prompt: str, system_prompt: Optional[str] = None) -> Dict[str, Any]:
131
- """
132
- Kullanıcıdan tek bir API key istemeden en uygun ücretsiz sağlayıcıyı
133
- otomatik seçip yanıtı döndüren ana fonksiyon.
134
- """
77
+ """Return an Ollama completion or report that local inference is unavailable."""
135
78
  sys_p = system_prompt or "Sen Siber Akademi T-Zero Jarvis otonom yazılım mühendisisin."
136
79
 
137
80
  # 1. Öncelik: Yerel Ollama (Maksimum Gizlilik & Sıfır İnternet)
@@ -148,23 +91,12 @@ class ZeroKeyAIRouter:
148
91
  except Exception:
149
92
  pass
150
93
 
151
- # 2. Öncelik: Pollinations Free Cloud Inference (Sıfır Key / Sıfır Maliyet)
152
- try:
153
- ans = cls.call_pollinations_free(prompt, system_prompt=sys_p)
154
- return {
155
- "provider": "pollinations_free_cloud",
156
- "model": "deepseek-coder/free",
157
- "cost": "0.00$",
158
- "response": ans
159
- }
160
- except Exception as e:
161
- # 3. Fallback: Deterministik yanıt
162
- return {
163
- "provider": "tzero_deterministic_engine",
164
- "model": "ast-rule-engine",
165
- "cost": "0.00$",
166
- "response": f"[T-Zero Deterministik Zeka]: İstek AST motoru tarafından işlendi. Ağ bağlantısı veya yerel LLM olmadan deterministik çözüm uygulandı."
167
- }
94
+ return {
95
+ "provider": "unavailable",
96
+ "model": "",
97
+ "cost": "0.00$",
98
+ "response": "Local Ollama is unavailable or returned no response.",
99
+ }
168
100
 
169
101
  route_query = query_intelligence
170
102
 
@@ -513,7 +513,7 @@ class TZeroLSPServer:
513
513
  "hoverProvider": True,
514
514
  "codeActionProvider": True,
515
515
  },
516
- "serverInfo": {"name": "tzero-lsp", "version": "12.2.2"},
516
+ "serverInfo": {"name": "tzero-lsp", "version": "12.3.3"},
517
517
  },
518
518
  }]
519
519