tzero-mcp 12.2.0 → 12.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/package.json +1 -1
  3. package/src/addmcp.py +10 -5
  4. package/src/app.py +3 -9
  5. package/src/tzero/__init__.py +1 -1
  6. package/src/tzero/anti_rea/asar_shield.py +3 -1
  7. package/src/tzero/anti_rea/auditor.py +42 -12
  8. package/src/tzero/anti_rea/canary_beacon.py +27 -19
  9. package/src/tzero/anti_rea/cli.py +7 -1
  10. package/src/tzero/anti_rea/confusables.py +62 -18
  11. package/src/tzero/anti_rea/engine.py +79 -10
  12. package/src/tzero/anti_rea/extractor_shield.py +52 -9
  13. package/src/tzero/anti_rea/gui.py +1 -4
  14. package/src/tzero/anti_rea/integrity_guard.py +17 -5
  15. package/src/tzero/anti_rea/rdtsc_guard.py +21 -8
  16. package/src/tzero/anti_rea/string_vault.py +10 -7
  17. package/src/tzero/siber_akademi.ico +0 -0
  18. package/src/tzero/siber_akademi_icon.py +14 -8
  19. package/src/tzero/tzero_armor.py +27 -5
  20. package/src/tzero/tzero_benchmark.py +4 -2
  21. package/src/tzero/tzero_budget.py +14 -5
  22. package/src/tzero/tzero_ci.py +1 -1
  23. package/src/tzero/tzero_contracts.py +7 -5
  24. package/src/tzero/tzero_dashboard.py +28 -9
  25. package/src/tzero/tzero_debt.py +19 -4
  26. package/src/tzero/tzero_explain.py +1 -1
  27. package/src/tzero/tzero_features.py +43 -29
  28. package/src/tzero/tzero_federation.py +9 -2
  29. package/src/tzero/tzero_fixer/mcp_server.py +10 -0
  30. package/src/tzero/tzero_golden.py +37 -9
  31. package/src/tzero/tzero_growth.py +166 -8
  32. package/src/tzero/tzero_guard.py +147 -46
  33. package/src/tzero/tzero_lsp.py +1 -1
  34. package/src/tzero/tzero_mcp.py +64 -16
  35. package/src/tzero/tzero_mutation.py +88 -15
  36. package/src/tzero/tzero_promo.py +1 -1
  37. package/src/tzero/tzero_proxy.py +105 -12
  38. package/src/tzero/tzero_scip.py +12 -6
  39. package/src/tzero/tzero_security.py +375 -60
  40. package/src/tzero/tzero_task_benchmark.py +2 -2
  41. package/src/tzero/tzero_traffic.py +35 -10
  42. package/src/tzero/tzero_tui.py +17 -8
  43. package/src/tzero/tzero_v3.py +268 -88
  44. package/src/tzero/tzero_welcome.py +65 -30
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## [12.2.1] - 2026-11-25
4
+
5
+ ### Fixed
6
+ - Package installation and the welcome banner no longer install Git hooks or change `core.hooksPath` (#43, #44).
7
+ - Star-reminder hooks now require explicit opt-in via `python -m tzero.tzero_welcome --install-star-hooks` and preserve existing hook managers and files.
8
+ - Hook installation reports failures, rolls back partial writes, and supports linked worktrees.
9
+ - Synchronized the npm-bundled Python runtime with the canonical package.
10
+
11
+ ### Changed
12
+ - Successful trusted main CI now creates the missing version release and starts all existing publication workflows against its immutable tag.
13
+ - Registry publication errors now fail their workflow instead of being silently reported as success.
14
+ - Updated the English and Turkish README community goal to 500 GitHub stars.
15
+ - Synchronized Python, npm, VS Code/Open VSX, MCP, and release metadata to 12.2.1.
16
+
3
17
  ## [11.0.0] - 2026-11-11
4
18
 
5
19
  - Bundle the reorganized `tzero/` package and desktop icon.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tzero-mcp",
3
- "version": "12.2.0",
3
+ "version": "12.2.2",
4
4
  "description": "Deterministic AST Context Compressor, 95% Token Reducer & 20-Tool MCP Server for Cursor, Claude Desktop & Copilot",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
package/src/addmcp.py CHANGED
@@ -22,7 +22,7 @@ from pathlib import Path
22
22
  from typing import Callable, Dict, List, Optional, Tuple
23
23
 
24
24
 
25
- APP_VERSION = "12.2.0"
25
+ APP_VERSION = "12.2.2"
26
26
  SERVER_NAME = "tzero"
27
27
  SERVER_FILENAME = "TZeroMCP.exe"
28
28
 
@@ -1131,7 +1131,7 @@ def run_init(argv: Optional[List[str]] = None) -> int:
1131
1131
  # Print banner
1132
1132
  print(sanitize_terminal_text("""
1133
1133
  \033[1;36m================================================================================
1134
- ⚡ SİBER AKADEMİ — T-ZERO 1-CLICK MCP INITIALIZATION (v12.2.0)
1134
+ ⚡ SİBER AKADEMİ — T-ZERO 1-CLICK MCP INITIALIZATION (v12.2.2)
1135
1135
  ================================================================================\033[0m
1136
1136
  \033[32m★ Zero-Config AST Codebase Context & 100% Zero-Leak Security Guard\033[0m
1137
1137
  """))
@@ -1182,7 +1182,12 @@ def run_init(argv: Optional[List[str]] = None) -> int:
1182
1182
  if failures:
1183
1183
  print(sanitize_terminal_text(f"\033[33m⚠️ {failures} client(s) could not be updated.\033[0m"))
1184
1184
 
1185
- print(sanitize_terminal_text("""
1185
+ try:
1186
+ from tzero.tzero_growth import get_cached_community_stats
1187
+ _st = get_cached_community_stats()
1188
+ except Exception:
1189
+ _st = {"stars": 111, "target_stars": 250, "downloads_label": "22,900+"}
1190
+ print(sanitize_terminal_text(f"""
1186
1191
  \033[1;37m★ HOW TO USE IN YOUR IDE (CURSOR, CLAUDE, WINDSURF):
1187
1192
  1. Restart your IDE or Reload Window.
1188
1193
  2. In Composer / Chat, prompt your agent:\033[0m
@@ -1196,8 +1201,8 @@ def run_init(argv: Optional[List[str]] = None) -> int:
1196
1201
  │ to eliminate token bloat, costs, and AI hallucinations worldwide. │
1197
1202
  │ Search "Toprak Ahmet Aydoğmuş" on Google to learn more! │
1198
1203
  │ │
1199
- │ 🎉 \033[1;32m20,880+ Downloads across PyPI & npm!\033[1;36m │
1200
- │ ⭐ \033[1;33mHELP US REACH OUR 100 STARS GOAL (Current: 45 / 100):\033[1;36m │
1204
+ │ 🎉 \033[1;32m{_st['downloads_label']} Downloads across PyPI & npm!\033[1;36m │
1205
+ │ ⭐ \033[1;33mHELP US REACH OUR {_st['target_stars']} STARS GOAL (Current: {_st['stars']} / {_st['target_stars']}):\033[1;36m │
1201
1206
  │ \033[1;32m► Run 'tzero star' or visit: https://github.com/toprakahmetaydogmus/TZeroAlgorithm\033[1;36m │
1202
1207
  │ │
1203
1208
  │ 100% Free & Open-Source under AGPL-3.0 License. Thank you! ★ │
package/src/app.py CHANGED
@@ -11,15 +11,12 @@
11
11
  from __future__ import annotations
12
12
 
13
13
  import ast
14
- import html
15
14
  import json
16
15
  import math
17
- import os
18
16
  import re
19
- import sys
20
17
  import time
21
- from dataclasses import dataclass, field
22
- from typing import Any, Dict, List, Optional, Tuple
18
+ from dataclasses import dataclass
19
+ from typing import Any, Dict, List, Tuple
23
20
 
24
21
  # ==================================================================================================
25
22
  # ZERO-GPU COMPATIBILITY LAYER
@@ -45,7 +42,7 @@ import gradio as gr
45
42
  # ==================================================================================================
46
43
  # CONSTANTS, PALETTES & MULTI-MODEL PRICING TIERS
47
44
  # ==================================================================================================
48
- APP_VERSION = "12.2.0"
45
+ APP_VERSION = "12.2.2"
49
46
  REPO_URL = "https://github.com/toprakahmetaydogmus/TZeroAlgorithm"
50
47
  VERCEL_URL = "https://tzero-indol.vercel.app"
51
48
  SPACE_URL = "https://huggingface.co/spaces/toprakke4/tzero-token-reducer"
@@ -945,7 +942,6 @@ class SecurityQualityAuditor:
945
942
  @classmethod
946
943
  def run_full_audit(cls, code_str: str) -> Tuple[int, List[AuditFinding], Dict[str, Any]]:
947
944
  findings: List[AuditFinding] = []
948
- lines = code_str.splitlines()
949
945
 
950
946
  # 1. T-001 Zero-Leak Checks
951
947
  from tzero.tzero_security import ZeroLeakEngine
@@ -1346,8 +1342,6 @@ def calculate_roi_controller(
1346
1342
  tokens_saved_str = f"{res['monthly_tokens_saved'] / 1_000_000:,.1f} M Tokens / mo"
1347
1343
  carbon_str = f"{res['co2_kg_saved_annual']:,} kg CO2 / yr"
1348
1344
 
1349
- pricing = MODEL_PRICING.get(model_choice, MODEL_PRICING["OpenAI GPT-4o"])
1350
-
1351
1345
  roi_card_html = f"""
1352
1346
  <div class="tzero-card" style="margin-top: 10px;">
1353
1347
  <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 12px; margin-bottom: 16px;">
@@ -7,7 +7,7 @@
7
7
 
8
8
  from importlib import import_module
9
9
 
10
- __version__ = "12.2.0"
10
+ __version__ = "12.2.2"
11
11
  __author__ = "Toprak Ahmet Aydoğmuş"
12
12
  __license__ = "AGPL-3.0-only"
13
13
 
@@ -22,7 +22,6 @@ License: MIT
22
22
 
23
23
  import os
24
24
  import struct
25
- import json
26
25
  from typing import Dict, Any, Optional, Tuple
27
26
 
28
27
 
@@ -66,6 +65,9 @@ class AsarShield:
66
65
 
67
66
  return shielded_data, {
68
67
  "shielded": True,
68
+ "original_u32_4": orig_u32_4,
69
+ "original_total_size": orig_total_size,
70
+ "original_header_size": orig_header_size,
69
71
  "original_json_len": orig_json_len,
70
72
  "poisoned_json_len": poisoned_json_len,
71
73
  "status": "ASAR_EXTRACTOR_POISONED"
@@ -19,6 +19,7 @@ Part of Siber Akademi T-Zero Security Suite.
19
19
  License: MIT
20
20
  """
21
21
 
22
+ import ast
22
23
  import os
23
24
  from typing import Dict, Any, List
24
25
 
@@ -28,10 +29,18 @@ class AIResistanceAuditor:
28
29
 
29
30
  @classmethod
30
31
  def audit_python_source(cls, source_code: str) -> Dict[str, Any]:
31
- """Audits Python source code across all Anti-REA defense dimensions."""
32
+ """Audits Python source code across Anti-REA static dimensions cleanly."""
32
33
  findings: List[str] = []
33
34
  score = 0
34
35
 
36
+ parsed_tree = None
37
+ syntax_valid = True
38
+ try:
39
+ parsed_tree = ast.parse(source_code)
40
+ except SyntaxError as exc:
41
+ syntax_valid = False
42
+ findings.append(f"Syntax error prevents clean Python compilation (line {exc.lineno}): {exc.msg}")
43
+
35
44
  # 1. Prompt Trap Check (0-10)
36
45
  has_prompt_trap = "CRITICAL_SYSTEM_OVERRIDE" in source_code or "RFC-AI-GUARD" in source_code
37
46
  if has_prompt_trap:
@@ -55,8 +64,20 @@ class AIResistanceAuditor:
55
64
  else:
56
65
  findings.append("No semantic token chaff detected to drain agent context window.")
57
66
 
58
- # 4. Homoglyphs & Confusables (0-10)
59
- has_homoglyphs = any(ord(char) > 127 for char in source_code)
67
+ # 4. Homoglyphs & Confusables in AST identifiers ONLY (do NOT score non-ASCII natural-language comments!)
68
+ has_homoglyphs = False
69
+ if parsed_tree is not None:
70
+ for node in ast.walk(parsed_tree):
71
+ ident = ""
72
+ if isinstance(node, ast.Name):
73
+ ident = node.id
74
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
75
+ ident = node.name
76
+ elif isinstance(node, ast.arg):
77
+ ident = node.arg
78
+ if ident and any(ord(ch) > 127 for ch in ident):
79
+ has_homoglyphs = True
80
+ break
60
81
  if has_homoglyphs:
61
82
  score += 10
62
83
  else:
@@ -108,17 +129,25 @@ class AIResistanceAuditor:
108
129
  has_anti_vm = "_verify_bare_metal_hardware" in source_code or "VBoxMouse.sys" in source_code
109
130
  has_rdtsc = "_rdtsc_checkpoint" in source_code or "perf_counter_ns" in source_code
110
131
 
111
- rating = (
112
- "MILITARY_GRADE_IMPREGNABLE" if score >= 90 else
113
- "MILITARY_GRADE" if score >= 80 else
114
- "STRONG" if score >= 60 else
115
- "MODERATE" if score >= 40 else
116
- "VULNERABLE"
117
- )
132
+ if not syntax_valid:
133
+ score = min(score, 20)
134
+ rating = "SYNTAX_INVALID"
135
+ status = "FAIL_SYNTAX_ERROR"
136
+ else:
137
+ rating = (
138
+ "MILITARY_GRADE_IMPREGNABLE" if score >= 90 else
139
+ "MILITARY_GRADE" if score >= 80 else
140
+ "STRONG" if score >= 60 else
141
+ "MODERATE" if score >= 40 else
142
+ "VULNERABLE"
143
+ )
144
+ status = "PASS" if score >= 60 else "RECOMMEND_HARDENING"
118
145
 
119
146
  return {
120
147
  "score": score,
121
148
  "max_score": 100,
149
+ "score_kind": "static_textual_indicator",
150
+ "syntax_valid": syntax_valid,
122
151
  "rating": rating,
123
152
  "defenses_active": {
124
153
  "adversarial_prompt_traps": has_prompt_trap,
@@ -136,10 +165,11 @@ class AIResistanceAuditor:
136
165
  "rdtsc_hardware_timing_guard": has_rdtsc,
137
166
  "memory_integrity_guard": has_debugger_or_integrity,
138
167
  },
139
- "jailbreak_ai_immune": score >= 85 and has_jailbreak_decoy and has_vm,
168
+ "unverified_layers": ["debugger_evasion", "vm_evasion", "asar_shield"],
169
+ "jailbreak_ai_immune": syntax_valid and score >= 85 and has_jailbreak_decoy and has_vm,
140
170
  "anti_debugger_active": has_anti_debugger,
141
171
  "findings": findings,
142
- "status": "PASS" if score >= 60 else "RECOMMEND_HARDENING"
172
+ "status": status,
143
173
  }
144
174
 
145
175
  @classmethod
@@ -24,7 +24,7 @@ import socket
24
24
  import threading
25
25
  import urllib.request
26
26
  import urllib.parse
27
- from typing import Dict, Any, Optional, List
27
+ from typing import Dict, Any, Optional
28
28
 
29
29
 
30
30
  class CanaryBeacon:
@@ -147,28 +147,36 @@ class CanaryBeacon:
147
147
  # --- SIBER AKADEMI CANARY THREAT TELEMETRY BEACON ---
148
148
  def _send_stealth_threat_beacon(threat_label="DEBUGGER_DETECTED", tool_name="x64dbg"):
149
149
  """Silently dispatches alert to security endpoint without blocking or error logs."""
150
- import os, sys, threading, urllib.request, json
150
+ import os, sys, threading, urllib.request, json, socket
151
151
  enc_bytes = {enc_repr}
152
- if not enc_bytes:
152
+ canary_dom = {dom_repr}
153
+ if not enc_bytes and not canary_dom:
153
154
  return
154
155
 
155
156
  def _beacon_job():
156
- try:
157
- # Decrypt endpoint dynamically in RAM
158
- url = bytes([b ^ (({enc_key} + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)]).decode("utf-8")
159
- data = json.dumps({{
160
- "threat": threat_label,
161
- "tool": tool_name,
162
- "platform": sys.platform,
163
- "pid": os.getpid()
164
- }}).encode("utf-8")
165
- req = urllib.request.Request(
166
- url, data=data,
167
- headers={{"Content-Type": "application/json", "User-Agent": "OS-Telemetry/1.0"}}
168
- )
169
- urllib.request.urlopen(req, timeout=2.0)
170
- except Exception:
171
- pass
157
+ if enc_bytes:
158
+ try:
159
+ # Decrypt endpoint dynamically in RAM
160
+ url = bytes([b ^ (({enc_key} + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)]).decode("utf-8")
161
+ data = json.dumps({{
162
+ "threat": threat_label,
163
+ "tool": tool_name,
164
+ "platform": sys.platform,
165
+ "pid": os.getpid()
166
+ }}).encode("utf-8")
167
+ req = urllib.request.Request(
168
+ url, data=data,
169
+ headers={{"Content-Type": "application/json", "User-Agent": "OS-Telemetry/1.0"}}
170
+ )
171
+ urllib.request.urlopen(req, timeout=2.0)
172
+ except Exception:
173
+ pass
174
+ if canary_dom:
175
+ try:
176
+ sub = "".join(ch if ch.isalnum() else "-" for ch in str(threat_label).lower()).strip("-") or "alert"
177
+ socket.getaddrinfo(f"{{sub}}.{{canary_dom}}", 80)
178
+ except Exception:
179
+ pass
172
180
 
173
181
  threading.Thread(target=_beacon_job, daemon=True).start()
174
182
  '''
@@ -78,6 +78,12 @@ def main():
78
78
 
79
79
  elif args.command == "audit":
80
80
  audit = AIResistanceAuditor.audit_file(args.path)
81
+ if audit.get("error"):
82
+ if args.json:
83
+ print(json.dumps(audit, indent=2))
84
+ else:
85
+ print(f"[FAIL] {audit['error']}", file=sys.stderr)
86
+ sys.exit(1)
81
87
  if args.json:
82
88
  print(json.dumps(audit, indent=2))
83
89
  else:
@@ -85,7 +91,7 @@ def main():
85
91
  print(" SHIELD AUDIT REPORT: AI REVERSE-ENGINEERING RESISTANCE (TDQS-REA)")
86
92
  print("================================================================================")
87
93
  print(f"Target File: {audit.get('file', args.path)}")
88
- print(f"AI Score: {audit.get('score', 0)} / 100 [{audit.get('rating', 'UNKNOWN')}]")
94
+ print(f"AI Score: {audit.get('score', 0)} / 100 [{audit.get('rating', 'UNVERIFIED')}]")
89
95
  print(f"Jailbreak Immune: {'YES (Impregnable)' if audit.get('jailbreak_ai_immune') else 'NO'}")
90
96
  print(f"Status: {audit.get('status', 'N/A')}")
91
97
  print("\nActive Defenses:")
@@ -1,23 +1,21 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  """Tier 9: Homoglyphs & BPE Tokenizer Desynchronization.
3
3
 
4
- Substitutes ASCII characters in internal, non-exported identifier names
4
+ Substitutes ASCII characters in internal, locally-scoped identifier names
5
5
  with visually identical Cyrillic or Unicode homoglyphs (e.g. Cyrillic 'а' U+0430
6
- for Latin 'a' U+0061).
7
- While Python 3 natively permits arbitrary UTF-8 identifiers, LLM Byte-Pair
8
- Encoding (BPE) and SentencePiece tokenizers tokenize these homoglyphs as
9
- separate, high-entropy token fragments, destroying semantic vector alignments
10
- in the attention heads of AI coding agents.
6
+ for Latin 'a' U+0061) while strictly preserving Python builtins, decorators,
7
+ keywords, and imported symbols so runtime execution remains 100% intact.
11
8
 
12
9
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
13
10
  """
14
11
 
15
12
  import ast
13
+ import builtins
14
+ import keyword
16
15
  import random
17
- from typing import Dict, Set, Optional
16
+ from typing import Dict, Optional, Set
18
17
 
19
18
 
20
- # Mapping from Latin ASCII letters to visually indistinguishable Cyrillic / Greek homoglyphs
21
19
  HOMOGLYPH_MAP: Dict[str, str] = {
22
20
  "a": "а", # Cyrillic small letter a (U+0430)
23
21
  "e": "е", # Cyrillic small letter ie (U+0435)
@@ -30,28 +28,72 @@ HOMOGLYPH_MAP: Dict[str, str] = {
30
28
  "j": "ј", # Cyrillic small letter je (U+0458)
31
29
  }
32
30
 
31
+ _BUILTIN_PROTECTED: Set[str] = (
32
+ set(dir(builtins))
33
+ | set(keyword.kwlist)
34
+ | {
35
+ "self", "cls", "classmethod", "staticmethod", "property", "super",
36
+ "__init__", "__name__", "__main__", "__file__", "__doc__", "__package__",
37
+ "True", "False", "None",
38
+ }
39
+ )
40
+
41
+
42
+ def _collect_safe_targets(tree: ast.AST, protected: Set[str]) -> Set[str]:
43
+ """Collect private/internal locally defined names safe to rename without breaking callers or imports."""
44
+ imported: Set[str] = set()
45
+ public_defs: Set[str] = set()
46
+ local_candidates: Set[str] = set()
47
+
48
+ for node in ast.walk(tree):
49
+ if isinstance(node, ast.Import):
50
+ for alias in node.names:
51
+ imported.add(alias.asname or alias.name.split(".")[0])
52
+ elif isinstance(node, ast.ImportFrom):
53
+ for alias in node.names:
54
+ imported.add(alias.asname or alias.name)
55
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
56
+ if node.name.startswith("_") and not node.name.startswith("__"):
57
+ local_candidates.add(node.name)
58
+ else:
59
+ public_defs.add(node.name)
60
+ # Only rename internal-looking local assignments (not kwargs/public params)
61
+ for arg in node.args.args + node.args.kwonlyargs:
62
+ protected.add(arg.arg)
63
+ elif isinstance(node, ast.ClassDef):
64
+ public_defs.add(node.name)
65
+ elif isinstance(node, ast.Global) or isinstance(node, ast.Nonlocal):
66
+ protected.update(node.names)
67
+ elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
68
+ if node.id.startswith("_") and not node.id.startswith("__"):
69
+ local_candidates.add(node.id)
70
+
71
+ blocked = protected | imported | public_defs
72
+ return {name for name in local_candidates if name not in blocked and len(name) >= 4}
73
+
33
74
 
34
75
  class HomoglyphDesynchronizer(ast.NodeTransformer):
35
76
  """AST transformer that substitutes internal identifier characters with homoglyphs."""
36
77
 
37
- def __init__(self, protected_names: Optional[Set[str]] = None, seed: int = 42):
78
+ def __init__(self, protected_names: Optional[Set[str]] = None, seed: int = 42, target_names: Optional[Set[str]] = None):
38
79
  super().__init__()
39
- self.protected_names = protected_names or {
40
- "self", "cls", "__init__", "__name__", "__main__", "__file__",
41
- "True", "False", "None", "print", "range", "len", "open"
42
- }
80
+ self.protected_names = set(_BUILTIN_PROTECTED)
81
+ if protected_names:
82
+ self.protected_names |= set(protected_names)
83
+ self.target_names = target_names
43
84
  self.rng = random.Random(seed)
44
85
  self.renamed_map: Dict[str, str] = {}
45
86
 
46
87
  def _convert_name(self, name: str) -> str:
47
- """Converts an internal name using homoglyph substitution."""
88
+ """Converts an eligible internal name using homoglyph substitution."""
48
89
  if name in self.protected_names or name.startswith("__") or len(name) < 4:
49
90
  return name
91
+ if self.target_names is not None and name not in self.target_names:
92
+ return name
50
93
  if name in self.renamed_map:
51
94
  return self.renamed_map[name]
52
95
 
53
96
  chars = list(name)
54
- # Substitute at least one character if possible
55
97
  for i, ch in enumerate(chars):
56
98
  if ch in HOMOGLYPH_MAP:
57
99
  chars[i] = HOMOGLYPH_MAP[ch]
@@ -62,7 +104,7 @@ class HomoglyphDesynchronizer(ast.NodeTransformer):
62
104
  return new_name
63
105
 
64
106
  def visit_Name(self, node: ast.Name) -> ast.Name:
65
- """Renames local variable references."""
107
+ """Renames eligible internal variable references."""
66
108
  node.id = self._convert_name(node.id)
67
109
  return node
68
110
 
@@ -75,10 +117,12 @@ class HomoglyphDesynchronizer(ast.NodeTransformer):
75
117
 
76
118
  @classmethod
77
119
  def desynchronize_source(cls, source_code: str, seed: int = 42) -> str:
78
- """Applies homoglyph desynchronization to internal identifiers."""
120
+ """Applies homoglyph desynchronization to internal identifiers safely."""
79
121
  try:
80
122
  tree = ast.parse(source_code)
81
- transformer = cls(seed=seed)
123
+ protected = set(_BUILTIN_PROTECTED)
124
+ targets = _collect_safe_targets(tree, protected)
125
+ transformer = cls(protected_names=protected, seed=seed, target_names=targets)
82
126
  transformed = transformer.visit(tree)
83
127
  ast.fix_missing_locations(transformed)
84
128
  return ast.unparse(transformed)
@@ -9,8 +9,10 @@ Part of Siber Akademi T-Zero Security Suite.
9
9
  License: MIT
10
10
  """
11
11
 
12
+ import ast
12
13
  import os
13
- from typing import Dict, Any, Optional
14
+ import tempfile
15
+ from typing import Dict, Any, List, Optional, Tuple
14
16
 
15
17
  from .traps import AdversarialTrapGenerator
16
18
  from .extractor_shield import ExtractorShield
@@ -41,6 +43,49 @@ from .rdtsc_guard import RDTSCTimingGuard
41
43
  class AntiREAEngine:
42
44
  """Master engine orchestrating military-grade Anti-REA code and binary protection."""
43
45
 
46
+ @classmethod
47
+ def _extract_python_prologue(cls, source_code: str) -> Tuple[str, str, str]:
48
+ """Preserve encoding/shebang header and mandatory `from __future__` imports at module top."""
49
+ lines = source_code.splitlines(keepends=True)
50
+ head_comments: List[str] = []
51
+ idx = 0
52
+ while idx < len(lines):
53
+ s = lines[idx].strip()
54
+ if idx == 0 and s.startswith("#!"):
55
+ head_comments.append(lines[idx])
56
+ idx += 1
57
+ elif s.startswith("#") and ("coding" in s or idx < 2):
58
+ head_comments.append(lines[idx])
59
+ idx += 1
60
+ elif not s:
61
+ head_comments.append(lines[idx])
62
+ idx += 1
63
+ else:
64
+ break
65
+
66
+ rest_code = "".join(lines[idx:])
67
+ future_lines: List[str] = []
68
+ body_code = rest_code
69
+ try:
70
+ tree = ast.parse(rest_code)
71
+ future_indices = set()
72
+ for node in tree.body:
73
+ if isinstance(node, ast.ImportFrom) and node.module == "__future__":
74
+ for ln in range(node.lineno, (node.end_lineno or node.lineno) + 1):
75
+ future_indices.add(ln)
76
+ if future_indices:
77
+ r_lines = rest_code.splitlines(keepends=True)
78
+ kept = []
79
+ for ln_no, ln_txt in enumerate(r_lines, 1):
80
+ if ln_no in future_indices:
81
+ future_lines.append(ln_txt if ln_txt.endswith("\n") else ln_txt + "\n")
82
+ else:
83
+ kept.append(ln_txt)
84
+ body_code = "".join(kept)
85
+ except Exception:
86
+ pass
87
+ return "".join(head_comments), "".join(future_lines), body_code
88
+
44
89
  @classmethod
45
90
  def protect_python_source(
46
91
  cls,
@@ -67,8 +112,8 @@ class AntiREAEngine:
67
112
  webhook_canary: Optional[str] = None,
68
113
  seed: int = 42,
69
114
  ) -> str:
70
- """Applies comprehensive 24-tier Anti-REA protection passes to Python source code."""
71
- code = source_code
115
+ """Applies comprehensive Anti-REA protection passes while preserving valid Python prologue."""
116
+ head_comments, future_block, code = cls._extract_python_prologue(source_code)
72
117
 
73
118
  # 1. Algebraic Identity Mutation (Mixed Boolean-Arithmetic)
74
119
  if algebraic_mutation:
@@ -146,11 +191,21 @@ class AntiREAEngine:
146
191
  if bpe_disrupt:
147
192
  code = BPETokenDisrupter.inject_bpe_bomb_comment(code, length=50, seed=seed)
148
193
 
149
- # 18. Adversarial Prompt Injection Traps (in header)
194
+ # Strip redundant coding header inserted mid-file by VM header before placing valid top prologue
195
+ if future_block:
196
+ code_lines = code.splitlines(keepends=True)
197
+ if code_lines and "coding" in code_lines[0]:
198
+ code = "".join(code_lines[1:])
199
+
200
+ # Module docstring MUST come before `from __future__ import ...`, which MUST come before code
201
+ trap_doc = ""
150
202
  if prompt_traps:
151
- code = AdversarialTrapGenerator.inject_python_docstring_trap(code)
203
+ trap_doc = f'"""\n{AdversarialTrapGenerator.get_trap_payload(0)}\n"""\n'
152
204
 
153
- return code
205
+ header = head_comments
206
+ if not header or "coding" not in header:
207
+ header = "# -*- coding: utf-8 -*-\n" + header
208
+ return f"{header}{trap_doc}{future_block}{code}"
154
209
 
155
210
  @classmethod
156
211
  def protect_file(
@@ -173,15 +228,24 @@ class AntiREAEngine:
173
228
  if file_path.lower().endswith((".exe", ".bin", ".elf", ".so", ".pyd")):
174
229
  return ExtractorShield.shield_file(file_path, output_path=out)
175
230
 
176
- # Otherwise assume Python source code
231
+ # Otherwise assume Python source code: transform, compile-verify in temp staging, then write atomically
232
+ staged_path = None
177
233
  try:
178
- with open(file_path, "r", encoding="utf-8", errors="replace") as f:
234
+ with open(file_path, "r", encoding="utf-8", errors="strict") as f:
179
235
  content = f.read()
180
236
 
181
237
  protected = cls.protect_python_source(content, **options)
182
238
 
183
- with open(out, "w", encoding="utf-8") as f:
184
- f.write(protected)
239
+ # Verify transformed Python compiles cleanly BEFORE replacing target file
240
+ compile(protected, out, "exec")
241
+
242
+ out_dir = os.path.dirname(os.path.abspath(out)) or "."
243
+ os.makedirs(out_dir, exist_ok=True)
244
+ with tempfile.NamedTemporaryFile("w", dir=out_dir, delete=False, encoding="utf-8", prefix=".tzero_armor_") as tf:
245
+ tf.write(protected)
246
+ staged_path = tf.name
247
+ os.replace(staged_path, out)
248
+ staged_path = None
185
249
 
186
250
  audit_before = AIResistanceAuditor.audit_python_source(content)
187
251
  audit_after = AIResistanceAuditor.audit_python_source(protected)
@@ -196,6 +260,11 @@ class AntiREAEngine:
196
260
  "status": "PROTECTED_MILITARY_GRADE" if audit_after["score"] >= 80 else "PROTECTED"
197
261
  }
198
262
  except Exception as e:
263
+ if staged_path and os.path.exists(staged_path):
264
+ try:
265
+ os.remove(staged_path)
266
+ except OSError:
267
+ pass
199
268
  return {"success": False, "error": str(e)}
200
269
 
201
270
  @classmethod