Text Generation
Transformers
Safetensors
English
Arabic
code
qwen3_5
image-text-to-text
qwen3.8
rootformer
coding
software-engineering
agentic
arabic-grammarian-algorithms
qata-al-waswasa
next-codewazn-prediction
vllm
bfloat16
conversational
Run this model with HF Jobs
Run enver/rootformer-code-v19.2-qwen38-nwp on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/enver/rootformer-code-v19.2-qwen38-nwp. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use enver/rootformer-code-v19.2-qwen38-nwp with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use enver/rootformer-code-v19.2-qwen38-nwp with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="enver/rootformer-code-v19.2-qwen38-nwp") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("enver/rootformer-code-v19.2-qwen38-nwp") model = AutoModelForMultimodalLM.from_pretrained("enver/rootformer-code-v19.2-qwen38-nwp", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use enver/rootformer-code-v19.2-qwen38-nwp with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "enver/rootformer-code-v19.2-qwen38-nwp" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "enver/rootformer-code-v19.2-qwen38-nwp", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/enver/rootformer-code-v19.2-qwen38-nwp
- SGLang
How to use enver/rootformer-code-v19.2-qwen38-nwp with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "enver/rootformer-code-v19.2-qwen38-nwp" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "enver/rootformer-code-v19.2-qwen38-nwp", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "enver/rootformer-code-v19.2-qwen38-nwp" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "enver/rootformer-code-v19.2-qwen38-nwp", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use enver/rootformer-code-v19.2-qwen38-nwp with Docker Model Runner:
docker model run hf.co/enver/rootformer-code-v19.2-qwen38-nwp
File size: 18,784 Bytes
c5a2aed | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 | #!/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, "<code_gsca_static>", "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()
|