tzero-mcp 11.15.2 → 12.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CONTRIBUTING.md +4 -4
  2. package/README.md +5 -5
  3. package/bin/postinstall.js +10 -2
  4. package/bin/tzero-mcp.js +1 -1
  5. package/bin/tzero.js +17 -0
  6. package/package.json +1 -1
  7. package/src/addmcp.py +34 -23
  8. package/src/app.py +1 -1
  9. package/src/main.py +6 -0
  10. package/src/tzero/__init__.py +10 -0
  11. package/src/tzero/anti_rea/__init__.py +70 -0
  12. package/src/tzero/anti_rea/algebraic_mutator.py +86 -0
  13. package/src/tzero/anti_rea/anti_agent_guard.py +96 -0
  14. package/src/tzero/anti_rea/anti_debugger.py +239 -0
  15. package/src/tzero/anti_rea/anti_vm.py +160 -0
  16. package/src/tzero/anti_rea/asar_shield.py +99 -0
  17. package/src/tzero/anti_rea/auditor.py +158 -0
  18. package/src/tzero/anti_rea/bpe_disrupter.py +48 -0
  19. package/src/tzero/anti_rea/bytecode_trap.py +85 -0
  20. package/src/tzero/anti_rea/canary_beacon.py +187 -0
  21. package/src/tzero/anti_rea/cli.py +102 -0
  22. package/src/tzero/anti_rea/confusables.py +86 -0
  23. package/src/tzero/anti_rea/engine.py +204 -0
  24. package/src/tzero/anti_rea/extractor_shield.py +102 -0
  25. package/src/tzero/anti_rea/flattener.py +136 -0
  26. package/src/tzero/anti_rea/gui.py +267 -0
  27. package/src/tzero/anti_rea/honeypot.py +58 -0
  28. package/src/tzero/anti_rea/integrity_guard.py +66 -0
  29. package/src/tzero/anti_rea/jailbreak_decoy.py +77 -0
  30. package/src/tzero/anti_rea/mcp_poison.py +41 -0
  31. package/src/tzero/anti_rea/native_bridge.py +169 -0
  32. package/src/tzero/anti_rea/rdtsc_guard.py +64 -0
  33. package/src/tzero/anti_rea/string_vault.py +94 -0
  34. package/src/tzero/anti_rea/sybil_network.py +53 -0
  35. package/src/tzero/anti_rea/timing_guard.py +46 -0
  36. package/src/tzero/anti_rea/token_bomb.py +65 -0
  37. package/src/tzero/anti_rea/traps.py +76 -0
  38. package/src/tzero/anti_rea/vm_obfuscator.py +182 -0
  39. package/src/tzero/siber_akademi.ico +0 -0
  40. package/src/tzero/siber_akademi_icon.py +1 -1
  41. package/src/tzero/tzero_armor.py +165 -0
  42. package/src/tzero/tzero_benchmark.py +2 -2
  43. package/src/tzero/tzero_bridge.py +28 -15
  44. package/src/tzero/tzero_budget.py +10 -3
  45. package/src/tzero/tzero_card.py +7 -5
  46. package/src/tzero/tzero_ci.py +1 -0
  47. package/src/tzero/tzero_contracts.py +30 -11
  48. package/src/tzero/tzero_dashboard.py +34 -14
  49. package/src/tzero/tzero_debt.py +14 -5
  50. package/src/tzero/tzero_features.py +1 -1
  51. package/src/tzero/tzero_federation.py +11 -6
  52. package/src/tzero/tzero_fixer/security_zero_leak.py +21 -3
  53. package/src/tzero/tzero_golden.py +11 -6
  54. package/src/tzero/tzero_graph_hud.html +1 -1
  55. package/src/tzero/tzero_growth.py +10 -10
  56. package/src/tzero/tzero_jarvis/agent_guard.py +16 -10
  57. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +34 -23
  58. package/src/tzero/tzero_lsp.py +1 -1
  59. package/src/tzero/tzero_mcp.py +90 -32
  60. package/src/tzero/tzero_mutation.py +44 -16
  61. package/src/tzero/tzero_neural_cortex.py +1 -1
  62. package/src/tzero/tzero_pc_fixer.py +21 -3
  63. package/src/tzero/tzero_promo.py +196 -36
  64. package/src/tzero/tzero_rust_bridge.py +1086 -42
  65. package/src/tzero/tzero_scip.py +15 -2
  66. package/src/tzero/tzero_semantic_merge.py +34 -10
  67. package/src/tzero/tzero_task_benchmark.py +2 -2
  68. package/src/tzero/tzero_telemetry.py +146 -0
  69. package/src/tzero/tzero_terminal.py +366 -0
  70. package/src/tzero/tzero_traffic.py +350 -0
  71. package/src/tzero/tzero_tui.py +342 -133
  72. package/src/tzero/tzero_v3.py +707 -57
  73. package/src/tzero/tzero_welcome.py +72 -12
@@ -1,8 +1,8 @@
1
1
  # -*- coding: utf-8 -*-
2
- """T-Zero Rust Core Bridge (ctypes / subprocess / WASM Agent Kernel Sandbox).
2
+ """T-Zero Rust Core Bridge (ctypes / subprocess / PyO3 / WASM Agent Kernel Sandbox).
3
3
 
4
- Bridges Python engines to `crates/tzero_jarvis_core` compiled shared libraries
5
- (`cdylib` via `ctypes`) or native CLI binaries when compiled, with an identical
4
+ Bridges Python engines to `crates/tzero_core` and `crates/tzero_jarvis_core` compiled shared libraries
5
+ (`cdylib` via `ctypes` or `pyo3` native extension module) with an identical
6
6
  pure-Python fallback when Rust binaries are not present on the host.
7
7
 
8
8
  100% Free, Local, Offline, Zero-Leak Certified.
@@ -10,15 +10,31 @@ pure-Python fallback when Rust binaries are not present on the host.
10
10
 
11
11
  from __future__ import annotations
12
12
 
13
+ import collections
13
14
  import ctypes
15
+ import importlib.machinery
16
+ import importlib.util
14
17
  import json
18
+ import math
15
19
  import os
16
20
  import shutil
17
- from typing import Any, Dict, List, Optional, Set
21
+ from typing import Any, Dict, List, Optional, Set, Tuple
22
+
23
+
24
+ def _repo_crate_dirs() -> List[str]:
25
+ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+ return [
27
+ os.path.join(root, "crates", "tzero_core"),
28
+ os.path.join(root, "crates", "tzero_jarvis_core"),
29
+ ]
18
30
 
19
31
 
20
32
  def _repo_crate_dir() -> str:
21
- return os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "crates", "tzero_jarvis_core")
33
+ dirs = _repo_crate_dirs()
34
+ for d in dirs:
35
+ if os.path.isdir(d):
36
+ return d
37
+ return dirs[0]
22
38
 
23
39
 
24
40
  def _pure_fnv1a_64(text: str) -> int:
@@ -49,88 +65,1116 @@ def _pure_jaccard_shingles(a: str, b: str, ngram: int = 3) -> float:
49
65
  return round(len(ta & tb) / union, 6) if union else 0.0
50
66
 
51
67
 
