tzero-mcp 11.15.3 → 12.2.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 (71) hide show
  1. package/CONTRIBUTING.md +4 -4
  2. package/README.md +5 -5
  3. package/bin/postinstall.js +10 -2
  4. package/bin/tzero-mcp.js +1 -1
  5. package/bin/tzero.js +17 -0
  6. package/package.json +1 -1
  7. package/src/addmcp.py +34 -23
  8. package/src/app.py +1 -1
  9. package/src/main.py +6 -0
  10. package/src/tzero/__init__.py +10 -0
  11. package/src/tzero/anti_rea/__init__.py +70 -0
  12. package/src/tzero/anti_rea/algebraic_mutator.py +86 -0
  13. package/src/tzero/anti_rea/anti_agent_guard.py +96 -0
  14. package/src/tzero/anti_rea/anti_debugger.py +239 -0
  15. package/src/tzero/anti_rea/anti_vm.py +160 -0
  16. package/src/tzero/anti_rea/asar_shield.py +99 -0
  17. package/src/tzero/anti_rea/auditor.py +158 -0
  18. package/src/tzero/anti_rea/bpe_disrupter.py +48 -0
  19. package/src/tzero/anti_rea/bytecode_trap.py +85 -0
  20. package/src/tzero/anti_rea/canary_beacon.py +187 -0
  21. package/src/tzero/anti_rea/cli.py +102 -0
  22. package/src/tzero/anti_rea/confusables.py +86 -0
  23. package/src/tzero/anti_rea/engine.py +204 -0
  24. package/src/tzero/anti_rea/extractor_shield.py +102 -0
  25. package/src/tzero/anti_rea/flattener.py +136 -0
  26. package/src/tzero/anti_rea/gui.py +267 -0
  27. package/src/tzero/anti_rea/honeypot.py +58 -0
  28. package/src/tzero/anti_rea/integrity_guard.py +66 -0
  29. package/src/tzero/anti_rea/jailbreak_decoy.py +77 -0
  30. package/src/tzero/anti_rea/mcp_poison.py +41 -0
  31. package/src/tzero/anti_rea/native_bridge.py +169 -0
  32. package/src/tzero/anti_rea/rdtsc_guard.py +64 -0
  33. package/src/tzero/anti_rea/string_vault.py +94 -0
  34. package/src/tzero/anti_rea/sybil_network.py +53 -0
  35. package/src/tzero/anti_rea/timing_guard.py +46 -0
  36. package/src/tzero/anti_rea/token_bomb.py +65 -0
  37. package/src/tzero/anti_rea/traps.py +76 -0
  38. package/src/tzero/anti_rea/vm_obfuscator.py +182 -0
  39. package/src/tzero/siber_akademi.ico +0 -0
  40. package/src/tzero/siber_akademi_icon.py +1 -1
  41. package/src/tzero/tzero_armor.py +165 -0
  42. package/src/tzero/tzero_bridge.py +28 -15
  43. package/src/tzero/tzero_budget.py +10 -3
  44. package/src/tzero/tzero_card.py +7 -5
  45. package/src/tzero/tzero_ci.py +1 -0
  46. package/src/tzero/tzero_contracts.py +30 -11
  47. package/src/tzero/tzero_dashboard.py +34 -14
  48. package/src/tzero/tzero_debt.py +14 -5
  49. package/src/tzero/tzero_federation.py +11 -6
  50. package/src/tzero/tzero_fixer/security_zero_leak.py +21 -3
  51. package/src/tzero/tzero_golden.py +11 -6
  52. package/src/tzero/tzero_graph_hud.html +1 -1
  53. package/src/tzero/tzero_growth.py +10 -10
  54. package/src/tzero/tzero_jarvis/agent_guard.py +16 -10
  55. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +34 -23
  56. package/src/tzero/tzero_lsp.py +1 -1
  57. package/src/tzero/tzero_mcp.py +89 -31
  58. package/src/tzero/tzero_mutation.py +44 -16
  59. package/src/tzero/tzero_neural_cortex.py +1 -1
  60. package/src/tzero/tzero_pc_fixer.py +21 -3
  61. package/src/tzero/tzero_promo.py +196 -36
  62. package/src/tzero/tzero_rust_bridge.py +1086 -42
  63. package/src/tzero/tzero_scip.py +15 -2
  64. package/src/tzero/tzero_semantic_merge.py +34 -10
  65. package/src/tzero/tzero_task_benchmark.py +2 -2
  66. package/src/tzero/tzero_telemetry.py +146 -0
  67. package/src/tzero/tzero_terminal.py +366 -0
  68. package/src/tzero/tzero_traffic.py +350 -0
  69. package/src/tzero/tzero_tui.py +342 -133
  70. package/src/tzero/tzero_v3.py +652 -29
  71. package/src/tzero/tzero_welcome.py +72 -12
