tzero-mcp 11.0.0 → 11.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +56 -56
  2. package/CONTRIBUTING.md +71 -71
  3. package/LICENSE +21 -21
  4. package/README.md +64 -64
  5. package/bin/tzero-mcp.js +62 -62
  6. package/bin/tzero.js +61 -61
  7. package/index.d.ts +25 -25
  8. package/index.js +15 -15
  9. package/package.json +89 -88
  10. package/src/addmcp.py +1203 -1197
  11. package/src/app.py +1810 -1810
  12. package/src/main.py +60 -60
  13. package/src/pc_fixer_mcp.py +25 -25
  14. package/src/tzero/__init__.py +54 -54
  15. package/src/tzero/__main__.py +6 -6
  16. package/src/tzero/siber_akademi_icon.py +77 -77
  17. package/src/tzero/tzero_arch_test.py +463 -463
  18. package/src/tzero/tzero_benchmark.py +475 -475
  19. package/src/tzero/tzero_blackboard.py +257 -257
  20. package/src/tzero/tzero_bridge.py +546 -546
  21. package/src/tzero/tzero_budget.py +195 -195
  22. package/src/tzero/tzero_card.py +431 -0
  23. package/src/tzero/tzero_ci.py +153 -153
  24. package/src/tzero/tzero_commit.py +192 -192
  25. package/src/tzero/tzero_contracts.py +1093 -1093
  26. package/src/tzero/tzero_cost.py +166 -166
  27. package/src/tzero/tzero_dashboard.py +1960 -1960
  28. package/src/tzero/tzero_debt.py +461 -461
  29. package/src/tzero/tzero_deps.py +462 -462
  30. package/src/tzero/tzero_drift.py +208 -208
  31. package/src/tzero/tzero_explain.py +306 -306
  32. package/src/tzero/tzero_features.py +3024 -3024
  33. package/src/tzero/tzero_federation.py +299 -299
  34. package/src/tzero/tzero_fix.py +557 -228
  35. package/src/tzero/tzero_fixer/__init__.py +63 -63
  36. package/src/tzero/tzero_fixer/amalgamation.py +334 -334
  37. package/src/tzero/tzero_fixer/ast_syntax_healer.py +464 -464
  38. package/src/tzero/tzero_fixer/ast_type_modernizer.py +288 -288
  39. package/src/tzero/tzero_fixer/async_io_modernizer.py +127 -127
  40. package/src/tzero/tzero_fixer/automated_regression_suite.py +600 -600
  41. package/src/tzero/tzero_fixer/benchmarks_and_diagnostics.py +174 -174
  42. package/src/tzero/tzero_fixer/ci_cd_self_healing_gate.py +246 -246
  43. package/src/tzero/tzero_fixer/code_duplicity_and_refactorer.py +151 -151
  44. package/src/tzero/tzero_fixer/code_smells_healer.py +260 -260
  45. package/src/tzero/tzero_fixer/cwe_remediator.py +171 -171
  46. package/src/tzero/tzero_fixer/dead_code_eliminator.py +150 -150
  47. package/src/tzero/tzero_fixer/dependency_vulnerability_auditor.py +309 -309
  48. package/src/tzero/tzero_fixer/git_advanced_surgeon.py +280 -280
  49. package/src/tzero/tzero_fixer/hardware_and_disk_doctor.py +325 -325
  50. package/src/tzero/tzero_fixer/import_graph_healer.py +412 -412
  51. package/src/tzero/tzero_fixer/interactive_tui.py +91 -91
  52. package/src/tzero/tzero_fixer/knowledge_base.py +295 -295
  53. package/src/tzero/tzero_fixer/knowledge_base_extended.py +940 -940
  54. package/src/tzero/tzero_fixer/linters_and_static_analyzer.py +307 -307
  55. package/src/tzero/tzero_fixer/mcp_server.py +489 -489
  56. package/src/tzero/tzero_fixer/models.py +385 -385
  57. package/src/tzero/tzero_fixer/orchestrator.py +375 -375
  58. package/src/tzero/tzero_fixer/os_doctor.py +502 -502
  59. package/src/tzero/tzero_fixer/packaging_abi_surgeon.py +323 -323
  60. package/src/tzero/tzero_fixer/pc_fixer_doctor.py +600 -600
  61. package/src/tzero/tzero_fixer/performance_and_memory_profiler.py +274 -274
  62. package/src/tzero/tzero_fixer/polyglot_ast_parsers.py +313 -313
  63. package/src/tzero/tzero_fixer/polyglot_build_healer.py +364 -364
  64. package/src/tzero/tzero_fixer/polyglot_config_healer.py +318 -318
  65. package/src/tzero/tzero_fixer/polyglot_doctor.py +372 -372
  66. package/src/tzero/tzero_fixer/polyglot_linters.py +619 -619
  67. package/src/tzero/tzero_fixer/polyglot_schema_validator.py +305 -305
  68. package/src/tzero/tzero_fixer/security_cwe_database.py +444 -444
  69. package/src/tzero/tzero_fixer/security_deep_rules.py +114 -114
  70. package/src/tzero/tzero_fixer/security_rules_catalog.py +110 -110
  71. package/src/tzero/tzero_fixer/security_zero_leak.py +326 -326
  72. package/src/tzero/tzero_fixer/smart_patch_recommender.py +223 -223
  73. package/src/tzero/tzero_fixer/synthetic_workspace_generator.py +220 -220
  74. package/src/tzero/tzero_fixer/system_diagnostics_extended.py +493 -493
  75. package/src/tzero/tzero_fixer/system_repair_recipes.py +447 -447
  76. package/src/tzero/tzero_fixer/venv_doctor.py +309 -309
  77. package/src/tzero/tzero_golden.py +319 -319
  78. package/src/tzero/tzero_graph_hud.html +338 -338
  79. package/src/tzero/tzero_graph_rag.py +263 -263
  80. package/src/tzero/tzero_growth.py +415 -0
  81. package/src/tzero/tzero_guard.py +251 -243
  82. package/src/tzero/tzero_hooks.py +565 -565
  83. package/src/tzero/tzero_infra.py +274 -274
  84. package/src/tzero/tzero_jarvis/__init__.py +134 -124
  85. package/src/tzero/tzero_jarvis/causal_graph.py +310 -310
  86. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  87. package/src/tzero/tzero_jarvis/graph_visualizer.py +395 -395
  88. package/src/tzero/tzero_jarvis/hybrid_search.py +214 -214
  89. package/src/tzero/tzero_jarvis/latent_press.py +137 -137
  90. package/src/tzero/tzero_jarvis/memory_consolidation.py +212 -212
  91. package/src/tzero/tzero_jarvis/minhash_lsh.py +184 -184
  92. package/src/tzero/tzero_jarvis/orchestrator.py +335 -335
  93. package/src/tzero/tzero_jarvis/self_healing.py +308 -308
  94. package/src/tzero/tzero_jarvis/semantic_compressor.py +887 -887
  95. package/src/tzero/tzero_jarvis/swarm.py +261 -261
  96. package/src/tzero/tzero_jarvis/swarm_bft.py +144 -144
  97. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1167 -1167
  98. package/src/tzero/tzero_jarvis/zero_key_router.py +173 -173
  99. package/src/tzero/tzero_lsp.py +634 -634
  100. package/src/tzero/tzero_mcp.py +5314 -5237
  101. package/src/tzero/tzero_mutation.py +358 -358
  102. package/src/tzero/tzero_neural_cortex.py +1425 -1425
  103. package/src/tzero/tzero_packer.py +577 -577
  104. package/src/tzero/tzero_patch.py +624 -624
  105. package/src/tzero/tzero_pc_fixer.py +12699 -12699
  106. package/src/tzero/tzero_pipe.py +95 -95
  107. package/src/tzero/tzero_polyglot.py +799 -799
  108. package/src/tzero/tzero_proxy.py +127 -127
  109. package/src/tzero/tzero_reachability.py +272 -272
  110. package/src/tzero/tzero_replay.py +141 -141
  111. package/src/tzero/tzero_rust_bridge.py +198 -198
  112. package/src/tzero/tzero_scip.py +368 -368
  113. package/src/tzero/tzero_security.py +573 -573
  114. package/src/tzero/tzero_semantic_merge.py +189 -189
  115. package/src/tzero/tzero_snapshot.py +471 -471
  116. package/src/tzero/tzero_stubs.py +313 -313
  117. package/src/tzero/tzero_subagent_engine.py +459 -459
  118. package/src/tzero/tzero_superdesign.py +774 -774
  119. package/src/tzero/tzero_sync.py +241 -241
  120. package/src/tzero/tzero_task_benchmark.py +506 -458
  121. package/src/tzero/tzero_tui.py +313 -313
  122. package/src/tzero/tzero_turbo.py +264 -264
  123. package/src/tzero/tzero_v3.py +9997 -9900
  124. package/src/tzero.py +6 -6
  125. package/src/tzero_mcp.py +25 -0
  126. package/test/package.test.js +55 -55
