Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.
#!/usr/bin/env python3
"""
Zero-App Ephemeral OS — Stage 3 End-to-End Bare-Metal Verification in QEMU KVM.
Verifies:
1. Bootable BIOS ISO (GRUB2 -> zero-app-os.elf) boots cleanly to prompt.
2. Bare-metal MiniCPM5-2B Q4_K_M (.zappm via Multiboot module) + SMP AVX2 active cores.
3. Live Ring-3 #PF crash -> Red HUD -> MiniCPM5-2B live auto-repair -> 60 frames working game!
4. Captures QMP screendump PNG of the repaired app running in Ring 3.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import socket
import subprocess
import sys
import tempfile
import time
def qmp_screendump(qmp_sock: str, ppm_path: str) -> bool:
try:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(5.0)
s.connect(qmp_sock)
s.recv(4096)
s.sendall(b'{"execute":"qmp_capabilities"}\n')
s.recv(4096)
cmd = json.dumps({"execute": "screendump", "arguments": {"filename": ppm_path}}) + "\n"
s.sendall(cmd.encode())
resp = s.recv(4096).decode(errors="replace")
s.close()
return '"return"' in resp and os.path.exists(ppm_path)
except Exception as e:
print(f"[warn] QMP screendump failed: {e}", flush=True)
return False
def test_iso_boot(iso_path: str) -> None:
print(f"[stage3] 1/2 Testing GRUB2 BIOS ISO boot: {iso_path}", flush=True)
proc = subprocess.Popen(
[
"qemu-system-x86_64", "-enable-kvm", "-cpu", "host",
"-m", "512M", "-smp", "2", "-vga", "std", "-display", "none",
"-serial", "stdio", "-cdrom", iso_path, "-boot", "d",
],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, bufsize=1,
)
buf = ""
t0 = time.time()
ok = False
try:
while time.time() - t0 < 25.0:
ch = proc.stdout.read(1)
if not ch:
break
buf += ch
if "zero-app> " in buf:
ok = True
proc.stdin.write("halt\n")
proc.stdin.flush()
break
proc.wait(timeout=8)
finally:
if proc.poll() is None:
proc.kill()
assert ok, f"ISO failed to boot to zero-app> prompt!\nLog:\n{buf[-1200:]}"
print("[PASS] Bootable GRUB2 ISO booted cleanly to zero-app> shell!", flush=True)
def test_live_repair(kernel: str, model: str, smp: int, out_dir: str,
command: str = "repairtest", fault: str | None = "#PF") -> dict:
os.makedirs(out_dir, exist_ok=True)
qmp_sock = os.path.join(tempfile.gettempdir(), f"zapp_stage3_qmp_{os.getpid()}.sock")
if os.path.exists(qmp_sock):
os.remove(qmp_sock)
model_sz = os.path.getsize(model)
if model_sz >= 2 * 1024 * 1024 * 1024:
print(f"[stage3] 2/2 Launching Zero-App OS + MiniCPM5-2B ({smp} AVX2 vCPUs, NVDIMM {model_sz // (1024*1024)} MiB)...", flush=True)
cmd = [
"qemu-system-x86_64", "-enable-kvm", "-cpu", "host",
"-machine", "pc,nvdimm=on",
"-m", "3G,slots=2,maxmem=8G", "-smp", str(smp), "-vga", "std", "-display", "none",
"-serial", "stdio",
"-qmp", f"unix:{qmp_sock},server,nowait",
"-object", f"memory-backend-file,id=zmodel,mem-path={model},size={model_sz},readonly=on",
"-device", "nvdimm,id=nv1,memdev=zmodel,unarmed=on",
"-kernel", kernel,
]
else:
print(f"[stage3] 2/2 Launching Zero-App OS + MiniCPM5-2B ({smp} AVX2 vCPUs, 4G RAM)...", flush=True)
cmd = [
"qemu-system-x86_64", "-enable-kvm", "-cpu", "host",
"-m", "4G", "-smp", str(smp), "-vga", "std", "-display", "none",
"-serial", "stdio",
"-qmp", f"unix:{qmp_sock},server,nowait",
"-kernel", kernel,
"-initrd", model,
]
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, bufsize=1,
)
log_lines = []
buf = ""
sent_cmd = False
passed = False
saw_model = False
saw_smp = False
saw_pf = False
pass_line = ""
tag = "STAGE3_GEN" if command == "gentest" else "STAGE3_REPAIR"
t0 = time.time()
ppm_path = os.path.join(out_dir, "stage3_repaired.ppm")
png_path = os.path.join(out_dir, "stage3_repaired.png")
try:
while time.time() - t0 < 480.0:
ch = proc.stdout.read(1)
if not ch:
break
buf += ch
if ch == "\n":
line = buf.rstrip("\r\n")
log_lines.append(line)
buf = ""
if any(k in line for k in ("[ai]", "[FAULT", "[uasm]", "[STAGE3_", "=== HARDWARE")):
print(" |", line, flush=True)
if "Found MiniCPM5-2B" in line:
saw_model = True
if "SMP AVX2 pool:" in line and "active cores" in line:
saw_smp = True
if fault and f"[FAULT CAUGHT] HARDWARE {fault}" in line:
saw_pf = True
if f"[{tag}] PASS" in line and re.search(r"frames=60\b", line):
passed = True
pass_line = line
# Capture screenshot right while repaired frame is on screen!
if qmp_screendump(qmp_sock, ppm_path):
try:
from PIL import Image
Image.open(ppm_path).save(png_path)
os.remove(ppm_path)
print(f"[PASS] Saved screenshot -> {png_path}", flush=True)
except Exception:
print(f"[PASS] Saved PPM screenshot -> {ppm_path}", flush=True)
elif not sent_cmd and buf.endswith("zero-app> "):
log_lines.append(buf)
buf = ""
sent_cmd = True
print(f"[stage3] Prompt ready -> sending {command!r}...", flush=True)
proc.stdin.write(command + "\n")
proc.stdin.flush()
elif sent_cmd and buf.endswith("zero-app> "):
proc.stdin.write("halt\n")
proc.stdin.flush()
break
proc.wait(timeout=10)
finally:
if proc.poll() is None:
proc.kill()
if os.path.exists(qmp_sock):
os.remove(qmp_sock)
with open(os.path.join(out_dir, "verify_stage3_serial.log"), "w") as f:
f.write("\n".join(log_lines) + "\n")
assert saw_model, "MiniCPM5-2B .zappm was not detected at boot!"
assert saw_smp, "SMP AVX2 pool did not initialize!"
if fault:
assert saw_pf, f"Initial broken app did not trigger hardware {fault}!"
assert passed, f"{command} did not complete 60 frames. Last lines:\n" + "\n".join(log_lines[-20:])
print(f"[PASS] {command} completed 60 frames in Ring 3", flush=True)
print(f" {pass_line}", flush=True)
return {"pass_line": pass_line, "png": png_path if os.path.exists(png_path) else ppm_path}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--kernel", default="/mnt/nvme/projects/zero-app-os/build/zero-app-os.elf")
ap.add_argument("--iso", default="/mnt/nvme/projects/zero-app-os/build/zero-app-os.iso")
ap.add_argument("--model", help="ZAPPM path (v2 Q8_0 for all presets, original model for repairtest)")
ap.add_argument("--smp", type=int, default=8)
ap.add_argument("--out-dir", default="/mnt/nvme/projects/zero-app-os/runs/stage3-verify")
ap.add_argument("--skip-iso", action="store_true")
ap.add_argument("--all-presets", action="store_true", help="Exercise presets 1–5 for 60 frames each")
args = ap.parse_args()
if not args.model:
model_dir = "/mnt/ssd/models/minicpm5-2b-zeroapp"
model_file = "minicpm5-2b-zeroapp-v2-q8_0.zappm" if args.all_presets else "minicpm5-2b-zeroapp.zappm"
args.model = os.path.join(model_dir, model_file)
if not args.skip_iso:
test_iso_boot(args.iso)
if not args.all_presets:
res = test_live_repair(args.kernel, args.model, args.smp, args.out_dir)
print(json.dumps(res, indent=2))
return
results = {}
for preset, (command, fault) in enumerate(
(("repairtest", "#PF"), ("repairtest 2", "#PF"), ("repairtest 3", "#UD"),
("gentest", None), ("repairtest 5", "#PF")), 1
):
out_dir = os.path.join(args.out_dir, f"preset-{preset}")
try:
result = test_live_repair(args.kernel, args.model, args.smp, out_dir, command, fault)
if preset == 5:
line = result["pass_line"]
assert re.search(r"attempts=1\b", line), f"Canary repair must take exactly one PATCH: {line}"
assert int(re.search(r"colors=(\d+)", line)[1]) >= 2, f"Canary scene lacks color: {line}"
results[preset] = {"passed": True, **result}
except (AssertionError, subprocess.TimeoutExpired) as exc:
results[preset] = {"passed": False, "error": str(exc)}
print(f"[FAIL] Preset {preset}: {exc}", flush=True)
print(json.dumps(results, indent=2))
if not all(result["passed"] for result in results.values()):
sys.exit(1)
if __name__ == "__main__":
main()