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.
File size: 24,223 Bytes
eff008a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
nwp_code_wazn_engine.py
=======================
Stage 19.0 — **Next-CodeWazn Prediction (`NWP` / `التنبؤ بالوزن البرمجي`) Core Engine**
Grounded directly in:
  - **Al-Khalīl (`Kitāb al-ʿAyn`, L74–84, L164, L179):** Instant deterministic *Mustaʿmal* vs *Muhmal* pruning
    (live Python `inspect.signature`, preserved prompt constants/signatures, deprecated API elimination).
  - **Sībawayh (`Al-Kitāb`, L149, L325–332):** *ʿĀmil → Maʿmūl* contract governance & 4-state *Bāb al-Istiqāma*
    live verification (`Mustaqīm Ḥasan`, `Qabīḥ`, `Muḥāl`, `Kadhib`).
  - **Al-Zajjājī (`Al-Īḍāḥ fī ʿIlal al-Naḥw`, L416–426):** *al-ʿIlal al-Taʿlīmiyya* (finite executable operational
    laws instead of `$5,000` brute-force token memorization).
  - **Ibn Jinnī (`Al-Khaṣāʾiṣ`, L16353) & Al-Ghazālī (`Al-Mustaṣfā`, L12534):** *Imtināʿ min Naqḍ al-Gharaḍ*
    (locked-invariant monotonicity) + independent cross-trajectory *al-Farq* falsification!