@@ -0,0 +1,165 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Siber Akademi T-Zero — Anti-REA Defense & Armor Engine.
3
+
4
+ Military-grade defense engine protecting codebases and executables
5
+ against AI-driven automated reverse engineering (e.g. morluto/rea,
6
+ Ghidra MCP bridge, IDA Pro LLM plugins, pyinstxtractor) and uncensored/jailbroken LLMs.
7
+ Includes native Ring-3 anti-debugging against x64dbg, IDA Pro, WinDbg, and Cheat Engine,
8
+ stealth canary beacon telemetry, in-flight string vault, and Electron asar shielding.
9
+
10
+ Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
11
+ Part of Siber Akademi T-Zero Context Architect v12.2.0 Master Edition.
12
+ License: MIT
13
+ """
14
+
15
+ import os
16
+ import sys
17
+ from pathlib import Path
18
+ from typing import Dict, Any, Optional
19
+
20
+ # Attempt import from tzero.anti_rea, packages/anti_rea, or standalone anti_rea
21
+ PACKAGE_ROOT = Path(__file__).resolve().parent.parent / "packages" / "anti_rea"
22
+ if str(PACKAGE_ROOT) not in sys.path and PACKAGE_ROOT.is_dir():
23
+ sys.path.insert(0, str(PACKAGE_ROOT))
24
+
25
+ try:
26
+ from tzero.anti_rea.engine import AntiREAEngine
27
+ from tzero.anti_rea.auditor import AIResistanceAuditor
28
+ from tzero.anti_rea.extractor_shield import ExtractorShield
29
+ from tzero.anti_rea.traps import AdversarialTrapGenerator
30
+ from tzero.anti_rea.flattener import ControlFlowFlattener
31
+ from tzero.anti_rea.token_bomb import TokenBombGenerator
32
+ from tzero.anti_rea.confusables import HomoglyphDesynchronizer
33
+ from tzero.anti_rea.honeypot import HoneypotGenerator
34
+ from tzero.anti_rea.mcp_poison import MCPProtocolPoisoner
35
+ from tzero.anti_rea.sybil_network import SybilNetworkGenerator
36
+ from tzero.anti_rea.timing_guard import TimingGuard
37
+ from tzero.anti_rea.vm_obfuscator import DynamicVMObfuscator
38
+ from tzero.anti_rea.bytecode_trap import BytecodeTrap
39
+ from tzero.anti_rea.jailbreak_decoy import CognitiveJailbreakDecoy
40
+ from tzero.anti_rea.anti_agent_guard import AntiAgentGuard
41
+ from tzero.anti_rea.algebraic_mutator import AlgebraicMutator
42
+ from tzero.anti_rea.integrity_guard import MemoryIntegrityGuard
43
+ from tzero.anti_rea.bpe_disrupter import BPETokenDisrupter
44
+ from tzero.anti_rea.native_bridge import NativeBridge
45
+ from tzero.anti_rea.anti_debugger import AntiDebugger
46
+ from tzero.anti_rea.canary_beacon import CanaryBeacon
47
+ from tzero.anti_rea.string_vault import StringVault
48
+ from tzero.anti_rea.asar_shield import AsarShield
49
+ from tzero.anti_rea.anti_vm import AntiVMGuard
50
+ from tzero.anti_rea.rdtsc_guard import RDTSCTimingGuard
51
+ except ImportError:
52
+ try:
53
+ from anti_rea.engine import AntiREAEngine
54
+ from anti_rea.auditor import AIResistanceAuditor
55
+ from anti_rea.extractor_shield import ExtractorShield
56
+ from anti_rea.traps import AdversarialTrapGenerator
57
+ from anti_rea.flattener import ControlFlowFlattener
58
+ from anti_rea.token_bomb import TokenBombGenerator
59
+ from anti_rea.confusables import HomoglyphDesynchronizer
60
+ from anti_rea.honeypot import HoneypotGenerator
61
+ from anti_rea.mcp_poison import MCPProtocolPoisoner
62
+ from anti_rea.sybil_network import SybilNetworkGenerator
63
+ from anti_rea.timing_guard import TimingGuard
64
+ from anti_rea.vm_obfuscator import DynamicVMObfuscator
65
+ from anti_rea.bytecode_trap import BytecodeTrap
66
+ from anti_rea.jailbreak_decoy import CognitiveJailbreakDecoy
67
+ from anti_rea.anti_agent_guard import AntiAgentGuard
68
+ from anti_rea.algebraic_mutator import AlgebraicMutator
69
+ from anti_rea.integrity_guard import MemoryIntegrityGuard
70
+ from anti_rea.bpe_disrupter import BPETokenDisrupter
71
+ from anti_rea.native_bridge import NativeBridge
72
+ from anti_rea.anti_debugger import AntiDebugger
73
+ from anti_rea.canary_beacon import CanaryBeacon
74
+ from anti_rea.string_vault import StringVault
75
+ from anti_rea.asar_shield import AsarShield
76
+ from anti_rea.anti_vm import AntiVMGuard
77
+ from anti_rea.rdtsc_guard import RDTSCTimingGuard
78
+ except ImportError:
79
+ sys.path.append(str(Path(__file__).resolve().parent))
80
+ from anti_rea.engine import AntiREAEngine
81
+ from anti_rea.auditor import AIResistanceAuditor
82
+ from anti_rea.extractor_shield import ExtractorShield
83
+ from anti_rea.anti_vm import AntiVMGuard
84
+ from anti_rea.rdtsc_guard import RDTSCTimingGuard
85
+
86
+
87
+ def protect_path_with_armor(
88
+ path: str,
89
+ output_path: Optional[str] = None,
90
+ seed: int = 42,
91
+ **options: Any
92
+ ) -> Dict[str, Any]:
93
+ """Protects target Python file, directory, or archive with Anti-REA military armor."""
94
+ p = Path(path)
95
+ if not p.exists():
96
+ return {"success": False, "error": f"Path not found: {path}"}
97
+
98
+ if p.is_file():
99
+ return AntiREAEngine.protect_file(str(p), output_path=output_path, seed=seed, **options)
100
+
101
+ # If directory, protect all .py files within
102
+ results = []
103
+ count = 0
104
+ for py_file in p.rglob("*.py"):
105
+ if "__pycache__" in str(py_file) or ".venv" in str(py_file):
106
+ continue
107
+ res = AntiREAEngine.protect_file(str(py_file), seed=seed, **options)
108
+ if res.get("success"):
109
+ count += 1
110
+ results.append(res)
111
+
112
+ return {
113
+ "success": count > 0,
114
+ "directory": str(p),
115
+ "files_protected": count,
116
+ "details": results
117
+ }
118
+
119
+
120
+ def audit_path_rea_resistance(path: str) -> Dict[str, Any]:
121
+ """Audits target file or codebase for resistance against AI reverse-engineering agents."""
122
+ p = Path(path)
123
+ if not p.exists():
124
+ return {"success": False, "error": f"Path not found: {path}", "score": 0}
125
+
126
+ if p.is_file():
127
+ return AIResistanceAuditor.audit_file(str(p))
128
+
129
+ # If directory, compute average resistance score across python files
130
+ scores = []
131
+ findings = []
132
+ py_files = list(p.rglob("*.py"))
133
+ for py_file in py_files:
134
+ if "__pycache__" in str(py_file) or ".venv" in str(py_file):
135
+ continue
136
+ audit = AIResistanceAuditor.audit_file(str(py_file))
137
+ if "score" in audit:
138
+ scores.append(audit["score"])
139
+ if audit.get("findings"):
140
+ findings.extend(audit["findings"])
141
+
142
+ avg_score = round(sum(scores) / max(1, len(scores)), 1)
143
+ rating = (
144
+ "MILITARY_GRADE_IMPREGNABLE" if avg_score >= 90 else
145
+ "MILITARY_GRADE" if avg_score >= 80 else
146
+ "STRONG" if avg_score >= 60 else
147
+ "MODERATE" if avg_score >= 40 else
148
+ "VULNERABLE"
149
+ )
150
+
151
+ return {
152
+ "success": True,
153
+ "directory": str(p),
154
+ "files_scanned": len(scores),
155
+ "score": avg_score,
156
+ "max_score": 100,
157
+ "rating": rating,
158
+ "status": "PASS" if avg_score >= 60 else "RECOMMEND_HARDENING",
159
+ "sample_findings": list(set(findings))[:5]
160
+ }
161
+
162
+
163
+ def shield_executable(binary_path: str, output_path: Optional[str] = None) -> Dict[str, Any]:
164
+ """Shields a compiled PyInstaller executable against pyinstxtractor archive parsing."""
165
+ return ExtractorShield.shield_file(binary_path, output_path=output_path)
@@ -432,13 +432,30 @@ class PolyglotTypeBridge:
432
432
  flavor = model_flavor.lower().strip()
433
433
  models = []
434
434
 
435
+ def _extract_brace_blocks(src: str, header_re: re.Pattern) -> List[Tuple[str, str]]:
436
+ blocks: List[Tuple[str, str]] = []
437
+ for m in header_re.finditer(src):
438
+ open_idx = m.end() - 1
439
+ depth = 0
440
+ close_idx = -1
441
+ for pos in range(open_idx, len(src)):
442
+ ch = src[pos]
443
+ if ch == "{":
444
+ depth += 1
445
+ elif ch == "}":
446
+ depth -= 1
447
+ if depth == 0:
448
+ close_idx = pos
449
+ break
450
+ if close_idx > open_idx:
451
+ blocks.append((m.group(1), src[open_idx + 1:close_idx]))
452
+ return blocks
453
+
435
454
  if lang in ("ts", "typescript"):
436
- pattern = re.compile(r'(?:export\s+)?(?:interface|type)\s+([A-Za-z0-9_]+)(?:\s*=\s*)?\s*\{([^}]+)\}', re.MULTILINE)
437
- for m in pattern.finditer(code):
438
- name = m.group(1)
439
- body = m.group(2)
455
+ pattern = re.compile(r'(?:export\s+)?(?:interface|type)\s+([A-Za-z0-9_]+)(?:[ \t]*=[ \t]*|[ \t]*)\{', re.MULTILINE)
456
+ for name, body in _extract_brace_blocks(code, pattern):
440
457
  fields = []
441
- for line in re.split(r'[\n;]+', body):
458
+ for line in body.replace(";", "\n").splitlines():
442
459
  line = line.strip().rstrip(";,")
443
460
  if not line or line.startswith("//"):
444
461
  continue
@@ -453,12 +470,10 @@ class PolyglotTypeBridge:
453
470
  models.append((name, fields))
454
471
 
455
472
  elif lang in ("rust", "rs"):
456
- pattern = re.compile(r'(?:pub\s+)?struct\s+([A-Za-z0-9_]+)\s*\{([^}]+)\}', re.MULTILINE)
457
- for m in pattern.finditer(code):
458
- name = m.group(1)
459
- body = m.group(2)
473
+ pattern = re.compile(r'(?:pub\s+)?struct\s+([A-Za-z0-9_]+)[ \t]*\{', re.MULTILINE)
474
+ for name, body in _extract_brace_blocks(code, pattern):
460
475
  fields = []
461
- for line in re.split(r'[\n,;]+', body):
476
+ for line in body.replace(",", "\n").replace(";", "\n").splitlines():
462
477
  line = line.strip().rstrip(",")
463
478
  if not line or line.startswith("//"):
464
479
  continue
@@ -476,12 +491,10 @@ class PolyglotTypeBridge:
476
491
  models.append((name, fields))
477
492
 
478
493
  elif lang in ("go", "golang"):
479
- pattern = re.compile(r'type\s+([A-Za-z0-9_]+)\s+struct\s*\{([^}]+)\}', re.MULTILINE)
480
- for m in pattern.finditer(code):
481
- name = m.group(1)
482
- body = m.group(2)
494
+ pattern = re.compile(r'type\s+([A-Za-z0-9_]+)\s+struct[ \t]*\{', re.MULTILINE)
495
+ for name, body in _extract_brace_blocks(code, pattern):
483
496
  fields = []
484
- for line in re.split(r'[\n;]+', body):
497
+ for line in body.replace(";", "\n").splitlines():
485
498
  line = re.sub(r'`[^`]*`', '', line).strip()
486
499
  if not line or line.startswith("//"):
487
500
  continue
@@ -12,7 +12,7 @@ Capabilities:
12
12
  - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
13
13
 
14
14
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
15
- Part of T-Zero Context Architect v11.15.2 Master Edition.
15
+ Part of T-Zero Context Architect v12.2.0 Master Edition.
16
16
  """