68
+ def _pure_shannon_entropy(data: str) -> float:
69
+ if not data:
70
+ return 0.0
71
+ try:
72
+ from tzero.tzero_security import calculate_shannon_entropy
73
+ return float(calculate_shannon_entropy(data))
74
+ except Exception:
75
+ length = len(data)
76
+ counts = collections.Counter(data)
77
+ entropy = 0.0
78
+ for count in counts.values():
79
+ p = count / length
80
+ entropy -= p * math.log2(p)
81
+ return float(entropy)
82
+
83
+
84
+ def _pure_scan_entropy_secrets(
85
+ text: str,
86
+ threshold: float = 4.75,
87
+ min_length: int = 28,
88
+ ) -> List[Dict[str, Any]]:
89
+ try:
90
+ from tzero.tzero_security import ZeroLeakEngine
91
+ findings = ZeroLeakEngine.scan_text(text, check_entropy=True)
92
+ results = []
93
+ for f in findings:
94
+ ent = getattr(f, "entropy", 0.0)
95
+ if ent >= threshold:
96
+ results.append({
97
+ "token": getattr(f, "secret_value", ""),
98
+ "entropy": ent,
99
+ "line": getattr(f, "line_no", 0),
100
+ "column": 0,
101
+ "is_anomaly": getattr(f, "is_entropy_anomaly", True),
102
+ "rule_id": getattr(f, "rule_id", "SEC-ENTROPY-001"),
103
+ "provider": getattr(f, "provider", "EntropyAnomaly"),
104
+ "description": getattr(f, "description", ""),
105
+ })
106
+ return results
107
+ except Exception:
108
+ return []
109
+
110
+
111
+ def _pure_redact_entropy_secrets(text: str, threshold: float = 4.4) -> Tuple[str, int]:
112
+ try:
113
+ import re
114
+ from tzero.tzero_security import ZeroLeakEngine, calculate_shannon_entropy
115
+ if not text:
116
+ return "", 0
117
+ count = 0
118
+
119
+ def _replace_entropy(m):
120
+ nonlocal count
121
+ token = m.group(1)
122
+ if not ZeroLeakEngine.is_placeholder(token) and calculate_shannon_entropy(token) >= threshold:
123
+ count += 1
124
+ return f'"{token[:4]}...[ZERO_LEAK_HIGH_ENTROPY_SECRET]"'
125
+ return m.group(0)
126
+
127
+ sanitized = re.sub(r"""['"]([^'"]{20,})['"]""", _replace_entropy, text)
128
+ return sanitized, count
129
+ except Exception:
130
+ return text, 0
131
+
132
+
133
+ def _pure_prune_ast(code: str, language: str = "python") -> str:
134
+ try:
135
+ from tzero.tzero_polyglot import PolyglotTokenReducer
136
+ ext_map = {
137
+ "python": "test.py", "py": "test.py", "pyw": "test.pyw",
138
+ "typescript": "test.ts", "ts": "test.ts", "tsx": "test.tsx",
139
+ "javascript": "test.js", "js": "test.js", "jsx": "test.jsx",
140
+ "mjs": "test.mjs", "cjs": "test.cjs",
141
+ "rust": "test.rs", "rs": "test.rs",
142
+ "go": "test.go", "golang": "test.go",
143
+ }
144
+ lang_key = (language or "python").lower().strip()
145
+ fname = ext_map.get(lang_key, f"test.{lang_key}")
146
+ return PolyglotTokenReducer.reduce_code(code, filename=fname)
147
+ except Exception:
148
+ return code
149
+
150
+
151
+ def _pure_prune_ast_stats(code: str, language: str = "python") -> Dict[str, Any]:
152
+ pruned = _pure_prune_ast(code, language=language)
153
+ orig_lines = max(1, len((code or "").splitlines()))
154
+ pruned_lines = len(pruned.splitlines())
155
+ reduction = round(max(0.0, (orig_lines - pruned_lines) / orig_lines * 100.0), 1)
156
+ return {
157
+ "pruned_code": pruned,
158
+ "original_lines": orig_lines,
159
+ "pruned_lines": pruned_lines,
160
+ "reduction_ratio": reduction,
161
+ "language": language,
162
+ }
163
+
164
+
165
+ def _pure_count_bpe_tokens(text: str, model_name: str = "gpt-4o") -> int:
166
+ try:
167
+ from tzero.tzero_polyglot import count_bpe_tokens
168
+ return int(count_bpe_tokens(text, model_name=model_name))
169
+ except Exception:
170
+ return max(1, len(text) // 4) if text else 0
171
+
172
+
173
+ def _pure_tokenize_code(text: str) -> List[str]:
174
+ import re
175
+ s = re.sub(r"([a-z])([A-Z])", r"\1 \2", text or "")
176
+ tokens = re.findall(r"[a-zA-Z0-9]{2,}", s)
177
+ return [t.lower() for t in tokens]
178
+
179
+
180
+ def _pure_bm25_search(
181
+ documents: List[Dict[str, str]],
182
+ query: str,
183
+ top_k: int = 10,
184
+ k1: float = 1.2,
185
+ b: float = 0.75,
186
+ ) -> List[Dict[str, Any]]:
187
+ query_terms = _pure_tokenize_code(query)
188
+ if not query_terms or not documents:
189
+ return []
190
+
191
+ doc_tokens = [_pure_tokenize_code(d.get("content", "")) for d in documents]
192
+ doc_lens = [len(dt) for dt in doc_tokens]
193
+ avg_len = sum(doc_lens) / max(1, len(doc_lens))
194
+ num_docs = len(documents)
195
+
196
+ df: Dict[str, int] = collections.defaultdict(int)
197
+ for dt in doc_tokens:
198
+ for t in set(dt):
199
+ df[t] += 1
200
+
201
+ idfs: Dict[str, float] = {}
202
+ for t in set(query_terms):
203
+ df_t = df.get(t, 0)
204
+ idfs[t] = math.log(((num_docs - df_t + 0.5) / (df_t + 0.5)) + 1.0) if df_t else 0.0
205
+
206
+ scores = []
207
+ for idx, (doc, dt, d_len) in enumerate(zip(documents, doc_tokens, doc_lens)):
208
+ tf_map = collections.Counter(dt)
209
+ score = 0.0
210
+ for q in set(query_terms):
211
+ tf = tf_map.get(q, 0)
212
+ if tf > 0:
213
+ idf = idfs.get(q, 0.0)
214
+ denom = tf + k1 * (1.0 - b + b * (d_len / (avg_len or 1.0)))
215
+ score += idf * (tf * (k1 + 1.0)) / (denom or 1.0)
216
+ if score > 0:
217
+ content = doc.get("content", "")
218
+ first_pos = 0
219
+ low = content.lower()
220
+ for q in query_terms:
221
+ pos = low.find(q)
222
+ if pos >= 0:
223
+ first_pos = pos
224
+ break
225
+ snippet = content[max(0, first_pos - 40):first_pos + 160].replace("\n", " ")
226
+ scores.append({
227
+ "id": doc.get("id", str(idx)),
228
+ "path": doc.get("path", ""),
229
+ "score": round(score, 4),
230
+ "snippet": snippet,
231
+ })
232
+
233
+ scores.sort(key=lambda x: x["score"], reverse=True)
234
+ return scores[:top_k]
235
+
236
+
237
+ def _pure_extract_symbols(path: str, content: str) -> Dict[str, Any]:
238
+ symbols = []
239
+ edges = []
240
+ file_stem = os.path.splitext(os.path.basename(path))[0] if path else "module"
241
+ for idx, line in enumerate((content or "").splitlines(), 1):
242
+ tr = line.strip()
243
+ if tr.startswith("def ") and "(" in tr:
244
+ name = tr[4:].split("(")[0].strip()
245
+ symbols.append({"name": name, "kind": "function", "line": idx, "path": path, "signature": tr})
246
+ elif tr.startswith("class ") and (":" in tr or "(" in tr or " " in tr[6:]):
247
+ name = tr[6:].split(":")[0].split("(")[0].split()[0].strip()
248
+ symbols.append({"name": name, "kind": "class", "line": idx, "path": path, "signature": tr})
249
+ elif tr.startswith("import ") or tr.startswith("from "):
250
+ parts = tr.split()
251
+ if len(parts) >= 2:
252
+ mod = parts[1] if parts[0] == "from" else parts[1].split(".")[0]
253
+ edges.append({"source": file_stem, "target": mod, "kind": "import"})
254
+ return {"symbols": symbols, "edges": edges}
255
+
256
+
257
+ def _pure_calculate_cyclomatic_complexity(code: str, language: str = "python") -> int:
258
+ try:
259
+ from tzero.tzero_debt import calculate_cyclomatic_complexity
260
+ return int(calculate_cyclomatic_complexity(code))
261
+ except Exception:
262
+ cc = 1
263
+ for line in (code or "").splitlines():
264
+ tr = line.strip()
265
+ if tr.startswith("#") or tr.startswith("//"):
266
+ continue
267
+ for pat in ("if ", "elif ", "else if ", "for ", "while ", "case ", "match ", "catch ", "except ", " && ", " || ", " and ", " or "):
268
+ cc += tr.count(pat)
269
+ return cc
270
+
271
+
272
+ def _pure_calculate_cognitive_complexity(code: str) -> int:
273
+ try:
274
+ from tzero.tzero_debt import calculate_cognitive_complexity
275
+ return int(calculate_cognitive_complexity(code))
276
+ except Exception:
277
+ cog = 0
278
+ nesting = 0
279
+ for line in (code or "").splitlines():
280
+ tr = line.strip()
281
+ if not tr or tr.startswith("#") or tr.startswith("//"):
282
+ continue
283
+ if any(tr.startswith(p) for p in ("if ", "elif ", "else if ", "for ", "while ", "match ", "switch ")):
284
+ cog += (1 + nesting)
285
+ nesting += 1
286
+ elif any(tr.startswith(p) for p in ("else", "except", "catch")):
287
+ cog += 1
288
+ if tr.startswith("}") or tr.endswith("}"):
289
+ nesting = max(0, nesting - 1)
290
+ return cog
291
+
292
+
293
+ def _pure_analyze_file_complexity(path: str, code: str, language: str = "python") -> Dict[str, Any]:
294
+ lines = (code or "").splitlines()
295
+ loc = len([l for l in lines if l.strip()])
296
+ cc = _pure_calculate_cyclomatic_complexity(code, language=language)
297
+ cog = _pure_calculate_cognitive_complexity(code)
298
+ loc_f = max(1.0, float(loc))
299
+ v_f = loc_f * math.log2(max(8.0, loc_f))
300
+ raw_mi = 171.0 - 5.2 * math.log(v_f) - 0.23 * float(cc) - 16.2 * math.log(loc_f)
301
+ mi = round(max(0.0, min(100.0, (raw_mi / 171.0) * 100.0)), 1)
302
+ rating = "A" if mi >= 85 else ("B" if mi >= 65 else ("C" if mi >= 50 else "D"))
303
+ todo_count = sum(1 for l in lines if any(k in l.upper() for k in ("TODO", "FIXME", "HACK", "BUG")))
304
+ debt_hours = round(max(0.0, (cc - 10) * 0.5) + max(0.0, (cog - 15) * 0.75) + todo_count * 0.25, 1)
305
+ debt_usd = round(debt_hours * 75.0, 2)
306
+ return {
307
+ "file_path": path,
308
+ "lines_of_code": loc,
309
+ "maintainability_index": mi,
310
+ "rating": rating,
311
+ "cyclomatic_complexity": cc,
312
+ "cognitive_complexity": cog,
313
+ "debt_hours": debt_hours,
314
+ "debt_cost_usd": debt_usd,
315
+ "todo_count": todo_count,
316
+ }
317
+
318
+
319
+ def _pure_compute_pagerank(
320
+ edges: List[Dict[str, Any]],
321
+ damping: float = 0.85,
322
+ max_iter: int = 100,
323
+ tolerance: float = 1e-6,
324
+ ) -> List[Dict[str, Any]]:
325
+ all_nodes: Set[str] = set()
326
+ in_neighbors: Dict[str, List[str]] = collections.defaultdict(list)
327
+ out_degrees: Dict[str, int] = collections.defaultdict(int)
328
+ in_degrees: Dict[str, int] = collections.defaultdict(int)
329
+
330
+ for e in edges:
331
+ s = str(e.get("source", ""))
332
+ t = str(e.get("target", ""))
333
+ all_nodes.add(s)
334
+ all_nodes.add(t)
335
+ in_neighbors[t].append(s)
336
+ out_degrees[s] += 1
337
+ in_degrees[t] += 1
338
+
339
+ n = len(all_nodes)
340
+ if not n:
341
+ return []
342
+
343
+ initial = 1.0 / n
344
+ current_pr: Dict[str, float] = {node: initial for node in all_nodes}
345
+
346
+ for _ in range(max_iter):
347
+ dangling_sum = sum(pr for node, pr in current_pr.items() if out_degrees[node] == 0)
348
+ base = (1.0 - damping) / n + damping * (dangling_sum / n)
349
+ diff = 0.0
350
+ next_pr: Dict[str, float] = {}
351
+
352
+ for node in all_nodes:
353
+ in_sum = sum(current_pr[in_node] / max(1, out_degrees[in_node]) for in_node in in_neighbors[node])
354
+ new_val = base + damping * in_sum
355
+ diff += abs(new_val - current_pr[node])
356
+ next_pr[node] = new_val
357
+
358
+ current_pr = next_pr
359
+ if diff < tolerance:
360
+ break
361
+
362
+ results = []
363
+ for node, score in current_pr.items():
364
+ results.append({
365
+ "node": node,
366
+ "score": round(score, 4),
367
+ "rank": 0,
368
+ "in_degree": in_degrees[node],
369
+ "out_degree": out_degrees[node],
370
+ })
371
+
372
+ results.sort(key=lambda x: x["score"], reverse=True)
373
+ for idx, r in enumerate(results, 1):
374
+ r["rank"] = idx
375
+ return results
376
+
377
+
378
+ def _pure_analyze_reachability(
379
+ symbols: List[Dict[str, Any]],
380
+ invocations: List[Tuple[str, str]],
381
+ entrypoints: List[str],
382
+ ) -> Dict[str, Any]:
383
+ call_graph: Dict[str, List[str]] = collections.defaultdict(list)
384
+ all_symbols = {s["name"] for s in symbols if "name" in s}
385
+
386
+ for caller, callee in invocations:
387
+ call_graph[caller].append(callee)
388
+
389
+ queue = collections.deque()
390
+ visited: Set[str] = set()
391
+
392
+ for ep in entrypoints:
393
+ if ep in all_symbols and ep not in visited:
394
+ visited.add(ep)
395
+ queue.append(ep)
396
+
397
+ if not queue:
398
+ for name in all_symbols:
399
+ low = name.lower()
400
+ if low == "main" or low.startswith(("run", "cli", "test")):
401
+ if name not in visited:
402
+ visited.add(name)
403
+ queue.append(name)
404
+
405
+ while queue:
406
+ curr = queue.popleft()
407
+ for callee in call_graph.get(curr, []):
408
+ if callee in all_symbols and callee not in visited:
409
+ visited.add(callee)
410
+ queue.append(callee)
411
+
412
+ dead = sorted(list(all_symbols - visited))
413
+ reachable = sorted(list(visited))
414
+ total = len(symbols)
415
+ ratio = round((len(dead) / total) * 100.0, 1) if total else 0.0
416
+
417
+ return {
418
+ "total_symbols": total,
419
+ "reachable_count": len(reachable),
420
+ "dead_symbol_count": len(dead),
421
+ "dead_code_ratio": ratio,
422
+ "reachable_symbols": reachable,
423
+ "dead_symbols": dead,
424
+ }
425
+
426
+
427
+ def _pure_compare_api_contracts(old_code: str, new_code: str) -> Dict[str, Any]:
428
+ try:
429
+ from tzero.tzero_contracts import ASTContractExtractor
430
+ old_f, _ = ASTContractExtractor.extract_from_code(old_code)
431
+ new_f, _ = ASTContractExtractor.extract_from_code(new_code)
432
+ breaking = []
433
+ additions = []
434
+ for name in old_f:
435
+ if name not in new_f:
436
+ breaking.append({
437
+ "severity": "BREAKING",
438
+ "category": "REMOVED_SYMBOL",
439
+ "symbol": name,
440
+ "details": f"Function {name} was removed.",
441
+ })
442
+ for name in new_f:
443
+ if name not in old_f:
444
+ additions.append({
445
+ "severity": "ADDITION",
446
+ "category": "NEW_SYMBOL",
447
+ "symbol": name,
448
+ "details": f"New function {name} introduced.",
449
+ })
450
+ is_breaking = len(breaking) > 0
451
+ bump = "MAJOR" if is_breaking else ("MINOR" if additions else "PATCH")
452
+ return {
453
+ "recommended_bump": bump,
454
+ "is_breaking": is_breaking,
455
+ "breaking_changes": breaking,
456
+ "non_breaking_additions": additions,
457
+ }
458
+ except Exception:
459
+ return {"recommended_bump": "PATCH", "is_breaking": False, "breaking_changes": []}
460
+
461
+
462
+ def _pure_find_code_duplicity(files: List[Tuple[str, str]], min_lines: int = 6) -> Dict[str, Any]:
463
+ window = max(3, int(min_lines))
464
+ hashes: Dict[int, Tuple[str, int, str]] = {}
465
+ duplicates = []
466
+ total_lines = 0
467
+
468
+ for path, content in files:
469
+ lines = (content or "").splitlines()
470
+ total_lines += len(lines)
471
+ if len(lines) < window:
472
+ continue
473
+ for i in range(len(lines) - window + 1):
474
+ block = [l.strip() for l in lines[i:i + window] if l.strip() and not l.strip().startswith(("#", "//"))]
475
+ if len(block) < window - 1:
476
+ continue
477
+ h = _pure_fnv1a_64("\n".join(block))
478
+ if h in hashes:
479
+ prev_path, prev_line, prev_snippet = hashes[h]
480
+ if prev_path != path or (i + 1) != prev_line:
481
+ duplicates.append({
482
+ "file_a": prev_path,
483
+ "start_line_a": prev_line,
484
+ "file_b": path,
485
+ "start_line_b": i + 1,
486
+ "line_count": window,
487
+ "snippet": prev_snippet,
488
+ })
489
+ else:
490
+ hashes[h] = (path, i + 1, "\n".join(lines[i:i + window]))
491
+
492
+ dup_lines = len(duplicates) * window
493
+ pct = round((dup_lines / total_lines) * 100.0, 1) if total_lines else 0.0
494
+ return {
495
+ "total_files_scanned": len(files),
496
+ "duplicate_block_count": len(duplicates),
497
+ "total_duplicate_lines": dup_lines,
498
+ "duplicate_percentage": min(100.0, pct),
499
+ "blocks": duplicates,
500
+ }
501
+
502
+
503
+ def _pure_damerau_levenshtein(s1: str, s2: str) -> int:
504
+ len1, len2 = len(s1), len(s2)
505
+ if not len1:
506
+ return len2
507
+ if not len2:
508
+ return len1
509
+ d = [[0] * (len2 + 1) for _ in range(len1 + 1)]
510
+ for i in range(len1 + 1):
511
+ d[i][0] = i
512
+ for j in range(len2 + 1):
513
+ d[0][j] = j
514
+ for i in range(1, len1 + 1):
515
+ for j in range(1, len2 + 1):
516
+ cost = 0 if s1[i - 1] == s2[j - 1] else 1
517
+ d[i][j] = min(
518
+ d[i - 1][j] + 1,
519
+ d[i][j - 1] + 1,
520
+ d[i - 1][j - 1] + cost,
521
+ )
522
+ if i > 1 and j > 1 and s1[i - 1] == s2[j - 2] and s1[i - 2] == s2[j - 1]:
523
+ d[i][j] = min(d[i][j], d[i - 2][j - 2] + 1)
524
+ return d[len1][len2]
525
+
526
+
527
+ def _pure_fuzzy_similarity(s1: str, s2: str) -> float:
528
+ max_len = max(len(s1), len(s2))
529
+ if not max_len:
530
+ return 1.0
531
+ dist = _pure_damerau_levenshtein(s1, s2)
532
+ return round(max(0.0, 1.0 - dist / max_len), 3)
533
+
534
+
535
+ def _pure_fuzzy_symbol_search(
536
+ query: str,
537
+ candidates: List[str],
538
+ min_similarity: float = 0.6,
539
+ top_k: int = 5,
540
+ ) -> List[Dict[str, Any]]:
541
+ matches = []
542
+ for cand in candidates:
543
+ sim = _pure_fuzzy_similarity(query, cand)
544
+ if sim >= min_similarity:
545
+ matches.append({
546
+ "target": cand,
547
+ "distance": _pure_damerau_levenshtein(query, cand),
548
+ "similarity": sim,
549
+ })
550
+ matches.sort(key=lambda x: x["similarity"], reverse=True)
551
+ return matches[:top_k]
552
+
553
+
554
+ def _pure_build_context_tree(root_dir: str, tier: int = 3) -> Dict[str, Any]:
555
+ total_lines = 0
556
+ file_count = 0
557
+ nodes = []
558
+ ignored = {".git", "node_modules", "venv", ".venv", "__pycache__", "dist", "build", "target", ".pytest_cache", ".gemini"}
559
+ for root, dirs, files in os.walk(root_dir):
560
+ dirs[:] = [d for d in dirs if d not in ignored and not d.startswith('.')]
561
+ for f in files:
562
+ if f.endswith((".py", ".rs", ".ts", ".js", ".go", ".json", ".toml", ".md")):
563
+ fpath = os.path.join(root, f)
564
+ try:
565
+ with open(fpath, "r", encoding="utf-8", errors="ignore") as fp:
566
+ content = fp.read()
567
+ lines = len(content.splitlines())
568
+ total_lines += lines
569
+ file_count += 1
570
+ rel = os.path.relpath(fpath, root_dir).replace("\\", "/")
571
+ nodes.append({
572
+ "path": fpath,
573
+ "relative_path": rel,
574
+ "lines": lines,
575
+ "raw_tokens": len(content) // 4,
576
+ "pruned_tokens": max(5, (len(content) // 4) // 10),
577
+ })
578
+ except Exception:
579
+ pass
580
+ raw_toks = sum(n["raw_tokens"] for n in nodes)
581
+ pruned_toks = sum(n["pruned_tokens"] for n in nodes)
582
+ red = round(((raw_toks - pruned_toks) / raw_toks) * 100.0, 1) if raw_toks else 0.0
583
+ tree_text = f"T-ZERO CONTEXT TREE (Tier {tier}) | {file_count} files, {total_lines} lines\nTokens: {raw_toks} raw -> {pruned_toks} context ({red}% reduction)\n"
584
+ for n in nodes[:30]:
585
+ tree_text += f"+-- {n['relative_path']} ({n['lines']} lines)\n"
586
+ return {
587
+ "root_dir": root_dir,
588
+ "tier": tier,
589
+ "total_files": file_count,
590
+ "total_lines": total_lines,
591
+ "raw_tokens": raw_toks,
592
+ "pruned_tokens": pruned_toks,
593
+ "token_reduction_percent": red,
594
+ "formatted_tree": tree_text,
595
+ }
596
+
597
+
598
+ def _pure_enforce_boundaries(edges: List[Tuple[str, str]], banned: Optional[List[str]] = None) -> Dict[str, Any]:
599
+ banned_set = set(banned or ["eval", "exec", "pickle"])
600
+ violations = []
601
+ circular = []
602
+ banned_findings = []
603
+ graph = collections.defaultdict(list)
604
+ all_mods = set()
605
+
606
+ for src, dst in edges:
607
+ all_mods.add(src)
608
+ all_mods.add(dst)
609
+ graph[src].append(dst)
610
+ for b in banned_set:
611
+ if b in dst:
612
+ banned_findings.append(f"Module '{src}' imports banned symbol/module '{dst}'")
613
+
614
+ src_low = src.lower()
615
+ dst_low = dst.lower()
616
+ src_is_persist = any(k in src_low for k in ("model", "persist", "db", "ast"))
617
+ dst_is_pres = any(k in dst_low for k in ("cli", "api", "ui", "mcp"))
618
+ if src_is_persist and dst_is_pres:
619
+ violations.append({
620
+ "source_module": src,
621
+ "source_layer": "Persistence",
622
+ "target_module": dst,
623
+ "target_layer": "Presentation",
624
+ "violation_type": "LayerBreach",
625
+ "description": f"Inward-only violation: Persistence module '{src}' cannot depend on outer Presentation module '{dst}'",
626
+ })
627
+
628
+ visited = set()
629
+ rec_stack = set()
630
+ path = []
631
+
632
+ def dfs(node):
633
+ visited.add(node)
634
+ rec_stack.add(node)
635
+ path.append(node)
636
+ for nbr in graph.get(node, []):
637
+ if nbr not in visited:
638
+ dfs(nbr)
639
+ elif nbr in rec_stack:
640
+ idx = path.index(nbr) if nbr in path else 0
641
+ cycle = path[idx:] + [nbr]
642
+ circular.append({"cycle": cycle, "length": len(cycle) - 1})
643
+ path.pop()
644
+ rec_stack.remove(node)
645
+
646
+ for m in all_mods:
647
+ if m not in visited:
648
+ dfs(m)
649
+
650
+ is_compliant = not violations and not circular and not banned_findings
651
+ return {
652
+ "total_modules_checked": len(all_mods),
653
+ "total_edges_checked": len(edges),
654
+ "is_compliant": is_compliant,
655
+ "violations": violations,
656
+ "circular_dependencies": circular,
657
+ "banned_import_findings": banned_findings,
658
+ }
659
+
660
+
661
+ def _pure_verify_hallucinations(code: str, valid_symbols: List[str]) -> Dict[str, Any]:
662
+ import re
663
+ valid_set = set(valid_symbols) | {
664
+ "print", "len", "range", "str", "int", "float", "bool", "list", "dict",
665
+ "set", "tuple", "open", "isinstance", "sum", "min", "max", "sorted",
666
+ "enumerate", "zip",
667
+ }
668
+ call_re = re.compile(r"([a-zA-Z0-9_]+)\s*\(")
669
+ detected = []
670
+ total_checked = 0
671
+ lines = code.splitlines()
672
+
673
+ for idx, line in enumerate(lines, 1):
674
+ tr = line.strip()
675
+ if tr.startswith(("#", "//", "def ", "async def ", "class ", "fn ", "pub fn ", "func ")):
676
+ continue
677
+ for m in call_re.finditer(line):
678
+ call_name = m.group(1)
679
+ if call_name in ("if", "while", "for", "with", "match", "def", "class", "return"):
680
+ continue
681
+ total_checked += 1
682
+ if call_name not in valid_set and not call_name.startswith("_"):
683
+ best_cand = None
684
+ best_sim = 0.0
685
+ for cand in valid_symbols:
686
+ sim = _pure_fuzzy_similarity(call_name, cand)
687
+ if sim > best_sim and sim >= 0.5:
688
+ best_sim = sim
689
+ best_cand = cand
690
+ detected.append({
691
+ "symbol": call_name,
692
+ "kind": "call_identifier",
693
+ "line": idx,
694
+ "suggested_replacement": best_cand,
695
+ "similarity_confidence": round(best_sim, 2),
696
+ })
697
+
698
+ total = max(1, total_checked)
699
+ score = round(((total - len(detected)) / total) * 100.0, 1)
700
+ return {
701
+ "total_symbols_checked": total,
702
+ "hallucination_count": len(detected),
703
+ "hallucination_free": len(detected) == 0,
704
+ "safety_score": score,
705
+ "hallucinations": detected,
706
+ }
707
+
708
+
709
+ def _pure_estimate_costs(
710
+ raw_tokens: int,
711
+ pruned_tokens: int,
712
+ output_tokens: int = 2000,
713
+ model: str = "gpt-4o",
714
+ ) -> Dict[str, Any]:
715
+ pricing_table = {
716
+ "gpt-4o": (2.50, 10.00),
717
+ "gpt-4o-mini": (0.15, 0.60),
718
+ "o3-mini": (1.10, 4.40),
719
+ "claude-3-5-sonnet": (3.00, 15.00),
720
+ "claude-3-5-haiku": (0.80, 4.00),
721
+ "gemini-1-5-pro": (1.25, 5.00),
722
+ "gemini-1-5-flash": (0.075, 0.30),
723
+ "gemini-2-0-flash": (0.10, 0.40),
724
+ "deepseek-v3": (0.14, 0.28),
725
+ "deepseek-r1": (0.55, 2.19),
726
+ }
727
+ inp_price, out_price = pricing_table.get(model, (2.50, 10.00))
728
+ base_in = (raw_tokens / 1_000_000.0) * inp_price
729
+ base_out = (output_tokens / 1_000_000.0) * out_price
730
+ baseline_cost = round(base_in + base_out, 5)
731
+
732
+ opt_in = (pruned_tokens / 1_000_000.0) * inp_price
733
+ opt_out = (output_tokens / 1_000_000.0) * out_price
734
+ optimized_cost = round(opt_in + opt_out, 5)
735
+
736
+ savings = max(0.0, round(baseline_cost - optimized_cost, 5))
737
+ red_pct = round((savings / baseline_cost) * 100.0, 1) if baseline_cost > 0 else 0.0
738
+ monthly_savings = round(savings * 20_000.0, 2)
739
+
740
+ return {
741
+ "input_tokens": raw_tokens,
742
+ "output_tokens": output_tokens,
743
+ "pruned_input_tokens": pruned_tokens,
744
+ "baseline_model": model,
745
+ "baseline_cost_usd": baseline_cost,
746
+ "optimized_cost_usd": optimized_cost,
747
+ "cost_savings_usd": savings,
748
+ "cost_reduction_percent": red_pct,
749
+ "monthly_projected_savings_usd": monthly_savings,
750
+ }
751
+
752
+
52
753
  class RustCoreBridge:
53
- """Adaptive FFI/subprocess bridge to crates/tzero_jarvis_core with pure-Python fallback."""
754
+ """Adaptive FFI/subprocess/PyO3 bridge to crates/tzero_core with pure-Python fallback."""
54
755
 
55
756
  def __init__(self, prefer_native: bool = True) -> None:
56
757
  self._cdylib: Optional[Any] = None
57
758
  self._pyo3_mod: Optional[Any] = None
58
759
  self._bin_path: Optional[str] = None
59
760
  if prefer_native:
60
- self._cdylib = self._try_load_cdylib()
61
- if self._cdylib is None:
62
- self._pyo3_mod = self._try_load_pyo3()
761
+ # Primary: PyO3 native extension module
762
+ self._pyo3_mod = self._try_load_pyo3()
763
+ # Secondary: ctypes shared library (cdylib)
764
+ if self._pyo3_mod is None:
765
+ self._cdylib = self._try_load_cdylib()
766
+ # Tertiary: compiled standalone CLI binary
63
767
  if self._cdylib is None and self._pyo3_mod is None:
64
768
  self._bin_path = self._find_native_binary()
65
769
 
66
770
  @classmethod
67
771
  def _try_load_cdylib(cls) -> Optional[Any]:
68
- crate = _repo_crate_dir()
69
- ext = ".dll" if os.name == "nt" else (".dylib" if os.uname().sysname == "Darwin" else ".so")
70
- names = [f"tzero_jarvis_core{ext}", f"libtzero_jarvis_core{ext}"]
71
- for build in ("release", "debug"):
72
- for fname in names:
73
- cand = os.path.join(crate, "target", build, fname)
74
- if os.path.isfile(cand):
75
- try:
76
- lib = ctypes.CDLL(cand)
77
- if hasattr(lib, "tzero_fnv1a_hash64"):
78
- lib.tzero_fnv1a_hash64.argtypes = [ctypes.c_char_p, ctypes.c_size_t]
79
- lib.tzero_fnv1a_hash64.restype = ctypes.c_uint64
80
- if hasattr(lib, "tzero_jaccard_shingles_f64"):
81
- lib.tzero_jaccard_shingles_f64.argtypes = [
82
- ctypes.c_char_p, ctypes.c_size_t,
83
- ctypes.c_char_p, ctypes.c_size_t,
84
- ctypes.c_size_t,
85
- ]
86
- lib.tzero_jaccard_shingles_f64.restype = ctypes.c_double
87
- return lib
88
- except OSError:
89
- pass
772
+ ext = ".dll" if os.name == "nt" else (
773
+ ".dylib" if (hasattr(os, "uname") and os.uname().sysname == "Darwin") else ".so"
774
+ )
775
+ for crate in _repo_crate_dirs():
776
+ names = [
777
+ f"tzero_core{ext}", f"libtzero_core{ext}",
778
+ f"tzero_jarvis_core{ext}", f"libtzero_jarvis_core{ext}",
779
+ ]
780
+ for build in ("release", "debug"):
781
+ for fname in names:
782
+ cand = os.path.join(crate, "target", build, fname)
783
+ if os.path.isfile(cand):
784
+ try:
785
+ lib = ctypes.CDLL(cand)
786
+ if hasattr(lib, "tzero_fnv1a_hash64"):
787
+ lib.tzero_fnv1a_hash64.argtypes = [ctypes.c_char_p, ctypes.c_size_t]
788
+ lib.tzero_fnv1a_hash64.restype = ctypes.c_uint64
789
+ if hasattr(lib, "tzero_jaccard_shingles_f64"):
790
+ lib.tzero_jaccard_shingles_f64.argtypes = [
791
+ ctypes.c_char_p, ctypes.c_size_t,
792
+ ctypes.c_char_p, ctypes.c_size_t,
793
+ ctypes.c_size_t,
794
+ ]
795
+ lib.tzero_jaccard_shingles_f64.restype = ctypes.c_double
796
+ if hasattr(lib, "tzero_shannon_entropy"):
797
+ lib.tzero_shannon_entropy.argtypes = [ctypes.c_char_p, ctypes.c_size_t]
798
+ lib.tzero_shannon_entropy.restype = ctypes.c_double
799
+ return lib
800
+ except OSError:
801
+ pass
90
802
  return None
91
803
 
92
804
  @classmethod
93
805
  def _try_load_pyo3(cls) -> Optional[Any]:
806
+ try:
807
+ from tzero import tzero_core # type: ignore
808
+ return tzero_core
809
+ except ImportError:
810
+ pass
811
+ try:
812
+ import tzero_core # type: ignore
813
+ return tzero_core
814
+ except ImportError:
815
+ pass
94
816
  try:
95
817
  import tzero_jarvis_core # type: ignore
96
818
  return tzero_jarvis_core
97
819
  except ImportError:
98
- return None
820
+ pass
821
+
822
+ # Scan target directories for compiled .pyd / .so modules
823
+ for crate in _repo_crate_dirs():
824
+ for build in ("release", "debug"):
825
+ target_dir = os.path.join(crate, "target", build)
826
+ if not os.path.isdir(target_dir):
827
+ continue
828
+ try:
829
+ for fname in os.listdir(target_dir):
830
+ if (fname.startswith("tzero_core") or fname.startswith("libtzero_core")) and (
831
+ fname.endswith(".pyd") or fname.endswith(".so") or fname.endswith(".dylib")
832
+ ):
833
+ full_path = os.path.join(target_dir, fname)
834
+ try:
835
+ loader = importlib.machinery.ExtensionFileLoader("tzero_core", full_path)
836
+ spec = importlib.util.spec_from_file_location("tzero_core", full_path, loader=loader)
837
+ if spec and spec.loader:
838
+ mod = importlib.util.module_from_spec(spec)
839
+ spec.loader.exec_module(mod)
840
+ return mod
841
+ except Exception:
842
+ pass
843
+ except OSError:
844
+ pass
845
+ return None
99
846
 
100
847
  @classmethod
101
848
  def _find_native_binary(cls) -> Optional[str]:
102
- crate = _repo_crate_dir()
103
- exe = "tzero-jarvis.exe" if os.name == "nt" else "tzero-jarvis"
104
- for build in ("release", "debug"):
105
- cand = os.path.join(crate, "target", build, exe)
106
- if os.path.isfile(cand):
107
- return cand
849
+ for crate in _repo_crate_dirs():
850
+ for exe in ("tzero-core.exe", "tzero-core", "tzero-jarvis.exe", "tzero-jarvis"):
851
+ for build in ("release", "debug"):
852
+ cand = os.path.join(crate, "target", build, exe)
853
+ if os.path.isfile(cand):
854
+ return cand
108
855
  return None
109
856
 
110
857
  def backend(self) -> str:
111
- if self._cdylib is not None:
112
- return "ctypes"
113
858
  if self._pyo3_mod is not None:
114
859
  return "pyo3"
860
+ if self._cdylib is not None:
861
+ return "ctypes"
115
862
  if self._bin_path is not None:
116
863
  return "subprocess"
117
864
  return "python-fallback"
118
865
 
866
+ def is_native_available(self) -> bool:
867
+ return self.backend() != "python-fallback"
868
+
119
869
  def fnv1a_hash(self, text: str) -> int:
870
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "fnv1a_hash"):
871
+ return int(self._pyo3_mod.fnv1a_hash(text))
120
872
  if self._cdylib is not None and hasattr(self._cdylib, "tzero_fnv1a_hash64"):
121
873
  raw = (text or "").encode("utf-8", errors="replace")
122
874
  return int(self._cdylib.tzero_fnv1a_hash64(raw, len(raw)))
123
875
  return _pure_fnv1a_64(text)
124
876
 
125
877
  def shingle_similarity(self, a: str, b: str, ngram: int = 3) -> float:
878
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "shingle_similarity"):
879
+ return float(self._pyo3_mod.shingle_similarity(a, b, int(ngram)))
880
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "jaccard_shingles"):
881
+ return float(self._pyo3_mod.jaccard_shingles(a, b, int(ngram)))
126
882
  if self._cdylib is not None and hasattr(self._cdylib, "tzero_jaccard_shingles_f64"):
