tzero-mcp 11.11.0 → 11.14.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.
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * T-Zero npm postinstall welcome & GitHub star prompt
5
+ */
6
+
7
+ const isTest = process.env.TEST_POSTINSTALL === "1" || process.env.TZERO_FORCE_BANNER === "1";
8
+ const noBanner = !isTest && (process.env.TZERO_NO_BANNER === "1" || process.env.CI === "true" || process.env.npm_config_loglevel === "silent");
9
+
10
+ if (!noBanner) {
11
+ console.log(`\x1b[36m
12
+ ┌──────────────────────────────────────────────────────────────────────────────┐
13
+ │ ⚡ T-ZERO MCP INSTALLED SUCCESSFULLY! │
14
+ ├──────────────────────────────────────────────────────────────────────────────┤
15
+ │ ⭐ Star on GitHub: \x1b[33mhttps://github.com/toprakahmetaydogmus/TZeroAlgorithm\x1b[36m │
16
+ │ │
17
+ │ 💡 1-Click Setup: │
18
+ │ \x1b[37mnpx tzero-mcp --install\x1b[36m Configure Cursor, Claude, Windsurf, VS Code │
19
+ │ \x1b[37mnpx tzero --help\x1b[36m View all CLI AST reduction commands │
20
+ └──────────────────────────────────────────────────────────────────────────────┘
21
+ \x1b[0m`);
22
+ }
package/bin/tzero-mcp.js CHANGED
@@ -22,7 +22,8 @@ const banner = `\x1b[36m
22
22
  └──────────────────────────────────────────────────────────────────────────────┘
23
23
  \x1b[0m`;
24
24
 