17
17
 
18
18
  import hashlib
@@ -65,7 +65,12 @@ class ASTTokenBudgetOptimizer:
65
65
  @classmethod
66
66
  def estimate_raw_tokens(cls, workspace_root: str, max_files: int = 300) -> Tuple[int, int, str]:
67
67
  """Calculates raw token count and aggregated content hash for the workspace."""
68
- abs_root = os.path.abspath(workspace_root)
68
+ import tempfile
69
+ ws_root = os.path.realpath(".")
70
+ tmp_root = os.path.realpath(tempfile.gettempdir())
71
+ abs_root = os.path.normpath(os.path.realpath(os.path.abspath(workspace_root)))
72
+ if abs_root != ws_root and not abs_root.startswith(ws_root + os.sep) and not abs_root.startswith(tmp_root + os.sep):
73
+ raise ValueError(f"Workspace path outside allowed scope: {workspace_root}")
69
74
  total_chars = 0
70
75
  file_count = 0
71
76
  hasher = hashlib.sha256()
@@ -87,7 +92,9 @@ class ASTTokenBudgetOptimizer:
87
92
  dirs[:] = [d for d in dirs if d not in ignore_dirs and not d.startswith(".")]
88
93
  for f in files:
89
94
  if f.endswith((".py", ".ts", ".js", ".rs", ".go", ".cpp", ".c", ".h", ".swift", ".kt", ".dart")):