127
883
  ba = (a or "").encode("utf-8", errors="replace")
128
884
  bb = (b or "").encode("utf-8", errors="replace")
129
885
  return float(self._cdylib.tzero_jaccard_shingles_f64(ba, len(ba), bb, len(bb), max(1, int(ngram))))
130
- if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "jaccard_shingles"):
131
- return float(self._pyo3_mod.jaccard_shingles(a, b, int(ngram)))
132
886
  return _pure_jaccard_shingles(a, b, ngram=ngram)
133
887
 
888
+ def calculate_entropy(self, text: str) -> float:
889
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "calculate_shannon_entropy"):
890
+ return float(self._pyo3_mod.calculate_shannon_entropy(text))
891
+ if self._cdylib is not None and hasattr(self._cdylib, "tzero_shannon_entropy"):
892
+ raw = (text or "").encode("utf-8", errors="replace")
893
+ return float(self._cdylib.tzero_shannon_entropy(raw, len(raw)))
894
+ return _pure_shannon_entropy(text)
895
+
896
+ def scan_entropy_secrets(
897
+ self,
898
+ text: str,
899
+ threshold: float = 4.75,
900
+ min_length: int = 28,
901
+ ) -> List[Dict[str, Any]]:
902
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "scan_entropy_secrets"):
903
+ return list(self._pyo3_mod.scan_entropy_secrets(text, threshold, min_length))
904
+ return _pure_scan_entropy_secrets(text, threshold=threshold, min_length=min_length)
905
+
906
+ def redact_entropy_secrets(self, text: str, threshold: float = 4.4) -> Tuple[str, int]:
907
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "redact_entropy_secrets"):
908
+ res = self._pyo3_mod.redact_entropy_secrets(text, threshold)
909
+ return str(res[0]), int(res[1])
910
+ return _pure_redact_entropy_secrets(text, threshold=threshold)
911
+
912
+ def prune_ast(self, code: str, language: str = "python") -> str:
913
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "prune_ast"):
914
+ return str(self._pyo3_mod.prune_ast(code, language))
915
+ return _pure_prune_ast(code, language=language)
916
+
917
+ def prune_ast_stats(self, code: str, language: str = "python") -> Dict[str, Any]:
918
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "prune_ast_stats"):
919
+ res = self._pyo3_mod.prune_ast_stats(code, language)
920
+ if isinstance(res, dict):
921
+ return res
922
+ return _pure_prune_ast_stats(code, language=language)
923
+
924
+ def count_bpe_tokens(self, text: str, model_name: str = "gpt-4o") -> int:
925
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "count_bpe_tokens"):
926
+ return int(self._pyo3_mod.count_bpe_tokens(text, model_name))
927
+ return _pure_count_bpe_tokens(text, model_name=model_name)
928
+
929
+ def bm25_search(
930
+ self,
931
+ documents: List[Dict[str, str]],
932
+ query: str,
933
+ top_k: int = 10,
934
+ ) -> List[Dict[str, Any]]:
935
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "bm25_search"):
936
+ return list(self._pyo3_mod.bm25_search(documents, query, top_k))
937
+ return _pure_bm25_search(documents, query, top_k=top_k)
938
+
939
+ def extract_symbols(self, path: str, content: str) -> Dict[str, Any]:
940
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "extract_symbols"):
941
+ res = self._pyo3_mod.extract_symbols(path, content)
942
+ if isinstance(res, dict):
943
+ return res
944
+ return _pure_extract_symbols(path, content)
945
+
946
+ def calculate_cyclomatic_complexity(self, code: str, language: str = "python") -> int:
947
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "calculate_cyclomatic_complexity"):
948
+ return int(self._pyo3_mod.calculate_cyclomatic_complexity(code, language))
949
+ return _pure_calculate_cyclomatic_complexity(code, language=language)
950
+
951
+ def calculate_cognitive_complexity(self, code: str) -> int:
952
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "calculate_cognitive_complexity"):
953
+ return int(self._pyo3_mod.calculate_cognitive_complexity(code))
954
+ return _pure_calculate_cognitive_complexity(code)
955
+
956
+ def analyze_file_complexity(self, path: str, code: str, language: str = "python") -> Dict[str, Any]:
957
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "analyze_file_complexity"):
958
+ res = self._pyo3_mod.analyze_file_complexity(path, code, language)
959
+ if isinstance(res, dict):
960
+ return res
961
+ return _pure_analyze_file_complexity(path, code, language=language)
962
+
963
+ def compute_pagerank(
964
+ self,
965
+ edges: List[Dict[str, Any]],
966
+ damping: float = 0.85,
967
+ max_iter: int = 100,
968
+ ) -> List[Dict[str, Any]]:
969
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "compute_pagerank"):
970
+ return list(self._pyo3_mod.compute_pagerank(edges, damping, max_iter))
971
+ return _pure_compute_pagerank(edges, damping=damping, max_iter=max_iter)
972
+
973
+ def analyze_reachability(
974
+ self,
975
+ symbols: List[Dict[str, Any]],
976
+ invocations: List[Tuple[str, str]],
977
+ entrypoints: List[str],
978
+ ) -> Dict[str, Any]:
979
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "analyze_reachability"):
980
+ res = self._pyo3_mod.analyze_reachability(symbols, invocations, entrypoints)
981
+ if isinstance(res, dict):
982
+ return res
983
+ return _pure_analyze_reachability(symbols, invocations, entrypoints)
984
+
985
+ def compare_api_contracts(self, old_code: str, new_code: str) -> Dict[str, Any]:
986
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "compare_api_contracts"):
987
+ res = self._pyo3_mod.compare_api_contracts(old_code, new_code)
988
+ if isinstance(res, dict):
989
+ return res
990
+ return _pure_compare_api_contracts(old_code, new_code)
991
+
992
+ def find_code_duplicity(self, files: List[Tuple[str, str]], min_lines: int = 6) -> Dict[str, Any]:
993
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "find_code_duplicity"):
994
+ res = self._pyo3_mod.find_code_duplicity(files, min_lines)
995
+ if isinstance(res, dict):
996
+ return res
997
+ return _pure_find_code_duplicity(files, min_lines=min_lines)
998
+
999
+ def damerau_levenshtein(self, s1: str, s2: str) -> int:
1000
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "damerau_levenshtein"):
1001
+ return int(self._pyo3_mod.damerau_levenshtein(s1, s2))
1002
+ return _pure_damerau_levenshtein(s1, s2)
1003
+
1004
+ def fuzzy_similarity(self, s1: str, s2: str) -> float:
1005
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "fuzzy_similarity"):
1006
+ return float(self._pyo3_mod.fuzzy_similarity(s1, s2))
1007
+ return _pure_fuzzy_similarity(s1, s2)
1008
+
1009
+ def fuzzy_symbol_search(
1010
+ self,
1011
+ query: str,
1012
+ candidates: List[str],
1013
+ min_similarity: float = 0.6,
1014
+ top_k: int = 5,
1015
+ ) -> List[Dict[str, Any]]:
1016
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "fuzzy_symbol_search"):
1017
+ return list(self._pyo3_mod.fuzzy_symbol_search(query, candidates, min_similarity, top_k))
1018
+ return _pure_fuzzy_symbol_search(query, candidates, min_similarity=min_similarity, top_k=top_k)
1019
+
1020
+ def build_context_tree(self, root_dir: str, tier: int = 3) -> Dict[str, Any]:
1021
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "build_context_tree"):
1022
+ res = self._pyo3_mod.build_context_tree(root_dir, tier)
1023
+ if isinstance(res, dict):
1024
+ return res
1025
+ return _pure_build_context_tree(root_dir, tier=tier)
1026
+
1027
+ def enforce_boundaries(self, edges: List[Tuple[str, str]], banned: Optional[List[str]] = None) -> Dict[str, Any]:
1028
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "enforce_boundaries"):
1029
+ res = self._pyo3_mod.enforce_boundaries(edges, banned)
1030
+ if isinstance(res, dict):
1031
+ return res
1032
+ return _pure_enforce_boundaries(edges, banned=banned)
1033
+
1034
+ def verify_hallucinations(self, code: str, valid_symbols: List[str]) -> Dict[str, Any]:
1035
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "verify_hallucinations"):
1036
+ res = self._pyo3_mod.verify_hallucinations(code, valid_symbols)
1037
+ if isinstance(res, dict):
1038
+ return res
1039
+ return _pure_verify_hallucinations(code, valid_symbols)
1040
+
1041
+ def estimate_costs(
1042
+ self,
1043
+ raw_tokens: int,
1044
+ pruned_tokens: int,
1045
+ output_tokens: int = 2000,
1046
+ model: str = "gpt-4o",
1047
+ ) -> Dict[str, Any]:
1048
+ if self._pyo3_mod is not None and hasattr(self._pyo3_mod, "estimate_costs"):
1049
+ res = self._pyo3_mod.estimate_costs(raw_tokens, pruned_tokens, output_tokens, model)
1050
+ if isinstance(res, dict):
1051
+ return res
1052
+ return _pure_estimate_costs(raw_tokens, pruned_tokens, output_tokens=output_tokens, model=model)
1053
+
1054
+
1055
+ _GLOBAL_BRIDGE: Optional[RustCoreBridge] = None
1056
+
1057
+
1058
+ def get_bridge() -> RustCoreBridge:
1059
+ global _GLOBAL_BRIDGE
1060
+ if _GLOBAL_BRIDGE is None:
1061
+ _GLOBAL_BRIDGE = RustCoreBridge()
1062
+ return _GLOBAL_BRIDGE
1063
+
1064
+
1065
+ def calculate_shannon_entropy(data: str) -> float:
1066
+ return get_bridge().calculate_entropy(data)
1067
+
1068
+
1069
+ def scan_entropy_secrets(
1070
+ text: str,
1071
+ threshold: float = 4.75,
1072
+ min_length: int = 28,
1073
+ ) -> List[Dict[str, Any]]:
1074
+ return get_bridge().scan_entropy_secrets(text, threshold=threshold, min_length=min_length)
1075
+
1076
+
1077
+ def redact_entropy_secrets(text: str, threshold: float = 4.4) -> Tuple[str, int]:
1078
+ return get_bridge().redact_entropy_secrets(text, threshold=threshold)
1079
+
1080
+
1081
+ def prune_ast(code: str, language: str = "python") -> str:
1082
+ return get_bridge().prune_ast(code, language=language)
1083
+
1084
+
1085
+ def prune_ast_stats(code: str, language: str = "python") -> Dict[str, Any]:
1086
+ return get_bridge().prune_ast_stats(code, language=language)
1087
+
1088
+
1089
+ def count_bpe_tokens(text: str, model_name: str = "gpt-4o") -> int:
1090
+ return get_bridge().count_bpe_tokens(text, model_name=model_name)
1091
+
1092
+
1093
+ def fnv1a_hash(text: str) -> int:
1094
+ return get_bridge().fnv1a_hash(text)
1095
+
1096
+
1097
+ def shingle_similarity(a: str, b: str, ngram: int = 3) -> float:
1098
+ return get_bridge().shingle_similarity(a, b, ngram=ngram)
1099
+
1100
+
1101
+ def is_native_available() -> bool:
1102
+ return get_bridge().is_native_available()
1103
+
1104
+
1105
+ def backend() -> str:
1106
+ return get_bridge().backend()
1107
+
1108
+
1109
+ def calculate_cyclomatic_complexity(code: str, language: str = "python") -> int:
1110
+ return get_bridge().calculate_cyclomatic_complexity(code, language=language)
1111
+
1112
+
1113
+ def calculate_cognitive_complexity(code: str) -> int:
1114
+ return get_bridge().calculate_cognitive_complexity(code)
1115
+
1116
+
1117
+ def analyze_file_complexity(path: str, code: str, language: str = "python") -> Dict[str, Any]:
1118
+ return get_bridge().analyze_file_complexity(path, code, language=language)
1119
+
1120
+
1121
+ def compute_pagerank(edges: List[Dict[str, Any]], damping: float = 0.85, max_iter: int = 100) -> List[Dict[str, Any]]:
1122
+ return get_bridge().compute_pagerank(edges, damping=damping, max_iter=max_iter)
1123
+
1124
+
1125
+ def analyze_reachability(
1126
+ symbols: List[Dict[str, Any]],
1127
+ invocations: List[Tuple[str, str]],
1128
+ entrypoints: List[str],
1129
+ ) -> Dict[str, Any]:
1130
+ return get_bridge().analyze_reachability(symbols, invocations, entrypoints)
1131
+
1132
+
1133
+ def compare_api_contracts(old_code: str, new_code: str) -> Dict[str, Any]:
1134
+ return get_bridge().compare_api_contracts(old_code, new_code)
1135
+
1136
+
1137
+ def find_code_duplicity(files: List[Tuple[str, str]], min_lines: int = 6) -> Dict[str, Any]:
1138
+ return get_bridge().find_code_duplicity(files, min_lines=min_lines)
1139
+
1140
+
1141
+ def damerau_levenshtein(s1: str, s2: str) -> int:
1142
+ return get_bridge().damerau_levenshtein(s1, s2)
1143
+
1144
+
1145
+ def fuzzy_similarity(s1: str, s2: str) -> float:
1146
+ return get_bridge().fuzzy_similarity(s1, s2)
1147
+
1148
+
1149
+ def fuzzy_symbol_search(
1150
+ query: str,
1151
+ candidates: List[str],
1152
+ min_similarity: float = 0.6,
1153
+ top_k: int = 5,
1154
+ ) -> List[Dict[str, Any]]:
1155
+ return get_bridge().fuzzy_symbol_search(query, candidates, min_similarity=min_similarity, top_k=top_k)
1156
+
1157
+
1158
+ def build_context_tree(root_dir: str, tier: int = 3) -> Dict[str, Any]:
1159
+ return get_bridge().build_context_tree(root_dir, tier=tier)
1160
+
1161
+
1162
+ def enforce_boundaries(edges: List[Tuple[str, str]], banned: Optional[List[str]] = None) -> Dict[str, Any]:
1163
+ return get_bridge().enforce_boundaries(edges, banned=banned)
1164
+
1165
+
1166
+ def verify_hallucinations(code: str, valid_symbols: List[str]) -> Dict[str, Any]:
1167
+ return get_bridge().verify_hallucinations(code, valid_symbols)
1168
+
1169
+
1170
+ def estimate_costs(
1171
+ raw_tokens: int,
1172
+ pruned_tokens: int,
1173
+ output_tokens: int = 2000,
1174
+ model: str = "gpt-4o",
1175
+ ) -> Dict[str, Any]:
1176
+ return get_bridge().estimate_costs(raw_tokens, pruned_tokens, output_tokens=output_tokens, model=model)
1177
+
134
1178
 
135
1179
  class AgentKernelSandbox:
136
1180
  """Zero-network WASM/capability validator for autonomous T-Zero agent kernel tasks."""