@@ -1,458 +1,506 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- T-Zero Task-Completion & Real Tokenizer Benchmark Engine
4
- =========================================================
5
- Empirically benchmarks token reduction and task-completion correctness
6
- comparing Raw Codebase Ingestion against T-Zero Tier-2 Smart Skeletons.
7
- Uses official BPE tokenizer (tiktoken cl100k_base / o200k_base) for exact token counts.
8
-
9
- Author: Siber Akademi (Toprak Ahmet Aydoğmuş)
10
- License: MIT
11
- """
12
-
13
- import ast
14
- import json
15
- import os
16
- import re
17
- import sys
18
- import time
19
- import urllib.error
20
- import urllib.request
21
- from dataclasses import dataclass, field, asdict
22
- from typing import Dict, List, Any, Optional
23
-
24
- try:
25
- import tiktoken
26
- TIKTOKEN_AVAILABLE = True
27
- except ImportError:
28
- tiktoken = None
29
- TIKTOKEN_AVAILABLE = False
30
-
31
-
32
- def count_bpe_tokens(text: str, model_encoding: str = "cl100k_base") -> int:
33
- """Calculates exact BPE tokens using tiktoken if available, else standard char/4 fallback."""
34
- if TIKTOKEN_AVAILABLE and tiktoken is not None:
35
- try:
36
- enc = tiktoken.get_encoding(model_encoding)
37
- return len(enc.encode(text, disallowed_special=()))
38
- except Exception:
39
- pass
40
- return max(1, len(text) // 4)
41
-
42
-
43
- @dataclass
44
- class TaskEvaluationResult:
45
- task_id: str
46
- task_title: str
47
- raw_bpe_tokens: int
48
- tzero_bpe_tokens: int
49
- token_savings_pct: float
50
- signature_contract_retention_pct: float
51
- syntax_valid: bool
52
- hallucination_count: int
53
- task_success: bool
54
- latency_ms: float
55
- description: str
56
-
57
-
58
- @dataclass
59
- class TaskBenchmarkReport:
60
- version: str = "11.0.0"
61
- tokenizer: str = "tiktoken (cl100k_base)" if TIKTOKEN_AVAILABLE else "character-ratio fallback"
62
- total_tasks: int = 0
63
- passed_tasks: int = 0
64
- success_rate_pct: float = 0.0
65
- average_token_reduction_pct: float = 0.0
66
- total_raw_tokens: int = 0
67
- total_tzero_tokens: int = 0
68
- results: List[TaskEvaluationResult] = field(default_factory=list)
69
-
70
-
71
- class TaskCompletionBenchmark:
72
- """
73
- Evaluates whether an AI coding agent with signature-only surrounding context
74
- (T-Zero Tier-2 Smart Skeleton) can successfully synthesize correct, valid,
75
- and non-hallucinated code compared to raw full-file context ingestion.
76
- """
77
-
78
- TASKS = [
79
- {
80
- "id": "TASK-01",
81
- "title": "Cross-Module Token Bucket Rate Limiter",
82
- "description": "Implement rate limiting middleware calling RedisSessionStore, MetricsCollector, and AuditLogger.",
83
- "dependency_code": '''
84
- class RedisSessionStore:
85
- """Handles high-throughput distributed session state."""
86
- def __init__(self, cluster_url: str, pool_size: int = 20, timeout_ms: int = 500):
87
- self.cluster_url = cluster_url
88
- self.pool_size = pool_size
89
- self.timeout_ms = timeout_ms
90
- self._connected = True
91
- self._cache = {}
92
-
93
- def get_token_quota(self, client_id: str) -> int:
94
- """Retrieves remaining token quota for client."""
95
- # Simulated complex implementation (50 lines)
96
- val = self._cache.get(client_id, 1000)
97
- for i in range(10):
98
- val = max(0, val - 1)
99
- return val
100
-
101
- def decrement_quota(self, client_id: str, tokens: int = 1) -> bool:
102
- """Atomically decrements quota by specified tokens."""
103
- curr = self.get_token_quota(client_id)
104
- if curr >= tokens:
105
- self._cache[client_id] = curr - tokens
106
- return True
107
- return False
108
-
109
- class MetricsCollector:
110
- """Emits OpenTelemetry compliant counters and histograms."""
111
- def record_latency(self, metric_name: str, duration_ms: float, tags: dict = None) -> None:
112
- """Records latency in milliseconds."""
113
- pass
114
-
115
- def increment_counter(self, counter_name: str, value: int = 1, labels: dict = None) -> None:
116
- """Increments dimensional metric counter."""
117
- pass
118
-
119
- class AuditLogger:
120
- """Enterprise zero-leak audit logging engine."""
121
- def log_security_event(self, event_type: str, actor_id: str, severity: str = "INFO") -> None:
122
- """Appends tamper-evident security record."""
123
- pass
124
- ''',
125
- "focus_prompt": "Synthesize a client rate-limiter function using RedisSessionStore, MetricsCollector, and AuditLogger.",
126
- "target_implementation": '''
127
- def enforce_rate_limit(client_id: str, store: RedisSessionStore, metrics: MetricsCollector, audit: AuditLogger) -> bool:
128
- """Validates and decrements token quota while recording audit events."""
129
- quota = store.get_token_quota(client_id)
130
- if quota <= 0:
131
- audit.log_security_event("RATE_LIMIT_EXCEEDED", client_id, severity="WARNING")
132
- metrics.increment_counter("rate_limit_blocks", 1, {"client": client_id})
133
- return False
134
- store.decrement_quota(client_id, 1)
135
- metrics.increment_counter("rate_limit_allows", 1, {"client": client_id})
136
- return True
137
- '''
138
- },
139
- {
140
- "id": "TASK-02",
141
- "title": "Crypto Vault Key Rotation & Signature Verification",
142
- "description": "Rotate encryption keys and sign payloads using KeyringVault and HMACEngine.",
143
- "dependency_code": '''
144
- class KeyringVault:
145
- """Interfaces with platform credential manager."""
146
- def __init__(self, service_name: str = "tzero_vault"):
147
- self.service_name = service_name
148
- self._keys = {}
149
-
150
- def get_active_signing_key(self, key_id: str) -> bytes:
151
- """Retrieves cryptographically secure key material."""
152
- return b"sec_master_key_990_deterministic_bytes_fixed"
153
-
154
- def rotate_key(self, key_id: str, new_material: bytes) -> bool:
155
- """Rotates key material atomically."""
156
- self._keys[key_id] = new_material
157
- return True
158
-
159
- class HMACEngine:
160
- """Deterministic HMAC-SHA256 signature generator."""
161
- def generate_digest(self, secret_key: bytes, payload: bytes) -> str:
162
- """Computes hexadecimal digest."""
163
- import hashlib, hmac
164
- return hmac.new(secret_key, payload, hashlib.sha256).hexdigest()
165
-
166
- def verify_digest(self, secret_key: bytes, payload: bytes, expected_digest: str) -> bool:
167
- """Constant-time verification of digest."""
168
- computed = self.generate_digest(secret_key, payload)
169
- import hmac
170
- return hmac.compare_digest(computed, expected_digest)
171
- ''',
172
- "focus_prompt": "Implement sign_and_record_payload function using KeyringVault and HMACEngine.",
173
- "target_implementation": '''
174
- def sign_and_record_payload(payload_bytes: bytes, key_id: str, vault: KeyringVault, hmac_eng: HMACEngine) -> str:
175
- """Signs payload using active key from vault."""
176
- signing_key = vault.get_active_signing_key(key_id)
177
- digest = hmac_eng.generate_digest(signing_key, payload_bytes)
178
- return digest
179
- '''
180
- },
181
- {
182
- "id": "TASK-03",
183
- "title": "AST Slicer & Blast Radius Impact Assessment",
184
- "description": "Calculate downstream dependent blast radius using CallGraphDAG and SymbolTable.",
185
- "dependency_code": '''
186
- class SymbolTable:
187
- """Maintains indexed AST symbol hierarchy."""
188
- def __init__(self):
189
- self.symbols = {}
190
-
191
- def lookup_symbol(self, symbol_path: str) -> Optional[dict]:
192
- """Resolves symbol metadata by qualified name."""
193
- return self.symbols.get(symbol_path)
194
-
195
- def register_symbol(self, symbol_path: str, meta: dict) -> None:
196
- """Registers a symbol in the table."""
197
- self.symbols[symbol_path] = meta
198
-
199
- class CallGraphDAG:
200
- """Directed acyclic graph tracking caller-callee relationships."""
201
- def get_downstream_dependents(self, symbol_path: str) -> List[str]:
202
- """Returns direct and transitive caller symbol paths."""
203
- return ["app.api.routes", "app.workers.indexer"]
204
-
205
- def compute_blast_radius_score(self, dependents: List[str]) -> float:
206
- """Calculates bounded 0-100 blast radius impact."""
207
- return min(100.0, len(dependents) * 18.5)
208
- ''',
209
- "focus_prompt": "Implement analyze_symbol_impact function using SymbolTable and CallGraphDAG.",
210
- "target_implementation": '''
211
- def analyze_symbol_impact(symbol_path: str, table: SymbolTable, dag: CallGraphDAG) -> dict:
212
- """Calculates blast radius impact for modified symbol."""
213
- sym = table.lookup_symbol(symbol_path)
214
- dependents = dag.get_downstream_dependents(symbol_path)
215
- score = dag.compute_blast_radius_score(dependents)
216
- return {
217
- "symbol": symbol_path,
218
- "exists": sym is not None,
219
- "dependents_count": len(dependents),
220
- "blast_radius_score": score,
221
- "safe_to_patch": score < 40.0
222
- }
223
- '''
224
- }
225
- ]
226
-
227
- @classmethod
228
- def prune_to_ast_skeleton(cls, python_code: str) -> str:
229
- """Prunes function/method bodies to docstrings & ellipsis, preserving full signatures & types."""
230
- try:
231
- tree = ast.parse(python_code)
232
- except SyntaxError:
233
- return python_code
234
-
235
- class SkeletonPruner(ast.NodeTransformer):
236
- def visit_FunctionDef(self, node):
237
- self.generic_visit(node)
238
- # Keep docstring if present
239
- doc = ast.get_docstring(node)
240
- new_body = []
241
- if doc:
242
- new_body.append(ast.Expr(value=ast.Constant(value=doc)))
243
- new_body.append(ast.Expr(value=ast.Constant(value=Ellipsis)))
244
- node.body = new_body
245
- return node
246
-
247
- def visit_AsyncFunctionDef(self, node):
248
- self.generic_visit(node)
249
- doc = ast.get_docstring(node)
250
- new_body = []
251
- if doc:
252
- new_body.append(ast.Expr(value=ast.Constant(value=doc)))
253
- new_body.append(ast.Expr(value=ast.Constant(value=Ellipsis)))
254
- node.body = new_body
255
- return node
256
-
257
- pruned = SkeletonPruner().visit(tree)
258
- ast.fix_missing_locations(pruned)
259
- return ast.unparse(pruned)
260
-
261
- @classmethod
262
- def evaluate_all(cls) -> TaskBenchmarkReport:
263
- """Executes standard 3-task offline benchmark evaluation."""
264
- return cls.evaluate_suite(suite="core")
265
-
266
- @classmethod
267
- def _build_adversarial_tasks(cls) -> List[Dict[str, str]]:
268
- """Synthesizes 8 multi-file cross-domain verification tasks for adversarial accuracy audits."""
269
- specs = [
270
- ("ADV-01", "Order Settlement Contract", "OrderLedger", "settle_invoice", "tx_id: str, cents: int", "bool"),
271
- ("ADV-02", "Zero-Leak Token Masker", "SecretVault", "redact_payload", "raw_text: str", "str"),
272
- ("ADV-03", "AST Dependency Graph", "ImportResolver", "topological_order", "nodes: list", "list"),
273
- ("ADV-04", "Budget Allocator Pack", "WindowPacker", "allocate_tiers", "limit: int, items: list", "dict"),
274
- ("ADV-05", "Merkle Chunk Signer", "ChunkVerifier", "compute_root", "hashes: list", "str"),
275
- ("ADV-06", "Polyglot Signature Extractor", "SyntaxScanner", "extract_headers", "source: str, ext: str", "str"),
276
- ("ADV-07", "Mutation Killer Evaluator", "MutantHarness", "evaluate_mutant", "module_path: str", "float"),
277
- ("ADV-08", "Semantic Merge Healer", "ConflictResolver", "reconcile_hunk", "left: str, right: str", "str"),
278
- ]
279
- tasks: List[Dict[str, str]] = []
280
- for tid, title, cls_name, method_name, sig_args, ret_type in specs:
281
- body_lines = "\n".join(
282
- f" step_{i} = len(str({sig_args.split(':')[0].strip()})) + {i * 7}"
283
- for i in range(18)
284
- )
285
- return_value = 'True' if ret_type == 'bool' else ('1.0' if ret_type == 'float' else ('[]' if ret_type == 'list' else ('{}' if ret_type == 'dict' else '"ok"')))
286
- dep_code = (
287
- f"class {cls_name}:\n"
288
- f' """{title} domain contract."""\n'
289
- f" def __init__(self, strict: bool = True):\n"
290
- f" self.strict = strict\n\n"
291
- f" def {method_name}(self, {sig_args}) -> {ret_type}:\n"
292
- f"{body_lines}\n"
293
- f" return {return_value}\n"
294
- )
295
- call_args = ", ".join(
296
- '""' if "str" in a else ("[]" if "list" in a else "128")
297
- for a in sig_args.split(",")
298
- )
299
- target_impl = (
300
- f"def run_{tid.lower().replace('-', '_')}(svc):\n"
301
- f" return svc.{method_name}({call_args})\n"
302
- )
303
- tasks.append({
304
- "id": tid,
305
- "title": title,
306
- "description": f"Verify AST skeleton preserves {cls_name}.{method_name} under adversarial load.",
307
- "dependency_code": dep_code,
308
- "target_implementation": target_impl,
309
- })
310
- return tasks
311
-
312
- @staticmethod
313
- def _query_ollama_implementation(
314
- pruned_dep: str,
315
- task_title: str,
316
- ollama_model: str,
317
- ollama_url: str,
318
- ) -> str:
319
- prompt = (
320
- f"Write ONLY Python code implementing a helper calling this AST contract for '{task_title}':\n"
321
- f"```python\n{pruned_dep}\n```"
322
- )
323
- req = urllib.request.Request(
324
- ollama_url,
325
- data=json.dumps({"model": ollama_model, "prompt": prompt, "stream": False}).encode("utf-8"),
326
- headers={"Content-Type": "application/json"},
327
- method="POST",
328
- )
329
- with urllib.request.urlopen(req, timeout=15) as resp:
330
- data = json.loads(resp.read().decode("utf-8"))
331
- raw = str(data.get("response") or "")
332
- fence = re.search(r"```(?:python)?\s*(.*?)```", raw, re.DOTALL)
333
- return fence.group(1).strip() if fence else raw.strip()
334
-
335
- @classmethod
336
- def evaluate_suite(
337
- cls,
338
- suite: str = "core",
339
- ollama_model: Optional[str] = None,
340
- ollama_url: str = "http://127.0.0.1:11434/api/generate",
341
- limit_tasks: Optional[int] = None,
342
- ) -> TaskBenchmarkReport:
343
- """Executes benchmark evaluation across 'core' (3 tasks) or 'adversarial' (8 tasks), optionally querying Ollama."""
344
- report = TaskBenchmarkReport()
345
- total_raw = 0
346
- total_tzero = 0
347
- reductions = []
348
-
349
- task_list = cls._build_adversarial_tasks() if suite == "adversarial" else list(cls.TASKS)
350
- if limit_tasks is not None:
351
- task_list = task_list[:limit_tasks]
352
-
353
- for task in task_list:
354
- t0 = time.perf_counter()
355
- dep_code = task["dependency_code"]
356
- target_impl = task["target_implementation"]
357
-
358
- raw_context = dep_code + "\n" + target_impl
359
- raw_tokens = count_bpe_tokens(raw_context)
360
-
361
- pruned_dep = cls.prune_to_ast_skeleton(dep_code)
362
- tzero_context = pruned_dep + "\n" + target_impl
363
- tzero_tokens = count_bpe_tokens(tzero_context)
364
-
365
- if ollama_model:
366
- try:
367
- target_impl = cls._query_ollama_implementation(
368
- pruned_dep=pruned_dep,
369
- task_title=task["title"],
370
- ollama_model=ollama_model,
371
- ollama_url=ollama_url,
372
- )
373
- except (urllib.error.URLError, OSError, ValueError) as exc:
374
- print(f"[WARN] Ollama benchmark query failed for {task['id']}: {exc}", file=sys.stderr)
375
- target_impl = ""
376
-
377
- saved = raw_tokens - tzero_tokens
378
- savings_pct = (saved / raw_tokens * 100.0) if raw_tokens else 0.0
379
-
380
- target_ast = None
381
- syntax_valid = False
382
- if target_impl.strip():
383
- try:
384
- target_ast = ast.parse(target_impl)
385
- syntax_valid = True
386
- except SyntaxError:
387
- syntax_valid = False
388
-
389
- dep_ast = ast.parse(pruned_dep)
390
- declared_methods = {
391
- node.name
392
- for node in ast.walk(dep_ast)
393
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
394
- }
395
-
396
- called_methods = set()
397
- if target_ast is not None:
398
- for node in ast.walk(target_ast):
399
- if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
400
- called_methods.add(node.func.attr)
401
-
402
- hallucinations = sum(1 for cm in called_methods if cm not in declared_methods)
403
- retention_pct = 100.0 if not hallucinations else max(0.0, 100.0 - (hallucinations * 25.0))
404
- task_success = syntax_valid and (hallucinations == 0)
405
-
406
- latency_ms = (time.perf_counter() - t0) * 1000.0
407
-
408
- res = TaskEvaluationResult(
409
- task_id=task["id"],
410
- task_title=task["title"],
411
- raw_bpe_tokens=raw_tokens,
412
- tzero_bpe_tokens=tzero_tokens,
413
- token_savings_pct=round(savings_pct, 1),
414
- signature_contract_retention_pct=round(retention_pct, 1),
415
- syntax_valid=syntax_valid,
416
- hallucination_count=hallucinations,
417
- task_success=task_success,
418
- latency_ms=round(latency_ms, 2),
419
- description=task["description"],
420
- )
421
- report.results.append(res)
422
- total_raw += raw_tokens
423
- total_tzero += tzero_tokens
424
- reductions.append(savings_pct)
425
-
426
- report.total_tasks = len(task_list)
427
- report.passed_tasks = sum(1 for r in report.results if r.task_success)
428
- report.success_rate_pct = round(report.passed_tasks / max(1, report.total_tasks) * 100.0, 1)
429
- report.average_token_reduction_pct = round(sum(reductions) / max(1, len(reductions)), 1)
430
- report.total_raw_tokens = total_raw
431
- report.total_tzero_tokens = total_tzero
432
-
433
- return report
434
-
435
- @classmethod
436
- def format_terminal_summary(cls, report: TaskBenchmarkReport) -> str:
437
- """Formats ANSI-styled benchmark summary table."""
438
- lines = []
439
- lines.append("=" * 78)
440
- lines.append(" T-ZERO TASK-COMPLETION & BPE TOKENIZER BENCHMARK REPORT (v11.0.0)")
441
- lines.append(f" Tokenizer: {report.tokenizer} | Tasks Evaluated: {report.total_tasks}")
442
- lines.append("=" * 78)
443
- lines.append(f"{'Task ID':<10} | {'Raw BPE':<8} | {'T-Zero':<8} | {'Saved %':<8} | {'Contract %':<10} | {'Status'}")
444
- lines.append("-" * 78)
445
- for r in report.results:
446
- status = "PASS (0 Halluc)" if r.task_success else "FAIL"
447
- lines.append(f"{r.task_id:<10} | {r.raw_bpe_tokens:<8} | {r.tzero_bpe_tokens:<8} | {r.token_savings_pct:<7}% | {r.signature_contract_retention_pct:<9}% | {status}")
448
- lines.append("-" * 78)
449
- lines.append(f"OVERALL TASK SUCCESS RATE: {report.success_rate_pct}% ({report.passed_tasks}/{report.total_tasks} Tasks Clean)")
450
- lines.append(f"AVERAGE TOKEN REDUCTION : {report.average_token_reduction_pct}% (BPE Exact Tokens)")
451
- lines.append(f"TOTAL TOKENS BENCHMARKED: {report.total_raw_tokens} -> {report.total_tzero_tokens} tokens")
452
- lines.append("=" * 78)
453
- return "\n".join(lines)
454
-
455
-
456
- if __name__ == "__main__":
457
- rep = TaskCompletionBenchmark.evaluate_all()
458
- print(TaskCompletionBenchmark.format_terminal_summary(rep))
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-Zero Task-Completion & Real Tokenizer Benchmark Engine
4
+ =========================================================
5
+ Empirically benchmarks token reduction and task-completion correctness
6
+ comparing Raw Codebase Ingestion against T-Zero Tier-2 Smart Skeletons.
7
+ Uses official BPE tokenizer (tiktoken cl100k_base / o200k_base) for exact token counts.
8
+
9
+ Author: Siber Akademi (Toprak Ahmet Aydoğmuş)
10
+ License: MIT
11
+ """
12
+
13
+ import ast
14
+ import json
15
+ import os
16
+ import re
17
+ import sys
18
+ import time
19
+ import urllib.error
20
+ import urllib.request
21
+ from dataclasses import dataclass, field, asdict
22
+ from typing import Dict, List, Any, Optional
23
+
24
+ try:
25
+ import tiktoken
26
+ TIKTOKEN_AVAILABLE = True
27
+ except ImportError:
28
+ tiktoken = None
29
+ TIKTOKEN_AVAILABLE = False
30
+
31
+
32
+ def count_bpe_tokens(text: str, model_encoding: str = "cl100k_base") -> int:
33
+ """Calculates exact BPE tokens using tiktoken if available, else standard char/4 fallback."""
34
+ if TIKTOKEN_AVAILABLE and tiktoken is not None:
35
+ try:
36
+ enc = tiktoken.get_encoding(model_encoding)
37
+ return len(enc.encode(text, disallowed_special=()))
38
+ except Exception:
39
+ pass
40
+ return max(1, len(text) // 4)
41
+
42
+
43
+ def detect_installed_ollama_model(ollama_url: str = "http://127.0.0.1:11434") -> Optional[str]:
44
+ """Auto-detects already installed models on local Ollama without triggering any downloads."""
45
+ try:
46
+ url = ollama_url.rstrip("/") + "/api/tags"
47
+ req = urllib.request.Request(url, method="GET")
48
+ with urllib.request.urlopen(req, timeout=3) as resp:
49
+ data = json.loads(resp.read().decode("utf-8"))
50
+ models = [m.get("name", "") for m in data.get("models", []) if m.get("name")]
51
+ for m in models:
52
+ if "qwen" in m.lower():
53
+ return m
54
+ if models:
55
+ return models[0]
56
+ except Exception:
57
+ pass
58
+ return None
59
+
60
+
61
+ @dataclass
62
+ class TaskEvaluationResult:
63
+ task_id: str
64
+ task_title: str
65
+ raw_bpe_tokens: int
66
+ tzero_bpe_tokens: int
67
+ token_savings_pct: float
68
+ signature_contract_retention_pct: float
69
+ syntax_valid: bool
70
+ hallucination_count: int
71
+ task_success: bool
72
+ latency_ms: float
73
+ description: str
74
+
75
+
76
+ @dataclass
77
+ class TaskBenchmarkReport:
78
+ version: str = "11.11.0"
79
+ tokenizer: str = "tiktoken (cl100k_base)" if TIKTOKEN_AVAILABLE else "character-ratio fallback"
80
+ total_tasks: int = 0
81
+ passed_tasks: int = 0
82
+ success_rate_pct: float = 0.0
83
+ average_token_reduction_pct: float = 0.0
84
+ total_raw_tokens: int = 0
85
+ total_tzero_tokens: int = 0
86
+ results: List[TaskEvaluationResult] = field(default_factory=list)
87
+
88
+
89
+ class TaskCompletionBenchmark:
90
+ """
91
+ Evaluates whether an AI coding agent with signature-only surrounding context
92
+ (T-Zero Tier-2 Smart Skeleton) can successfully synthesize correct, valid,
93
+ and non-hallucinated code compared to raw full-file context ingestion.
94
+ """
95
+
96
+ TASKS = [
97
+ {
98
+ "id": "TASK-01",
99
+ "title": "Cross-Module Token Bucket Rate Limiter",
100
+ "description": "Implement rate limiting middleware calling RedisSessionStore, MetricsCollector, and AuditLogger.",
101
+ "dependency_code": '''
102
+ class RedisSessionStore:
103
+ """Handles high-throughput distributed session state."""
104
+ def __init__(self, cluster_url: str, pool_size: int = 20, timeout_ms: int = 500):
105
+ self.cluster_url = cluster_url
106
+ self.pool_size = pool_size
107
+ self.timeout_ms = timeout_ms
108
+ self._connected = True
109
+ self._cache = {}
110
+
111
+ def get_token_quota(self, client_id: str) -> int:
112
+ """Retrieves remaining token quota for client."""
113
+ # Simulated complex implementation (50 lines)
114
+ val = self._cache.get(client_id, 1000)
115
+ for i in range(10):
116
+ val = max(0, val - 1)
117
+ return val
118
+
119
+ def decrement_quota(self, client_id: str, tokens: int = 1) -> bool:
120
+ """Atomically decrements quota by specified tokens."""
121
+ curr = self.get_token_quota(client_id)
122
+ if curr >= tokens:
123
+ self._cache[client_id] = curr - tokens
124
+ return True
125
+ return False
126
+
127
+ class MetricsCollector:
128
+ """Emits OpenTelemetry compliant counters and histograms."""
129
+ def record_latency(self, metric_name: str, duration_ms: float, tags: dict = None) -> None:
130
+ """Records latency in milliseconds."""
131
+ pass
132
+
133
+ def increment_counter(self, counter_name: str, value: int = 1, labels: dict = None) -> None:
134
+ """Increments dimensional metric counter."""
135
+ pass
136
+
137
+ class AuditLogger:
138
+ """Enterprise zero-leak audit logging engine."""
139
+ def log_security_event(self, event_type: str, actor_id: str, severity: str = "INFO") -> None:
140
+ """Appends tamper-evident security record."""
141
+ pass
142
+ ''',
143
+ "focus_prompt": "Synthesize a client rate-limiter function using RedisSessionStore, MetricsCollector, and AuditLogger.",
144
+ "target_implementation": '''
145
+ def enforce_rate_limit(client_id: str, store: RedisSessionStore, metrics: MetricsCollector, audit: AuditLogger) -> bool:
146
+ """Validates and decrements token quota while recording audit events."""
147
+ quota = store.get_token_quota(client_id)
148
+ if quota <= 0:
149
+ audit.log_security_event("RATE_LIMIT_EXCEEDED", client_id, severity="WARNING")
150
+ metrics.increment_counter("rate_limit_blocks", 1, {"client": client_id})
151
+ return False
152
+ store.decrement_quota(client_id, 1)
153
+ metrics.increment_counter("rate_limit_allows", 1, {"client": client_id})
154
+ return True
155
+ '''
156
+ },
157
+ {
158
+ "id": "TASK-02",
159
+ "title": "Crypto Vault Key Rotation & Signature Verification",
160
+ "description": "Rotate encryption keys and sign payloads using KeyringVault and HMACEngine.",
161
+ "dependency_code": '''
162
+ class KeyringVault:
163
+ """Interfaces with platform credential manager."""
164
+ def __init__(self, service_name: str = "tzero_vault"):
165
+ self.service_name = service_name
166
+ self._keys = {}
167
+
168
+ def get_active_signing_key(self, key_id: str) -> bytes:
169
+ """Retrieves cryptographically secure key material."""
170
+ return b"sec_master_key_990_deterministic_bytes_fixed"
171
+
172
+ def rotate_key(self, key_id: str, new_material: bytes) -> bool:
173
+ """Rotates key material atomically."""
174
+ self._keys[key_id] = new_material
175
+ return True
176
+
177
+ class HMACEngine:
178
+ """Deterministic HMAC-SHA256 signature generator."""
179
+ def generate_digest(self, secret_key: bytes, payload: bytes) -> str:
180
+ """Computes hexadecimal digest."""
181
+ import hashlib, hmac
182
+ return hmac.new(secret_key, payload, hashlib.sha256).hexdigest()
183
+
184
+ def verify_digest(self, secret_key: bytes, payload: bytes, expected_digest: str) -> bool:
185
+ """Constant-time verification of digest."""
186
+ computed = self.generate_digest(secret_key, payload)
187
+ import hmac
188
+ return hmac.compare_digest(computed, expected_digest)
189
+ ''',
190
+ "focus_prompt": "Implement sign_and_record_payload function using KeyringVault and HMACEngine.",
191
+ "target_implementation": '''
192
+ def sign_and_record_payload(payload_bytes: bytes, key_id: str, vault: KeyringVault, hmac_eng: HMACEngine) -> str:
193
+ """Signs payload using active key from vault."""
194
+ signing_key = vault.get_active_signing_key(key_id)
195
+ digest = hmac_eng.generate_digest(signing_key, payload_bytes)
196
+ return digest
197
+ '''
198
+ },
199
+ {
200
+ "id": "TASK-03",
201
+ "title": "AST Slicer & Blast Radius Impact Assessment",
202
+ "description": "Calculate downstream dependent blast radius using CallGraphDAG and SymbolTable.",
203
+ "dependency_code": '''
204
+ class SymbolTable:
205
+ """Maintains indexed AST symbol hierarchy."""
206
+ def __init__(self):
207
+ self.symbols = {}
208
+
209
+ def lookup_symbol(self, symbol_path: str) -> Optional[dict]:
210
+ """Resolves symbol metadata by qualified name."""
211
+ return self.symbols.get(symbol_path)
212
+
213
+ def register_symbol(self, symbol_path: str, meta: dict) -> None:
214
+ """Registers a symbol in the table."""
215
+ self.symbols[symbol_path] = meta
216
+
217
+ class CallGraphDAG:
218
+ """Directed acyclic graph tracking caller-callee relationships."""
219
+ def get_downstream_dependents(self, symbol_path: str) -> List[str]:
220
+ """Returns direct and transitive caller symbol paths."""
221
+ return ["app.api.routes", "app.workers.indexer"]
222
+
223
+ def compute_blast_radius_score(self, dependents: List[str]) -> float:
224
+ """Calculates bounded 0-100 blast radius impact."""
225
+ return min(100.0, len(dependents) * 18.5)
226
+ ''',
227
+ "focus_prompt": "Implement analyze_symbol_impact function using SymbolTable and CallGraphDAG.",
228
+ "target_implementation": '''
229
+ def analyze_symbol_impact(symbol_path: str, table: SymbolTable, dag: CallGraphDAG) -> dict:
230
+ """Calculates blast radius impact for modified symbol."""
231
+ sym = table.lookup_symbol(symbol_path)
232
+ dependents = dag.get_downstream_dependents(symbol_path)
233
+ score = dag.compute_blast_radius_score(dependents)
234
+ return {
235
+ "symbol": symbol_path,
236
+ "exists": sym is not None,
237
+ "dependents_count": len(dependents),
238
+ "blast_radius_score": score,
239
+ "safe_to_patch": score < 40.0
240
+ }
241
+ '''
242
+ }
243
+ ]
244
+
245
+ @classmethod
246
+ def prune_to_ast_skeleton(cls, python_code: str) -> str:
247
+ """Prunes function/method bodies to docstrings & ellipsis, preserving full signatures & types."""
248
+ try:
249
+ tree = ast.parse(python_code)
250
+ except SyntaxError:
251
+ return python_code
252
+
253
+ class SkeletonPruner(ast.NodeTransformer):
254
+ def visit_FunctionDef(self, node):
255
+ self.generic_visit(node)
256
+ # Keep docstring if present
257
+ doc = ast.get_docstring(node)
258
+ new_body = []
259
+ if doc:
260
+ new_body.append(ast.Expr(value=ast.Constant(value=doc)))
261
+ new_body.append(ast.Expr(value=ast.Constant(value=Ellipsis)))
262
+ node.body = new_body
263
+ return node
264
+
265
+ def visit_AsyncFunctionDef(self, node):
266
+ self.generic_visit(node)
267
+ doc = ast.get_docstring(node)
268
+ new_body = []
269
+ if doc:
270
+ new_body.append(ast.Expr(value=ast.Constant(value=doc)))
271
+ new_body.append(ast.Expr(value=ast.Constant(value=Ellipsis)))
272
+ node.body = new_body
273
+ return node
274
+
275
+ pruned = SkeletonPruner().visit(tree)
276
+ ast.fix_missing_locations(pruned)
277
+ return ast.unparse(pruned)
278
+
279
+ @classmethod
280
+ def evaluate_all(cls) -> TaskBenchmarkReport:
281
+ """Executes standard 3-task offline benchmark evaluation."""
282
+ return cls.evaluate_suite(suite="core")
283
+
284
+ @classmethod
285
+ def _build_adversarial_tasks(cls) -> List[Dict[str, str]]:
286
+ """Synthesizes 8 multi-file cross-domain verification tasks for adversarial accuracy audits."""
287
+ specs = [
288
+ ("ADV-01", "Order Settlement Contract", "OrderLedger", "settle_invoice", "tx_id: str, cents: int", "bool"),
289
+ ("ADV-02", "Zero-Leak Token Masker", "SecretVault", "redact_payload", "raw_text: str", "str"),
290
+ ("ADV-03", "AST Dependency Graph", "ImportResolver", "topological_order", "nodes: list", "list"),
291
+ ("ADV-04", "Budget Allocator Pack", "WindowPacker", "allocate_tiers", "limit: int, items: list", "dict"),
292
+ ("ADV-05", "Merkle Chunk Signer", "ChunkVerifier", "compute_root", "hashes: list", "str"),
293
+ ("ADV-06", "Polyglot Signature Extractor", "SyntaxScanner", "extract_headers", "source: str, ext: str", "str"),
294
+ ("ADV-07", "Mutation Killer Evaluator", "MutantHarness", "evaluate_mutant", "module_path: str", "float"),
295
+ ("ADV-08", "Semantic Merge Healer", "ConflictResolver", "reconcile_hunk", "left: str, right: str", "str"),
296
+ ]
297
+ tasks: List[Dict[str, str]] = []
298
+ for tid, title, cls_name, method_name, sig_args, ret_type in specs:
299
+ body_lines = "\n".join(
300
+ f" step_{i} = len(str({sig_args.split(':')[0].strip()})) + {i * 7}"
301
+ for i in range(18)
302
+ )
303
+ return_value = 'True' if ret_type == 'bool' else ('1.0' if ret_type == 'float' else ('[]' if ret_type == 'list' else ('{}' if ret_type == 'dict' else '"ok"')))
304
+ dep_code = (
305
+ f"class {cls_name}:\n"
306
+ f' """{title} domain contract."""\n'
307
+ f" def __init__(self, strict: bool = True):\n"
308
+ f" self.strict = strict\n\n"
309
+ f" def {method_name}(self, {sig_args}) -> {ret_type}:\n"
310
+ f"{body_lines}\n"
311
+ f" return {return_value}\n"
312
+ )
313
+ call_args = ", ".join(
314
+ '""' if "str" in a else ("[]" if "list" in a else "128")
315
+ for a in sig_args.split(",")
316
+ )
317
+ target_impl = (
318
+ f"def run_{tid.lower().replace('-', '_')}(svc):\n"
319
+ f" return svc.{method_name}({call_args})\n"
320
+ )
321
+ tasks.append({
322
+ "id": tid,
323
+ "title": title,
324
+ "description": f"Verify AST skeleton preserves {cls_name}.{method_name} under adversarial load.",
325
+ "dependency_code": dep_code,
326
+ "target_implementation": target_impl,
327
+ })
328
+ return tasks
329
+
330
+ @staticmethod
331
+ def _query_ollama_implementation(
332
+ pruned_dep: str,
333
+ task_title: str,
334
+ ollama_model: str,
335
+ ollama_url: str,
336
+ ) -> str:
337
+ prompt = (
338
+ f"You are an expert Python engineer. You are given these existing classes and method signatures:\n"
339
+ f"```python\n{pruned_dep}\n```\n\n"
340
+ f"Task: Write a Python helper function that implements '{task_title}'.\n"
341
+ f"Requirements:\n"
342
+ f"1. You MUST use and call the methods on the classes defined above.\n"
343
+ f"2. Do NOT redefine the classes.\n"
344
+ f"3. Return executable Python code only enclosed in ```python ``` code block."
345
+ )
346
+ req = urllib.request.Request(
347
+ ollama_url,
348
+ data=json.dumps({
349
+ "model": ollama_model,
350
+ "prompt": prompt,
351
+ "stream": False,
352
+ "options": {"temperature": 0.1, "num_predict": 512}
353
+ }).encode("utf-8"),
354
+ headers={"Content-Type": "application/json"},
355
+ method="POST",
356
+ )
357
+ with urllib.request.urlopen(req, timeout=15) as resp:
358
+ data = json.loads(resp.read().decode("utf-8"))
359
+ raw = str(data.get("response") or "")
360
+ fence = re.search(r"```(?:python)?\s*(.*?)```", raw, re.DOTALL)
361
+ return fence.group(1).strip() if fence else raw.strip()
362
+
363
+ @classmethod
364
+ def evaluate_suite(
365
+ cls,
366
+ suite: str = "core",
367
+ ollama_model: Optional[str] = None,
368
+ ollama_url: str = "http://127.0.0.1:11434/api/generate",
369
+ limit_tasks: Optional[int] = None,
370
+ ) -> TaskBenchmarkReport:
371
+ """Executes benchmark evaluation across 'core' (3 tasks) or 'adversarial' (8 tasks), optionally querying Ollama."""
372
+ report = TaskBenchmarkReport()
373
+ total_raw = 0
374
+ total_tzero = 0
375
+ reductions = []
376
+
377
+ task_list = cls._build_adversarial_tasks() if suite == "adversarial" else list(cls.TASKS)
378
+ if limit_tasks is not None:
379
+ task_list = task_list[:limit_tasks]
380
+
381
+ for task in task_list:
382
+ t0 = time.perf_counter()
383
+ dep_code = task["dependency_code"]
384
+ target_impl = task["target_implementation"]
385
+
386
+ raw_context = dep_code + "\n" + target_impl
387
+ raw_tokens = count_bpe_tokens(raw_context)
388
+
389
+ pruned_dep = cls.prune_to_ast_skeleton(dep_code)
390
+ tzero_context = pruned_dep + "\n" + target_impl
391
+ tzero_tokens = count_bpe_tokens(tzero_context)
392
+
393
+ if ollama_model:
394
+ try:
395
+ target_impl = cls._query_ollama_implementation(
396
+ pruned_dep=pruned_dep,
397
+ task_title=task["title"],
398
+ ollama_model=ollama_model,
399
+ ollama_url=ollama_url,
400
+ )
401
+ except (urllib.error.URLError, OSError, ValueError) as exc:
402
+ print(f"[WARN] Ollama benchmark query failed for {task['id']}: {exc}", file=sys.stderr)
403
+ target_impl = ""
404
+
405
+ saved = raw_tokens - tzero_tokens
406
+ savings_pct = (saved / raw_tokens * 100.0) if raw_tokens else 0.0
407
+
408
+ target_ast = None
409
+ syntax_valid = False
410
+ if target_impl.strip():
411
+ try:
412
+ target_ast = ast.parse(target_impl)
413
+ syntax_valid = True
414
+ except SyntaxError:
415
+ syntax_valid = False
416
+
417
+ dep_ast = ast.parse(pruned_dep)
418
+ declared_methods = {
419
+ node.name
420
+ for node in ast.walk(dep_ast)
421
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
422
+ }
423
+
424
+ called_methods = set()
425
+ if target_ast is not None:
426
+ for node in ast.walk(target_ast):
427
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
428
+ called_methods.add(node.func.attr)
429
+
430
+ hallucinations = sum(1 for cm in called_methods if cm not in declared_methods)
431
+ retention_pct = 100.0 if not hallucinations else max(0.0, 100.0 - (hallucinations * 25.0))
432
+ task_success = syntax_valid and (hallucinations == 0)
433
+
434
+ latency_ms = (time.perf_counter() - t0) * 1000.0
435
+
436
+ res = TaskEvaluationResult(
437
+ task_id=task["id"],
438
+ task_title=task["title"],
439
+ raw_bpe_tokens=raw_tokens,
440
+ tzero_bpe_tokens=tzero_tokens,
441
+ token_savings_pct=round(savings_pct, 1),
442
+ signature_contract_retention_pct=round(retention_pct, 1),
443
+ syntax_valid=syntax_valid,
444
+ hallucination_count=hallucinations,
445
+ task_success=task_success,
446
+ latency_ms=round(latency_ms, 2),
447
+ description=task["description"],
448
+ )
449
+ report.results.append(res)
450
+ total_raw += raw_tokens
451
+ total_tzero += tzero_tokens
452
+ reductions.append(savings_pct)
453
+
454
+ report.total_tasks = len(task_list)
455
+ report.passed_tasks = sum(1 for r in report.results if r.task_success)
456
+ report.success_rate_pct = round(report.passed_tasks / max(1, report.total_tasks) * 100.0, 1)
457
+ report.average_token_reduction_pct = round(sum(reductions) / max(1, len(reductions)), 1)
458
+ report.total_raw_tokens = total_raw
459
+ report.total_tzero_tokens = total_tzero
460
+
461
+ return report
462
+
463
+ @classmethod
464
+ def format_terminal_summary(cls, report: TaskBenchmarkReport) -> str:
465
+ """Formats ANSI-styled benchmark summary table."""
466
+ lines = []
467
+ lines.append("=" * 78)
468
+ lines.append(" T-ZERO TASK-COMPLETION & BPE TOKENIZER BENCHMARK REPORT (v11.11.0)")
469
+ lines.append(f" Tokenizer: {report.tokenizer} | Tasks Evaluated: {report.total_tasks}")
470
+ lines.append("=" * 78)
471
+ lines.append(f"{'Task ID':<10} | {'Raw BPE':<8} | {'T-Zero':<8} | {'Saved %':<8} | {'Contract %':<10} | {'Status'}")
472
+ lines.append("-" * 78)
473
+ for r in report.results:
474
+ status = "PASS (0 Halluc)" if r.task_success else "FAIL"
475
+ lines.append(f"{r.task_id:<10} | {r.raw_bpe_tokens:<8} | {r.tzero_bpe_tokens:<8} | {r.token_savings_pct:<7}% | {r.signature_contract_retention_pct:<9}% | {status}")
476
+ lines.append("-" * 78)
477
+ lines.append(f"OVERALL TASK SUCCESS RATE: {report.success_rate_pct}% ({report.passed_tasks}/{report.total_tasks} Tasks Clean)")
478
+ lines.append(f"AVERAGE TOKEN REDUCTION : {report.average_token_reduction_pct}% (BPE Exact Tokens)")
479
+ lines.append(f"TOTAL TOKENS BENCHMARKED: {report.total_raw_tokens} -> {report.total_tzero_tokens} tokens")
480
+ lines.append("=" * 78)
481
+ return "\n".join(lines)
482
+
483
+
484
+ if __name__ == "__main__":
485
+ import argparse
486
+ parser = argparse.ArgumentParser(description="T-Zero Task-Completion & Real Tokenizer Benchmark Engine")
487
+ parser.add_argument("--suite", choices=["core", "adversarial"], default="core", help="Benchmark suite to evaluate")
488
+ parser.add_argument("--ollama", action="store_true", help="Query local Ollama instance without pulling extra models")
489
+ parser.add_argument("--model", type=str, default=None, help="Local Ollama model name (auto-detects if omitted)")
490
+ args = parser.parse_args()
491
+
492
+ selected_model = args.model
493
+ if args.ollama and not selected_model:
494
+ selected_model = detect_installed_ollama_model()
495
+ if not selected_model:
496
+ print("[WARN] No local Ollama model detected. Running offline AST benchmark.", file=sys.stderr)
497
+
498
+ if selected_model:
499
+ print(f"🤖 Running benchmark with local Ollama model: {selected_model}")
500
+ rep = TaskCompletionBenchmark.evaluate_suite(suite=args.suite, ollama_model=selected_model)
501
+ elif args.suite == "adversarial":
502
+ rep = TaskCompletionBenchmark.evaluate_suite(suite="adversarial")
503
+ else:
504
+ rep = TaskCompletionBenchmark.evaluate_all()
505
+
506
+ print(TaskCompletionBenchmark.format_terminal_summary(rep))