90
- full_p = os.path.join(root, f)
95
+ full_p = os.path.realpath(os.path.join(root, f))
96
+ if not (full_p == abs_root or full_p.startswith(abs_root + os.sep)):
97
+ continue
91
98
  try:
92
99
  with open(full_p, "rb") as fp:
93
100
  content = fp.read()
@@ -28,6 +28,7 @@ class TZeroShowcaseGenerator:
28
28
  raw_tokens: int = 10809938,
29
29
  pruned_tokens: int = 1297192,
30
30
  annual_savings_usd: float = 14280.0,
31
+ current_stars: int = 32,
31
32
  output_file: str = "assets/tzero_badge_card.svg"
32
33
  ) -> str:
33
34
  """Generates a futuristic, high-DPI 800x240 SVG banner card for repository READMEs."""
@@ -143,7 +144,7 @@ class TZeroShowcaseGenerator:
143
144
  <rect x="0" y="0" width="178" height="90" rx="10" fill="#1e1b4b" stroke="#6366f1" stroke-width="1"/>
144
145
  <text x="16" y="26" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif" font-size="11" font-weight="700" fill="#a5b4fc">ROAD TO 100 STARS</text>
145
146
  <text x="16" y="54" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif" font-size="18" font-weight="900" fill="#ffffff">⭐ STAR ON GITHUB</text>
146
- <text x="16" y="76" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif" font-size="10" font-weight="600" fill="#38bdf8">16 / 100 Milestone</text>
147
+ <text x="16" y="76" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif" font-size="10" font-weight="600" fill="#38bdf8">Road to 100 Stars ⭐</text>
147
148
  </g>
148
149
  </g>
149
150
 
@@ -188,7 +189,8 @@ class TZeroShowcaseGenerator:
188
189
  cls,
189
190
  output_file: str = "tzero_showcase.html",
190
191
  raw_code_sample: Optional[str] = None,
191
- pruned_code_sample: Optional[str] = None
192
+ pruned_code_sample: Optional[str] = None,
193
+ current_stars: int = 32
192
194
  ) -> str:
193
195
  """Generates an interactive standalone split-screen HTML5 comparison slider."""
