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
"""
Automated QEMU KVM + QMP + VNC + Serial + Visual Verification Suite
for Zero-App Ephemeral OS (Stage 1).
Tests:
1. Built-in selftest (6/6): #PF unmapped (line# + CR2), #PF RO-ABI,
#UD, #DE, APIC timer infinite-loop preemption, mouse_box Ring 3 render.
2. Live interactive Ring 3 mouse_box:
- Launches via serial shell `run mouse`
- Captures framebuffer screenshot #1 (square centered at 512,368)
- Injects real PS/2 mouse motion + LMB press via QMP input-send-event
- Captures screenshot #2 and verifies square moved to new coords & turned magenta!
- Injects ESC key via QMP and verifies instant clean abort back to shell!
3. Live `#PF` HUD visual capture:
- Runs `run pf`, verifies red HUD banner with exact `#PF at 0x... (line 13) CR2=0xDEADBEEF`
and captures screenshot #3.
4. Live custom micro-asm upload over serial (`asm` ... `END`):
- Assembles custom Ring 3 program on the fly, draws bright green 100x100 box
at (100,100) using ONLY fb_ptr & stride, calls `exit 42`, verifies `EXIT code=42`
and pixel color in screenshot #4!
5. Clean ACPI poweroff (`halt`) with exit code 0.
"""
import argparse
import json
import os
import socket
import subprocess
import sys
import time
from datetime import datetime, timezone
from PIL import Image
class QMPClient:
def __init__(self, sock_path: str):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.settimeout(10.0)
for _ in range(50):
try:
self.sock.connect(sock_path)
break
except OSError:
time.sleep(0.05)
self.buf = b""
greeting = self._recv_msg()
assert "QMP" in greeting, f"Unexpected QMP greeting: {greeting}"
self.cmd("qmp_capabilities")
def _recv_msg(self):
while b"\n" not in self.buf:
chunk = self.sock.recv(4096)
if not chunk:
raise EOFError("QMP closed")
self.buf += chunk
line, self.buf = self.buf.split(b"\n", 1)
return json.loads(line.decode("utf-8"))
def cmd(self, execute: str, arguments=None):
req = {"execute": execute}
if arguments is not None:
req["arguments"] = arguments
self.sock.sendall((json.dumps(req) + "\n").encode("utf-8"))
while True:
msg = self._recv_msg()
if "event" in msg:
continue
if "error" in msg:
raise RuntimeError(f"QMP error on {execute}: {msg['error']}")
return msg.get("return")
def screendump_png(self, ppm_path: str, png_path: str) -> Image.Image:
self.cmd("screendump", {"filename": ppm_path})
img = Image.open(ppm_path).convert("RGB")
img.save(png_path)
os.remove(ppm_path)
return img
def mouse_move_rel(self, dx: int, dy: int, steps: int = 6):
sx = dx // steps
sy = dy // steps
rx = dx - sx * steps
ry = dy - sy * steps
for i in range(steps):
cx = sx + (rx if i == steps - 1 else 0)
cy = sy + (ry if i == steps - 1 else 0)
events = []
if cx:
events.append({"type": "rel", "data": {"axis": "x", "value": cx}})
if cy:
events.append({"type": "rel", "data": {"axis": "y", "value": cy}})
if events:
self.cmd("input-send-event", {"events": events})
time.sleep(0.03)
def mouse_btn(self, button: str, down: bool):
self.cmd("input-send-event", {
"events": [{"type": "btn", "data": {"down": down, "button": button}}]
})
def send_key(self, qcode: str):
self.cmd("input-send-event", {
"events": [{"type": "key", "data": {"down": True, "key": {"type": "qcode", "data": qcode}}}]
})
time.sleep(0.04)
self.cmd("input-send-event", {
"events": [{"type": "key", "data": {"down": False, "key": {"type": "qcode", "data": qcode}}}]
})
def close(self):
self.sock.close()
class SerialClient:
def __init__(self, sock_path: str):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.settimeout(0.2)
for _ in range(50):
try:
self.sock.connect(sock_path)
break
except OSError:
time.sleep(0.05)
self.log = ""
def read_until(self, needle: str, timeout: float = 8.0) -> str:
t0 = time.time()
start_len = len(self.log)
while time.time() - t0 < timeout:
if needle in self.log[start_len:]:
return self.log[start_len:]
try:
data = self.sock.recv(4096)
if data:
self.log += data.decode("utf-8", errors="replace")
else:
break
except socket.timeout:
pass
raise TimeoutError(f"Timeout waiting for {needle!r}; got:\n{self.log[start_len:]}")
def send_line(self, line: str):
self.sock.sendall((line + "\n").encode("utf-8"))
time.sleep(0.02)
def close(self):
self.sock.close()
def find_color_centroid(img: Image.Image, pred, y_min=32):
w, h = img.size
px = img.load()
xs, ys = [], []
for y in range(y_min, h, 2):
for x in range(0, w, 2):
r, g, b = px[x, y]
if pred(r, g, b):
xs.append(x)
ys.append(y)
if not xs:
return None
return (sum(xs) / len(xs), sum(ys) / len(ys), len(xs))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--kernel", default="build/zero-app-os.elf")
ap.add_argument("--run-dir", default=None)
args = ap.parse_args()
if args.run_dir:
run_dir = args.run_dir
else:
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
run_dir = os.path.join("runs", f"{ts}-verify")
os.makedirs(run_dir, exist_ok=True)
qmp_sock = os.path.join(run_dir, "qmp.sock")
ser_sock = os.path.join(run_dir, "serial.sock")
for p in (qmp_sock, ser_sock):
if os.path.exists(p):
os.remove(p)
qemu_cmd = [
"qemu-system-x86_64",
"-enable-kvm", "-cpu", "host",
"-m", "256M", "-smp", "1",
"-vga", "std",
"-vnc", "127.0.0.1:59",
"-qmp", f"unix:{qmp_sock},server,nowait",
"-serial", f"unix:{ser_sock},server,nowait",
"-kernel", args.kernel,
]
print(f"[verify] Launching QEMU KVM (VNC 127.0.0.1:5959, run_dir={run_dir})")
proc = subprocess.Popen(qemu_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
qmp = None
ser = None
try:
qmp = QMPClient(qmp_sock)
ser = SerialClient(ser_sock)
# Wait for boot prompt
boot_out = ser.read_until("zero-app> ")
assert "1024x768x32" in boot_out, "Missing LFB boot line"
print("[PASS] Booted 1024x768x32bpp bare-metal kernel to shell")
# 1. Run built-in 6/6 selftest
ser.send_line("selftest")
st_out = ser.read_until("zero-app> ", timeout=10.0)
assert "RESULT: 6/6 PASSED" in st_out, f"Selftest failed:\n{st_out}"
assert "#PF at 0x1001002E (line 13) CR2=0xDEADBEEF" in st_out, f"Missing exact #PF line 13:\n{st_out}"
assert "#PF at 0x10010000 (line 2) CR2=0x10000000" in st_out, f"Missing RO-ABI #PF line 2:\n{st_out}"
assert "#UD at 0x10010007 (line 3)" in st_out, f"Missing #UD line 3:\n{st_out}"
assert "#DE at 0x10010009 (line 5)" in st_out, f"Missing #DE line 5:\n{st_out}"
assert "TIMEOUT (150 ms) at 0x100100" in st_out and ("(line 11)" in st_out or "(line 12)" in st_out), f"Missing timeout line 11:\n{st_out}"
print("[PASS] 6/6 built-in selftest passed with exact source-line fault attribution!")
# 2. Live interactive Ring 3 mouse_box + PS/2 mouse movement + LMB click + ESC abort
ser.send_line("run mouse")
ser.read_until("[uasm] assembled mouse_box:")
time.sleep(0.25)
img1, c1 = None, None
for _ in range(8):
img1 = qmp.screendump_png(
os.path.join(run_dir, "tmp1.ppm"),
os.path.join(run_dir, "01_mouse_initial.png"),
)
c1 = find_color_centroid(img1, lambda r, g, b: b > 200 and g > 150 and r < 50)
if c1 is not None and c1[2] >= 200:
break
time.sleep(0.07)
assert img1.size == (1024, 768), f"Expected 1024x768, got {img1.size}"
hud_px = img1.getpixel((5, 2))
assert hud_px == (0x14, 0x28, 0x48), f"Unexpected HUD color: {hud_px}"
assert c1 is not None, "Cyan mouse box not found on initial screenshot!"
print(f"[PASS] Initial mouse_box rendered at centroid=({c1[0]:.1f}, {c1[1]:.1f}), samples={c1[2]}")
# Move PS/2 mouse (+180, -120) and press Left Mouse Button!
qmp.mouse_move_rel(180, -120, steps=6)
qmp.mouse_btn("left", True)
time.sleep(0.25)
img2, c2 = None, None
for _ in range(8):
img2 = qmp.screendump_png(
os.path.join(run_dir, "tmp2.ppm"),
os.path.join(run_dir, "02_mouse_moved_lmb.png"),
)
c2 = find_color_centroid(img2, lambda r, g, b: r > 220 and g < 80 and b > 100)
if c2 is not None and c2[2] >= 200:
break
time.sleep(0.07)
qmp.mouse_btn("left", False)
assert c2 is not None, "Magenta LMB mouse box not found after mouse move + click!"
dx_obs = c2[0] - c1[0]
dy_obs = c2[1] - c1[1]
assert dx_obs > 100 and dy_obs < -60, f"Mouse box did not move as expected: c1={c1}, c2={c2}"
# Verify kernel HUD still intact!
assert img2.getpixel((5, 2)) == (0x14, 0x28, 0x48), "Kernel HUD corrupted!"
print(f"[PASS] PS/2 mouse moved box to ({c2[0]:.1f}, {c2[1]:.1f}) (delta={dx_obs:+.1f},{dy_obs:+.1f}) & LMB changed color to neon magenta!")
# Press ESC via QMP PS/2 keyboard -> must immediately abort Ring 3 back to shell!
qmp.send_key("esc")
abort_out = ser.read_until("zero-app> ", timeout=5.0)
assert "ABORT (ESC," in abort_out, f"ESC did not abort Ring 3 cleanly:\n{abort_out}"
print("[PASS] PS/2 ESC key preempted Ring 3 app cleanly back to shell!")
# 3. Visual capture of #PF caught red HUD banner
ser.send_line("run pf")
pf_out = ser.read_until("zero-app> ", timeout=5.0)
assert "#PF at 0x1001002E (line 13) CR2=0xDEADBEEF" in pf_out
img3 = qmp.screendump_png(
os.path.join(run_dir, "tmp3.ppm"),
os.path.join(run_dir, "03_pf_caught_hud.png"),
)
# Top HUD must be red alert (0x8A, 0x11, 0x18)
assert img3.getpixel((5, 2)) == (0x8A, 0x11, 0x18), f"Expected red #PF HUD, got {img3.getpixel((5, 2))}"
print("[PASS] #PF red diagnostic HUD banner rendered on Supervisor-only top bar!")
# 4. Live custom micro-asm uploaded over serial (`asm` ... `END`)
custom_prog = [
"; Live custom micro-asm: draw 100x100 neon green box at (100,100) & exit 42",
"mov r12, [rdi + 0x00]",
"mov r13, [rdi + 0x08]",
"mov r8d, 100",
"ly:",
"cmp r8d, 200",
"jae ldone",
"mov rax, r8",
"imul rax, r13",
"lea r9, [r12 + rax]",
"mov ebx, 100",
"lx:",
"cmp ebx, 200",
"jae ly_next",
"mov dword [r9 + rbx*4], 0x0033FF66",
"inc ebx",
"jmp lx",
"ly_next:",
"inc r8d",
"jmp ly",
"ldone:",
"exit 42",
]
ser.send_line("asm")
ser.read_until("END':")
for ln in custom_prog:
ser.send_line(ln)
ser.send_line("END")
asm_out = ser.read_until("zero-app> ", timeout=5.0)
assert "EXIT code=42" in asm_out, f"Custom asm did not exit 42:\n{asm_out}"
img4 = qmp.screendump_png(
os.path.join(run_dir, "tmp4.ppm"),
os.path.join(run_dir, "04_custom_live_asm.png"),
)
# Check pixel inside custom green box: app (150,150) -> screen (150, 150+32=182)
px_custom = img4.getpixel((150, 182))
assert px_custom == (0x33, 0xFF, 0x66), f"Expected (0x33,0xFF,0x66), got {px_custom}"
print("[PASS] Live custom micro-asm assembled, drew green 100x100 box at (100,100), and exited with code=42!")
# 5. Clean ACPI poweroff
ser.send_line("halt")
rc = proc.wait(timeout=5.0)
assert rc == 0, f"QEMU exited with code {rc}"
print("[PASS] Clean ACPI poweroff (exit code 0)")
with open(os.path.join(run_dir, "serial.log"), "w") as f:
f.write(ser.log)
print(f"\nALL VERIFICATION CHECKS PASSED! Artifacts saved in {run_dir}/")
finally:
if qmp:
qmp.close()
if ser:
ser.close()
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.kill()
for p in (qmp_sock, ser_sock):
if os.path.exists(p):
os.remove(p)
if __name__ == "__main__":
main()