Zero hidden-test leakage: operates strictly on public prompts, live Python introspection, and isolated temp-cwd sandboxes.
"""

from __future__ import annotations

import ast
import os
import re
import subprocess
import sys
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

ROOT = Path("/workspace/rootstar") if Path("/workspace/rootstar").exists() else Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from scripts.eval_code_sandbox import extract_python_code  # noqa: E402
from scripts.khalil_code_wazn_calculator import (  # noqa: E402
    audit_code_true_diction_ast,
    calculate_possible_awzan,
    extract_code_root,
    score_candidate_true_diction,
    synthesize_deterministic_root_inputs,
)


@dataclass
class SibawayhAmilContract:
    """Exact deterministic *ʿĀmil* contract extracted strictly from the public prompt (0 hidden tests)."""
    entry_point: str
    required_imports: List[str] = field(default_factory=list)
    required_constants: List[Tuple[str, str]] = field(default_factory=list)  # (var_name, source_line)
    expected_arg_names: List[str] = field(default_factory=list)
    expected_min_args: int = 0
    expected_max_args: int = 99
    has_varargs: bool = False
    returns_clauses: List[str] = field(default_factory=list)
    raises_clauses: List[str] = field(default_factory=list)
    requirements_clauses: List[str] = field(default_factory=list)
    awzan_card: str = ""
    python_version: str = ""
    contract_card: str = ""


def _extract_docstring_sections(prompt: str) -> Tuple[List[str], List[str], List[str]]:
    """Extracts explicit Returns / Raises / Requirements lines straight from the public prompt."""
    returns_c, raises_c, reqs_c = [], [], []
    cur = None
    for raw_ln in prompt.splitlines():
        ln = raw_ln.strip()
        low = ln.lower()
        if re.match(r"^(returns?|return value)\s*:", low):
            cur = "ret"
            after = ln.split(":", 1)[1].strip()
            if after:
                returns_c.append(after)
            continue
        if re.match(r"^(raises?|exceptions?|errors?)\s*:", low):
            cur = "raise"
            after = ln.split(":", 1)[1].strip()
            if after:
                raises_c.append(after)
            continue
        if re.match(r"^(requirements?|constraints?|notes?|constants?)\s*:", low):
            cur = "req"
            after = ln.split(":", 1)[1].strip()
            if after:
                reqs_c.append(after)
            continue
        if re.match(r"^(parameters?|args?|arguments?|examples?|>>>|\"\"\"|''')", low) or not ln:
            if not ln:
                continue
            if re.match(r"^(parameters?|args?|arguments?|examples?|>>>)", low):
                cur = None
                continue
        if cur == "ret" and len(returns_c) < 5:
            returns_c.append(ln)
        elif cur == "raise" and len(raises_c) < 5:
            raises_c.append(ln)
        elif cur == "req" and len(reqs_c) < 6:
            reqs_c.append(ln)
    return returns_c, raises_c, reqs_c


def extract_sibawayh_amil_contract(
    user_prompt: str,
    entry_point: str = "",
    code_prompt: str = "",
    explicit_libs: Any = None,
) -> SibawayhAmilContract:
    """
    Deterministically extracts Sībawayh's *ʿĀmil* contract + Al-Khalīl's live *Mustaʿmal* API card
    from the public specification alone (`<1 ms`, zero hidden tests).
    """
    src_for_ast = code_prompt.strip() or user_prompt.strip()
    req_imports: List[str] = []
    req_consts: List[Tuple[str, str]] = []
    exp_args: List[str] = []
    min_args, max_args, has_va = 0, 99, False
    ep = entry_point.strip()

    # Parse any leading Python header/stub from code_prompt or fenced blocks in user_prompt
    candidate_blocks = [src_for_ast]
    for m in re.finditer(r"```(?:python|py)?\s*\n(.*?)```", user_prompt, flags=re.DOTALL | re.IGNORECASE):
        candidate_blocks.append(m.group(1))

    parsed_tree = None
    for blk in candidate_blocks:
        for suffix in ("", "\n    pass\n"):
            try:
                parsed_tree = ast.parse(blk + suffix)
                break
            except SyntaxError:
                continue
        if parsed_tree is not None:
            break

    if parsed_tree is not None:
        for node in parsed_tree.body:
            if isinstance(node, (ast.Import, ast.ImportFrom)):
                req_imports.append(ast.unparse(node))
            elif isinstance(node, ast.Assign):
                for tgt in node.targets:
                    if isinstance(tgt, ast.Name) and tgt.id.isupper() and len(tgt.id) >= 2:
                        req_consts.append((tgt.id, ast.unparse(node)))
            elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None:
                if node.target.id.isupper() and len(node.target.id) >= 2:
                    req_consts.append((node.target.id, ast.unparse(node)))
            elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
                if not ep or node.name == ep:
                    ep = node.name
                    all_a = list(node.args.posonlyargs) + list(node.args.args)
                    exp_args = [a.arg for a in all_a]
                    n_def = len(node.args.defaults)
                    min_args = max(0, len(all_a) - n_def)
                    has_va = bool(node.args.vararg or node.args.kwarg)
                    max_args = 99 if has_va else (len(all_a) + len(node.args.kwonlyargs))

    # Fallback line scan for module-level UPPER_CASE constants if AST failed on prose prompt
    if not req_consts:
        for ln in (code_prompt or user_prompt).splitlines():
            m_c = re.match(r"^([A-Z][A-Z0-9_]{1,})\s*=\s*(.+)$", ln.strip())
            if m_c and not m_c.group(1).startswith(("NOTE", "TODO", "HTTP", "UTF")):
                req_consts.append((m_c.group(1), ln.strip()))

    # Deduplicate constants preserving order
    seen_c = set()
    clean_consts: List[Tuple[str, str]] = []
    for cname, cline in req_consts:
        if cname not in seen_c:
            seen_c.add(cname)
            clean_consts.append((cname, cline))

    cr = extract_code_root(user_prompt, entry_point=ep, explicit_libs=explicit_libs)
    if not ep and cr.entry_point:
        ep = cr.entry_point
    awz = calculate_possible_awzan(cr, user_prompt)
    awzan_card = awz.get("grounding_card", "") or ""
    ret_c, raise_c, req_c = _extract_docstring_sections(user_prompt)

    py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
    card_lines = [f"[NWP Sībawayh ʿĀmil Contract — Python {py_ver}]"]
    if ep:
        sig_str = f"{ep}({', '.join(exp_args)})" if exp_args else ep
        card_lines.append(f"ENTRY_POINT: `{sig_str}` (preserve exact name, parameter order, and default values!)")
    if clean_consts:
        card_lines.append(
            "MANDATORY MODULE CONSTANTS (MUST be defined at top-level of your emitted code so standalone execution never hits NameError): "
            + " | ".join(cl for _, cl in clean_consts[:8])
        )
    if ret_c:
        card_lines.append("RETURN CONTRACT: " + " ".join(ret_c)[:300])
    if raise_c:
        card_lines.append("EXCEPTION CONTRACT: " + " ".join(raise_c)[:240])
    if awzan_card:
        card_lines.append(awzan_card)

    return SibawayhAmilContract(
        entry_point=ep,
        required_imports=req_imports[:12],
        required_constants=clean_consts[:10],
        expected_arg_names=exp_args,
        expected_min_args=min_args,
        expected_max_args=max_args,
        has_varargs=has_va,
        returns_clauses=ret_c,
        raises_clauses=raise_c,
        requirements_clauses=req_c,
        awzan_card=awzan_card,
        python_version=py_ver,
        contract_card="\n".join(card_lines),
    )


def enforce_prompt_constants(code: str, contract: SibawayhAmilContract) -> str:
    """
    Deterministic *Sībawayh ʿĀmil* Hygiene (0 LLM tokens): if the public prompt explicitly defined
    module-level constants (e.g. `SERVER_ADDRESS = 'localhost'`, `BUFFER_SIZE = 1024`) and the candidate
    function references them (or relies on them) without re-declaring them at module top-level,
    inject the exact prompt constant declarations cleanly right after imports!
    """
    if not code or not contract.required_constants:
        return code
    try:
        tree = ast.parse(code)
    except SyntaxError:
        return code

    defined_top = set()
    for node in tree.body:
        if isinstance(node, ast.Assign):
            for t in node.targets:
                if isinstance(t, ast.Name):
                    defined_top.add(t.id)
        elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
            defined_top.add(node.target.id)

    missing_lines = [cline for cname, cline in contract.required_constants if cname not in defined_top]
    if not missing_lines:
        return code

    # Insert right after leading import block
    lines = code.splitlines()
    ins_idx = 0
    for idx, ln in enumerate(lines):
        s = ln.strip()
        if not s or s.startswith("#") or s.startswith(("import ", "from ")):
            ins_idx = idx + 1
        else:
            break
    new_lines = lines[:ins_idx] + [""] + missing_lines + [""] + lines[ins_idx:]
    candidate = "\n".join(new_lines).strip() + "\n"
    try:
        ast.parse(candidate)
        return candidate
    except SyntaxError:
        return code


def audit_amil_contract(code: str, user_prompt: str, contract: SibawayhAmilContract, code_root: Any) -> Dict[str, Any]:
    """
    Al-Khalīl + Sībawayh *Mustaʿmal* vs *Muhmal* instantaneous structural audit (`<2 ms`):
      - Syntax validity
      - Entry point exists with compatible arity
      - All required prompt constants declared
      - Live Python `inspect.signature` API check (from `khalil_code_wazn_calculator`)
    """
    issues: List[str] = []
    if not code or len(code.strip()) < 10:
        return {"is_licit": False, "hard_issues": ["EMPTY_CODE"], "td": {"is_licit": False, "score": -100.0, "hard_issues": ["empty"]}}
    try:
        tree = ast.parse(code)
    except SyntaxError as e:
        return {"is_licit": False, "hard_issues": [f"SYNTAX_ERROR: {e}"], "td": {"is_licit": False, "score": -100.0, "hard_issues": [str(e)]}}

    # Check entry point & signature arity compatibility
    if contract.entry_point:
        fn_node = None
        for n in tree.body:
            if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and n.name == contract.entry_point:
                fn_node = n
                break
        if fn_node is None:
            issues.append(f"MISSING_ENTRY_POINT: expected `{contract.entry_point}`")
        elif isinstance(fn_node, (ast.FunctionDef, ast.AsyncFunctionDef)) and contract.expected_arg_names:
            c_all = list(fn_node.args.posonlyargs) + list(fn_node.args.args)
            c_min = max(0, len(c_all) - len(fn_node.args.defaults))
            c_has_va = bool(fn_node.args.vararg or fn_node.args.kwarg)
            c_max = 99 if c_has_va else (len(c_all) + len(fn_node.args.kwonlyargs))
            if c_min > contract.expected_max_args or c_max < contract.expected_min_args:
                issues.append(
                    f"ARITY_MISMATCH: `{contract.entry_point}` accepts [{c_min}..{c_max}] args, "
                    f"spec expects [{contract.expected_min_args}..{contract.expected_max_args}] ({contract.expected_arg_names})"
                )

    td_ast = audit_code_true_diction_ast(code, user_prompt, code_root)
    if not td_ast["is_licit"]:
        issues.extend(td_ast.get("hard_issues", []))

    return {"is_licit": len(issues) == 0, "hard_issues": issues, "td": td_ast}


def run_live_repl_sandbox(
    script_code: str,
    timeout_sec: float = 4.5,
) -> Dict[str, Any]:
    """
    Executes a Python verification/REPL script in an isolated temporary directory (`use_temp_cwd=True`)
    capturing BOTH stdout (observed live object types/values/prints!) AND stderr (exact traceback!).
    """
    with tempfile.TemporaryDirectory(prefix="nwp_repl_") as td:
        script_path = os.path.join(td, "nwp_run.py")
        with open(script_path, "w", encoding="utf-8") as f:
            f.write(script_code + "\n")
        try:
            proc = subprocess.run(
                [sys.executable, "-I", script_path],
                cwd=td,
                capture_output=True,
                text=True,
                timeout=timeout_sec,
                env={"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "PYTHONHASHSEED": "0"},
            )
            ok = (proc.returncode == 0)
            stdout_s = (proc.stdout or "").strip()
            stderr_s = (proc.stderr or "").strip()
            return {
                "ok": ok,
                "returncode": proc.returncode,
                "stdout": stdout_s[-700:],
                "stderr": stderr_s[-800:],
                "error_kind": _classify_error(stderr_s or stdout_s) if not ok else "NONE",
            }
        except subprocess.TimeoutExpired:
            return {
                "ok": False,
                "returncode": -1,
                "stdout": "",
                "stderr": f"TimeoutError: Live REPL probe exceeded {timeout_sec:.1f}s (possible infinite loop, blocking socket, or live network call without mock).",
                "error_kind": "TIMEOUT",
            }
        except Exception as e:
            return {
                "ok": False,
                "returncode": -2,
                "stdout": "",
                "stderr": f"SandboxError: {type(e).__name__}: {e}",
                "error_kind": "SANDBOX",
            }


def _classify_error(err_txt: str) -> str:
    for kind in ("SyntaxError", "NameError", "AttributeError", "TypeError", "ImportError", "ModuleNotFoundError",
                 "ZeroDivisionError", "IndexError", "KeyError", "ValueError", "FileNotFoundError", "AssertionError"):
        if kind in err_txt:
            return kind
    return "RuntimeError" if err_txt else "UNKNOWN"


def parse_dual_solution_and_verify(raw_output: str, entry_point: str) -> Tuple[str, str]:
    """
    Parses a Turn-1 NWP output containing TWO fenced blocks:
      1) The solution implementation (`def <entry_point>(...)`)
      2) The Sībawayh 4-state live *Istiqāma* verification harness (`def _nwp_verify():`)
    Handles cleanly if model emits only 1 block or uses labeled fences.
    """
    txt = re.sub(r"<think>.*?</think>", "", raw_output, flags=re.DOTALL).replace("<|im_end|>", "").strip()
    blocks = re.findall(r"```(?:python|py)?\s*\n(.*?)```", txt, flags=re.DOTALL | re.IGNORECASE)
    sol_code = ""
    ver_code = ""

    for b in blocks:
        bc = b.strip()
        if not bc:
            continue
        try:
            tree = ast.parse(bc)
        except SyntaxError:
            continue
        has_ep_def = bool(entry_point) and any(
            isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and n.name == entry_point
            for n in tree.body
        )
        has_ver_def = any(
            isinstance(n, ast.FunctionDef) and n.name.startswith("_nwp_verify")
            for n in tree.body
        )
        if has_ep_def and not has_ver_def and not sol_code:
            sol_code = bc
        elif has_ver_def and not has_ep_def and not ver_code:
            ver_code = _ensure_top_level_call(bc, "_nwp_verify")
        elif has_ep_def and has_ver_def:
            # Split cleanly if combined in one block
            sol_code = sol_code or bc
        elif not sol_code and not has_ver_def and "assert " not in bc:
            sol_code = bc
        elif not ver_code and ("assert " in bc or "_nwp_verify" in bc or "unittest" in bc):
            ver_code = _ensure_top_level_call(bc, "_nwp_verify")

    if not sol_code:
        sol_code = extract_python_code(raw_output)
    return sol_code, ver_code


def parse_independent_istiqama_probe(raw_output: str, entry_point: str, probe_fn: str = "_nwp_adv_probe") -> str:
    """
    Parses Stream B's independent adversarial Sībawayh *Istiqāma* test harness,
    guaranteeing it does NOT redefine `entry_point` and DOES invoke `probe_fn()` at top level!
    """
    code = extract_python_code(raw_output)
    if not code:
        return ""
    if entry_point and entry_point not in code:
        return ""
    try:
        tree = ast.parse(code)
    except SyntaxError:
        return ""
    for n in tree.body:
        if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and n.name == entry_point:
            return ""
    return _ensure_top_level_call(code, probe_fn)


def _ensure_top_level_call(code: str, fn_prefix: str) -> str:
    try:
        tree = ast.parse(code)
    except SyntaxError:
        return code
    def_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and n.name.startswith(fn_prefix)]
    if not def_names:
        return code
    target_fn = def_names[-1]
    has_call = any(
        isinstance(n, ast.Expr)
        and isinstance(n.value, ast.Call)
        and isinstance(n.value.func, ast.Name)
        and n.value.func.id == target_fn
        for n in tree.body
    )
    if not has_call:
        code = code + f"\n{target_fn}()\n"
    return code


def build_nwp_turn1_prompt(user_prompt: str, contract: SibawayhAmilContract) -> str:
    ep = contract.entry_point or "task_func"
    return (
        f"Solve the specification below using **Next-CodeWazn Prediction (NWP)**:\n"
        f"Inside `<think>`, explicitly decompose into Sībawayh's 4 *Awzān*:\n"
        f"  1. **ʿĀmil & Imports/Constants**: Check exact function signature, defaults, module constants, and live Python {contract.python_version} APIs (NO deprecated calls!).\n"
        f"  2. **Input/IO & Setup**: Exact file/socket/CSV/ZIP/subprocess handling and edge conditions.\n"
        f"  3. **Core Transform & Return Contract**: Exact return type (`isinstance`), keys, ordering, formatting, and non-mutation.\n"
        f"  4. **Istiqāma Self-Check**: Expected exceptions (`Raises:`) and subtle edge cases.\n\n"
        f"Then output **TWO** clean Python 3 code blocks:\n"
        f"  - **Block 1 (Complete Self-Contained Solution)**: Include ALL required imports, ALL module-level constants from the prompt, and the complete `{ep}` implementation.\n"
        f"  - **Block 2 (Live Sībawayh *Istiqāma* REPL Probe `def _nwp_verify():`)**: Do NOT redefine `{ep}`. Test `{ep}` LIVE using `tempfile.TemporaryDirectory()` for files and `unittest.mock.patch` / `MagicMock` for any network/socket/SMTP/FTP/subprocess calls (ZERO real network access!). Print observed outputs/types (`print('OBSERVED:', type(res), repr(res)[:160])`) and assert ONLY behaviors 100% unambiguously guaranteed by the specification. End Block 2 with `_nwp_verify()`.\n\n"
        f"Specification:\n{user_prompt}"
    )


def build_nwp_adversarial_probe_prompt(user_prompt: str, contract: SibawayhAmilContract, focus: str, fn_name: str) -> str:
    ep = contract.entry_point or "task_func"
    return (
        f"Write a short, completely self-contained, OFFLINE Python 3 Sībawayh *Istiqāma* audit function `def {fn_name}():` "
        f"to test `{ep}` with focus on: **{focus}**.\n"
        f"Strict Rules:\n"
        f"  1. Do NOT implement or redefine `{ep}` — assume `{ep}` and all prompt imports/constants are already in scope.\n"
        f"  2. Run 100% OFFLINE in <1s: use `tempfile.TemporaryDirectory()` for files/dirs, and `unittest.mock.patch` / `MagicMock` "
        f"for ANY socket, SSL, SMTP, FTP, HTTP, urllib, getpass, or subprocess calls.\n"
        f"  3. Assert ONLY behavior 100% unambiguously mandated by the specification (return types, exact keys/values, exact exceptions in `Raises:`, non-mutation, file creation). NEVER invent arbitrary mock call counts or unspecified formatting details.\n"
        f"  4. Print brief observed facts (`print('PROBE_OK:', ...)`) and end with `{fn_name}()`.\n"
        f"Output ONLY the Python 3 verification code inside a single ```python ... ``` block.\n\n"
        f"Specification:\n{user_prompt}"
    )


def build_nwp_live_repl_repair_prompt(
    user_prompt: str,
    contract: SibawayhAmilContract,
    current_code: str,
    turn_idx: int,
    max_turns: int,
    amil_issues: List[str],
    own_repl_res: Optional[Dict[str, Any]],
    failed_probes: List[Tuple[str, str, str]],  # (probe_name, probe_code_snippet, error_msg)
    passed_probe_names: List[str],
    boundary_warnings: List[str],
) -> str:
    ep = contract.entry_point or "task_func"
    diag_parts: List[str] = []
    if amil_issues:
        diag_parts.append("[1. Al-Khalīl ʿĀmil / API Contract Violations (MUST FIX)]:\n" + "\n".join(f"  - {x}" for x in amil_issues))
    if own_repl_res is not None:
        st = "PASS" if own_repl_res["ok"] else f"FAIL ({own_repl_res['error_kind']})"
        diag_parts.append(f"[2. Own Live REPL Probe: {st}]")
        if own_repl_res["stdout"]:
            diag_parts.append(f"  Observed STDOUT:\n{own_repl_res['stdout'][:420]}")
        if not own_repl_res["ok"] and own_repl_res["stderr"]:
            diag_parts.append(f"  Exact Traceback:\n{own_repl_res['stderr'][:550]}")
    if failed_probes:
        diag_parts.append("[3. Independent Adversarial *Istiqāma* Failures]:")
        for pname, pcode, perr in failed_probes[:2]:
            diag_parts.append(f"  --- Failed Probe `{pname}` ---\n  Traceback:\n{perr[:420]}\n  Probe snippet:\n{pcode[:420]}")
    if boundary_warnings:
        diag_parts.append("[4. Al-Khalīl Deterministic Root Boundary Probes]:\n" + "\n".join(f"  - {w}" for w in boundary_warnings[:4]))

    lock_txt = (
        f"LOCKED PASSING INVARIANTS (Ibn Jinnī *Imtināʿ min Naqḍ al-Gharaḍ*): Your current code ALREADY PASSED: "
        f"{', '.join(passed_probe_names)}. You MUST preserve ALL passing behavior with ZERO regressions!\n\n"
        if passed_probe_names
        else ""
    )

    diag_text = "\n\n".join(diag_parts)
    return (
        f"Next-CodeWazn Prediction — Live Execution Feedback Turn {turn_idx}/{max_turns} for `{ep}`:\n\n"
        f"{diag_text}\n\n"
        f"{lock_txt}"
        f"Current Implementation:\n```python\n{current_code}\n```\n\n"
        f"Instructions:\n"
        f"  1. Carefully compare the LIVE Python execution output & traceback above against EVERY word of the Specification below.\n"
        f"  2. Note: if an independent probe failed ONLY because the probe itself used an invalid mock or contradicted the spec, fix any real bugs in your code AND ignore the broken probe assumption; otherwise fix the REAL bug in `{ep}` completely!\n"
        f"  3. Ensure ALL required imports, ALL module-level constants from the prompt, and the exact signature of `{ep}` are present.\n"
        f"  4. Output the COMPLETE updated Python 3 implementation inside a single ```python ... ``` block.\n\n"
        f"Original Specification:\n{user_prompt}"
    )