194
196
  raw_code = raw_code_sample or '''class EnterpriseAuthService:
@@ -396,15 +398,15 @@ class TZeroShowcaseGenerator:
396
398
 
397
399
  <div style="margin-top: 32px; padding: 26px 32px; background: rgba(56, 189, 248, 0.08); border: 1px solid rgba(56, 189, 248, 0.35); border-radius: 16px; max-width: 900px; width: 100%; text-align: center; box-shadow: 0 8px 32px rgba(0,0,0,0.45);">
398
400
  <div style="display: inline-flex; align-items: center; gap: 8px; background: rgba(245, 158, 11, 0.15); border: 1px solid #f59e0b; padding: 4px 16px; border-radius: 20px; color: #fbbf24; font-size: 13px; font-weight: 700; margin-bottom: 12px;">
399
- ⭐ ROAD TO 100 STARS MILESTONE (16 / 100)
401
+ ⭐ ROAD TO 100 STARS MILESTONE
400
402
  </div>
401
403
  <p style="font-size: 19px; font-weight: 800; color: #f8fafc; margin-bottom: 8px;">
402
404
  Support Open-Source Local AI Tooling &bull; Yıldız Vererek Destekleyin!
403
405
  </p>
404
406
  <p style="font-size: 14px; line-height: 1.6; color: #cbd5e1; margin-bottom: 16px;">
405
- 15-year-old solo open-source developer (<strong>Toprak Ahmet Aydoğmuş</strong>, Siber Akademi).<br>
407
+ Solo open-source developer (<strong>Toprak Ahmet Aydoğmuş</strong>, Siber Akademi).<br>
406
408
  Built 100% free, offline, and zero-leak to eliminate AI prompt token bloat across Cursor, Claude, and local LLMs.<br>
407
- <em>15 yaşında bağımsız açık kaynak geliştiricisiyim. Projeyi ücretsiz ve çevrimdışı tutabilmem için bir yıldızınız çok değerli.</em>
409
+ <em>Bağımsız açık kaynak geliştiricisiyim. Projeyi ücretsiz ve çevrimdışı tutabilmem için bir yıldızınız çok değerli.</em>
408
410
  </p>
409
411
  <div style="display: flex; gap: 12px; justify-content: center; flex-wrap: wrap;">
410
412
  <a href="https://github.com/toprakahmetaydogmus/TZeroAlgorithm" class="cta-btn" target="_blank">
@@ -755,6 +755,7 @@ def main():
755
755
  prog="tzero-ci",
756
756
  description="Siber Akademi T-Zero Local CI Pipeline & Pre-Push Verification Shield"
757
757
  )
758
+ parser.add_argument("--version", "-v", action="version", version="%(prog)s 12.2.0")
758
759
  parser.add_argument("--quick", "-q", action="store_true", help="Run fast verification battery (seconds)")
759
760
  parser.add_argument("--all", "-a", action="store_true", help="Run full matrix verification battery")
760
761
  parser.add_argument("--fix", action="store_true", help="Attempt auto-repair for auto-fixable gates (metadata sync)")
@@ -13,7 +13,7 @@ Capabilities:
13
13
  - 100% Offline, $0 cost, zero external dependencies (pure Python standard library).
14
14
 
15
15
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
16
- Part of T-Zero Context Architect v11.15.2 Master Edition.
16
+ Part of T-Zero Context Architect v12.2.0 Master Edition.
17
17
  """
18
18
 
19
19
  import ast
@@ -458,14 +458,22 @@ class ASTContractExtractor:
458
458
  @classmethod
459
459
  def _extract_ts_contracts(cls, clean_code: str, functions: Dict[str, FunctionContract], classes: Dict[str, ClassContract]) -> None:
460
460
  class_pattern = re.compile(
461
- r'(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z0-9_$]+)(?:\s+extends\s+([^{]+))?\s*\{'
461
+ r'(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z0-9_$]+)'
462
462
  )
463
463
  top_level_code = list(clean_code)
464
464
 
465
465
  for m in class_pattern.finditer(clean_code):
466
466
  cls_name = m.group(1)
467
- bases = [b.strip() for b in m.group(2).split(",")] if m.group(2) else []
468
- brace_idx = m.end() - 1
467
+ brace_idx = clean_code.find("{", m.end())
468
+ if brace_idx == -1:
469
+ continue
470
+ header_tail = clean_code[m.end():brace_idx]
471
+ if "\n" in header_tail and "extends" not in header_tail:
472
+ continue
473
+ bases: List[str] = []
474
+ ext_m = re.search(r'\bextends\s+(.+)$', header_tail, re.DOTALL)
475
+ if ext_m:
476
+ bases = [b.strip() for b in ext_m.group(1).split(",") if b.strip()]
469
477
  end_brace = cls._find_matching_brace(clean_code, brace_idx)
470
478
  if end_brace == -1:
471
479
  end_brace = len(clean_code) - 1
@@ -494,7 +502,7 @@ class ASTContractExtractor:
494
502
 
495
503
  if method_depth == 0:
496
504
  m_hdr = re.match(
497
- r'^(?:(?:public|static|async|get|set|override|readonly)\s+)*([A-Za-z0-9_$]+)\s*(?:<[^>]+>)?\s*\(',
505
+ r'^(?:(?:public|static|async|get|set|override|readonly)\s+)*([A-Za-z0-9_$]+)(?:[ \t]*<[^>\n]+>[ \t]*|[ \t]*)\(',
498
506
  class_body[idx:]
499
507
  )
500
508
  if m_hdr:
@@ -537,7 +545,7 @@ class ASTContractExtractor:
537
545
 
538
546
  top_str = "".join(top_level_code)
539
547
  fn_pattern = re.compile(
540
- r'(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s+([A-Za-z0-9_$]+)\s*(?:<[^>]+>)?\s*\('
548
+ r'(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s+([A-Za-z0-9_$]+)'
541
549
  )
542
550
  for m in fn_pattern.finditer(top_str):
543
551
  fn_name = m.group(1)
@@ -546,7 +554,18 @@ class ASTContractExtractor:
546
554
  if fn_name.startswith("_") and not is_exported:
547
555
  continue
548
556
 
549
- paren_start = m.end() - 1
557
+ scan_pos = m.end()
558
+ while scan_pos < len(top_str) and top_str[scan_pos] in " \t\r\n":
559
+ scan_pos += 1
560
+ if scan_pos < len(top_str) and top_str[scan_pos] == "<":
561
+ gt_pos = top_str.find(">", scan_pos + 1)
562
+ if gt_pos != -1 and "\n" not in top_str[scan_pos:gt_pos]:
563
+ scan_pos = gt_pos + 1
564
+ while scan_pos < len(top_str) and top_str[scan_pos] in " \t\r\n":
565
+ scan_pos += 1
566
+ if scan_pos >= len(top_str) or top_str[scan_pos] != "(":
567
+ continue
568
+ paren_start = scan_pos
550
569
  paren_end = cls._find_matching_paren(top_str, paren_start)
551
570
  if paren_end != -1:
552
571
  raw_params = top_str[paren_start + 1:paren_end]
@@ -646,7 +665,7 @@ class ASTContractExtractor:
646
665
  classes[impl_name] = ClassContract(name=impl_name, bases=[])
647
666
 
648
667
  impl_body = clean_code[brace_idx + 1:end_brace]
649
- for fn_m in re.finditer(r'\bpub\s+(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z0-9_]+)\s*(?:<[^>]+>)?\s*\(', impl_body):
668
+ for fn_m in re.finditer(r'\bpub\s+(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z0-9_]+)(?:[ \t]*<[^>\n]+>[ \t]*|[ \t]*)\(', impl_body):
650
669
  fn_name = fn_m.group(1)
651
670
  p_start = fn_m.end() - 1
652
671
  p_end = cls._find_matching_paren(impl_body, p_start)
@@ -663,7 +682,7 @@ class ASTContractExtractor:
663
682
  )
664
683
 
665
684
  top_str = "".join(top_level_code)
666
- for fn_m in re.finditer(r'\bpub\s+(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z0-9_]+)\s*(?:<[^>]+>)?\s*\(', top_str):
685
+ for fn_m in re.finditer(r'\bpub\s+(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z0-9_]+)(?:[ \t]*<[^>\n]+>[ \t]*|[ \t]*)\(', top_str):
667
686
  fn_name = fn_m.group(1)
668
687
  p_start = fn_m.end() - 1
669
688
  p_end = cls._find_matching_paren(top_str, p_start)
@@ -682,7 +701,7 @@ class ASTContractExtractor:
682
701
  @classmethod
683
702
  def _extract_java_cs_contracts(cls, clean_code: str, functions: Dict[str, FunctionContract], classes: Dict[str, ClassContract]) -> None:
684
703
  class_pattern = re.compile(
685
- r'\bpublic\s+(?:abstract\s+|static\s+|sealed\s+)?(?:class|interface)\s+([A-Za-z0-9_]+)(?:\s+extends\s+([^{]+))?\s*\{'
704
+ r'\bpublic\s+(?:abstract\s+|static\s+|sealed\s+)?(?:class|interface)\s+([A-Za-z0-9_]+)(?:\s+extends\s+([^\s{\r\n](?:[^{\r\n]*[^\s{\r\n])?))?[ \t]*\{'
686
705
  )
687
706
  for m in class_pattern.finditer(clean_code):
688
707
  cls_name = m.group(1)
@@ -1035,7 +1054,7 @@ class ASTContractComparator:
1035
1054
  "tool": {
1036
1055
  "driver": {
1037
1056
  "name": "T-Zero Contract Guardian",
1038
- "version": "11.15.2",
1057
+ "version": "12.2.0",
1039
1058
  "rules": rules_list
1040
1059
  }
1041
1060
  },
@@ -457,7 +457,7 @@ HTML_PAGE = """<!DOCTYPE html>
457
457
  <div class="brand-logo">T0</div>
458
458
  <div>
459
459
  <div class="brand-title">T-Zero Developer Console</div>
460
- <div class="brand-sub" id="headerBrandSub">Enterprise AST Context Architect &bull; v11.15.2</div>
460
+ <div class="brand-sub" id="headerBrandSub">Enterprise AST Context Architect &bull; v12.2.0</div>
461
461
  </div>
462
462
  </div>
463
463
  <div class="header-actions">
@@ -850,7 +850,7 @@ x = 2
850
850
  </main>
851
851
 
852
852
  <footer>
853
- <span id="footerBrand">T-Zero Context Architect v11.15.2</span> &bull; Developer: Toprak Ahmet Aydoğmuş &bull; Siber Akademi
853
+ <span id="footerBrand">T-Zero Context Architect v12.2.0</span> &bull; Developer: Toprak Ahmet Aydoğmuş &bull; Siber Akademi
854
854
  </footer>
855
855
 
856
856
  <script>
@@ -1481,7 +1481,7 @@ def compute_live_dashboard_stats(workspace_dir: str = ".") -> Dict[str, Any]:
1481
1481
  if cached is not None and (now - _DASHBOARD_STATS_CACHE["ts"]) < 60.0:
1482
1482
  return cached
1483
1483
 
1484
- version = "11.15.2"
1484
+ version = "12.2.0"
1485
1485
  tools_count = 57
1486
1486
  try:
1487
1487
  from tzero import tzero_mcp
@@ -1563,6 +1563,21 @@ def compute_live_dashboard_stats(workspace_dir: str = ".") -> Dict[str, Any]:
1563
1563
 
1564
1564
 
1565
1565
  class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
1566
+ @staticmethod
1567
+ def _resolve_safe_api_path(raw_path: str) -> str:
1568
+ """Restricts dashboard API file/workspace paths to CWD or temp directory."""
1569
+ import tempfile
1570
+ candidate = (raw_path or ".").strip() or "."
1571
+ if "\x00" in candidate:
1572
+ raise ValueError("Invalid null byte in path.")
1573
+ ws_root = os.path.realpath(".")
1574
+ tmp_root = os.path.realpath(tempfile.gettempdir())
1575
+ real_target = os.path.normpath(os.path.realpath(os.path.abspath(candidate)))
1576
+ in_ws = (real_target == ws_root) or real_target.startswith(ws_root + os.sep)
1577
+ in_tmp = (real_target == tmp_root) or real_target.startswith(tmp_root + os.sep)
1578
+ if not in_ws and not in_tmp:
1579
+ raise ValueError(f"Access denied: path outside allowed workspace or temp scope ({candidate})")
1580
+ return real_target
1566
1581
  """Handles static UI and JSON-RPC API endpoints for T-Zero Dashboard."""
1567
1582
 
1568
1583
  def log_message(self, format, *args):
@@ -1768,7 +1783,7 @@ class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
1768
1783
  body = self.rfile.read(content_length).decode("utf-8")
1769
1784
  try:
1770
1785
  payload = json.loads(body)
1771
- tgt_file = payload.get("file", "tzero_arch_test.py")
1786
+ tgt_file = self._resolve_safe_api_path(payload.get("file", "tzero_arch_test.py"))
1772
1787
  max_m = int(payload.get("max_mutants", 5))
1773
1788
  from tzero.tzero_mutation import ASTMutationEngine
1774
1789
  rep = ASTMutationEngine.run_mutation_analysis(target_file=tgt_file, max_mutants=max_m)
@@ -1818,7 +1833,7 @@ class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
1818
1833
  body = self.rfile.read(content_length).decode("utf-8")
1819
1834
  try:
1820
1835
  payload = json.loads(body) if body.strip() else {}
1821
- target_p = payload.get("path", ".")
1836
+ target_p = self._resolve_safe_api_path(payload.get("path", "."))
1822
1837
  from tzero.tzero_debt import CodeHealthAnalyzer
1823
1838
  if os.path.isfile(target_p):
1824
1839
  rep = CodeHealthAnalyzer.analyze_file(target_p)
@@ -1855,7 +1870,7 @@ class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
1855
1870
  body = self.rfile.read(content_length).decode("utf-8")
1856
1871
  try:
1857
1872
  payload = json.loads(body) if body.strip() else {}
1858
- target_p = payload.get("path", ".")
1873
+ target_p = self._resolve_safe_api_path(payload.get("path", "."))
1859
1874
  target_tokens = payload.get("target_tokens")
1860
1875
  model_name = payload.get("model", "claude-3-7")
1861
1876
  from tzero.tzero_budget import ASTTokenBudgetOptimizer
@@ -1884,7 +1899,7 @@ class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
1884
1899
  body = self.rfile.read(content_length).decode("utf-8")
1885
1900
  try:
1886
1901
  payload = json.loads(body) if body.strip() else {}
1887
- target_p = payload.get("path", ".")
1902
+ target_p = self._resolve_safe_api_path(payload.get("path", "."))
1888
1903
  from tzero.tzero_golden import ASTGoldenRegressionEngine
1889
1904
  rep = ASTGoldenRegressionEngine.verify_against_golden(target_p)
1890
1905
  resp = {
@@ -1903,7 +1918,8 @@ class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
1903
1918
  try:
1904
1919
  payload = self._read_json_body()
1905
1920
  symbol = str(payload.get("symbol") or "").strip()
1906
- scip_path = str(payload.get("scip_path") or "").strip() or None
1921
+ raw_scip = str(payload.get("scip_path") or "").strip()
1922
+ scip_path = self._resolve_safe_api_path(raw_scip) if raw_scip else None
1907
1923
  if not symbol:
1908
1924
  resp = {"success": False, "error": "symbol required"}
1909
1925
  else:
@@ -1916,13 +1932,17 @@ class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
1916
1932
  elif parsed.path == "/api/scip/summary":
1917
1933
  try:
1918
1934
  payload = self._read_json_body()
1919
- scip_path = str(payload.get("path") or "").strip()
1920
- if not scip_path or not os.path.isfile(scip_path):
1921
- resp = {"success": False, "error": f"SCIP/LSIF index file not found: {scip_path or '(empty)'}"}
1935
+ raw_scip = str(payload.get("path") or "").strip()
1936
+ if not raw_scip:
1937
+ resp = {"success": False, "error": "SCIP/LSIF index file not found: (empty)"}
1922
1938
  else:
1923
- from tzero.tzero_scip import ScipIndexImporter
1924
- graph = ScipIndexImporter.load(scip_path)
1925
- resp = {"success": True, **graph.export_tzero_graph()}
1939
+ scip_path = self._resolve_safe_api_path(raw_scip)
1940
+ if not os.path.isfile(scip_path):
1941
+ resp = {"success": False, "error": f"SCIP/LSIF index file not found: {raw_scip}"}
1942
+ else:
1943
+ from tzero.tzero_scip import ScipIndexImporter
1944
+ graph = ScipIndexImporter.load(scip_path)
1945
+ resp = {"success": True, **graph.export_tzero_graph()}
1926
1946
  except Exception as e:
1927
1947
  resp = {"success": False, "error": str(e)}
1928
1948
  self._send_json(resp)
@@ -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 v11.15.2 Master Edition.
16
+ Part of T-Zero Context Architect v12.2.0 Master Edition.
17
17
  """
18
18
 
19
19
  import ast
@@ -211,8 +211,14 @@ class CodeHealthAnalyzer:
211
211
  @classmethod
212
212
  def analyze_file(cls, file_path: str, code: Optional[str] = None) -> FileHealthReport:
213
213
  if code is None:
214
+ import tempfile
215
+ ws_root = os.path.realpath(".")
216
+ tmp_root = os.path.realpath(tempfile.gettempdir())
217
+ real_fp = os.path.normpath(os.path.realpath(os.path.abspath(file_path)))
218
+ if not real_fp.startswith(ws_root + os.sep) and not real_fp.startswith(tmp_root + os.sep):
219
+ raise ValueError(f"Path outside allowed workspace/temp root: {file_path}")
214
220
  try:
215
- with open(file_path, "r", encoding="utf-8", errors="replace") as f:
221
+ with open(real_fp, "r", encoding="utf-8", errors="replace") as f:
216
222
  code = f.read()
217
223
  except Exception as e:
218
224
  return FileHealthReport(
@@ -335,7 +341,7 @@ class CodeHealthAnalyzer:
335
341
 
336
342
  @classmethod
337
343
  def analyze_workspace(cls, workspace_root: str = ".", max_files: int = 250) -> WorkspaceHealthReport:
338
- abs_root = os.path.abspath(workspace_root)
344
+ abs_root = os.path.realpath(os.path.abspath(workspace_root))
339
345
  reports: List[FileHealthReport] = []
340
346
 
341
347
  ignore_dirs = {".git", ".venv", "venv", "__pycache__", "node_modules", "dist", "build", ".pytest_cache"}
@@ -344,8 +350,11 @@ class CodeHealthAnalyzer:
344
350
  dirs[:] = [d for d in dirs if d not in ignore_dirs and not d.startswith(".")]
345
351
  for f in files:
346
352
  if f.endswith(".py"):
347
- rel_p = os.path.relpath(os.path.join(root, f), abs_root)
348
- rep = cls.analyze_file(os.path.join(root, f))
353
+ full_p = os.path.realpath(os.path.join(root, f))
354
+ if not (full_p == abs_root or full_p.startswith(abs_root + os.sep)):
355
+ continue
356
+ rel_p = os.path.relpath(full_p, abs_root)
357
+ rep = cls.analyze_file(full_p)
349
358
  rep.file_path = rel_p.replace("\\", "/")
350
359
  reports.append(rep)
351
360
  if len(reports) >= max_files:
@@ -235,12 +235,17 @@ class FederationSyncEngine:
235
235
 
236
236
  # 3. Optional SCIP trace
237
237
  scip_trace: Optional[Dict[str, Any]] = None
238
- if scip_path and os.path.isfile(scip_path):
239
- try:
240
- from tzero.tzero_scip import ScipIndexImporter
241
- scip_trace = ScipIndexImporter.load(scip_path).trace_symbol(sym)
242
- except Exception as e:
243
- scip_trace = {"error": str(e)}
238
+ if scip_path:
239
+ import tempfile
240
+ ws_root = os.path.realpath(".")
241
+ tmp_root = os.path.realpath(tempfile.gettempdir())
242
+ safe_scip = os.path.normpath(os.path.realpath(os.path.abspath(scip_path)))
243
+ if (safe_scip.startswith(ws_root + os.sep) or safe_scip.startswith(tmp_root + os.sep)) and os.path.isfile(safe_scip):
244
+ try:
245
+ from tzero.tzero_scip import ScipIndexImporter
246
+ scip_trace = ScipIndexImporter.load(safe_scip).trace_symbol(sym)
247
+ except Exception as e:
248
+ scip_trace = {"error": str(e)}
244
249
 
245
250
  return {
246
251
  "symbol": sym,