25
- if (process.stderr.isTTY) {
25
+ const isQuietStderr = process.env.TZERO_NO_BANNER === "1" || process.env.CI === "true";
26
+ if (!isQuietStderr) {
26
27
  process.stderr.write(banner + "\n");
27
28
  }
28
29
 
package/bin/tzero.js CHANGED
@@ -21,7 +21,14 @@ const banner = `\x1b[36m
21
21
  └──────────────────────────────────────────────────────────────────────────────┘
22
22
  \x1b[0m`;
23
23
 
24
- if (process.stdout.isTTY && !process.argv.includes("--json") && !process.argv.includes("--pipe")) {
24
+ const isQuiet = process.env.TZERO_NO_BANNER === "1" ||
25
+ process.env.CI === "true" ||
26
+ process.argv.includes("--json") ||
27
+ process.argv.includes("--pipe") ||
28
+ process.argv.includes("--silent") ||
29
+ process.argv.includes("-q");
30
+
31
+ if (!isQuiet) {
25
32
  console.log(banner);
26
33
  }
27
34
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tzero-mcp",
3
- "version": "11.11.0",
3
+ "version": "11.14.0",
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",
@@ -35,6 +35,7 @@
35
35
  "tzero-mcp": "bin/tzero-mcp.js"
36
36
  },
37
37
  "scripts": {
38
+ "postinstall": "node bin/postinstall.js",
38
39
  "test": "node --test test/package.test.js"
39
40
  },
40
41
  "repository": {
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 = "11.11.0"
25
+ APP_VERSION = "11.13.0"
26
26
  SERVER_NAME = "tzero"
27
27
  SERVER_FILENAME = "TZeroMCP.exe"
28
28
 
@@ -1120,7 +1120,7 @@ def run_init(argv: Optional[List[str]] = None) -> int:
1120
1120
  # Print banner
1121
1121
  print("""
1122
1122
  \033[1;36m================================================================================
1123
- ⚡ SİBER AKADEMİ — T-ZERO 1-CLICK MCP INITIALIZATION (v11.11.0)
1123
+ ⚡ SİBER AKADEMİ — T-ZERO 1-CLICK MCP INITIALIZATION (v11.13.0)
1124
1124
  ================================================================================\033[0m
1125
1125
  \033[32m🎯 Zero-Config AST Codebase Context & 100% Zero-Leak Security Guard\033[0m
1126
1126
  """)
@@ -1181,7 +1181,7 @@ def run_init(argv: Optional[List[str]] = None) -> int:
1181
1181
  \033[1;36m┌──────────────────────────────────────────────────────────────────────────────┐
1182
1182
  │ ⚡ SIBER AKADEMI T-ZERO CONTEXT ARCHITECT & MCP ENGINE │
1183
1183
  │ │
1184
- │ Engineered by Toprak Ahmet Aydoğmuş (15-year-old solo dev) & Siber Akademi │
1184
+ │ Engineered by Toprak Ahmet Aydoğmuş & Siber Akademi │
1185
1185
  │ to eliminate token bloat, costs, and AI hallucinations worldwide. │
1186
1186
  │ Search "Toprak Ahmet Aydoğmuş" on Google to learn more! │
1187
1187
  │ │
@@ -0,0 +1,18 @@
1
+ # -*- coding: utf-8 -*-
2
+ """T-Zero MCP Installer Bridge Module.
3
+
4
+ Exposes addmcp functionality within the tzero package namespace.
5
+ """
6
+
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ try:
11
+ from addmcp import *
12
+ from addmcp import run_cli, run_init, build_client_targets, install_targets
13
+ except ImportError:
14
+ root = Path(__file__).resolve().parent.parent
15
+ if str(root) not in sys.path:
16
+ sys.path.insert(0, str(root))
17
+ from addmcp import *
18
+ from addmcp import run_cli, run_init, build_client_targets, install_targets
@@ -12,7 +12,7 @@ Capabilities:
12
12
  - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
13
13
 
14
14
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
15
- Part of T-Zero Context Architect v11.11.0 Master Edition.
15
+ Part of T-Zero Context Architect v11.13.0 Master Edition.
16
16
  """
17
17
 
18
18
  import hashlib
@@ -150,7 +150,7 @@ class TZeroShowcaseGenerator:
150
150
  <!-- Bottom Footer Strip -->
151
151
  <g transform="translate(32, 212)">
152
152
  <text x="0" y="8" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif" font-size="10" font-weight="500" fill="#475569">
153
- 🚀 Run <tspan fill="#38bdf8" font-family="monospace">npx -y tzero-mcp@latest</tspan> or <tspan fill="#38bdf8" font-family="monospace">pip install tzero-mcp</tspan> &bull; By Toprak Ahmet Aydoğmuş (15 y/o dev) &bull; MIT
153
+ 🚀 Run <tspan fill="#38bdf8" font-family="monospace">npx -y tzero-mcp@latest</tspan> or <tspan fill="#38bdf8" font-family="monospace">pip install tzero-mcp</tspan> • By Toprak Ahmet Aydoğmuş • MIT
154
154
  </text>
155
155
  <text x="736" y="8" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif" font-size="10" font-weight="600" fill="#64748b" text-anchor="end">
156
156
  Siber Akademi Engine v5.1.0
@@ -13,7 +13,7 @@ Capabilities:
13
13
  - 100% Offline, $0 cost, zero external dependencies (pure Python standard library).
14
14
 
15
15
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
16
- Part of T-Zero Context Architect v11.11.0 Master Edition.
16
+ Part of T-Zero Context Architect v11.13.0 Master Edition.
17
17
  """
18
18
 
19
19
  import ast
@@ -1035,7 +1035,7 @@ class ASTContractComparator:
1035
1035
  "tool": {
1036
1036
  "driver": {
1037
1037
  "name": "T-Zero Contract Guardian",
1038
- "version": "11.11.0",
1038
+ "version": "11.13.0",
1039
1039
  "rules": rules_list
1040
1040
  }
1041
1041
  },
@@ -457,7 +457,7 @@ HTML_PAGE = """<!DOCTYPE html>
457
457
  <div class="brand-logo">T0</div>
458
458
  <div>
459
459
  <div class="brand-title">T-Zero Developer Console</div>
460
- <div class="brand-sub" id="headerBrandSub">Enterprise AST Context Architect &bull; v11.11.0</div>
460
+ <div class="brand-sub" id="headerBrandSub">Enterprise AST Context Architect &bull; v11.13.0</div>
461
461
  </div>
462
462
  </div>
463
463
  <div class="header-actions">
@@ -850,7 +850,7 @@ x = 2
850
850
  </main>
851
851
 
852
852
  <footer>
853
- <span id="footerBrand">T-Zero Context Architect v11.11.0</span> &bull; Developer: Toprak Ahmet Aydoğmuş &bull; Siber Akademi
853
+ <span id="footerBrand">T-Zero Context Architect v11.13.0</span> &bull; Developer: Toprak Ahmet Aydoğmuş &bull; Siber Akademi
854
854
  </footer>
855
855
 
856
856
  <script>
@@ -1481,7 +1481,7 @@ def compute_live_dashboard_stats(workspace_dir: str = ".") -> Dict[str, Any]:
1481
1481
  if cached is not None and (now - _DASHBOARD_STATS_CACHE["ts"]) < 60.0:
1482
1482
  return cached
1483
1483
 
1484
- version = "11.11.0"
1484
+ version = "11.13.0"
1485
1485
  tools_count = 57
1486
1486
  try:
1487
1487
  from tzero import tzero_mcp
@@ -13,7 +13,7 @@ Capabilities:
13
13
  - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
14
14
 
15
15
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
16
- Part of T-Zero Context Architect v11.11.0 Master Edition.
16
+ Part of T-Zero Context Architect v11.13.0 Master Edition.
17
17
  """
18
18
 
19
19
  import ast
@@ -723,18 +723,20 @@ globs: **/*
723
723
  prof = WorkspaceProfiler(project_dir).profile()
724
724
  agent_md_content = WorkspaceGovernanceSynthesizer.generate_agent_md(prof)
725
725
 
726
- agent_p = os.path.join(project_dir, "AGENT.md")
727
- with open(agent_p, "w", encoding="utf-8") as f:
728
- f.write(agent_md_content)
729
- created.append(agent_p)
730
-
731
726
  agents_p = os.path.join(project_dir, "AGENTS.md")
732
727
  with open(agents_p, "w", encoding="utf-8") as f:
733
728
  f.write(agent_md_content)
734
729
  created.append(agents_p)
735
730
 
736
- # 8. ARCHITECTURE.md if not exists
737
- arch_p = os.path.join(project_dir, "ARCHITECTURE.md")
731
+ agent_p = os.path.join(project_dir, "AGENT.md")
732
+ with open(agent_p, "w", encoding="utf-8") as f:
733
+ f.write(agent_md_content)
734
+ created.append(agent_p)
735
+
736
+ # 8. ARCHITECTURE.md (in docs/ if docs exists, else root)
737
+ docs_dir = os.path.join(project_dir, "docs")
738
+ target_arch_dir = docs_dir if os.path.isdir(docs_dir) else project_dir
739
+ arch_p = os.path.join(target_arch_dir, "ARCHITECTURE.md")
738
740
  if not os.path.isfile(arch_p):
739
741
  with open(arch_p, "w", encoding="utf-8") as f:
740
742
  f.write(WorkspaceGovernanceSynthesizer.generate_architecture_md(prof))
@@ -1621,6 +1623,62 @@ def launch_web_dashboard(project_dir: str = ".", port: int = 7300, open_browser:
1621
1623
  # 7. ZERO-HALLUCINATION GUARD & PRE-FLIGHT SYMBOL / CALL VALIDATOR (TOOL 17)
1622
1624
  # =============================================================================
1623
1625
 
1626
+ import importlib
1627
+ import builtins
1628
+
1629
+ PYTHON_BUILTIN_FUNCTIONS = set(dir(builtins))
1630
+
1631
+ BUILTIN_COMMON_METHODS = {
1632
+ # unittest / testing
1633
+ "assert", "assertequal", "assertnotequal", "asserttrue", "assertfalse",
1634
+ "assertis", "assertisnot", "assertisnone", "assertisnotnone",
1635
+ "assertin", "assertnotin", "assertisinstance", "assertnotisinstance",
1636
+ "assertgreater", "assertgreaterequal", "assertless", "assertlessequal",
1637
+ "assertalmostequal", "assertnotalmostequal", "assertraises", "assertwarns",
1638
+ "assertlogs", "assertcount", "assertsequenceequal", "assertdictequal",
1639
+ "setup", "teardown", "setupclass", "teardownclass",
1640
+ # pathlib & fs methods
1641
+ "write_text", "read_text", "write_bytes", "read_bytes", "mkdir", "unlink",
1642
+ "rmdir", "rename", "replace", "stat", "chmod", "touch", "iterdir", "glob",
1643
+ "rglob", "is_dir", "is_file", "is_symlink", "samefile", "expanduser",
1644
+ # dict / list / set / str / io / process methods
1645
+ "append", "extend", "insert", "remove", "pop", "clear", "index", "count",
1646
+ "sort", "reverse", "copy", "get", "setdefault", "update", "values",
1647
+ "keys", "items", "split", "rsplit", "splitlines", "join", "strip",
1648
+ "lstrip", "rstrip", "lower", "upper", "capitalize", "title", "startswith",
1649
+ "endswith", "replace", "find", "rfind", "encode", "decode", "format",
1650
+ "read", "readline", "readlines", "write", "writelines", "close", "seek",
1651
+ "tell", "flush", "seekable", "readable", "writable", "fileno", "isatty",
1652
+ "communicate", "poll", "wait", "terminate", "kill", "send_signal",
1653
+ "dump", "dumps", "load", "loads", "run", "call", "check_call", "check_output",
1654
+ "exists", "is_file", "is_dir", "resolve", "parent", "parents", "stem",
1655
+ "suffix", "suffixes", "name", "as_posix", "match", "search", "findall",
1656
+ "finditer", "sub", "subn", "group", "groups", "groupdict", "start", "end",
1657
+ "span", "sleep", "time", "monotonic", "now", "utcnow", "isoformat",
1658
+ "strftime", "strptime", "timestamp", "date", "year", "month", "day",
1659
+ "hour", "minute", "second", "microsecond", "total_seconds", "days",
1660
+ "parse", "unparse", "walk", "visit", "generic_visit"
1661
+ }
1662
+
1663
+ STD_SMART_ALIASES = {
1664
+ ("math", "squareroot"): "sqrt",
1665
+ ("math", "square_root"): "sqrt",
1666
+ ("math", "power"): "pow",
1667
+ ("json", "dumpp"): "dump",
1668
+ ("json", "dumpss"): "dumps",
1669
+ ("json", "loadd"): "load",
1670
+ ("json", "loadss"): "loads",
1671
+ ("os.path", "exsits"): "exists",
1672
+ ("os.path", "is_file"): "isfile",
1673
+ ("os.path", "is_dir"): "isdir",
1674
+ ("re", "matches"): "match",
1675
+ ("shutil", "copy_directory"): "copytree",
1676
+ ("shutil", "copy_dir"): "copytree",
1677
+ ("hashlib", "sha256_hex"): "sha256",
1678
+ ("datetime", "now_utc"): "utcnow",
1679
+ ("sys", "exit_process"): "exit",
1680
+ }
1681
+
1624
1682
  class _SelfHealingTransformer(ast.NodeTransformer):
1625
1683
  """AST transformer that automatically corrects hallucinated imports, function names, and kwargs."""
1626
1684
  def __init__(self, fixes: Dict[str, Any]):
@@ -1657,7 +1715,12 @@ class _SelfHealingTransformer(ast.NodeTransformer):
1657
1715
  attr = node.func.attr
1658
1716
  fname = attr
1659
1717
  try:
1660
- full_name = f"{ast.unparse(node.func.value)}.{attr}"
1718
+ val_unparsed = ast.unparse(node.func.value)
1719
+ full_name = f"{val_unparsed}.{attr}"
1720
+ if (val_unparsed, attr) in self.call_fixes:
1721
+ node.func.attr = self.call_fixes[(val_unparsed, attr)]
1722
+ attr = node.func.attr
1723
+ full_name = f"{val_unparsed}.{attr}"
1661
1724
  except Exception:
1662
1725
  full_name = attr
1663
1726
 
@@ -1861,6 +1924,8 @@ class ZeroHallucinationGuard:
1861
1924
  if item.name not in self.function_signatures:
1862
1925
  self.function_signatures[item.name] = sig
1863
1926
  if item.name == "__init__":
1927
+ self.function_signatures[node.name] = sig
1928
+ self.function_signatures[f"{stem}.{node.name}"] = sig
1864
1929
  for sub in ast.walk(item):
1865
1930
  if isinstance(sub, ast.Assign):
1866
1931
  for t in sub.targets:
@@ -1945,6 +2010,7 @@ class ZeroHallucinationGuard:
1945
2010
  "all_params": all_params,
1946
2011
  "sig_str": sig_str,
1947
2012
  "return_type": ret_type,
2013
+ "is_async": isinstance(node, ast.AsyncFunctionDef),
1948
2014
  }
1949
2015
 
1950
2016
  def validate_code(self, proposed_code: str, target_file: str = "") -> Dict[str, Any]:
@@ -1967,7 +2033,41 @@ class ZeroHallucinationGuard:
1967
2033
  repairs_applied: List[str] = []
1968
2034
 
1969
2035
  # ---------------------------------------------------------------------
1970
- # 1. TIER 1 & 2: GHOST DEPENDENCY & WORKSPACE IMPORT GUARDS
2036
+ # 0. MAP LOCAL IMPORTS & VARIABLE INFERRED TYPES
2037
+ # ---------------------------------------------------------------------
2038
+ imported_modules: Dict[str, str] = {}
2039
+ for node in ast.walk(tree):
2040
+ if isinstance(node, ast.Import):
2041
+ for alias in node.names:
2042
+ imported_modules[alias.asname or alias.name] = alias.name
2043
+ elif isinstance(node, ast.ImportFrom):
2044
+ if node.module:
2045
+ for alias in node.names:
2046
+ imported_modules[alias.asname or alias.name] = f"{node.module}.{alias.name}"
2047
+
2048
+ var_types: Dict[str, str] = {}
2049
+ for node in ast.walk(tree):
2050
+ if isinstance(node, ast.Assign):
2051
+ for target in node.targets:
2052
+ if isinstance(target, ast.Name):
2053
+ if isinstance(node.value, ast.Call):
2054
+ c_name = ""
2055
+ if isinstance(node.value.func, ast.Name):
2056
+ c_name = node.value.func.id
2057
+ elif isinstance(node.value.func, ast.Attribute):
2058
+ c_name = node.value.func.attr
2059
+ if c_name:
2060
+ var_types[target.id] = c_name
2061
+ elif isinstance(node, ast.AnnAssign):
2062
+ if isinstance(node.target, ast.Name) and node.annotation:
2063
+ try:
2064
+ ann_str = ast.unparse(node.annotation)
2065
+ var_types[node.target.id] = ann_str
2066
+ except Exception:
2067
+ pass
2068
+
2069
+ # ---------------------------------------------------------------------
2070
+ # 1. TIER 1 & 2: GHOST DEPENDENCY & WORKSPACE / STDLIB IMPORT GUARDS
1971
2071
  # ---------------------------------------------------------------------
1972
2072
  for node in ast.walk(tree):
1973
2073
  if isinstance(node, ast.ImportFrom):
@@ -1988,18 +2088,38 @@ class ZeroHallucinationGuard:
1988
2088
  f"Import Hallucination: Symbol `{alias.name}` does not exist in workspace module `{node.module}`.{did_you_mean}"
1989
2089
  )
1990
2090
  else:
1991
- # Check external third-party package against stdlib + manifests + environment
2091
+ # Check if module is standard library
1992
2092
  b_lower = base_mod.lower()
1993
2093
  is_std = b_lower in self.stdlib_modules
1994
- is_dec = b_lower in self.declared_packages or b_lower.replace("_", "-") in self.declared_packages
1995
- is_inst = b_lower in self.installed_packages or b_lower in self.known_package_aliases or self.known_package_aliases.get(b_lower) in self.installed_packages
1996
- if not (is_std or is_dec or is_inst):
1997
- all_known = list(self.declared_packages | self.installed_packages | set(self.known_package_aliases.keys()))
1998
- close_pkg = difflib.get_close_matches(b_lower, all_known, n=1, cutoff=0.6)
1999
- hint = f" Did you mean `{close_pkg[0]}`?" if close_pkg else ""
2000
- violations.append(
2001
- f"Ghost Dependency Hallucination: Package `{base_mod}` is not part of Python stdlib, not declared in requirements.txt/pyproject.toml, and not installed in environment.{hint}"
2002
- )
2094
+ if is_std:
2095
+ try:
2096
+ std_mod = importlib.import_module(node.module)
2097
+ for alias in node.names:
2098
+ if alias.name != "*" and not hasattr(std_mod, alias.name):
2099
+ candidates = [m for m in dir(std_mod) if not m.startswith("_")]
2100
+ smart_match = STD_SMART_ALIASES.get((node.module, alias.name))
2101
+ close = [smart_match] if smart_match else difflib.get_close_matches(alias.name, candidates, n=1, cutoff=0.55)
2102
+ did_you_mean = f" Did you mean: `{close[0]}`?" if close else ""
2103
+ if close:
2104
+ fixes["imports"][(node.module, alias.name)] = close[0]
2105
+ fixes["calls"][alias.name] = close[0]
2106
+ repairs_applied.append(f"Import `{alias.name}` -> `{close[0]}` (in stdlib `{node.module}`)")
2107
+ violations.append(
2108
+ f"Stdlib Import Hallucination: Symbol `{alias.name}` does not exist in standard library module `{node.module}`.{did_you_mean}"
2109
+ )
2110
+ except Exception:
2111
+ pass
2112
+ else:
2113
+ # Check external third-party package against manifests + environment
2114
+ is_dec = b_lower in self.declared_packages or b_lower.replace("_", "-") in self.declared_packages
2115
+ is_inst = b_lower in self.installed_packages or b_lower in self.known_package_aliases or self.known_package_aliases.get(b_lower) in self.installed_packages
2116
+ if not (is_dec or is_inst):
2117
+ all_known = list(self.declared_packages | self.installed_packages | set(self.known_package_aliases.keys()))
2118
+ close_pkg = difflib.get_close_matches(b_lower, all_known, n=1, cutoff=0.6)
2119
+ hint = f" Did you mean `{close_pkg[0]}`?" if close_pkg else ""
2120
+ violations.append(
2121
+ f"Ghost Dependency Hallucination: Package `{base_mod}` is not part of Python stdlib, not declared in requirements.txt/pyproject.toml, and not installed in environment.{hint}"
2122
+ )
2003
2123
 
2004
2124
  elif isinstance(node, ast.Import):
2005
2125
  for alias in node.names:
@@ -2019,22 +2139,110 @@ class ZeroHallucinationGuard:
2019
2139
  )
2020
2140
 
2021
2141
  # ---------------------------------------------------------------------
2022
- # 2. TIER 3 & 4: CALL SIGNATURE, KWARGS & SCHEMA FIELD GUARDS
2142
+ # 2. TIER 3 & 4: CALL SIGNATURE, STDLIB, CLASS & SCHEMA FIELD GUARDS
2023
2143
  # ---------------------------------------------------------------------
2024
2144
  for node in ast.walk(tree):
2025
2145
  if isinstance(node, ast.Call):
2026
2146
  func_name = ""
2027
2147
  attr_name = ""
2148
+ val_str = ""
2149
+ is_attr_call = False
2150
+ sig = None
2028
2151
  if isinstance(node.func, ast.Name):
2029
2152
  func_name = node.func.id
2030
2153
  elif isinstance(node.func, ast.Attribute):
2031
- val_str = ast.unparse(node.func.value)
2154
+ is_attr_call = True
2155
+ try:
2156
+ val_str = ast.unparse(node.func.value)
2157
+ except Exception:
2158
+ val_str = ""
2032
2159
  attr_name = node.func.attr
2033
- func_name = f"{val_str}.{attr_name}"
2160
+ func_name = f"{val_str}.{attr_name}" if val_str else attr_name
2161
+
2162
+ # A. Validate Standard Library Module Method Calls
2163
+ if is_attr_call and val_str:
2164
+ mod_to_check = imported_modules.get(val_str, val_str)
2165
+ root_std = mod_to_check.split('.')[0].lower()
2166
+ if root_std in self.stdlib_modules:
2167
+ try:
2168
+ mod_obj = importlib.import_module(mod_to_check)
2169
+ if not hasattr(mod_obj, attr_name):
2170
+ candidates = [m for m in dir(mod_obj) if not m.startswith("_")]
2171
+ smart_match = STD_SMART_ALIASES.get((mod_to_check, attr_name)) or STD_SMART_ALIASES.get((root_std, attr_name))
2172
+ close = [smart_match] if smart_match else difflib.get_close_matches(attr_name, candidates, n=1, cutoff=0.55)
2173
+ hint = f" Did you mean `{close[0]}`?" if close else ""
2174
+ if close:
2175
+ fixes["calls"][attr_name] = close[0]
2176
+ fixes["calls"][(val_str, attr_name)] = close[0]
2177
+ repairs_applied.append(f"Stdlib `{val_str}.{attr_name}()` -> `.{close[0]}()`")
2178
+ violations.append(
2179
+ f"Stdlib Method Hallucination: Standard library module `{mod_to_check}` has no method or attribute `{attr_name}`.{hint}"
2180
+ )
2181
+ continue
2182
+ else:
2183
+ # Attribute is valid on stdlib module; do not flag as workspace mismatch
2184
+ continue
2185
+ except Exception:
2186
+ pass
2187
+
2188
+ # B. Skip built-in python methods (append, get, strip, etc.) and private methods
2189
+ if is_attr_call and (attr_name.startswith("_") or attr_name.lower() in BUILTIN_COMMON_METHODS):
2190
+ continue
2191
+
2192
+ # C. Validate Class Instance Method Calls
2193
+ if is_attr_call and val_str in var_types:
2194
+ raw_class = var_types[val_str]
2195
+ inferred_class = raw_class
2196
+ for (mod, old_sym), new_sym in fixes["imports"].items():
2197
+ if old_sym == raw_class:
2198
+ inferred_class = new_sym
2199
+ break
2200
+ if inferred_class in fixes["calls"]:
2201
+ inferred_class = fixes["calls"][inferred_class]
2202
+
2203
+ if inferred_class in self.class_methods:
2204
+ c_methods = self.class_methods[inferred_class]
2205
+ c_fields = self.class_fields.get(inferred_class, set())
2206
+ if attr_name in c_methods or attr_name in c_fields:
2207
+ sig = self.function_signatures.get(f"{inferred_class}.{attr_name}") or self.function_signatures.get(attr_name)
2208
+ else:
2209
+ candidates = list(c_methods | c_fields)
2210
+ close = difflib.get_close_matches(attr_name, candidates, n=1, cutoff=0.50)
2211
+ hint = f" Did you mean `{close[0]}`?" if close else ""
2212
+ if close:
2213
+ fixes["calls"][attr_name] = close[0]
2214
+ fixes["calls"][(val_str, attr_name)] = close[0]
2215
+ repairs_applied.append(f"Method `{val_str}.{attr_name}()` -> `.{close[0]}()`")
2216
+ violations.append(
2217
+ f"Class Member Hallucination: Class `{inferred_class}` has no declared method or attribute `{attr_name}`.{hint}"
2218
+ )
2219
+ continue
2220
+
2221
+ # D. Validate Explicit Workspace Module Function Calls
2222
+ if is_attr_call and val_str not in var_types and val_str in imported_modules and val_str in self.modules:
2223
+ avail = self.exported_symbols.get(val_str, set())
2224
+ if attr_name in avail or f"{val_str}.{attr_name}" in self.function_signatures or attr_name in self.function_signatures:
2225
+ sig = self.function_signatures.get(f"{val_str}.{attr_name}") or self.function_signatures.get(attr_name)
2226
+ else:
2227
+ matches = difflib.get_close_matches(attr_name, list(avail) or [s.split('.')[-1] for s in self.function_signatures.keys()], n=1, cutoff=0.50)
2228
+ hint = f" Did you mean `{matches[0]}`?" if matches else ""
2229
+ if matches:
2230
+ fixes["calls"][attr_name] = matches[0]
2231
+ fixes["calls"][(val_str, attr_name)] = matches[0]
2232
+ repairs_applied.append(f"Method `{val_str}.{attr_name}()` -> `.{matches[0]}()`")
2233
+ violations.append(
2234
+ f"Workspace Method Hallucination: Module `{val_str}` has no exported function or attribute `{attr_name}`.{hint}"
2235
+ )
2236
+ continue
2034
2237
 
2035
- sig = self.function_signatures.get(func_name)
2238
+ # E. Look up signature for parameter / kwarg validation
2239
+ if not sig:
2240
+ sig = self.function_signatures.get(func_name)
2036
2241
  if not sig and attr_name:
2037
- sig = self.function_signatures.get(attr_name)
2242
+ if (val_str in self.modules or val_str in var_types or
2243
+ any(val_str == c for c in self.class_methods) or
2244
+ not is_attr_call):
2245
+ sig = self.function_signatures.get(attr_name)
2038
2246
 
2039
2247
  # Schema & Dataclass field validation on class instantiation
2040
2248
  target_class = func_name or attr_name
@@ -2063,6 +2271,7 @@ class ZeroHallucinationGuard:
2063
2271
  target_k = func_name or sig["name"]
2064
2272
  fixes["kwargs"][(target_k, kw.arg)] = close_kw[0]
2065
2273
  fixes["kwargs"][(sig["name"], kw.arg)] = close_kw[0]
2274
+ fixes["kwargs"][("", kw.arg)] = close_kw[0]
2066
2275
  if attr_name:
2067
2276
  fixes["kwargs"][(attr_name, kw.arg)] = close_kw[0]
2068
2277
  repairs_applied.append(f"Param `{kw.arg}` -> `{close_kw[0]}` in `{func_name or sig['name']}()`")
@@ -2074,7 +2283,7 @@ class ZeroHallucinationGuard:
2074
2283
  is_method_attr_call = isinstance(node.func, ast.Attribute)
2075
2284
  effective_min = sig["min_pos"]
2076
2285
  effective_max = sig["max_pos"]
2077
- if is_method_attr_call and "self" in sig["all_params"]:
2286
+ if "self" in sig["all_params"]:
2078
2287
  effective_min = max(0, effective_min - 1)
2079
2288
  if effective_max != float("inf"):
2080
2289
  effective_max = max(0, effective_max - 1)
@@ -2087,17 +2296,16 @@ class ZeroHallucinationGuard:
2087
2296
  violations.append(
2088
2297
  f"Call Hallucination: `{func_name or sig['name']}` received too many positional arguments ({num_pos} provided, at most {effective_max} allowed). Valid signature: `{sig['sig_str']}`"
2089
2298
  )
2090
- elif isinstance(node.func, ast.Attribute):
2091
- target_attr = node.func.attr
2299
+ elif not is_attr_call and func_name not in PYTHON_BUILTIN_FUNCTIONS and func_name not in imported_modules:
2300
+ # Check standalone function call against workspace functions
2092
2301
  all_sigs = list(self.function_signatures.keys())
2093
- matches = difflib.get_close_matches(target_attr, [s.split('.')[-1] for s in all_sigs], n=1, cutoff=0.5)
2302
+ matches = difflib.get_close_matches(func_name, [s.split('.')[-1] for s in all_sigs], n=1, cutoff=0.60)
2094
2303
  if matches:
2095
2304
  cand_sigs = [self.function_signatures[m]["sig_str"] for m in matches if m in self.function_signatures]
2096
- val_str = ast.unparse(node.func.value)
2097
- fixes["calls"][target_attr] = matches[0]
2098
- repairs_applied.append(f"Method `{val_str}.{target_attr}()` -> `.{matches[0]}()`")
2305
+ fixes["calls"][func_name] = matches[0]
2306
+ repairs_applied.append(f"Function `{func_name}()` -> `{matches[0]}()`")
2099
2307
  violations.append(
2100
- f"Call Hallucination: Method or function `{val_str}.{target_attr}` does not exist! Did you mean: `{'; '.join(cand_sigs or matches)}`?"
2308
+ f"Call Hallucination: Function `{func_name}` does not exist! Did you mean: `{'; '.join(cand_sigs or matches)}`?"
2101
2309
  )
2102
2310
 
2103
2311
  # ---------------------------------------------------------------------
@@ -2115,15 +2323,38 @@ class ZeroHallucinationGuard:
2115
2323
  violations.append(
2116
2324
  f"Return Contract Hallucination: Function `{c_name}` returns `{rt}`, which is not iterable in a loop!"
2117
2325
  )
2118
- # Check attribute access on None return: func().attr
2326
+ # Check attribute access on return: func().attr
2119
2327
  elif isinstance(node, ast.Attribute):
2120
2328
  if isinstance(node.value, ast.Call):
2121
2329
  c_name = ast.unparse(node.value.func).strip()
2122
2330
  sig = self.function_signatures.get(c_name) or self.function_signatures.get(c_name.split('.')[-1])
2123
- if sig and sig.get("return_type") in ("None", "NoneType"):
2124
- violations.append(
2125
- f"Return Contract Hallucination: Function `{c_name}` has declared return type 'None', cannot access member `.{node.attr}` on NoneType!"
2126
- )
2331
+ if sig and sig.get("return_type"):
2332
+ rt = sig["return_type"].strip()
2333
+ rt_clean = rt.split("[")[0].strip().lower()
2334
+ if rt in ("None", "NoneType"):
2335
+ violations.append(
2336
+ f"Return Contract Hallucination: Function `{c_name}` has declared return type 'None', cannot access member `.{node.attr}` on NoneType!"
2337
+ )
2338
+ elif rt_clean in ("list", "sequence") and node.attr not in dir(list):
2339
+ violations.append(
2340
+ f"Return Contract Hallucination: Function `{c_name}` returns a list/sequence, which has no member or method `.{node.attr}`!"
2341
+ )
2342
+ elif rt_clean in ("dict", "mapping") and node.attr not in dir(dict):
2343
+ violations.append(
2344
+ f"Return Contract Hallucination: Function `{c_name}` returns a dict/mapping, which has no member or method `.{node.attr}`!"
2345
+ )
2346
+ elif rt_clean == "set" and node.attr not in dir(set):
2347
+ violations.append(
2348
+ f"Return Contract Hallucination: Function `{c_name}` returns a set, which has no member or method `.{node.attr}`!"
2349
+ )
2350
+ elif rt_clean == "str" and node.attr not in dir(str):
2351
+ violations.append(
2352
+ f"Return Contract Hallucination: Function `{c_name}` returns a str, which has no member or method `.{node.attr}`!"
2353
+ )
2354
+ elif rt_clean in ("int", "float", "bool") and node.attr not in dir(int):
2355
+ violations.append(
2356
+ f"Return Contract Hallucination: Function `{c_name}` returns a primitive `{rt}`, which has no member or method `.{node.attr}`!"
2357
+ )
2127
2358
 
2128
2359
  # ---------------------------------------------------------------------
2129
2360
  # 4. SELF-HEALING AST REPAIR SYNTHESIS
@@ -11,7 +11,7 @@ Capabilities:
11
11
  - 100% Offline, $0 cost, zero cloud dependencies (Python standard library only).
12
12
 
13
13
  Author: Toprak Ahmet Aydoğmuş (Siber Akademi)
14
- Part of T-Zero Context Architect v11.11.0 Master Edition.
14
+ Part of T-Zero Context Architect v11.13.0 Master Edition.
15
15
  """
16
16
 
17
17
  import ast
@@ -192,7 +192,7 @@ class ASTGoldenRegressionEngine:
192
192
 
193
193
  return GoldenBaseline(
194
194
  workspace_root=abs_root,
195
- version="11.11.0",
195
+ version="11.13.0",
196
196
  created_at=time.time(),
197
197
  symbols=all_sigs,
198
198
  total_symbols=len(all_sigs),