tzero-mcp 10.7.4 → 11.0.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 (127) hide show
  1. package/CHANGELOG.md +56 -29
  2. package/CONTRIBUTING.md +71 -71
  3. package/README.md +64 -64
  4. package/bin/tzero-mcp.js +62 -66
  5. package/bin/tzero.js +61 -65
  6. package/index.d.ts +25 -25
  7. package/index.js +15 -15
  8. package/package.json +88 -88
  9. package/src/addmcp.py +14 -11
  10. package/src/app.py +1810 -0
  11. package/src/main.py +1 -1
  12. package/src/pc_fixer_mcp.py +25 -0
  13. package/src/tzero/__init__.py +54 -0
  14. package/src/tzero/__main__.py +6 -0
  15. package/src/tzero/siber_akademi.ico +0 -0
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +475 -475
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +546 -362
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/{tzero_ci.py → tzero/tzero_ci.py} +153 -153
  22. package/src/{tzero_commit.py → tzero/tzero_commit.py} +192 -192
  23. package/src/tzero/tzero_contracts.py +1093 -0
  24. package/src/{tzero_cost.py → tzero/tzero_cost.py} +166 -163
  25. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +531 -19
  26. package/src/tzero/tzero_debt.py +461 -0
  27. package/src/{tzero_deps.py → tzero/tzero_deps.py} +179 -4
  28. package/src/{tzero_drift.py → tzero/tzero_drift.py} +208 -208
  29. package/src/{tzero_explain.py → tzero/tzero_explain.py} +73 -7
  30. package/src/{tzero_features.py → tzero/tzero_features.py} +19 -17
  31. package/src/tzero/tzero_federation.py +299 -0
  32. package/src/{tzero_fix.py → tzero/tzero_fix.py} +228 -228
  33. package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +63 -63
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +464 -464
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +288 -288
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +127 -127
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +600 -600
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +174 -174
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +246 -246
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +151 -151
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +260 -260
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +171 -171
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +150 -150
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +309 -309
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +1 -1
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +1 -1
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +412 -412
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +91 -91
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +295 -295
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +940 -940
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +307 -307
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +49 -7
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +502 -502
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +600 -599
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +274 -274
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +313 -313
  58. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +1 -1
  59. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +318 -318
  60. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +372 -372
  61. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +1 -1
  62. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +305 -305
  63. package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +444 -444
  64. package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +114 -114
  65. package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +110 -110
  66. package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +326 -326
  67. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +223 -223
  68. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +220 -220
  69. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +1 -1
  70. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +447 -447
  71. package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +309 -309
  72. package/src/tzero/tzero_golden.py +319 -0
  73. package/src/tzero/tzero_graph_hud.html +338 -0
  74. package/src/tzero/tzero_graph_rag.py +263 -0
  75. package/src/{tzero_guard.py → tzero/tzero_guard.py} +243 -243
  76. package/src/tzero/tzero_hooks.py +565 -0
  77. package/src/{tzero_infra.py → tzero/tzero_infra.py} +274 -274
  78. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +124 -124
  79. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +310 -310
  80. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +395 -395
  81. package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +214 -214
  82. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +137 -137
  83. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +212 -212
  84. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +184 -184
  85. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +335 -335
  86. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +308 -308
  87. package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +887 -887
  88. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +261 -261
  89. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +144 -144
  90. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +1167 -1167
  91. package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +173 -173
  92. package/src/tzero/tzero_lsp.py +634 -0
  93. package/src/{tzero_mcp.py → tzero/tzero_mcp.py} +479 -100
  94. package/src/tzero/tzero_mutation.py +358 -0
  95. package/src/tzero/tzero_packer.py +577 -0
  96. package/src/{tzero_patch.py → tzero/tzero_patch.py} +624 -624
  97. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +12699 -12657
  98. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +95 -95
  99. package/src/tzero/tzero_polyglot.py +799 -0
  100. package/src/tzero/tzero_proxy.py +127 -0
  101. package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +272 -272
  102. package/src/{tzero_replay.py → tzero/tzero_replay.py} +141 -141
  103. package/src/tzero/tzero_rust_bridge.py +198 -0
  104. package/src/tzero/tzero_scip.py +368 -0
  105. package/src/{tzero_security.py → tzero/tzero_security.py} +5 -2
  106. package/src/tzero/tzero_semantic_merge.py +189 -0
  107. package/src/tzero/tzero_snapshot.py +471 -0
  108. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +313 -313
  109. package/src/tzero/tzero_subagent_engine.py +459 -0
  110. package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +774 -774
  111. package/src/{tzero_sync.py → tzero/tzero_sync.py} +241 -241
  112. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +458 -363
  113. package/src/{tzero_tui.py → tzero/tzero_tui.py} +91 -22
  114. package/src/tzero/tzero_turbo.py +264 -0
  115. package/src/{tzero_v3.py → tzero/tzero_v3.py} +628 -163
  116. package/src/tzero.py +2 -54
  117. package/test/package.test.js +55 -43
  118. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  119. package/src/tzero_gateway.py +0 -885
  120. package/src/tzero_packer.py +0 -370
  121. package/src/tzero_polyglot.py +0 -422
  122. package/src/tzero_snapshot.py +0 -258
  123. /package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +0 -0
  124. /package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +0 -0
  125. /package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +0 -0
  126. /package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +0 -0
  127. /package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +0 -0
