#!/usr/bin/env python3 # -*- coding: utf-8 -*- r""" code_gsca_ast_grounder.py ========================= Zero-GPU (`<1 ms/prompt`), Strictly Non-Leaking **Code-GSCA (`Graph-Structured Code-AST & Morphology Grounder`)** and **Andalusian *Istiṣḥāb* Static AST Verifier** for **Rootformer-Code-27B (Stage 18.1+)**. Coding twin of Rootformer Stage 17.11/17.12's `6,236`-verse `Muṣḥaf` + `10,119`-root *Lisān/Ḍabṭ* grounder: - Inspects **ONLY** the user's own prompt text (`0` hidden test leakage, `0` hardcoded task answers). - Strictly context-gated: emits **ZERO** extra tokens on plain single-function algorithmic prompts where no multi-convention / custom-API / operator-precedence trap exists. - Modules: 1. **API & Symbol-Table Contract Extractor (*Taʿalluq al-ʿĀmil*)**: Parses embedded Python stubs (`ast.parse` on fenced/indented code blocks + backtick signatures) to pin exact class names, method names, keyword-only arguments, return types, and required exception classes so the model cannot hallucinate wrong method names or swap kwargs. 2. **Sībawayh Identifier-Morphology (*Wazn*) Cross-Convention Binder**: Detects mixed naming conventions (`snake_case` <-> `camelCase` <-> `PascalCase` <-> `UPPER_SNAKE`), acronym runs (`HTTPResponse`, `userID`), digit transitions (`200OK`), and `__dunder__`/`_private` prefix rules. 3. **Operator & Type Invariant Guard (*Shurūṭ al-ʿAmal*)**: Fires ONLY when the prompt explicitly specifies hazards such as `bool` vs `int` distinction (`isinstance(True, int) is True` in Python), truncating-toward-zero division (`int(a / b)` vs `//`), or multi-char lexer tokens (`==`, `!=`, `<=`, `>=`) alongside single `=`. 4. **Andalusian *Istiṣḥāb* Zero-Cheat Static AST Guard (`static_ast_verify`)**: Post-generation `<0.5 ms` Python `ast.parse` + `compile()` + required entrypoint/method & undefined-global audit (ZERO execution of unit tests!) for triggering a single clean repair pass only on static errors. """ from __future__ import annotations import ast import builtins import re from typing import Any, Dict, List, Optional, Set, Tuple _CAMEL_SPLIT_RE = re.compile( r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z])" ) _CODE_BLOCK_RE = re.compile(r"```(?:python|py)?\s*\n(.*?)```", flags=re.DOTALL | re.IGNORECASE) _BACKTICK_SIG_RE = re.compile(r"`((?:async\s+def|def|class)\s+[A-Za-z_][A-Za-z0-9_]*[^`\n]{0,160})`") _METHOD_SIG_RE = re.compile(r"`([A-Za-z_][A-Za-z0-9_]*\([^`\n]{0,140}\)\s*(?:->\s*[^`\n]{1,60})?)`") _EXC_NAME_RE = re.compile( r"\b(ValueError|TypeError|KeyError|NameError|IndexError|SyntaxError|ZeroDivisionError|" r"RuntimeError|PermissionError|OverflowError|LookupError|AttributeError|NotImplementedError|" r"[A-Z][A-Za-z0-9]*Error)\b" ) _FORBIDDEN_RE = re.compile( r"(?:without\s+(?:importing\s+or\s+)?using(?:\s+python'?s)?|do\s+not\s+use|forbid(?:s|den)?)\s+([^.\n]{2,80})", flags=re.IGNORECASE, ) _BUILTINS_SET: Set[str] = set(dir(builtins)) | { "Any", "Callable", "Dict", "Iterable", "Iterator", "List", "Mapping", "Optional", "Sequence", "Set", "Tuple", "Type", "Union", "Self", "dataclass", "field", } def canonical_stems(ident: str) -> List[str]: core = ident.strip("_") if not core: return [] out: List[str] = [] for part in core.split("_"): if not part: continue for sub in _CAMEL_SPLIT_RE.split(part): if sub: out.append(sub.lower()) return out def extract_prompt_api_contracts(prompt_text: str) -> Dict[str, Any]: """Deterministically extracts classes, methods, functions, kwargs, and exceptions from the prompt.""" classes: Dict[str, List[str]] = {} functions: List[str] = [] kwonly_args: List[str] = [] required_top_symbols: List[str] = [] # 1. Parse any fenced Python stubs inside the prompt using Python's AST for m in _CODE_BLOCK_RE.finditer(prompt_text): snippet = m.group(1) try: tree = ast.parse(snippet) except SyntaxError: continue for node in tree.body: if isinstance(node, ast.ClassDef): methods: List[str] = [] for item in node.body: if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): sig = _format_ast_sig(item) methods.append(sig) for kw in item.args.kwonlyargs: kwonly_args.append(f"{node.name}.{item.name}(*, {kw.arg})") classes[node.name] = methods elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): functions.append(_format_ast_sig(node)) for kw in node.args.kwonlyargs: kwonly_args.append(f"{node.name}(*, {kw.arg})") # 2. Extract explicit backtick signatures (`def ...`, `class ...`, `method(...) -> ...`) bt_sigs: List[str] = [] for m in _BACKTICK_SIG_RE.finditer(prompt_text): s = m.group(1).strip() if s not in bt_sigs: bt_sigs.append(s) m_nm = re.match(r"(?:async\s+def|def|class)\s+([A-Za-z_][A-Za-z0-9_]*)", s) if m_nm and m_nm.group(1) not in required_top_symbols: required_top_symbols.append(m_nm.group(1)) # Also catch `function `foo(...)`` / `class `Bar`` / `دالة `baz(...)`` (skipping optional def/class keywords inside backticks!) for m in re.finditer(r"(?:function|class|دالة|صنف|فئة)\s+`(?:(?:async\s+)?def\s+|class\s+)?([A-Za-z_][A-Za-z0-9_]*)", prompt_text, flags=re.IGNORECASE): nm = m.group(1) if nm not in ("def", "class", "async") and nm not in required_top_symbols and nm not in classes: required_top_symbols.append(nm) # Also catch explicit method specs like `- `post_journal_transfer(...) -> int`` method_sigs: List[str] = [] for m in _METHOD_SIG_RE.finditer(prompt_text): ms = m.group(1).strip() nm = ms.split("(", 1)[0] if nm in ("int", "str", "bool", "float", "list", "dict", "set", "tuple", "len", "sum", "min", "max", "eval", "exec", "strip"): continue if ms not in method_sigs and ms not in bt_sigs: method_sigs.append(ms) # 3. Extract explicit required exceptions exceptions = list(dict.fromkeys(_EXC_NAME_RE.findall(prompt_text))) # 4. Detect forbidden imports / builtins explicitly stated in prompt forbidden: List[str] = [] for m in _FORBIDDEN_RE.finditer(prompt_text): frag = m.group(1) for tok in ("eval", "exec", "re", "regex", "ast", "json", "heapq", "bisect", "itertools", "collections"): if re.search(rf"`?{tok}(?:\(\))?`?", frag, flags=re.IGNORECASE): if tok not in forbidden: forbidden.append(tok) # 5. Detect cross-convention identifier pairs (e.g., `transaction_sequence_id` <-> `transactionSequenceId`) raw_idents = list(dict.fromkeys(re.findall(r"\b[A-Za-z_][A-Za-z0-9_]{3,48}\b", prompt_text))) stem_groups: Dict[Tuple[str, ...], List[str]] = {} for ident in raw_idents: if "_" not in ident and not any(c.isupper() for c in ident[1:]): continue st = tuple(canonical_stems(ident)) if len(st) >= 2: stem_groups.setdefault(st, []).append(ident) cross_conv_pairs = [ vals for vals in stem_groups.values() if len(set(vals)) >= 2 ] return { "stub_classes": classes, "stub_functions": functions, "kwonly_args": list(dict.fromkeys(kwonly_args)), "backtick_sigs": bt_sigs, "method_sigs": method_sigs, "required_top_symbols": required_top_symbols, "exceptions": exceptions, "forbidden": forbidden, "cross_conv_pairs": cross_conv_pairs, } def _format_ast_sig(node: ast.AST) -> str: assert isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) args = node.args parts: List[str] = [] pos_args = list(args.posonlyargs) + list(args.args) n_def = len(args.defaults) for idx, a in enumerate(pos_args): s = a.arg if a.annotation is not None: s += f": {ast.unparse(a.annotation)}" def_idx = idx - (len(pos_args) - n_def) if def_idx >= 0: s += f" = {ast.unparse(args.defaults[def_idx])}" parts.append(s) if args.vararg is not None: parts.append(f"*{args.vararg.arg}") elif args.kwonlyargs: parts.append("*") for kw, kd in zip(args.kwonlyargs, args.kw_defaults): s = kw.arg if kw.annotation is not None: s += f": {ast.unparse(kw.annotation)}" if kd is not None: s += f" = {ast.unparse(kd)}" parts.append(s) if args.kwarg is not None: parts.append(f"**{args.kwarg.arg}") ret = f" -> {ast.unparse(node.returns)}" if node.returns is not None else "" return f"{node.name}({', '.join(parts)}){ret}" class CodeGSCAGrounder: """ Context-gated `<1 ms` CPU Code-GSCA pre-generation grounder. Emits compact, verified API/morphology/invariant directives ONLY when warranted by the prompt. """ def format_prompt_contract(self, prompt_text: str, is_humaneval_mbpp: bool = False) -> str: # Never inject English contract wrappers into Arabic-language technical prompts! if len(re.findall(r"[\u0600-\u06FF]", prompt_text)) >= 15: return "" c = extract_prompt_api_contracts(prompt_text) lines: List[str] = [] # On plain HumanEval/MBPP single-function prompts, stay minimally intrusive (only fire on true hazards) if not is_humaneval_mbpp: # 1. Provided library stubs / exact API surface (prevents API hallucination!) if c["stub_classes"]: stub_desc = [] for cls, meths in list(c["stub_classes"].items())[:6]: stub_desc.append(f"class {cls}: [{'; '.join(meths[:8])}]") lines.append("Provided API Stubs (use ONLY these exact class/method names & parameter orders; NEVER invent nonexistent methods): " + " | ".join(stub_desc)) if c["kwonly_args"]: lines.append("Keyword-Only Parameters (MUST pass by exact keyword name): " + ", ".join(c["kwonly_args"][:10])) if c["backtick_sigs"] or c["method_sigs"]: all_sigs = (c["backtick_sigs"] + c["method_sigs"])[:10] lines.append("Required Exact Signatures (`ʿAwāmil`): " + " ; ".join(all_sigs)) if c["exceptions"]: lines.append("Exact Required Exception Types: " + ", ".join(c["exceptions"][:8])) if c["forbidden"]: lines.append("Strictly Forbidden Modules/Builtins: " + ", ".join(c["forbidden"])) # 2. Cross-convention / acronym morphology invariants (context-gated) p_low = prompt_text.lower() if c["cross_conv_pairs"]: pairs_txt = ", ".join(" <-> ".join(p[:3]) for p in c["cross_conv_pairs"][:6]) lines.append(f"Cross-Convention Identifier Alignment (`Wazn`): Preserve exact spelling across conventions: {pairs_txt}.") if any(k in p_low for k in ("camelcase", "pascalcase", "snake_case", "screaming_snake", "kebab-case", "acronym", "dunder", "morpheme")): lines.append( "Identifier Morphology (`Wazn`) Rules: Split acronym runs before TitleCase (`HTTPResponse` -> `['http','response']`), " "split letter<->digit boundaries (`200OK` -> `['200','ok']`), preserve exact leading/trailing `_` counts, " "keep `__dunder__` untouched when specified, and lowercase the entire first morpheme in `camelCase`." ) # 3. Exact Python semantic / operator hazards (strictly context-gated on prompt keywords) if ("bool" in p_low and "int" in p_low) and any(k in p_low for k in ("typecheck", "typeerror", "isinstance", "strictly typed", "statically typed")): lines.append("Python `bool`/`int` Trap: In Python `isinstance(True, int)` is `True`; ALWAYS check `isinstance(x, bool)` BEFORE `isinstance(x, int)` (or use `type(x) is int`).") if any(k in p_low for k in ("truncat", "toward zero", "int(a / b)")): lines.append("Division Invariant: Use `int(a / b)` (truncating toward zero) — NEVER Python `a // b` (which floors toward -infinity on negatives).") if any(k in p_low for k in ("precedence", "lexer", "tokenize", "recursive-descent", "pratt", "infix")): if ("=" in prompt_text and "==" in prompt_text) or ("!=" in prompt_text and "<=" in prompt_text): lines.append("Lexer Ordering Invariant: Match two-char tokens (`==`, `!=`, `<=`, `>=`, `&&`, `||`) BEFORE single-char `=`, `<`, `>`, `!`.") if "unary" in p_low: lines.append("Unary Operator Invariant: Parse unary prefix operators (`-`, `+`, `!`) inside `parse_factor()`/`parse_unary()` recursively (supporting `-(-x)`, `!!b`).") if not lines: return "" return "[VERIFIED CODE-GSCA CONTRACT (`Taʿalluq al-ʿĀmil` — obey strictly without inventing APIs)]:\n- " + "\n- ".join(lines) def static_ast_verify(code_str: str, prompt_text: str, entry_point: Optional[str] = None) -> Tuple[bool, List[str]]: """ Andalusian *Istiṣḥāb* Zero-Cheat Static Verifier (`0` unit-test execution!). Catches syntax errors, missing required entrypoints, forbidden imports, and undefined globals. """ issues: List[str] = [] if not code_str or not code_str.strip(): return False, ["Empty Python code output."] try: tree = ast.parse(code_str) compile(tree, "", "exec") except SyntaxError as e: return False, [f"SyntaxError at line {e.lineno}: {e.msg}"] module_defined: Set[str] = set(_BUILTINS_SET) top_defs: Set[str] = set() imported_mods: Set[str] = set() called_names: Set[str] = set() for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): module_defined.add(node.name) top_defs.add(node.name) elif isinstance(node, ast.Import): for al in node.names: root_m = al.name.split(".")[0] imported_mods.add(root_m) module_defined.add(al.asname or root_m) elif isinstance(node, ast.ImportFrom): if node.module: imported_mods.add(node.module.split(".")[0]) for al in node.names: module_defined.add(al.asname or al.name) elif isinstance(node, ast.Assign): for tgt in node.targets: for sub in ast.walk(tgt): if isinstance(sub, ast.Name): module_defined.add(sub.id) elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): module_defined.add(node.target.id) for node in ast.walk(tree): if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): called_names.add(node.func.id) if entry_point and entry_point not in top_defs and entry_point not in module_defined: issues.append(f"Missing required entry point `{entry_point}`.") c = extract_prompt_api_contracts(prompt_text) for req_nm in c["required_top_symbols"]: # Do not flag stub class names that are pre-provided in the execution environment if req_nm in c["stub_classes"]: continue if req_nm not in top_defs and req_nm not in module_defined: issues.append(f"Missing required top-level symbol `{req_nm}`.") for fb in c["forbidden"]: if fb in ("eval", "exec") and fb in called_names: issues.append(f"Prompt forbids `{fb}()`, but `{fb}()` was called.") elif fb in ("re", "regex") and fb in imported_mods: issues.append(f"Prompt forbids importing `{fb}`, but it was imported.") # Strictly 100%-precision checks only (SyntaxError / IndentationError / missing entry_point / forbidden builtins): # avoids false-positive undefined-symbol triggers on valid helper/closure/test_import patterns! dedup = list(dict.fromkeys(issues)) return (len(dedup) == 0), dedup[:5] def _self_test() -> None: g = CodeGSCAGrounder() # 1. Plain HumanEval prompt -> MUST emit ZERO noise! plain_p = "def add(a: int, b: int) -> int:\n '''Return sum of a and b.'''\n" assert g.format_prompt_contract(plain_p, is_humaneval_mbpp=True) == "", "Plain HumanEval prompt should stay silent!" # 2. Arabic technical prompt -> MUST stay silent (no English contract clash!) ar_p = "اقرأ المواصفة البرمجية التالية المكتوبة بالعربية وحوّلها إلى كود بايثون ٣ لكتابة دالة `foo(x)`." assert g.format_prompt_contract(ar_p, is_humaneval_mbpp=False) == "", "Arabic prompt should stay silent!" # 3. Complex API + Morphology prompt -> MUST extract stub methods, kwargs, and cross-convention alignment hard_p = ( "Given the following provided library stub:\n" "```python\n" "class VaultClient:\n" " def fetch_secret_blob(self, *, vault_key: str, version_num: int = 1) -> dict:\n" " ...\n" "```\n" "Write `def export_secret_dto(client: VaultClient, vault_key: str) -> dict` returning `{'vaultKey': ...}` " "and raising `KeyError` on missing keys. Convert `snake_case` to `camelCase`." ) out = g.format_prompt_contract(hard_p, is_humaneval_mbpp=False) assert "VaultClient" in out and "fetch_secret_blob" in out and "vault_key" in out and "KeyError" in out assert "vault_key <-> vaultKey" in out or "vaultKey" in out # 4. Static AST verifier catches syntax truncation + missing entrypoint + passes clean code ok1, iss1 = static_ast_verify("def export_secret_dto(client, vault_key):\n return client.fetch_secret_blob(vault_key=vault_key)\n", hard_p, "export_secret_dto") assert ok1, f"Clean code failed static check: {iss1}" ok2, iss2 = static_ast_verify("def wrong_name(x):\n return x\n", hard_p, "export_secret_dto") assert not ok2 and any("export_secret_dto" in x for x in iss2) ok3, iss3 = static_ast_verify("def export_secret_dto(client, vault_key):\n if True:\n", hard_p, "export_secret_dto") assert not ok3 and any("SyntaxError" in x or "IndentationError" in x for x in iss3) print("CODE_GSCA_AST_GROUNDER_SELF_TEST_PASSED") if __name__ == "__main__": _self_test()