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
"""
Shared Ring-0 Line-Patch Protocol library for Zero-App OS Stage 2.4.
100% parity with C freestanding `apply_uasm_patches` in src/zapp_ai.c.
Grammar:
PATCH <start_line> <end_line>
<replacement uasm lines...>
END
Rules (1-based inclusive line numbers matching `1: ...` listing):
- Replace/Delete: 1 <= start <= end <= num_lines (0 body lines = delete).
- Insert before: end == 0 and 1 <= start <= num_lines + 1 (num_lines + 1 = append).
- Multiple PATCH blocks in one response must be disjoint and are applied
canonically (bottom-to-top / equivalent top-to-bottom streaming).
"""
from __future__ import annotations
import difflib
import re
from typing import List, Optional, Tuple
SYSTEM_PROMPT_SHORT = (
"You are Zero-App OS codegen. Emit ONLY pure compact x86-64 uasm (no comments, no prose, no <think>) "
"for the 160x120 1-frame ABI: r15=fb_ptr(0x20400000), r14=640, r13d=input5(1L,2R,4U,8D,16A), "
"r12d=ticks_ms, Arena=0x10100000(64KiB persistent), end with xor eax,eax; jmp exit."
)
_PATCH_HDR_RE = re.compile(r"^PATCH[ \t]+(\d+)[ \t]+(\d+)$")
class PatchError(ValueError):
pass
def strip_think_and_fence(raw: str) -> str:
if not raw:
return ""
s = raw.lstrip(" \t\r\n")
if s.startswith("<think>"):
end_idx = s.find("</think>")
if end_idx == -1:
raise PatchError("unclosed <think> tag")
s = s[end_idx + 8:]
s = s.lstrip(" \t\r\n")
if s.startswith("```"):
nl = s.find("\n")
s = s[nl + 1:] if nl != -1 else ""
return s
def clean_uasm_line(line: str) -> Optional[str]:
if ";" in line:
line = line.split(";", 1)[0]
line = line.strip(" \t\r")
if not line or line.startswith("#") or line.startswith("//"):
return None
return line
def extract_uasm(raw: str) -> str:
text = re.sub(r"<think>.*?</think>", "", raw or "", flags=re.DOTALL).strip()
m = re.search(r"```(?:uasm|asm|nasm|x86asm)?\s*\n(.*?)```", text, flags=re.DOTALL | re.IGNORECASE)
code = m.group(1) if m else text
lines = []
for ln in code.splitlines():
if ln.strip().startswith("```"):
break
cl = clean_uasm_line(ln)
if cl:
lines.append(cl)
return "\n".join(lines) + "\n" if lines else ""
def parse_and_normalize_patches(src: str, patch_text: str) -> Tuple[List[str], List[Tuple[int, int, List[str]]]]:
src_lines = [ln.rstrip("\r") for ln in src.splitlines()]
n_lines = len(src_lines)
s = strip_think_and_fence(patch_text)
lines = s.splitlines()
blocks: List[Tuple[int, int, List[str], int]] = []
i = 0
while i < len(lines):
hdr = lines[i].strip(" \t\r")
i += 1
if not hdr:
continue
if hdr.startswith("```"):
break
m = _PATCH_HDR_RE.match(hdr)
if not m:
raise PatchError(f"unexpected line outside PATCH block: {hdr!r}")
start = int(m.group(1))
end = int(m.group(2))
if end == 0:
if not (1 <= start <= n_lines + 1):
raise PatchError(f"insert line out of range: {start} (n={n_lines})")
else:
if not (1 <= start <= end <= n_lines):
raise PatchError(f"replace range out of range: {start}..{end} (n={n_lines})")
body: List[str] = []
found_end = False
while i < len(lines):
raw_ln = lines[i]
i += 1
trimmed = raw_ln.strip(" \t\r")
if trimmed == "END":
found_end = True
break
if trimmed.startswith("```"):
raise PatchError("code fence inside PATCH block before END")
if _PATCH_HDR_RE.match(trimmed):
raise PatchError("nested PATCH header before END")
cl = clean_uasm_line(raw_ln)
if cl is not None:
body.append(cl)
if not found_end:
raise PatchError("missing END for PATCH block")
blocks.append((start, end, body, len(blocks)))
if not blocks:
raise PatchError("no PATCH blocks found")
blocks.sort(key=lambda b: (b[0], b[1], b[3]))
for idx in range(len(blocks) - 1):
a_s, a_e, _, _ = blocks[idx]
b_s, _, _, _ = blocks[idx + 1]
if a_e > 0 and b_s <= a_e:
raise PatchError(f"overlapping PATCH blocks: [{a_s}..{a_e}] vs {b_s}")
return src_lines, [(s0, e0, body) for s0, e0, body, _ in blocks]
def apply_uasm_patches(src: str, patch_text: str) -> str:
src_lines, blocks = parse_and_normalize_patches(src, patch_text)
out_lines: List[str] = []
cur = 1
for start, end, body in blocks:
while cur < start:
out_lines.append(src_lines[cur - 1])
cur += 1
out_lines.extend(body)
if end > 0:
cur = end + 1
while cur <= len(src_lines):
out_lines.append(src_lines[cur - 1])
cur += 1
return "\n".join(out_lines) + "\n" if out_lines else ""
def format_patch_blocks(blocks: List[Tuple[int, int, List[str]]]) -> str:
parts = []
for start, end, body in blocks:
parts.append(f"PATCH {start} {end}")
parts.extend(body)
parts.append("END")
return "\n".join(parts) + "\n"
def diff_to_patch_text(broken_uasm: str, repaired_uasm: str) -> str:
"""Convert exact line diff between broken_uasm and repaired_uasm into canonical PATCH blocks."""
a = [ln.rstrip("\r") for ln in broken_uasm.splitlines()]
b = [ln.rstrip("\r") for ln in repaired_uasm.splitlines()]
sm = difflib.SequenceMatcher(None, a, b, autojunk=False)
blocks: List[Tuple[int, int, List[str]]] = []
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == "equal":
continue
if tag == "insert":
blocks.append((i1 + 1, 0, b[j1:j2]))
elif tag in ("replace", "delete"):
blocks.append((i1 + 1, i2, b[j1:j2]))
if not blocks:
raise PatchError("broken and repaired uasm are identical")
patch_text = format_patch_blocks(blocks)
# Verify round-trip!
applied = apply_uasm_patches(broken_uasm, patch_text)
norm_rep = "\n".join(b) + "\n" if b else ""
if applied != norm_rep:
raise PatchError("diff_to_patch_text round-trip mismatch")
return patch_text
def number_lines(code: str) -> str:
return "\n".join(f"{i+1}: {ln}" for i, ln in enumerate(code.splitlines()))
def build_patch_prompt(task: str, broken_uasm: str, observation: str) -> str:
return (
f"{SYSTEM_PROMPT_SHORT}\n\nTask: {task}\n\n"
f"Broken uasm:\n```uasm\n{number_lines(broken_uasm)}\n```\n\n"
f"Observation: {observation}\n\nPatch:\n```patch\n"
)
def format_obs(res) -> str:
if res.status == "asm_err":
return f"UASM ASSEMBLY ERROR at line {res.err_line}: {res.err_msg}"
if res.status == "fault":
extra = f" CR2={res.fault_cr2} ERR={res.fault_err}" if res.fault_vec == 14 else ""
return f"HARDWARE {res.fault_name} at RIP={res.fault_rip} (line {res.err_line}) on frame {res.fault_frame}{extra}."
if res.status == "timeout":
return f"APIC TIMER TIMEOUT (>100ms) at RIP={res.fault_rip} (line {res.err_line}) on frame {res.fault_frame}."
if res.status == "abi_err":
return f"ABI ERROR ({res.err_msg}) on frame {res.fault_frame}. End normal frames with xor eax,eax then jmp exit."
if not res.input_reactive:
return "BEHAVIOR CHECK FAILED: framebuffer hash identical for idle vs active input (r13d). Make visuals visibly react to r13d!"
return f"VISUAL CHECK FAILED: nonbg={res.nonbg_last}, colors={res.colors}. Draw multi-color graphics (>=2 colors, >32 px)."
if __name__ == "__main__":
base = "mov rbp,0x10100000\nxor eax,eax\nmov dword [rax],1\nmov [r15],eax\njmp exit\n"
assert apply_uasm_patches(base, "PATCH 3 3\nmov dword [rbp],1\nEND\n") == "mov rbp,0x10100000\nxor eax,eax\nmov dword [rbp],1\nmov [r15],eax\njmp exit\n"
assert apply_uasm_patches(base, "PATCH 2 3\nEND\n") == "mov rbp,0x10100000\nmov [r15],eax\njmp exit\n"
assert apply_uasm_patches(base, "PATCH 2 0\nmov rbx,10\nEND\nPATCH 6 0\nret\nEND\n") == "mov rbp,0x10100000\nmov rbx,10\nxor eax,eax\nmov dword [rax],1\nmov [r15],eax\njmp exit\nret\n"
assert apply_uasm_patches(base, "<think>ok</think>\n```patch\nPATCH 5 0\nxor eax,eax ; c\nEND\nPATCH 2 3\nmov eax,1\nEND\nPATCH 5 5\njmp exit\nEND\n```\n") == "mov rbp,0x10100000\nmov eax,1\nmov [r15],eax\nxor eax,eax\njmp exit\n"
assert apply_uasm_patches("", "PATCH 1 0\nxor eax,eax\njmp exit\nEND\n") == "xor eax,eax\njmp exit\n"
assert apply_uasm_patches("a\nb\n", "PATCH 1 2\nEND\n") == ""
pt = diff_to_patch_text(base, "mov rbp,0x10100000\nmov dword [rbp],1\nmov [r15],eax\nxor eax,eax\njmp exit\n")
assert apply_uasm_patches(base, pt) == "mov rbp,0x10100000\nmov dword [rbp],1\nmov [r15],eax\nxor eax,eax\njmp exit\n"
for bad in ["", "PATCH 1 1\nnop\n", "PATCH 6 6\nnop\nEND\n", "PATCH 2 4\nnop\nEND\nPATCH 3 0\nnop\nEND\n", "PATCH 4 2\nnop\nEND\n"]:
try:
apply_uasm_patches(base, bad)
raise AssertionError(f"Should have failed: {bad!r}")
except PatchError:
pass
print("ALL PYTHON v2_patch_lib.py TESTS PASSED!")