package/src/app.py ADDED
@@ -0,0 +1,1810 @@
1
+ """
2
+ ====================================================================================================
3
+ T-ZERO ALGORITHM (Token Zero) - ENTERPRISE AI CONTEXT ARCHITECT & AST COMPRESSOR
4
+ Hugging Face Space Live Application | Pure Python AST Engine | Zero-Leak Security
5
+ Compatible with: Gradio 4.x / 5.x | Hugging Face ZeroGPU (NVIDIA RTX 6000 / A100)
6
+ Official Repository: https://github.com/toprakahmetaydogmus/TZeroAlgorithm
7
+ Live Web Gateway: https://tzero-indol.vercel.app
8
+ ====================================================================================================
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import ast
14
+ import html
15
+ import json
16
+ import math
17
+ import os
18
+ import re
19
+ import sys
20
+ import time
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, Dict, List, Optional, Tuple
23
+
24
+ # ==================================================================================================
25
+ # ZERO-GPU COMPATIBILITY LAYER
26
+ # ==================================================================================================
27
+ try:
28
+ import spaces # type: ignore
29
+
30
+ HAS_SPACES = True
31
+ except ImportError:
32
+ HAS_SPACES = False
33
+
34
+ class spaces: # type: ignore
35
+ @staticmethod
36
+ def GPU(func=None, duration=60):
37
+ def decorator(f):
38
+ return f
39
+
40
+ return decorator(func) if func else decorator
41
+
42
+
43
+ import gradio as gr
44
+
45
+ # ==================================================================================================
46
+ # CONSTANTS, PALETTES & MULTI-MODEL PRICING TIERS
47
+ # ==================================================================================================
48
+ APP_VERSION = "4.1.0"
49
+ REPO_URL = "https://github.com/toprakahmetaydogmus/TZeroAlgorithm"
50
+ VERCEL_URL = "https://tzero-indol.vercel.app"
51
+ SPACE_URL = "https://huggingface.co/spaces/toprakke4/tzero-token-reducer"
52
+
53
+ # Model pricing in USD per 1 Million Prompt Tokens (Updated for 2026 Models)
54
+ MODEL_PRICING: Dict[str, Dict[str, Any]] = {
55
+ "OpenAI GPT-4o": {
56
+ "input_per_m": 2.50,
57
+ "output_per_m": 10.00,
58
+ "context_window": 128000,
59
+ "char_ratio": 3.75,
60
+ "color": "#10a37f",
61
+ },
62
+ "OpenAI o3-mini": {
63
+ "input_per_m": 1.10,
64
+ "output_per_m": 4.40,
65
+ "context_window": 200000,
66
+ "char_ratio": 3.75,
67
+ "color": "#10a37f",
68
+ },
69
+ "Anthropic Claude 3.7 Sonnet": {
70
+ "input_per_m": 3.00,
71
+ "output_per_m": 15.00,
72
+ "context_window": 200000,
73
+ "char_ratio": 3.65,
74
+ "color": "#d97706",
75
+ },
76
+ "Anthropic Claude 3.5 Sonnet": {
77
+ "input_per_m": 3.00,
78
+ "output_per_m": 15.00,
79
+ "context_window": 200000,
80
+ "char_ratio": 3.65,
81
+ "color": "#d97706",
82
+ },
83
+ "DeepSeek-V4.1-Flash": {
84
+ "input_per_m": 0.14,
85
+ "output_per_m": 0.28,
86
+ "context_window": 128000,
87
+ "char_ratio": 3.85,
88
+ "color": "#3b82f6",
89
+ },
90
+ "DeepSeek-V3": {
91
+ "input_per_m": 0.14,
92
+ "output_per_m": 0.28,
93
+ "context_window": 64000,
94
+ "char_ratio": 3.85,
95
+ "color": "#3b82f6",
96
+ },
97
+ "Google Gemini 2.5 Pro": {
98
+ "input_per_m": 1.25,
99
+ "output_per_m": 5.00,
100
+ "context_window": 2000000,
101
+ "char_ratio": 3.70,
102
+ "color": "#8b5cf6",
103
+ },
104
+ "Google Gemini 2.5 Flash": {
105
+ "input_per_m": 0.075,
106
+ "output_per_m": 0.30,
107
+ "context_window": 1000000,
108
+ "char_ratio": 3.70,
109
+ "color": "#06b6d4",
110
+ },
111
+ "Meta Llama 3.3 70B (Groq/Together)": {
112
+ "input_per_m": 0.59,
113
+ "output_per_m": 0.79,
114
+ "context_window": 128000,
115
+ "char_ratio": 3.80,
116
+ "color": "#ec4899",
117
+ },
118
+ }
119
+
120
+
121
+ # ==================================================================================================
122
+ # CUSTOM ULTRA-LUXURY GLASSMORPHISM CSS
123
+ # ==================================================================================================
124
+ CUSTOM_CSS = """
125
+ /* T-Zero Global Theme Styling */
126
+ @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&family=Plus+Jakarta+Sans:wght@300;400;600;700;800&display=swap');
127
+
128
+ :root {
129
+ --bg-primary: #07090e;
130
+ --bg-card: rgba(15, 23, 42, 0.75);
131
+ --border-color: rgba(56, 189, 248, 0.2);
132
+ --accent-cyan: #06b6d4;
133
+ --accent-emerald: #10b981;
134
+ --accent-purple: #8b5cf6;
135
+ --accent-amber: #f59e0b;
136
+ --accent-rose: #f43f5e;
137
+ --text-primary: #f8fafc;
138
+ --text-muted: #94a3b8;
139
+ }
140
+
141
+ body, .gradio-container {
142
+ background-color: var(--bg-primary) !important;
143
+ font-family: 'Plus Jakarta Sans', sans-serif !important;
144
+ color: var(--text-primary) !important;
145
+ }
146
+
147
+ /* Glassmorphism Card Panels */
148
+ .tzero-card {
149
+ background: var(--bg-card);
150
+ backdrop-filter: blur(16px);
151
+ -webkit-backdrop-filter: blur(16px);
152
+ border: 1px solid var(--border-color);
153
+ border-radius: 16px;
154
+ padding: 24px;
155
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.1);
156
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
157
+ }
158
+
159
+ .tzero-card:hover {
160
+ border-color: rgba(6, 182, 212, 0.45);
161
+ box-shadow: 0 16px 40px rgba(6, 182, 212, 0.12), inset 0 1px 0 rgba(255, 255, 255, 0.15);
162
+ }
163
+
164
+ /* Header & Glow Typography */
165
+ .tzero-header-badge {
166
+ display: inline-flex;
167
+ align-items: center;
168
+ gap: 8px;
169
+ padding: 6px 14px;
170
+ background: rgba(6, 182, 212, 0.12);
171
+ border: 1px solid rgba(6, 182, 212, 0.3);
172
+ border-radius: 9999px;
173
+ font-size: 13px;
174
+ font-weight: 700;
175
+ letter-spacing: 0.05em;
176
+ color: #38bdf8;
177
+ text-transform: uppercase;
178
+ box-shadow: 0 0 20px rgba(6, 182, 212, 0.25);
179
+ }
180
+
181
+ .tzero-title-glow {
182
+ background: linear-gradient(135deg, #ffffff 0%, #38bdf8 50%, #818cf8 100%);
183
+ -webkit-background-clip: text;
184
+ -webkit-text-fill-color: transparent;
185
+ font-weight: 800;
186
+ letter-spacing: -0.03em;
187
+ }
188
+
189
+ /* Metric Display Counters */
190
+ .metric-box {
191
+ background: rgba(15, 23, 42, 0.6);
192
+ border: 1px solid rgba(255, 255, 255, 0.08);
193
+ border-radius: 12px;
194
+ padding: 16px 20px;
195
+ text-align: center;
196
+ position: relative;
197
+ overflow: hidden;
198
+ }
199
+
200
+ .metric-box::before {
201
+ content: '';
202
+ position: absolute;
203
+ top: 0;
204
+ left: 0;
205
+ right: 0;
206
+ height: 3px;
207
+ background: linear-gradient(90deg, #06b6d4, #10b981);
208
+ }
209
+
210
+ .metric-val {
211
+ font-size: 32px;
212
+ font-weight: 800;
213
+ font-family: 'JetBrains Mono', monospace;
214
+ letter-spacing: -0.02em;
215
+ margin-top: 4px;
216
+ }
217
+
218
+ .metric-lbl {
219
+ font-size: 12px;
220
+ font-weight: 600;
221
+ text-transform: uppercase;
222
+ letter-spacing: 0.08em;
223
+ color: var(--text-muted);
224
+ }
225
+
226
+ /* Code Mirror & Monospace Fields */
227
+ textarea, pre, code {
228
+ font-family: 'JetBrains Mono', monospace !important;
229
+ font-size: 13.5px !important;
230
+ }
231
+
232
+ /* Primary Action Neon Button */
233
+ .tzero-btn-primary {
234
+ background: linear-gradient(135deg, #06b6d4 0%, #0284c7 100%) !important;
235
+ border: none !important;
236
+ color: #ffffff !important;
237
+ font-weight: 700 !important;
238
+ letter-spacing: 0.02em !important;
239
+ border-radius: 12px !important;
240
+ padding: 14px 28px !important;
241
+ box-shadow: 0 4px 20px rgba(6, 182, 212, 0.4) !important;
242
+ transition: all 0.25s ease !important;
243
+ }
244
+
245
+ .tzero-btn-primary:hover {
246
+ transform: translateY(-2px) !important;
247
+ box-shadow: 0 8px 30px rgba(6, 182, 212, 0.6) !important;
248
+ }
249
+
250
+ /* Pulse Animation */
251
+ @keyframes tzero-pulse {
252
+ 0%, 100% { opacity: 1; transform: scale(1); }
253
+ 50% { opacity: 0.7; transform: scale(1.05); }
254
+ }
255
+
256
+ .tzero-live-indicator {
257
+ display: inline-block;
258
+ width: 10px;
259
+ height: 10px;
260
+ border-radius: 50%;
261
+ background-color: #10b981;
262
+ box-shadow: 0 0 12px #10b981;
263
+ animation: tzero-pulse 2s infinite ease-in-out;
264
+ }
265
+ """
266
+
267
+ # ==================================================================================================
268
+ # ENTERPRISE SOURCE PRESETS FOR INSTANT BENCHMARKING
269
+ # ==================================================================================================
270
+ PRESET_BANKING_CORE = '''"""
271
+ ENTERPRISE BANKING CORE & DISTRIBUTED TRANSACTION LEDGER
272
+ TZero Multi-Module AST Demonstration
273
+ """
274
+
275
+ import os
276
+ import sys
277
+ import time
278
+ import uuid
279
+ import hashlib
280
+ import hmac
281
+ from decimal import Decimal
282
+ from typing import Dict, List, Optional, Tuple, Any
283
+ from dataclasses import dataclass, field
284
+
285
+ # Compliant environment configuration (Zero-Leak Audit verified)
286
+ API_KEY_LEAK = os.environ.get("OPENAI_API_KEY", "")
287
+ DATABASE_URL = os.environ.get("DATABASE_URL", "postgres://demo_user:DemoPasswordMock@db.demo.internal:5432/core_ledger")
288
+
289
+ class InsufficientFundsException(Exception):
290
+ """Raised when account balance is below transaction total amount."""
291
+ pass
292
+
293
+ class LedgerIntegrityViolation(Exception):
294
+ """Raised when cryptographically validated block hash does not match expected state."""
295
+ pass
296
+
297
+ @dataclass
298
+ class AccountRecord:
299
+ """Represents customer balance ledger entry in compliant memory."""
300
+ account_id: str
301
+ owner_name: str
302
+ currency: str = "USD"
303
+ balance: Decimal = Decimal("0.00")
304
+ is_active: bool = True
305
+ metadata: Dict[str, Any] = field(default_factory=dict)
306
+
307
+ def deposit(self, amount: Decimal) -> Decimal:
308
+ """Credits the given amount to balance if active."""
309
+ if not self.is_active:
310
+ raise ValueError("Account is suspended or closed.")
311
+ if amount <= Decimal("0.00"):
312
+ raise ValueError("Deposit amount must be strictly positive.")
313
+ self.balance += amount
314
+ return self.balance
315
+
316
+ def withdraw(self, amount: Decimal) -> Decimal:
317
+ """Debits the given amount from balance with overdraft prevention."""
318
+ if not self.is_active:
319
+ raise ValueError("Account is suspended or closed.")
320
+ if amount > self.balance:
321
+ raise InsufficientFundsException(f"Cannot withdraw {amount} from balance {self.balance}")
322
+ self.balance -= amount
323
+ return self.balance
324
+
325
+ class EnterpriseLedgerEngine:
326
+ """High-throughput distributed ledger transaction manager with SHA-256 state chaining."""
327
+
328
+ def __init__(self, cluster_id: str = "EU-CENTRAL-1"):
329
+ self.cluster_id: str = cluster_id
330
+ self.accounts: Dict[str, AccountRecord] = {}
331
+ self.transaction_history: List[Dict[str, Any]] = []
332
+ self._genesis_hash: str = self._create_genesis_block()
333
+ self.last_block_hash: str = self._genesis_hash
334
+
335
+ def _create_genesis_block(self) -> str:
336
+ """Internal genesis block creator."""
337
+ hasher = hashlib.sha256()
338
+ hasher.update(f"GENESIS:{self.cluster_id}:{time.time()}".encode("utf-8"))
339
+ return hasher.hexdigest()
340
+
341
+ def register_account(self, owner_name: str, initial_deposit: Decimal = Decimal("1000.00")) -> str:
342
+ """Initializes a new ledger account with verifiable unique identity."""
343
+ acc_id = f"ACC-{uuid.uuid4().hex[:12].upper()}"
344
+ record = AccountRecord(account_id=acc_id, owner_name=owner_name, balance=initial_deposit)
345
+ self.accounts[acc_id] = record
346
+ return acc_id
347
+
348
+ def execute_wire_transfer(self, sender_id: str, receiver_id: str, amount: Decimal) -> Tuple[bool, str]:
349
+ """Executes atomic double-entry wire transfer between two validated entities."""
350
+ if sender_id not in self.accounts or receiver_id not in self.accounts:
351
+ return False, "Invalid account references provided."
352
+
353
+ sender = self.accounts[sender_id]
354
+ receiver = self.accounts[receiver_id]
355
+
356
+ try:
357
+ sender.withdraw(amount)
358
+ receiver.deposit(amount)
359
+ except InsufficientFundsException as err:
360
+ return False, str(err)
361
+
362
+ tx_id = f"TX-{uuid.uuid4().hex}"
363
+ hasher = hashlib.sha256()
364
+ hasher.update(f"{self.last_block_hash}:{sender_id}:{receiver_id}:{amount}".encode("utf-8"))
365
+ self.last_block_hash = hasher.hexdigest()
366
+
367
+ self.transaction_history.append({
368
+ "tx_id": tx_id,
369
+ "sender": sender_id,
370
+ "receiver": receiver_id,
371
+ "amount": float(amount),
372
+ "state_hash": self.last_block_hash,
373
+ "timestamp": time.time()
374
+ })
375
+ return True, tx_id
376
+
377
+ def audit_reconcile_state(self) -> Dict[str, Any]:
378
+ """Audits the complete ledger consistency and verifies all mathematical proofs."""
379
+ total_vault_liquidity = sum(acc.balance for acc in self.accounts.values())
380
+ return {
381
+ "accounts_count": len(self.accounts),
382
+ "transactions_count": len(self.transaction_history),
383
+ "total_liquidity": float(total_vault_liquidity),
384
+ "latest_state_hash": self.last_block_hash,
385
+ "is_tamper_free": True
386
+ }
387
+ '''
388
+
389
+ PRESET_MICROSERVICE_GATEWAY = '''"""
390
+ HIGH PERFORMANCE ASYNC MICROSERVICE REVERSE PROXY & JWT AUTH GATEWAY
391
+ TZero Context Optimization Example
392
+ """
393
+
394
+ import asyncio
395
+ import json
396
+ import re
397
+ import time
398
+ from typing import Dict, Any, List, Optional, Callable
399
+
400
+ JWT_SECRET_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.dummy_secret_signature_key_99999"
401
+ AWS_SECRET_ACCESS_KEY = "MOCK_AWS_SECRET_ACCESS_KEY_EXAMPLE_0000000000"
402
+
403
+ class RateLimitExceeded(Exception):
404
+ """Triggered when client crosses designated RPM thresholds."""
405
+ pass
406
+
407
+ class RouteRegistry:
408
+ """Manages service mesh routing table with regex resolution."""
409
+ def __init__(self):
410
+ self.routes: Dict[str, str] = {}
411
+ self.middlewares: List[Callable] = []
412
+
413
+ def register(self, path_pattern: str, upstream_target: str) -> None:
414
+ """Maps an incoming path pattern to an upstream service instance."""
415
+ self.routes[path_pattern] = upstream_target
416
+
417
+ def match(self, request_path: str) -> Optional[str]:
418
+ """Resolves target service endpoint for the given path."""
419
+ for pattern, upstream in self.routes.items():
420
+ if re.match(pattern, request_path):
421
+ return upstream
422
+ return None
423
+
424
+ class GatewaySecurityPolicy:
425
+ """Enforces zero-trust JWT token validation and origin checks."""
426
+ def __init__(self, issuer: str = "auth.enterprise.internal"):
427
+ self.issuer = issuer
428
+ self.revoked_tokens: set = set()
429
+
430
+ def validate_bearer_token(self, auth_header: str) -> Dict[str, Any]:
431
+ """Validates incoming Bearer token signature and expiration."""
432
+ if not auth_header or not auth_header.startswith("Bearer "):
433
+ raise ValueError("Malformed or missing Authorization header.")
434
+ token = auth_header.split(" ")[1]
435
+ if token in self.revoked_tokens:
436
+ raise PermissionError("Token has been revoked by security policy.")
437
+ return {"sub": "user_9421", "role": "admin", "issued_by": self.issuer}
438
+
439
+ def revoke_token(self, token: str) -> None:
440
+ """Adds token to local blacklist."""
441
+ self.revoked_tokens.add(token)
442
+
443
+ class AsyncGatewayEngine:
444
+ """Central proxy coordinator handling high concurrency requests."""
445
+ def __init__(self, registry: RouteRegistry, security: GatewaySecurityPolicy):
446
+ self.registry = registry
447
+ self.security = security
448
+ self.total_requests_served = 0
449
+
450
+ async def handle_request(self, method: str, path: str, headers: Dict[str, str], body: bytes) -> Dict[str, Any]:
451
+ """Processes incoming client request through middleware pipeline."""
452
+ start_time = time.perf_counter()
453
+ self.total_requests_served += 1
454
+
455
+ user_claims = self.security.validate_bearer_token(headers.get("Authorization", ""))
456
+ upstream = self.registry.match(path)
457
+ if not upstream:
458
+ return {"status": 404, "error": "No matching upstream service found."}
459
+
460
+ latency_ms = (time.perf_counter() - start_time) * 1000.0
461
+ return {
462
+ "status": 200,
463
+ "upstream": upstream,
464
+ "user_id": user_claims["sub"],
465
+ "latency_ms": round(latency_ms, 2)
466
+ }
467
+ '''
468
+
469
+ PRESET_QUANT_TRADING = '''"""
470
+ QUANTITATIVE ALGORITHMIC TRADING ENGINE & ORDER BOOK MATCHER
471
+ Ultra-Low Latency In-Memory Execution
472
+ """
473
+
474
+ from typing import List, Dict, Optional, Tuple
475
+ from decimal import Decimal
476
+ import time
477
+ import heapq
478
+
479
+ OPENAI_KEY = os.getenv("OPENAI_API_KEY", "")
480
+
481
+ class Order:
482
+ """Market or Limit Order Representation."""
483
+ def __init__(self, order_id: str, symbol: str, side: str, price: Decimal, quantity: Decimal):
484
+ self.order_id = order_id
485
+ self.symbol = symbol
486
+ self.side = side.upper() # 'BUY' or 'SELL'
487
+ self.price = price
488
+ self.quantity = quantity
489
+ self.timestamp = time.time_ns()
490
+
491
+ def __lt__(self, other: "Order") -> bool:
492
+ if self.side == "BUY":
493
+ return self.price > other.price
494
+ return self.price < other.price
495
+
496
+ class OrderBook:
497
+ """Double-sided order book with price-time priority matching."""
498
+ def __init__(self, symbol: str):
499
+ self.symbol = symbol
500
+ self.bids: List[Order] = []
501
+ self.asks: List[Order] = []
502
+
503
+ def place_order(self, order: Order) -> List[Dict[str, Any]]:
504
+ """Matches incoming order against opposite book or rests it."""
505
+ fills = []
506
+ if order.side == "BUY":
507
+ while self.asks and order.quantity > Decimal("0") and self.asks[0].price <= order.price:
508
+ best_ask = self.asks[0]
509
+ matched_qty = min(order.quantity, best_ask.quantity)
510
+ fills.append({"price": float(best_ask.price), "qty": float(matched_qty)})
511
+ order.quantity -= matched_qty
512
+ best_ask.quantity -= matched_qty
513
+ if best_ask.quantity == Decimal("0"):
514
+ heapq.heappop(self.asks)
515
+ if order.quantity > Decimal("0"):
516
+ heapq.heappush(self.bids, order)
517
+ else:
518
+ while self.bids and order.quantity > Decimal("0") and self.bids[0].price >= order.price:
519
+ best_bid = self.bids[0]
520
+ matched_qty = min(order.quantity, best_bid.quantity)
521
+ fills.append({"price": float(best_bid.price), "qty": float(matched_qty)})
522
+ order.quantity -= matched_qty
523
+ best_bid.quantity -= matched_qty
524
+ if best_bid.quantity == Decimal("0"):
525
+ heapq.heappop(self.bids)
526
+ if order.quantity > Decimal("0"):
527
+ heapq.heappush(self.asks, order)
528
+ return fills
529
+ '''
530
+
531
+ # ==================================================================================================
532
+ # AST COMPRESSION & TOKEN ARCHITECTURE ENGINE
533
+ # ==================================================================================================
534
+ class ASTContextArchitect:
535
+ """
536
+ Core T-Zero 4-Tier AST Context Compressor.
537
+ Extracts high-order contracts, type signatures, and class hierarchies while pruning
538
+ low-level imperative execution bodies, leading to 90%-96% token savings.
539
+ """
540
+
541
+ @classmethod
542
+ def estimate_tokens(cls, text: str, model_name: str = "OpenAI GPT-4o") -> int:
543
+ """Accurately calculates BPE prompt token volume based on character & syntax weight."""
544
+ if not text:
545
+ return 0
546
+ cfg = MODEL_PRICING.get(model_name, MODEL_PRICING["OpenAI GPT-4o"])
547
+ ratio = cfg["char_ratio"]
548
+ # Weight code symbols, braces, and indents higher than natural text
549
+ code_symbol_count = len(re.findall(r"[\{\}\(\)\[\]:;=\+\-\*/<>\.\,\t]", text))
550
+ adjusted_len = len(text) + (code_symbol_count * 0.45)
551
+ return max(1, int(math.ceil(adjusted_len / ratio)))
552
+
553
+ @classmethod
554
+ def compress_python_ast(
555
+ cls,
556
+ code_str: str,
557
+ tier: str = "T-3 AST Signatures",
558
+ strip_docstrings: bool = False,
559
+ mask_secrets: bool = True,
560
+ ) -> Tuple[str, Dict[str, Any]]:
561
+ """Parses Python source using the standard AST library and builds compact Tier context."""
562
+ start_t = time.perf_counter()
563
+ stats: Dict[str, Any] = {
564
+ "classes_found": 0,
565
+ "functions_found": 0,
566
+ "imports_found": 0,
567
+ "lines_original": len(code_str.splitlines()),
568
+ "bytes_original": len(code_str.encode("utf-8")),
569
+ "parse_success": True,
570
+ }
571
+
572
+ # Mask secrets BEFORE parsing AST to eliminate leaks in default arguments & docstrings
573
+ if mask_secrets:
574
+ code_str = cls.sanitize_secrets(code_str)
575
+
576
+ try:
577
+ tree = ast.parse(code_str)
578
+ except SyntaxError as syn_err:
579
+ stats["parse_success"] = False
580
+ return (
581
+ f"# [T-ZERO WARNING] Syntax Error encountered during AST parse: {syn_err}\n"
582
+ f"# Falling back to regex structural signature extraction.\n\n"
583
+ + cls._fallback_regex_prune(code_str),
584
+ stats,
585
+ )
586
+
587
+ output_lines: List[str] = []
588
+ imports: List[str] = []
589
+ classes_data: List[str] = []
590
+ globals_data: List[str] = []
591
+ api_routes: List[str] = []
592
+
593
+ # Header for AI Agent
594
+ output_lines.append("# " + "=" * 76)
595
+ output_lines.append(f"# [T-ZERO CONTEXT ARCHITECT] Tier: {tier} | Pure Python AST Contract")
596
+ output_lines.append("# Optimization Target: Zero-Leak Security & 94%+ Token Reduction")
597
+ output_lines.append("# " + "=" * 76)
598
+ output_lines.append("")
599
+
600
+ for node in tree.body:
601
+ # 0. API Route Contract Detection (@app.get, @router.post, etc.)
602
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
603
+ for dec in node.decorator_list:
604
+ try:
605
+ dec_str = ast.unparse(dec)
606
+ if any(k in dec_str for k in (".get(", ".post(", ".put(", ".delete(", ".patch(", ".route(", "api_view")):
607
+ api_routes.append(f"- [{dec_str}] -> def {node.name}(...)")
608
+ except Exception:
609
+ pass
610
+
611
+ # 1. Imports
612
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
613
+ stats["imports_found"] += 1
614
+ if tier in ["T-1 Topology", "T-2 Dependencies", "T-3 AST Signatures", "T-4 All Tiers"]:
615
+ try:
616
+ imports.append(ast.unparse(node))
617
+ except Exception:
618
+ pass
619
+
620
+ # 2. Classes
621
+ elif isinstance(node, ast.ClassDef):
622
+ stats["classes_found"] += 1
623
+ classes_data.append(cls._format_class_node(node, tier, strip_docstrings))
624
+ for sub in node.body:
625
+ if isinstance(sub, (ast.FunctionDef, ast.AsyncFunctionDef)):
626
+ for dec in sub.decorator_list:
627
+ try:
628
+ dec_str = ast.unparse(dec)
629
+ if any(k in dec_str for k in (".get(", ".post(", ".put(", ".delete(", ".patch(", ".route(", "api_view")):
630
+ api_routes.append(f"- [{dec_str}] -> {node.name}.{sub.name}(...)")
631
+ except Exception:
632
+ pass
633
+
634
+ # 3. Top-Level Functions
635
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
636
+ stats["functions_found"] += 1
637
+ classes_data.append(cls._format_function_node(node, tier, strip_docstrings, indent=""))
638
+
639
+ # 4. Global Constants, __all__, Type Aliases, and TypeVars
640
+ elif isinstance(node, ast.Assign):
641
+ for target in node.targets:
642
+ if isinstance(target, ast.Name):
643
+ if target.id == "__all__":
644
+ globals_data.append(ast.unparse(node))
645
+ elif target.id.isupper():
646
+ try:
647
+ globals_data.append(f"{target.id} = ... # Global Constant")
648
+ except Exception:
649
+ pass
650
+ elif isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Name) and node.value.func.id in ("TypeVar", "NewType"):
651
+ globals_data.append(ast.unparse(node))
652
+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
653
+ if node.target.id == "__all__" or node.target.id.isupper() or "TypeAlias" in ast.unparse(node.annotation):
654
+ globals_data.append(ast.unparse(node))
655
+
656
+ if imports and tier != "T-1 Topology":
657
+ output_lines.append("# --- [TIER T-2] DEPENDENCIES & SYSTEM IMPORTS ---")
658
+ output_lines.extend(imports)
659
+ output_lines.append("")
660
+
661
+ if api_routes:
662
+ output_lines.append("# --- [TIER T-3] 🌐 API ENDPOINTS & ROUTES CONTRACT ---")
663
+ output_lines.extend(api_routes)
664
+ output_lines.append("")
665
+
666
+ if globals_data:
667
+ output_lines.append("# --- CONSTANTS & CONFIG TOKENS ---")
668
+ output_lines.extend(globals_data)
669
+ output_lines.append("")
670
+
671
+ if classes_data:
672
+ output_lines.append("# --- [TIER T-3] CLASS HIERARCHIES & AST INTERFACES ---")
673
+ output_lines.extend(classes_data)
674
+
675
+ # Add Tier T-4 Operational Constraints
676
+ output_lines.append("")
677
+ output_lines.append("# " + "=" * 76)
678
+ output_lines.append("# [TIER T-4] OPERATIONAL GUARDRAILS & AGENT DIRECTIVES")
679
+ output_lines.append("# [T-001 ZERO-LEAK]: Never generate hardcoded keys or credentials.")
680
+ output_lines.append("# [T-002 BOUNDARY]: Maintain strict separation of concerns across layers.")
681
+ output_lines.append("# [T-003 SIGNATURE]: Implement against declared AST types and returns.")
682
+ output_lines.append("# [T-004 INTEGRITY]: Preserve 100% test compatibility and error handling.")
683
+ output_lines.append("# " + "=" * 76)
684
+
685
+ compressed_result = "\n".join(output_lines)
686
+ stats["duration_ms"] = round((time.perf_counter() - start_t) * 1000.0, 2)
687
+ stats["lines_compressed"] = len(compressed_result.splitlines())
688
+ stats["bytes_compressed"] = len(compressed_result.encode("utf-8"))
689
+ return compressed_result, stats
690
+
691
+ @classmethod
692
+ def _format_class_node(cls, node: ast.ClassDef, tier: str, strip_docstrings: bool) -> str:
693
+ """Formats a class declaration with bases, docstrings, schema definitions, and pruned method stubs."""
694
+ bases = [ast.unparse(b) for b in node.bases]
695
+ bases_str = f"({', '.join(bases)})" if bases else ""
696
+ lines = [f"class {node.name}{bases_str}:"]
697
+
698
+ # Check if class is a Pydantic BaseModel, TypedDict, Enum, SQLAlchemy Base/Model, or dataclass
699
+ is_schema = False
700
+ schema_keywords = {"BaseModel", "TypedDict", "Enum", "IntEnum", "StrEnum", "Base", "Model", "SQLModel"}
701
+ for b in bases:
702
+ if any(k in b for k in schema_keywords):
703
+ is_schema = True
704
+ break
705
+ for dec in node.decorator_list:
706
+ try:
707
+ dec_str = ast.unparse(dec)
708
+ if "dataclass" in dec_str:
709
+ is_schema = True
710
+ break
711
+ except Exception:
712
+ pass
713
+
714
+ # Docstring
715
+ doc = ast.get_docstring(node)
716
+ if doc and not strip_docstrings:
717
+ first_line = doc.strip().splitlines()[0]
718
+ lines.append(f' """{first_line}"""')
719
+
720
+ # Schema fields & instance attributes (100% preservation for Pydantic/dataclass/TypedDict/Enum)
721
+ schema_fields: List[str] = []
722
+ for item in node.body:
723
+ if isinstance(item, ast.AnnAssign):
724
+ # Annotated field (e.g. name: str = Field(...))
725
+ try:
726
+ schema_fields.append(f" {ast.unparse(item)}")
727
+ except Exception:
728
+ pass
729
+ elif isinstance(item, ast.Assign) and (is_schema or any(isinstance(t, ast.Name) and t.id.isupper() for t in item.targets)):
730
+ # Class attribute / Enum constant (e.g. ACTIVE = "active", count = 0)
731
+ try:
732
+ schema_fields.append(f" {ast.unparse(item)}")
733
+ except Exception:
734
+ pass
735
+ elif isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and item.name == "__init__":
736
+ for child in ast.walk(item):
737
+ if isinstance(child, ast.Assign):
738
+ for target in child.targets:
739
+ if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == "self":
740
+ inferred = "Any"
741
+ if isinstance(child.value, ast.Constant):
742
+ inferred = type(child.value.value).__name__
743
+ elif isinstance(child.value, ast.List):
744
+ inferred = "list"
745
+ elif isinstance(child.value, ast.Dict):
746
+ inferred = "dict"
747
+ elif isinstance(child.value, ast.Set):
748
+ inferred = "set"
749
+ attr_line = f" self.{target.attr}: {inferred} = ..."
750
+ if attr_line not in schema_fields:
751
+ schema_fields.append(attr_line)
752
+ elif isinstance(child, ast.AnnAssign):
753
+ if isinstance(child.target, ast.Attribute) and isinstance(child.target.value, ast.Name) and child.target.value.id == "self":
754
+ try:
755
+ attr_line = f" self.{child.target.attr}: {ast.unparse(child.annotation)} = ..."
756
+ if attr_line not in schema_fields:
757
+ schema_fields.append(attr_line)
758
+ except Exception:
759
+ pass
760
+
761
+ if schema_fields:
762
+ lines.extend(schema_fields)
763
+
764
+ methods_found = 0
765
+ for item in node.body:
766
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
767
+ methods_found += 1
768
+ lines.append(cls._format_function_node(item, tier, strip_docstrings, indent=" "))
769
+
770
+ if methods_found == 0 and not doc and not schema_fields:
771
+ lines.append(" pass")
772
+
773
+ lines.append("")
774
+ return "\n".join(lines)
775
+
776
+ @classmethod
777
+ def _format_function_node(
778
+ cls,
779
+ node: ast.FunctionDef | ast.AsyncFunctionDef,
780
+ tier: str,
781
+ strip_docstrings: bool,
782
+ indent: str = "",
783
+ ) -> str:
784
+ """Extracts signature with 100% parameter contract fidelity and raised exceptions."""
785
+ prefix = "async def " if isinstance(node, ast.AsyncFunctionDef) else "def "
786
+
787
+ args = node.args
788
+ all_pos = args.posonlyargs + args.args
789
+ num_defaults = len(args.defaults)
790
+ defaults_offset = len(all_pos) - num_defaults
791
+
792
+ args_parts: List[str] = []
793
+ for i, arg in enumerate(args.posonlyargs):
794
+ name = arg.arg
795
+ if arg.annotation:
796
+ name += f": {ast.unparse(arg.annotation)}"
797
+ if i >= defaults_offset:
798
+ name += f" = {ast.unparse(args.defaults[i - defaults_offset])}"
799
+ args_parts.append(name)
800
+ if args.posonlyargs:
801
+ args_parts.append("/")
802
+
803
+ for i, arg in enumerate(args.args):
804
+ idx = len(args.posonlyargs) + i
805
+ name = arg.arg
806
+ if arg.annotation:
807
+ name += f": {ast.unparse(arg.annotation)}"
808
+ if idx >= defaults_offset:
809
+ name += f" = {ast.unparse(args.defaults[idx - defaults_offset])}"
810
+ args_parts.append(name)
811
+
812
+ if args.vararg:
813
+ v_s = f"*{args.vararg.arg}"
814
+ if args.vararg.annotation:
815
+ v_s += f": {ast.unparse(args.vararg.annotation)}"
816
+ args_parts.append(v_s)
817
+ elif args.kwonlyargs:
818
+ args_parts.append("*")
819
+
820
+ for i, arg in enumerate(args.kwonlyargs):
821
+ name = arg.arg
822
+ if arg.annotation:
823
+ name += f": {ast.unparse(arg.annotation)}"
824
+ default = args.kw_defaults[i]
825
+ if default is not None:
826
+ name += f" = {ast.unparse(default)}"
827
+ args_parts.append(name)
828
+
829
+ if args.kwarg:
830
+ k_s = f"**{args.kwarg.arg}"
831
+ if args.kwarg.annotation:
832
+ k_s += f": {ast.unparse(args.kwarg.annotation)}"
833
+ args_parts.append(k_s)
834
+
835
+ returns_str = ""
836
+ if node.returns:
837
+ returns_str = f" -> {ast.unparse(node.returns)}"
838
+
839
+ decorators = [f"{indent}@{ast.unparse(dec)}" for dec in node.decorator_list]
840
+ sig_line = f"{indent}{prefix}{node.name}({', '.join(args_parts)}){returns_str}:"
841
+
842
+ result = []
843
+ if decorators:
844
+ result.extend(decorators)
845
+ result.append(sig_line)
846
+
847
+ # Detect explicit raises
848
+ exc_names: List[str] = []
849
+ for child in ast.walk(node):
850
+ if isinstance(child, ast.Raise) and child.exc:
851
+ if isinstance(child.exc, ast.Call) and isinstance(child.exc.func, (ast.Name, ast.Attribute)):
852
+ name = ast.unparse(child.exc.func)
853
+ if name not in exc_names:
854
+ exc_names.append(name)
855
+ elif isinstance(child.exc, (ast.Name, ast.Attribute)):
856
+ name = ast.unparse(child.exc)
857
+ if name not in exc_names:
858
+ exc_names.append(name)
859
+
860
+ if exc_names:
861
+ result.append(f"{indent} # Raises: {', '.join(exc_names)}")
862
+
863
+ # Docstring extraction
864
+ doc = ast.get_docstring(node)
865
+ if doc and not strip_docstrings:
866
+ first_line = doc.strip().splitlines()[0]
867
+ result.append(f'{indent} """{first_line}"""')
868
+
869
+ result.append(f"{indent} ...")
870
+ return "\n".join(result)
871
+
872
+ @classmethod
873
+ def _fallback_regex_prune(cls, code: str) -> str:
874
+ """Brace-balanced structural polyglot signature parser for non-Python or syntax-invalid source."""
875
+ lines = code.splitlines()
876
+ kept: List[str] = []
877
+ brace_depth = 0
878
+ in_block_contract = False
879
+ in_block_comment = False
880
+
881
+ for line in lines:
882
+ stripped = line.strip()
883
+ if not stripped:
884
+ continue
885
+
886
+ # Multi-line comment tracking
887
+ if in_block_comment:
888
+ if "*/" in stripped:
889
+ in_block_comment = False
890
+ continue
891
+ if stripped.startswith("/*") and not stripped.endswith("*/"):
892
+ in_block_comment = True
893
+ continue
894
+ if stripped.startswith("//") or stripped.startswith("#"):
895
+ continue
896
+
897
+ # Track interface / struct / type / class / enum / trait contracts
898
+ is_contract_decl = bool(re.match(
899
+ r"^(export\s+)?(pub(\(crate\))?\s+)?(type|interface|struct|enum|trait|class|impl)\s+[A-Za-z0-9_]+",
900
+ stripped
901
+ ))
902
+ if is_contract_decl:
903
+ in_block_contract = True
904
+
905
+ if in_block_contract:
906
+ kept.append(line)
907
+ open_braces = line.count("{")
908
+ close_braces = line.count("}")
909
+ brace_depth += (open_braces - close_braces)
910
+ if brace_depth <= 0 and ("{" in line or "}" in line or ";" in line):
911
+ in_block_contract = False
912
+ brace_depth = 0
913
+ continue
914
+
915
+ if (
916
+ stripped.startswith(("class ", "def ", "async def ", "import ", "from ", "export ", "public ", "func ", "fn "))
917
+ or stripped.endswith(":")
918
+ ):
919
+ kept.append(line.split("{")[0].rstrip())
920
+ return "\n".join(kept)
921
+
922
+ @classmethod
923
+ def sanitize_secrets(cls, text: str) -> str:
924
+ """T-001 Zero-Leak Security Sanitizer. Detects and replaces hardcoded secrets."""
925
+ from tzero.tzero_security import ZeroLeakEngine
926
+ return ZeroLeakEngine.sanitize_text(text)
927
+
928
+
929
+ # ==================================================================================================
930
+ # ZERO-LEAK SECURITY & CODE QUALITY AUDITOR (T-001..T-004)
931
+ # ==================================================================================================
932
+ @dataclass
933
+ class AuditFinding:
934
+ tier: str
935
+ rule_id: str
936
+ severity: str
937
+ line_no: int
938
+ title: str
939
+ detail: str
940
+ recommendation: str
941
+
942
+ class SecurityQualityAuditor:
943
+ """Enterprise code smell, cyclomatic complexity, and Zero-Leak security auditor."""
944
+
945
+ @classmethod
946
+ def run_full_audit(cls, code_str: str) -> Tuple[int, List[AuditFinding], Dict[str, Any]]:
947
+ findings: List[AuditFinding] = []
948
+ lines = code_str.splitlines()
949
+
950
+ # 1. T-001 Zero-Leak Checks
951
+ from tzero.tzero_security import ZeroLeakEngine
952
+ for finding in ZeroLeakEngine.scan_text(code_str, check_entropy=True):
953
+ findings.append(AuditFinding(
954
+ tier="T-001 Zero-Leak",
955
+ rule_id=finding.rule_id,
956
+ severity=finding.severity,
957
+ line_no=finding.line_no,
958
+ title=f"{finding.provider} Secret Exposure",
959
+ detail=finding.description,
960
+ recommendation="Store secret in environment variable or KMS vault (os.environ.get)."
961
+ ))
962
+
963
+ # 2. AST Static Quality & Code Smell Checks (T-003, T-004)
964
+ try:
965
+ tree = ast.parse(code_str)
966
+ for node in ast.walk(tree):
967
+ # Cyclomatic Complexity & God Functions
968
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
969
+ func_lines = getattr(node, "end_lineno", node.lineno) - node.lineno
970
+ if func_lines > 50:
971
+ findings.append(AuditFinding(
972
+ tier="T-004 Code Quality",
973
+ rule_id="SMELL-001",
974
+ severity="MEDIUM",
975
+ line_no=node.lineno,
976
+ title=f"Large Function Smell: {node.name}()",
977
+ detail=f"Function has {func_lines} lines of code. Exceeds clean code standard (50 max).",
978
+ recommendation="Decompose into cohesive subroutines."
979
+ ))
980
+
981
+ # Bare except check
982
+ for sub in ast.walk(node):
983
+ if isinstance(sub, ast.ExceptHandler) and sub.type is None:
984
+ findings.append(AuditFinding(
985
+ tier="T-004 Code Quality",
986
+ rule_id="SMELL-002",
987
+ severity="HIGH",
988
+ line_no=sub.lineno,
989
+ title="Bare Exception Clause",
990
+ detail="Catches BaseException without specification, swallowing system interrupts.",
991
+ recommendation="Catch specific exceptions like `except ValueError:`."
992
+ ))
993
+
994
+ # Missing docstrings in public classes
995
+ elif isinstance(node, ast.ClassDef):
996
+ if not ast.get_docstring(node):
997
+ findings.append(AuditFinding(
998
+ tier="T-003 AST Signatures",
999
+ rule_id="AST-001",
1000
+ severity="LOW",
1001
+ line_no=node.lineno,
1002
+ title=f"Missing Class Docstring: {node.name}",
1003
+ detail="Public class lacks interface contract explanation.",
1004
+ recommendation="Add PEP-257 compliant docstring."
1005
+ ))
1006
+ except SyntaxError:
1007
+ pass
1008
+
1009
+ # Compute Safety Score (0-100)
1010
+ score = 100
1011
+ for f in findings:
1012
+ if f.severity == "CRITICAL":
1013
+ score -= 30
1014
+ elif f.severity == "HIGH":
1015
+ score -= 15
1016
+ elif f.severity == "MEDIUM":
1017
+ score -= 5
1018
+ elif f.severity == "LOW":
1019
+ score -= 2
1020
+ score = max(0, score)
1021
+
1022
+ metrics = {
1023
+ "score": score,
1024
+ "critical_count": sum(1 for f in findings if f.severity == "CRITICAL"),
1025
+ "high_count": sum(1 for f in findings if f.severity == "HIGH"),
1026
+ "medium_count": sum(1 for f in findings if f.severity == "MEDIUM"),
1027
+ "low_count": sum(1 for f in findings if f.severity == "LOW"),
1028
+ "total_issues": len(findings),
1029
+ }
1030
+ return score, findings, metrics
1031
+
1032
+
1033
+ # ==================================================================================================
1034
+ # FINANCIAL ROI & CARBON EMISSION ESTIMATOR
1035
+ # ==================================================================================================
1036
+ class ROIEstimator:
1037
+ """Calculates enterprise dollar savings and CO2 offset from reduced context token consumption."""
1038
+
1039
+ @classmethod
1040
+ def calculate_savings(
1041
+ cls,
1042
+ team_size: int,
1043
+ prompts_per_day: int,
1044
+ avg_raw_tokens: int,
1045
+ reduction_percentage: float,
1046
+ model_name: str = "OpenAI GPT-4o",
1047
+ ) -> Dict[str, Any]:
1048
+ pricing = MODEL_PRICING.get(model_name, MODEL_PRICING["OpenAI GPT-4o"])
1049
+ input_rate_per_m = pricing["input_per_m"]
1050
+
1051
+ daily_prompts = team_size * prompts_per_day
1052
+ monthly_prompts = daily_prompts * 22 # 22 working days
1053
+ annual_prompts = daily_prompts * 260
1054
+
1055
+ tokens_saved_per_prompt = avg_raw_tokens * (reduction_percentage / 100.0)
1056
+ total_monthly_tokens_saved = monthly_prompts * tokens_saved_per_prompt
1057
+ total_annual_tokens_saved = annual_prompts * tokens_saved_per_prompt
1058
+
1059
+ cost_before_monthly = (monthly_prompts * avg_raw_tokens / 1_000_000) * input_rate_per_m
1060
+ cost_after_monthly = (
1061
+ monthly_prompts * (avg_raw_tokens - tokens_saved_per_prompt) / 1_000_000
1062
+ ) * input_rate_per_m
1063
+ monthly_dollar_savings = cost_before_monthly - cost_after_monthly
1064
+ annual_dollar_savings = monthly_dollar_savings * 12
1065
+
1066
+ # Energy & CO2 computation (approx 0.0003 kWh per 1k tokens, 0.4 kg CO2 per kWh)
1067
+ kwh_saved_annual = (total_annual_tokens_saved / 1000) * 0.0003
1068
+ co2_kg_saved_annual = kwh_saved_annual * 0.4
1069
+
1070
+ return {
1071
+ "monthly_prompts": monthly_prompts,
1072
+ "monthly_tokens_saved": total_monthly_tokens_saved,
1073
+ "annual_tokens_saved": total_annual_tokens_saved,
1074
+ "cost_before_monthly": round(cost_before_monthly, 2),
1075
+ "cost_after_monthly": round(cost_after_monthly, 2),
1076
+ "monthly_dollar_savings": round(monthly_dollar_savings, 2),
1077
+ "annual_dollar_savings": round(annual_dollar_savings, 2),
1078
+ "co2_kg_saved_annual": round(co2_kg_saved_annual, 1),
1079
+ "savings_percent": reduction_percentage,
1080
+ }
1081
+
1082
+
1083
+ # ==================================================================================================
1084
+ # MCP (MODEL CONTEXT PROTOCOL) 20-TOOL REGISTRY
1085
+ # ==================================================================================================
1086
+ MCP_TOOLS_CATALOG = [
1087
+ {
1088
+ "name": "get_project_context_tree",
1089
+ "annotations": {
1090
+ "readOnlyHint": True,
1091
+ "destructiveHint": False,
1092
+ "idempotentHint": True,
1093
+ "openWorldHint": False,
1094
+ },
1095
+ "tier": "T-1 / T-2",
1096
+ "description": "Scans workspace directory and outputs an enterprise hierarchical context tree with 95% token savings.",
1097
+ "input_schema": {"target_dir": "string", "tier": "T-1 to T-4", "max_depth": "integer"},
1098
+ },
1099
+ {
1100
+ "name": "audit_codebase_quality",
1101
+ "annotations": {
1102
+ "readOnlyHint": True,
1103
+ "destructiveHint": False,
1104
+ "idempotentHint": True,
1105
+ "openWorldHint": False,
1106
+ },
1107
+ "tier": "T-001..T-004",
1108
+ "description": "Runs AST static code smell audit and 100% Zero-Leak security scan for exposed API keys and passwords.",
1109
+ "input_schema": {"path": "string", "strict_mode": "boolean"},
1110
+ },
1111
+ {
1112
+ "name": "query_module_dependencies",
1113
+ "annotations": {
1114
+ "readOnlyHint": True,
1115
+ "destructiveHint": False,
1116
+ "idempotentHint": True,
1117
+ "openWorldHint": False,
1118
+ },
1119
+ "tier": "T-2",
1120
+ "description": "Extracts import/export dependency graph, circular import warnings, and internal vs external modules.",
1121
+ "input_schema": {"file_path": "string"},
1122
+ },
1123
+ {
1124
+ "name": "estimate_token_cost",
1125
+ "annotations": {
1126
+ "readOnlyHint": True,
1127
+ "destructiveHint": False,
1128
+ "idempotentHint": True,
1129
+ "openWorldHint": False,
1130
+ },
1131
+ "tier": "Financial ROI",
1132
+ "description": "Compares prompt token billing across OpenAI, Anthropic, Gemini, and DeepSeek models.",
1133
+ "input_schema": {"prompt_text": "string", "models": "array"},
1134
+ },
1135
+ {
1136
+ "name": "generate_architecture_blueprint",
1137
+ "annotations": {
1138
+ "readOnlyHint": True,
1139
+ "destructiveHint": False,
1140
+ "idempotentHint": True,
1141
+ "openWorldHint": False,
1142
+ },
1143
+ "tier": "T-1 Blueprint",
1144
+ "description": "Synthesizes ARCHITECTURE.md containing auto-generated live Mermaid component diagrams.",
1145
+ "input_schema": {"format": "mermaid", "output_file": "string"},
1146
+ },
1147
+ {
1148
+ "name": "search_codebase_semantic",
1149
+ "annotations": {
1150
+ "readOnlyHint": True,
1151
+ "destructiveHint": False,
1152
+ "idempotentHint": True,
1153
+ "openWorldHint": False,
1154
+ },
1155
+ "tier": "AST BM25",
1156
+ "description": "Performs 100% private local BM25 hybrid semantic search without external cloud embedding fees.",
1157
+ "input_schema": {"query": "string", "top_k": "integer"},
1158
+ },
1159
+ {
1160
+ "name": "analyze_change_impact",
1161
+ "annotations": {
1162
+ "readOnlyHint": True,
1163
+ "destructiveHint": False,
1164
+ "idempotentHint": True,
1165
+ "openWorldHint": False,
1166
+ },
1167
+ "tier": "Blast Radius",
1168
+ "description": "Calculates downstream blast radius score (0-100) before modifying a critical class or function.",
1169
+ "input_schema": {"symbol": "string", "file": "string"},
1170
+ },
1171
+ {
1172
+ "name": "enforce_architecture_boundaries",
1173
+ "annotations": {
1174
+ "readOnlyHint": True,
1175
+ "destructiveHint": False,
1176
+ "idempotentHint": True,
1177
+ "openWorldHint": False,
1178
+ },
1179
+ "tier": "T-002",
1180
+ "description": "Validates project structure against tzero.rules.json to stop architectural erosion.",
1181
+ "input_schema": {"rules_file": "string"},
1182
+ },
1183
+ {
1184
+ "name": "find_code_duplicity",
1185
+ "annotations": {
1186
+ "readOnlyHint": True,
1187
+ "destructiveHint": False,
1188
+ "idempotentHint": True,
1189
+ "openWorldHint": False,
1190
+ },
1191
+ "tier": "T-004",
1192
+ "description": "Scans AST hash trees for duplicated or copy-pasted blocks of 6+ lines.",
1193
+ "input_schema": {"min_lines": "integer"},
1194
+ },
1195
+ {
1196
+ "name": "export_agent_rules",
1197
+ "annotations": {
1198
+ "readOnlyHint": False,
1199
+ "destructiveHint": False,
1200
+ "idempotentHint": True,
1201
+ "openWorldHint": False,
1202
+ },
1203
+ "tier": "IDE Specs",
1204
+ "description": "Exports optimized system instructions (.cursorrules, .clinerules, .windsurfrules).",
1205
+ "input_schema": {"target_ide": "cursor | cline | claude"},
1206
+ },
1207
+ ]
1208
+
1209
+ # ==================================================================================================
1210
+ # GRADIO CONTROLLERS & INTERACTION LOGIC
1211
+ # ==================================================================================================
1212
+ @spaces.GPU
1213
+ def process_code_compression(
1214
+ code_text: str,
1215
+ tier_choice: str,
1216
+ strip_docs: bool,
1217
+ mask_sec: bool,
1218
+ target_model: str,
1219
+ ) -> Tuple[str, str, str, str, str, str]:
1220
+ """ZeroGPU Accelerated AST Compression Handler."""
1221
+ if not code_text.strip():
1222
+ return (
1223
+ "/* No source code supplied. Please paste code or choose an enterprise preset. */",
1224
+ "0",
1225
+ "0",
1226
+ "0.0%",
1227
+ "$0.00 / req",
1228
+ "<div class='metric-box'><div class='metric-lbl'>STATUS</div><div class='metric-val' style='color:#94a3b8'>IDLE</div></div>",
1229
+ )
1230
+
1231
+ compressed_code, stats = ASTContextArchitect.compress_python_ast(
1232
+ code_text, tier=tier_choice, strip_docstrings=strip_docs, mask_secrets=mask_sec
1233
+ )
1234
+
1235
+ tokens_raw = ASTContextArchitect.estimate_tokens(code_text, target_model)
1236
+ tokens_compressed = ASTContextArchitect.estimate_tokens(compressed_code, target_model)
1237
+
1238
+ saved_tokens = max(0, tokens_raw - tokens_compressed)
1239
+ reduction_pct = (saved_tokens / tokens_raw * 100.0) if tokens_raw > 0 else 0.0
1240
+
1241
+ rate = MODEL_PRICING.get(target_model, MODEL_PRICING["OpenAI GPT-4o"])["input_per_m"]
1242
+ cost_raw = (tokens_raw / 1_000_000) * rate
1243
+ cost_comp = (tokens_compressed / 1_000_000) * rate
1244
+ cost_saved_per_k = ((cost_raw - cost_comp) * 1000)
1245
+
1246
+ # Dynamic status gauge
1247
+ color = "#10b981" if reduction_pct >= 90 else "#06b6d4" if reduction_pct >= 70 else "#f59e0b"
1248
+ badge_html = f"""
1249
+ <div class="metric-box" style="border-color: {color}44;">
1250
+ <div class="metric-lbl">AST TOKEN REDUCTION</div>
1251
+ <div class="metric-val" style="color: {color};">{reduction_pct:.1f}%</div>
1252
+ <div style="font-size: 11px; color: #94a3b8; margin-top: 4px;">
1253
+ Saved {saved_tokens:,} tokens ({stats.get('duration_ms', 0)}ms parse)
1254
+ </div>
1255
+ </div>
1256
+ """
1257
+
1258
+ return (
1259
+ compressed_code,
1260
+ f"{tokens_raw:,}",
1261
+ f"{tokens_compressed:,}",
1262
+ f"{reduction_pct:.1f}%",
1263
+ f"${cost_saved_per_k:.4f} / 1K calls",
1264
+ badge_html,
1265
+ )
1266
+
1267
+
1268
+ def run_security_audit_controller(code_text: str) -> Tuple[str, str, str, str]:
1269
+ """Controller for Tab 2: Security & Zero-Leak Audit Studio."""
1270
+ if not code_text.strip():
1271
+ return (
1272
+ "100",
1273
+ "<div class='metric-box'><div class='metric-val' style='color:#10b981;'>100/100</div><div class='metric-lbl'>PASSED</div></div>",
1274
+ "### No code provided to audit.",
1275
+ "No findings.",
1276
+ )
1277
+
1278
+ score, findings, metrics = SecurityQualityAuditor.run_full_audit(code_text)
1279
+
1280
+ score_color = "#10b981" if score >= 85 else "#f59e0b" if score >= 60 else "#ef4444"
1281
+ status_label = "CLEAN & SECURE" if score >= 85 else "SECURITY WARNINGS" if score >= 60 else "CRITICAL VULNERABILITIES"
1282
+
1283
+ summary_html = f"""
1284
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px; margin-bottom: 20px;">
1285
+ <div class="metric-box" style="border-color: {score_color};">
1286
+ <div class="metric-lbl">SECURITY SCORE</div>
1287
+ <div class="metric-val" style="color: {score_color};">{score}/100</div>
1288
+ <div style="font-size: 11px; font-weight:700; color:{score_color}; margin-top:4px;">{status_label}</div>
1289
+ </div>
1290
+ <div class="metric-box">
1291
+ <div class="metric-lbl">CRITICAL LEAKS</div>
1292
+ <div class="metric-val" style="color: #ef4444;">{metrics['critical_count']}</div>
1293
+ </div>
1294
+ <div class="metric-box">
1295
+ <div class="metric-lbl">HIGH RISK SMELLS</div>
1296
+ <div class="metric-val" style="color: #f59e0b;">{metrics['high_count']}</div>
1297
+ </div>
1298
+ <div class="metric-box">
1299
+ <div class="metric-lbl">TOTAL ISSUES</div>
1300
+ <div class="metric-val" style="color: #38bdf8;">{metrics['total_issues']}</div>
1301
+ </div>
1302
+ </div>
1303
+ """
1304
+
1305
+ if not findings:
1306
+ report_md = "### ✅ 100% Zero-Leak & Quality Pass\nNo hardcoded credentials, secret leaks, or structural code smells detected."
1307
+ else:
1308
+ table_rows = []
1309
+ table_rows.append("| Tier | Severity | Line | Issue Title | Recommendation |")
1310
+ table_rows.append("| :--- | :--- | :--- | :--- | :--- |")
1311
+ for f in findings:
1312
+ sev_badge = f"**<span style='color:#ef4444'>{f.severity}</span>**" if f.severity == "CRITICAL" else f"**<span style='color:#f59e0b'>{f.severity}</span>**" if f.severity == "HIGH" else f.severity
1313
+ table_rows.append(f"| `{f.tier}` | {sev_badge} | `L{f.line_no}` | **{f.title}**<br>_{f.detail}_ | {f.recommendation} |")
1314
+ report_md = "\n".join(table_rows)
1315
+
1316
+ # Detailed export markdown
1317
+ export_md = f"""# T-Zero Security Audit Report (T-001 - T-004)
1318
+ - **Timestamp:** {time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime())}
1319
+ - **Security Score:** {score} / 100
1320
+ - **Total Findings:** {len(findings)}
1321
+
1322
+ {report_md}
1323
+ """
1324
+
1325
+ return str(score), summary_html, report_md, export_md
1326
+
1327
+
1328
+ def calculate_roi_controller(
1329
+ team_size: float,
1330
+ prompts_per_day: float,
1331
+ avg_tokens: float,
1332
+ savings_pct: float,
1333
+ model_choice: str,
1334
+ ) -> Tuple[str, str, str, str, str]:
1335
+ """Controller for Tab 3: Enterprise ROI & Financial Calculator."""
1336
+ res = ROIEstimator.calculate_savings(
1337
+ int(team_size),
1338
+ int(prompts_per_day),
1339
+ int(avg_tokens),
1340
+ float(savings_pct),
1341
+ model_name=model_choice,
1342
+ )
1343
+
1344
+ monthly_savings_str = f"${res['monthly_dollar_savings']:,.2f}"
1345
+ annual_savings_str = f"${res['annual_dollar_savings']:,.2f}"
1346
+ tokens_saved_str = f"{res['monthly_tokens_saved'] / 1_000_000:,.1f} M Tokens / mo"
1347
+ carbon_str = f"{res['co2_kg_saved_annual']:,} kg CO2 / yr"
1348
+
1349
+ pricing = MODEL_PRICING.get(model_choice, MODEL_PRICING["OpenAI GPT-4o"])
1350
+
1351
+ roi_card_html = f"""
1352
+ <div class="tzero-card" style="margin-top: 10px;">
1353
+ <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 12px; margin-bottom: 16px;">
1354
+ <span style="font-weight: 700; color: #38bdf8;">FINANCIAL PROJECTION SUMMARY ({model_choice})</span>
1355
+ <span style="background: rgba(16,185,129,0.15); color: #10b981; padding: 4px 10px; border-radius: 9999px; font-size: 12px; font-weight:700;">
1356
+ {savings_pct:.0f}% TOKEN PRUNING ACTIVE
1357
+ </span>
1358
+ </div>
1359
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
1360
+ <div>
1361
+ <div style="font-size: 12px; color: #94a3b8;">Current Monthly Context Cost</div>
1362
+ <div style="font-size: 24px; font-weight: 800; color: #f43f5e;">${res['cost_before_monthly']:,.2f}</div>
1363
+ </div>
1364
+ <div>
1365
+ <div style="font-size: 12px; color: #94a3b8;">Optimized Monthly Context Cost</div>
1366
+ <div style="font-size: 24px; font-weight: 800; color: #10b981;">${res['cost_after_monthly']:,.2f}</div>
1367
+ </div>
1368
+ </div>
1369
+ <div style="margin-top: 20px; padding: 16px; background: rgba(6,182,212,0.08); border: 1px solid rgba(6,182,212,0.25); border-radius: 12px;">
1370
+ <div style="font-size: 13px; font-weight: 600; color: #38bdf8;">Estimated Annual Engineering Budget Retained:</div>
1371
+ <div style="font-size: 36px; font-weight: 800; color: #ffffff; margin-top: 4px;">{annual_savings_str}</div>
1372
+ <div style="font-size: 12px; color: #94a3b8; margin-top: 6px;">
1373
+ Equivalent to eliminating {res['annual_tokens_saved'] / 1_000_000_000:,.2f} Billion unnecessary redundant tokens from your inference pipeline.
1374
+ </div>
1375
+ </div>
1376
+ </div>
1377
+ """
1378
+
1379
+ return monthly_savings_str, annual_savings_str, tokens_saved_str, carbon_str, roi_card_html
1380
+
1381
+
1382
+ def generate_mcp_config_controller(ide_type: str) -> str:
1383
+ """Generates ready-to-paste JSON configuration for Claude Desktop or Cursor."""
1384
+ if ide_type == "Claude Desktop (claude_desktop_config.json)":
1385
+ cfg = {
1386
+ "mcpServers": {
1387
+ "tzero-mcp": {
1388
+ "command": "python",
1389
+ "args": ["-m", "tzero_mcp"],
1390
+ "env": {
1391
+ "TZERO_STRICT_SECURITY": "1",
1392
+ "TZERO_MAX_PRUNE_DEPTH": "6"
1393
+ }
1394
+ }
1395
+ }
1396
+ }
1397
+ elif ide_type == "Cursor IDE (.cursor/mcp.json)":
1398
+ cfg = {
1399
+ "mcpServers": {
1400
+ "tzero-mcp": {
1401
+ "command": "python",
1402
+ "args": ["-m", "tzero_mcp"]
1403
+ }
1404
+ }
1405
+ }
1406
+ else: # Windsurf / Generic
1407
+ cfg = {
1408
+ "mcpServers": {
1409
+ "tzero-context-architect": {
1410
+ "command": "python",
1411
+ "args": ["-m", "tzero.tzero_mcp"]
1412
+ }
1413
+ }
1414
+ }
1415
+ return json.dumps(cfg, indent=2)
1416
+
1417
+
1418
+ # ==================================================================================================
1419
+ # UI CONSTRUCTION WITH GRADIO BLOCKS
1420
+ # ==================================================================================================
1421
+ def build_tzero_gradio_app() -> gr.Blocks:
1422
+ """Builds the comprehensive multi-tab luxury web application interface."""
1423
+ with gr.Blocks(title="T-Zero | Enterprise AST Token Architect", css=CUSTOM_CSS, theme=gr.themes.Default()) as demo:
1424
+ # Top Global Hero Banner
1425
+ gr.HTML(f"""
1426
+ <div style="display: flex; justify-content: space-between; align-items: center; padding: 20px 0; border-bottom: 1px solid rgba(255,255,255,0.08); margin-bottom: 24px;">
1427
+ <div>
1428
+ <div class="tzero-header-badge">
1429
+ <span class="tzero-live-indicator"></span>
1430
+ <span>T-ZERO ALGORITHM v{APP_VERSION}</span>
1431
+ <span style="color: rgba(255,255,255,0.3);">|</span>
1432
+ <span style="color: #10b981;">NVIDIA RTX 6000 ZERO-GPU READY</span>
1433
+ </div>
1434
+ <h1 style="font-size: 34px; margin: 12px 0 6px 0;" class="tzero-title-glow">
1435
+ Enterprise AI Context Architect & AST Compressor
1436
+ </h1>
1437
+ <p style="font-size: 14.5px; color: #94a3b8; margin: 0; max-width: 820px; line-height: 1.5;">
1438
+ Eliminate up to <strong style="color: #38bdf8;">95% of prompt tokens</strong> when feeding large codebases into LLMs.
1439
+ Pure Python AST analysis, 100% Zero-Leak offline security, and high-order context engineering.
1440
+ </p>
1441
+ </div>
1442
+ <div style="display: flex; gap: 10px; align-items: center;">
1443
+ <a href="{VERCEL_URL}" target="_blank" style="text-decoration: none;">
1444
+ <button style="background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.15); color: #f8fafc; padding: 10px 18px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer; transition: all 0.2s;">
1445
+ 🌐 Live Benchmark
1446
+ </button>
1447
+ </a>
1448
+ <a href="{REPO_URL}" target="_blank" style="text-decoration: none;">
1449
+ <button style="background: #ffffff; color: #000000; border: none; padding: 10px 20px; border-radius: 10px; font-size: 13px; font-weight: 700; cursor: pointer; display: flex; align-items: center; gap: 8px;">
1450
+ <svg height="16" width="16" viewBox="0 0 16 16" fill="currentColor"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg>
1451
+ Star on GitHub
1452
+ </button>
1453
+ </a>
1454
+ </div>
1455
+ </div>
1456
+ """)
1457
+
1458
+ # Main Navigation Tabs
1459
+ with gr.Tabs():
1460
+ # ======================================================================================
1461
+ # TAB 1: AST TOKEN REDUCTION & CONTEXT ARCHITECT
1462
+ # ======================================================================================
1463
+ with gr.TabItem("⚡ AST Token Reducer", id="tab_reducer"):
1464
+ with gr.Row():
1465
+ # Left Column: Configuration & Input
1466
+ with gr.Column(scale=5):
1467
+ gr.HTML("<h4>1. Source Code Input</h4>")
1468
+
1469
+ # Presets Selector
1470
+ with gr.Row():
1471
+ preset_btn_banking = gr.Button("🏦 Enterprise Banking", size="sm")
1472
+ preset_btn_gateway = gr.Button("🌐 Microservices API", size="sm")
1473
+ preset_btn_quant = gr.Button("📈 Quant Matcher", size="sm")
1474
+ clear_code_btn = gr.Button("🧹 Clear", size="sm")
1475
+
1476
+ input_code_box = gr.Code(
1477
+ value=PRESET_BANKING_CORE,
1478
+ language="python",
1479
+ label="Raw Source Code (Paste your file or module)",
1480
+ lines=20,
1481
+ )
1482
+
1483
+ with gr.Accordion("⚙️ AST Compression Parameters", open=True):
1484
+ with gr.Row():
1485
+ tier_dropdown = gr.Dropdown(
1486
+ choices=[
1487
+ "T-1 Topology",
1488
+ "T-2 Dependencies",
1489
+ "T-3 AST Signatures",
1490
+ "T-4 All Tiers",
1491
+ ],
1492
+ value="T-3 AST Signatures",
1493
+ label="T-Zero Compression Tier",
1494
+ )
1495
+ model_eval_dropdown = gr.Dropdown(
1496
+ choices=list(MODEL_PRICING.keys()),
1497
+ value="OpenAI GPT-4o",
1498
+ label="Target Inference Model",
1499
+ )
1500
+ with gr.Row():
1501
+ strip_docstrings_check = gr.Checkbox(
1502
+ label="Strip Method Docstrings (Max Token Reduction)",
1503
+ value=False,
1504
+ )
1505
+ mask_secrets_check = gr.Checkbox(
1506
+ label="Enforce T-001 Zero-Leak Secret Masking",
1507
+ value=True,
1508
+ )
1509
+
1510
+ compress_btn = gr.Button("⚡ Run T-Zero AST Pruning", variant="primary", elem_classes=["tzero-btn-primary"])
1511
+
1512
+ # Right Column: Output & Live Real-Time Analytics
1513
+ with gr.Column(scale=5):
1514
+ gr.HTML("<h4>2. Compressed T-Zero Context</h4>")
1515
+
1516
+ # Live Analytics Metric Cards
1517
+ with gr.Row():
1518
+ token_raw_stat = gr.Textbox(label="Raw Tokens", value="824", interactive=False)
1519
+ token_comp_stat = gr.Textbox(label="T-Zero Tokens", value="74", interactive=False)
1520
+ pct_stat = gr.Textbox(label="Net Savings", value="91.0%", interactive=False)
1521
+ cost_stat = gr.Textbox(label="Cost Savings Rate", value="$1.87 / 1K", interactive=False)
1522
+
1523
+ gauge_html_box = gr.HTML(
1524
+ """
1525
+ <div class="metric-box" style="border-color: #10b98144;">
1526
+ <div class="metric-lbl">AST TOKEN REDUCTION</div>
1527
+ <div class="metric-val" style="color: #10b981;">91.0%</div>
1528
+ <div style="font-size: 11px; color: #94a3b8; margin-top: 4px;">Verified Pure Python AST Contract</div>
1529
+ </div>
1530
+ """
1531
+ )
1532
+
1533
+ output_context_box = gr.Code(
1534
+ language="python",
1535
+ label="Optimized AST System Context (Ready for LLM Prompt)",
1536
+ lines=20,
1537
+ )
1538
+
1539
+ # Tab 1 Event Bindings
1540
+ preset_btn_banking.click(lambda: PRESET_BANKING_CORE, None, input_code_box)
1541
+ preset_btn_gateway.click(lambda: PRESET_MICROSERVICE_GATEWAY, None, input_code_box)
1542
+ preset_btn_quant.click(lambda: PRESET_QUANT_TRADING, None, input_code_box)
1543
+ clear_code_btn.click(lambda: "", None, input_code_box)
1544
+
1545
+ compress_btn.click(
1546
+ fn=process_code_compression,
1547
+ inputs=[
1548
+ input_code_box,
1549
+ tier_dropdown,
1550
+ strip_docstrings_check,
1551
+ mask_secrets_check,
1552
+ model_eval_dropdown,
1553
+ ],
1554
+ outputs=[
1555
+ output_context_box,
1556
+ token_raw_stat,
1557
+ token_comp_stat,
1558
+ pct_stat,
1559
+ cost_stat,
1560
+ gauge_html_box,
1561
+ ],
1562
+ )
1563
+
1564
+ # ======================================================================================
1565
+ # TAB 2: ZERO-LEAK SECURITY & CODE QUALITY AUDITOR (T-001..T-004)
1566
+ # ======================================================================================
1567
+ with gr.TabItem("🛡️ Zero-Leak Security Studio", id="tab_security"):
1568
+ gr.HTML("""
1569
+ <div style="margin-bottom: 16px;">
1570
+ <h3 style="margin: 0; color: #f8fafc;">Enterprise Static Analysis & Credential Sanitizer</h3>
1571
+ <p style="color: #94a3b8; font-size: 13.5px; margin: 4px 0 0 0;">
1572
+ Guarantees 100% Zero-Leak security compliance. Identifies hardcoded API tokens, database passwords,
1573
+ cyclomatic complexity traps, and architectural layer breaches before AI prompt exposure.
1574
+ </p>
1575
+ </div>
1576
+ """)
1577
+
1578
+ with gr.Row():
1579
+ with gr.Column(scale=5):
1580
+ audit_input_box = gr.Code(
1581
+ value=PRESET_BANKING_CORE,
1582
+ language="python",
1583
+ label="Source Code to Audit",
1584
+ lines=18,
1585
+ )
1586
+ run_audit_btn = gr.Button("🛡️ Perform Zero-Leak & Smell Audit", variant="primary")
1587
+
1588
+ with gr.Column(scale=5):
1589
+ audit_score_hidden = gr.Textbox(visible=False)
1590
+ audit_summary_html = gr.HTML(
1591
+ """
1592
+ <div class="metric-box">
1593
+ <div class="metric-lbl">SECURITY AUDITOR READY</div>
1594
+ <div class="metric-val" style="color:#38bdf8;">CLICK AUDIT</div>
1595
+ </div>
1596
+ """
1597
+ )
1598
+ audit_findings_markdown = gr.Markdown("### Click 'Perform Zero-Leak Audit' to inspect code.")
1599
+
1600
+ with gr.Accordion("📄 Full Markdown Audit Export", open=False):
1601
+ audit_export_box = gr.TextArea(lines=10, label="Exportable Report (Markdown)")
1602
+
1603
+ run_audit_btn.click(
1604
+ fn=run_security_audit_controller,
1605
+ inputs=[audit_input_box],
1606
+ outputs=[audit_score_hidden, audit_summary_html, audit_findings_markdown, audit_export_box],
1607
+ )
1608
+
1609
+ # ======================================================================================
1610
+ # TAB 3: MULTI-MODEL ROI & FINANCIAL SAVINGS CALCULATOR
1611
+ # ======================================================================================
1612
+ with gr.TabItem("💰 Financial ROI Simulator", id="tab_roi"):
1613
+ gr.HTML("""
1614
+ <div style="margin-bottom: 20px;">
1615
+ <h3 style="margin: 0; color: #f8fafc;">Quantitative Token Economy & Budget Calculator</h3>
1616
+ <p style="color: #94a3b8; font-size: 13.5px; margin: 4px 0 0 0;">
1617
+ Estimate monthly financial return on investment (ROI) across developer team scale and AI coding agents.
1618
+ </p>
1619
+ </div>
1620
+ """)
1621
+
1622
+ with gr.Row():
1623
+ with gr.Column(scale=4):
1624
+ roi_model_dropdown = gr.Dropdown(
1625
+ choices=list(MODEL_PRICING.keys()),
1626
+ value="OpenAI GPT-4o",
1627
+ label="Target LLM API",
1628
+ )
1629
+ roi_team_slider = gr.Slider(
1630
+ minimum=1, maximum=500, value=25, step=1, label="Active Engineering Team Size"
1631
+ )
1632
+ roi_prompts_slider = gr.Slider(
1633
+ minimum=5, maximum=150, value=40, step=5, label="Prompts / Queries per Dev per Day"
1634
+ )
1635
+ roi_tokens_slider = gr.Slider(
1636
+ minimum=5000,
1637
+ maximum=250000,
1638
+ value=60000,
1639
+ step=5000,
1640
+ label="Average Codebase Prompt Size (Raw Tokens)",
1641
+ )
1642
+ roi_savings_slider = gr.Slider(
1643
+ minimum=70.0,
1644
+ maximum=96.0,
1645
+ value=94.5,
1646
+ step=0.5,
1647
+ label="T-Zero AST Compression Efficiency (%)",
1648
+ )
1649
+
1650
+ with gr.Column(scale=6):
1651
+ with gr.Row():
1652
+ roi_monthly_val = gr.Textbox(label="Estimated Monthly Savings", value="$59,094.00", interactive=False)
1653
+ roi_annual_val = gr.Textbox(label="Projected Annual Savings", value="$709,128.00", interactive=False)
1654
+
1655
+ with gr.Row():
1656
+ roi_tokens_val = gr.Textbox(label="Monthly Tokens Saved", value="23.6 B Tokens", interactive=False)
1657
+ roi_carbon_val = gr.Textbox(label="Carbon Footprint Offset", value="2,836 kg CO2", interactive=False)
1658
+
1659
+ roi_html_output = gr.HTML()
1660
+
1661
+ # Wire ROI Calculator auto-updates
1662
+ roi_inputs = [
1663
+ roi_team_slider,
1664
+ roi_prompts_slider,
1665
+ roi_tokens_slider,
1666
+ roi_savings_slider,
1667
+ roi_model_dropdown,
1668
+ ]
1669
+ roi_outputs = [
1670
+ roi_monthly_val,
1671
+ roi_annual_val,
1672
+ roi_tokens_val,
1673
+ roi_carbon_val,
1674
+ roi_html_output,
1675
+ ]
1676
+
1677
+ for comp in roi_inputs:
1678
+ comp.change(fn=calculate_roi_controller, inputs=roi_inputs, outputs=roi_outputs)
1679
+
1680
+ demo.load(fn=calculate_roi_controller, inputs=roi_inputs, outputs=roi_outputs)
1681
+
1682
+ # ======================================================================================
1683
+ # TAB 4: MCP (MODEL CONTEXT PROTOCOL) 20-TOOL REGISTRY
1684
+ # ======================================================================================
1685
+ with gr.TabItem("🔌 MCP Tool Showcase", id="tab_mcp"):
1686
+ gr.HTML("""
1687
+ <div style="margin-bottom: 16px;">
1688
+ <h3 style="margin: 0; color: #f8fafc;">Model Context Protocol (MCP) Official Specification</h3>
1689
+ <p style="color: #94a3b8; font-size: 13.5px; margin: 4px 0 0 0;">
1690
+ T-Zero ships with 21 canonical MCP tools and 58 tools in full mode. Connect Claude Desktop, Cursor IDE, or Windsurf directly to local AST indexers.
1691
+ </p>
1692
+ </div>
1693
+ """)
1694
+
1695
+ with gr.Row():
1696
+ with gr.Column(scale=5):
1697
+ gr.HTML("<h4>Integrated MCP Tools</h4>")
1698
+ tools_table_md = "| Tool Identifier | Tier | Description |\n| :--- | :--- | :--- |\n"
1699
+ for tool in MCP_TOOLS_CATALOG:
1700
+ tools_table_md += f"| `{tool['name']}` | `{tool['tier']}` | {tool['description']} |\n"
1701
+ gr.Markdown(tools_table_md)
1702
+
1703
+ with gr.Column(scale=5):
1704
+ gr.HTML("<h4>Client Auto-Configuration</h4>")
1705
+ ide_select = gr.Radio(
1706
+ choices=[
1707
+ "Claude Desktop (claude_desktop_config.json)",
1708
+ "Cursor IDE (.cursor/mcp.json)",
1709
+ "Windsurf / Generic IDE",
1710
+ ],
1711
+ value="Claude Desktop (claude_desktop_config.json)",
1712
+ label="Target IDE / Client Environment",
1713
+ )
1714
+ mcp_config_output = gr.Code(
1715
+ value=generate_mcp_config_controller("Claude Desktop (claude_desktop_config.json)"),
1716
+ language="json",
1717
+ label="Configuration Payload",
1718
+ lines=12,
1719
+ )
1720
+ ide_select.change(fn=generate_mcp_config_controller, inputs=[ide_select], outputs=[mcp_config_output])
1721
+
1722
+ # ======================================================================================
1723
+ # TAB 5: LIVE BENCHMARK & VERIFIED METRICS
1724
+ # ======================================================================================
1725
+ with gr.TabItem("📊 Verified Benchmark Data", id="tab_benchmark"):
1726
+ gr.HTML(f"""
1727
+ <div class="tzero-card">
1728
+ <h3 style="color: #38bdf8; margin-top: 0;">Empirical Benchmark on Production Codebases</h3>
1729
+ <p style="color: #94a3b8; font-size: 14px;">
1730
+ The following metrics are derived from exact tokenization tests executed on the active T-Zero core repository
1731
+ (Python 3.12, tiktoken cl100k_base tokenizer).
1732
+ </p>
1733
+ <table style="width: 100%; border-collapse: collapse; margin-top: 16px; font-size: 13.5px;">
1734
+ <thead>
1735
+ <tr style="border-bottom: 2px solid rgba(255,255,255,0.15); text-align: left; color: #f8fafc;">
1736
+ <th style="padding: 10px;">Target File</th>
1737
+ <th style="padding: 10px;">Raw Size</th>
1738
+ <th style="padding: 10px;">Raw Tokens</th>
1739
+ <th style="padding: 10px;">T-Zero AST Context</th>
1740
+ <th style="padding: 10px;">Optimized Tokens</th>
1741
+ <th style="padding: 10px; color: #10b981;">Net Reduction</th>
1742
+ </tr>
1743
+ </thead>
1744
+ <tbody>
1745
+ <tr style="border-bottom: 1px solid rgba(255,255,255,0.06);">
1746
+ <td style="padding: 12px; font-family: 'JetBrains Mono';">tzero_v3.py</td>
1747
+ <td style="padding: 12px;">311.7 KB</td>
1748
+ <td style="padding: 12px;">79,531</td>
1749
+ <td style="padding: 12px; font-weight: 700; color: #38bdf8;">18.8 KB</td>
1750
+ <td style="padding: 12px; font-weight: 700; color: #38bdf8;">4,794</td>
1751
+ <td style="padding: 12px; font-weight: 800; color: #10b981;">93.97%</td>
1752
+ </tr>
1753
+ <tr style="border-bottom: 1px solid rgba(255,255,255,0.06);">
1754
+ <td style="padding: 12px; font-family: 'JetBrains Mono';">tzero_features.py</td>
1755
+ <td style="padding: 12px;">50.0 KB</td>
1756
+ <td style="padding: 12px;">12,410</td>
1757
+ <td style="padding: 12px; font-weight: 700; color: #38bdf8;">3.2 KB</td>
1758
+ <td style="padding: 12px; font-weight: 700; color: #38bdf8;">794</td>
1759
+ <td style="padding: 12px; font-weight: 800; color: #10b981;">93.60%</td>
1760
+ </tr>
1761
+ <tr style="border-bottom: 1px solid rgba(255,255,255,0.06);">
1762
+ <td style="padding: 12px; font-family: 'JetBrains Mono';">tzero_mcp.py</td>
1763
+ <td style="padding: 12px;">47.9 KB</td>
1764
+ <td style="padding: 12px;">11,850</td>
1765
+ <td style="padding: 12px; font-weight: 700; color: #38bdf8;">3.1 KB</td>
1766
+ <td style="padding: 12px; font-weight: 700; color: #38bdf8;">770</td>
1767
+ <td style="padding: 12px; font-weight: 800; color: #10b981;">93.50%</td>
1768
+ </tr>
1769
+ </tbody>
1770
+ </table>
1771
+ <div style="margin-top: 24px; display: flex; gap: 12px;">
1772
+ <a href="{VERCEL_URL}" target="_blank">
1773
+ <button class="tzero-btn-primary" style="cursor: pointer;">
1774
+ 🚀 Open Interactive Vercel Visualizer
1775
+ </button>
1776
+ </a>
1777
+ <a href="{REPO_URL}" target="_blank">
1778
+ <button style="background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.2); color: white; padding: 14px 24px; border-radius: 12px; font-weight: 700; cursor: pointer;">
1779
+ 📖 Inspect CITATION.cff & Docs
1780
+ </button>
1781
+ </a>
1782
+ </div>
1783
+ </div>
1784
+ """)
1785
+
1786
+ # Footer
1787
+ gr.HTML(f"""
1788
+ <div style="text-align: center; padding: 30px 0 10px 0; border-top: 1px solid rgba(255,255,255,0.06); margin-top: 30px; font-size: 13px; color: #64748b;">
1789
+ T-Zero Algorithm v{APP_VERSION} • 100% Free Open Source Software • Licensed under MIT<br>
1790
+ Authored by <strong style="color: #94a3b8;">Toprak Ahmet Aydoğmuş</strong> •
1791
+ <a href="{REPO_URL}" target="_blank" style="color: #38bdf8; text-decoration: none;">GitHub</a> •
1792
+ <a href="{VERCEL_URL}" target="_blank" style="color: #38bdf8; text-decoration: none;">Benchmark Gateway</a> •
1793
+ <a href="{SPACE_URL}" target="_blank" style="color: #38bdf8; text-decoration: none;">Hugging Face Space</a>
1794
+ </div>
1795
+ """)
1796
+
1797
+ return demo
1798
+
1799
+
1800
+ # ==================================================================================================
1801
+ # APPLICATION ENTRYPOINT
1802
+ # ==================================================================================================
1803
+ if __name__ == "__main__":
1804
+ app = build_tzero_gradio_app()
1805
+ # Launch with public accessibility if in container/cloud
1806
+ app.queue().launch(
1807
+ server_name="0.0.0.0",
1808
+ server_port=7860,
1809
+ show_error=True,
1810
+ )