Datasets:
File size: 5,316 Bytes
36406a4 | 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 | #!/usr/bin/env python3
"""
EMGENA FACTORY v3.0 STRICT AST, SCHEMA, TRAINING & MCP VERIFIER
Verifies:
1. All *.jsonl, sharegpt_format.json, alpaca_format.json, dpo_format.json records + python code blocks via ast.parse
2. server.py / server_free.py / train_mlx.py / train_lora_unsloth.py syntax & zero external dependencies in MCP servers
3. Live MCP stdio JSON-RPC initialize -> tools/list -> tools/call (content[] spec)
4. Training scripts dry-run compatibility (train_lora_unsloth.py --dry-run & train_mlx.py)
"""
import ast
import json
import subprocess
import sys
from pathlib import Path
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
def _iter_strings(obj):
if isinstance(obj, str):
yield obj
elif isinstance(obj, dict):
for v in obj.values():
yield from _iter_strings(v)
elif isinstance(obj, list):
for v in obj:
yield from _iter_strings(v)
def _check_python_blocks(text: str, loc: str, errors: list):
if "```python" in text:
for b in text.split("```python")[1:]:
code = b.split("```")[0].strip()
if not code:
continue
try:
ast.parse(code)
except SyntaxError as se:
errors.append(f"{loc} Python block AST error: {se}")
def verify():
root = Path(__file__).parent
errors = []
# 1. Verify JSONL files
for jl in sorted(root.glob("*.jsonl")):
if jl.parent.name == "mlx_data":
continue
with jl.open("r", encoding="utf-8") as f:
for lno, line in enumerate(f, 1):
if not line.strip():
continue
try:
obj = json.loads(line)
for m in obj.get("messages", []):
_check_python_blocks(str(m.get("content", "")), f"{jl.name}:{lno}", errors)
except Exception as e:
errors.append(f"{jl.name}:{lno} JSON parse error: {e}")
# 2. Verify ShareGPT, Alpaca, DPO JSONs
for jf_name in ("sharegpt_format.json", "alpaca_format.json", "dpo_format.json"):
jf = root / jf_name
if jf.exists():
try:
arr = json.loads(jf.read_text(encoding="utf-8"))
if not isinstance(arr, list) or not arr:
errors.append(f"{jf_name} empty or invalid JSON list")
else:
for idx, item in enumerate(arr[:50]):
for s_val in _iter_strings(item):
_check_python_blocks(s_val, f"{jf_name}[{idx}]", errors)
except Exception as e:
errors.append(f"{jf_name} invalid JSON: {e}")
# 3. Verify Python scripts AST & MCP stdio if present
for pyf in ("server.py", "server_free.py", "eval_benchmark.py", "dashboard.py", "train_mlx.py", "train_lora_unsloth.py"):
p = root / pyf
if p.exists():
try:
ast.parse(p.read_text(encoding="utf-8"))
except SyntaxError as se:
errors.append(f"{pyf} SyntaxError: {se}")
srv = root / "server.py"
if srv.exists():
try:
proc = subprocess.Popen(
[sys.executable, str(srv)],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8"
)
proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n")
proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}) + "\n")
proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "audit", "arguments": {"code_content": "def clean():\n return 1\n"}}}) + "\n")
proc.stdin.flush()
proc.stdin.close()
lines = [ln for ln in proc.stdout.read().splitlines() if ln.strip()]
proc.wait(timeout=3)
if len(lines) < 3:
errors.append(f"MCP stdio returned only {len(lines)} responses")
else:
r3 = json.loads(lines[2])
content = r3.get("result", {}).get("content", [])
if not content or content[0].get("type") != "text":
errors.append("MCP tools/call missing standard result.content[] array")
except Exception as e:
errors.append(f"MCP live stdio test failed: {e}")
# 4. Dry-run training script
up = root / "train_lora_unsloth.py"
if up.exists():
dr = subprocess.run([sys.executable, str(up), "--dry-run"], capture_output=True, text=True)
if dr.returncode != 0:
errors.append(f"train_lora_unsloth.py --dry-run failed: {dr.stderr[:120]}")
if errors:
print(f"❌ Verification failed ({len(errors)} errors):")
for e in errors[:10]:
print(f" - {e}")
sys.exit(1)
print("✅ 100% Factory v3.0 Invariance Verified (AST + Datasets + MCP Spec + Training Dry-Run)!")
sys.exit(0)
if __name__ == "__main__":
verify()
|