Skip to content

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.

7.1 KB
Raw Blame
#!/usr/bin/env python3
"""Read warden JSON-lines and receiver counts from one KVM run."""
import argparse
import curses
import json
import textwrap
from collections import deque
from pathlib import Path

HEADS = ("exfil_risk", "evasion_chain", "benign_dev", "uncertainty")
WHITE, GOLD, CYAN, BLUE, GREEN, RED = range(1, 7)


class Stream:
    def __init__(self, run):
        self.run = run
        self.events = deque(maxlen=800)
        self.file = None
        self.gen = self.latest = self.memory = self.counts = None

    def poll(self):
        if self.file is None and (self.run / "events.jsonl").exists():
            self.file = (self.run / "events.jsonl").open()
        if self.file:
            while True:
                pos = self.file.tell()
                line = self.file.readline()
                if not line.endswith("\n"):
                    self.file.seek(pos)
                    break
                e = json.loads(line)
                kind = e["type"]
                if kind == "model":
                    self.gen = e["gen"]
                    continue
                # Focus the live view on file decisions and their descendant
                # lineage. The JSON stream retains startup execs and forks.
                if kind in ("task_alloc", "bprm_exec") and not e["inherited"]:
                    continue
                if kind == "file_open":
                    if "x" in e:
                        relevant = e["x"][1] > 0
                    else:
                        relevant = e["name"] in ("config.yaml", "dummy_secret.env")
                    if not relevant:
                        continue
                if kind in ("connect", "sendmsg"):
                    if e["port"] not in (19998, 19999):
                        continue
                    self.latest = e
                self.memory = e
                self.events.append(e)
        try:
            self.counts = json.loads((self.run / "counters.json").read_text())
        except FileNotFoundError:
            pass


def summary(e):
    kind, pid = e["type"], e["pid"]
    who = f"pid={pid} {e['comm']}"
    if kind == "task_alloc":
        color = CYAN
        body = f"{e['ppid']} → {pid} fork()  h[32] INHERITED"
    elif kind == "file_open":
        color = GOLD
        badge = "TAINT" if e["opens"] else "CLEAN"
        body = f"{who}  {e['name']}  h[32] UPDATED  [{badge}]"
    elif kind == "bprm_exec":
        color = BLUE
        body = f"pid={pid} {e['name']}  h[32] UPDATED"
    else:
        allowed = e["verdict"] == "ALLOW"
        color = GREEN if allowed else RED
        action = "ALLOW" if allowed else "BLOCKED (-EPERM)"
        scores = " ".join(f"{k}={v / 255:.0%}" for k, v in zip(("exfil","evasion","benign","uncert"), e["scores"]))
        body = f"{action}  {who} → :{e['port']}  {scores}"
    return color, f"[{kind}] {body}  hook_us={e['hook_ns'] / 1000:.3f}"


def render(stream, width, height, scroll):
    lines = []
    inner = max(10, width - 4)
    def row(msg="", color=WHITE):
        lines.append((color, "│ " + msg[:inner].ljust(inner) + " │"))
    def rule(title, first=False):
        prefix = ("┌" if first else "├") + "─ " + title + " "
        lines.append((CYAN, prefix + "─" * max(0, width - len(prefix) - 1) + ("┐" if first else "┤")))
    def wrapped(msg, color=WHITE):
        for part in textwrap.wrap(msg, inner):
            row(part, color)
    rule(f"eBPF-Jev    |    gen #{stream.gen or chr(8230)}", True)
    wrapped("Linux 6.12.118 BPF LSM  |  21 KB INT8 Recurrent Net (task_storage h[32])  |  0 userspace RTT")
    rule("LIVE EVENT FEED" if not scroll else f"EVENT HISTORY   ↑ {scroll} lines")
    header = lines[:]
    lines.clear()
    rule("JEV 4-HEAD SCORES   /   latest connect")
    last = stream.latest
    for i, label in enumerate(HEADS):
        val = last["scores"][i] if last else 0
        size = min(36, max(4, inner - 24))
        fill = round(val / 255 * size)
        pct = f"{val / 255:6.1%}" if last else "     -"
        row(f"{label:14} {('█' * fill + '░' * (size - fill))} {pct}", (RED,GOLD,GREEN,CYAN)[i])
    row("Verdict   " + (last["verdict"] if last else "Awaiting connect"), RED if last and last["verdict"] != "ALLOW" else GREEN)
    rule("TASK MEMORY   /   h[32]")
    e = stream.memory
    if e:
        wrapped(f"pid={e['pid']}   opens={e['opens']}   fork_depth={e['depth']}   execs={e['execs']}   inherited={'yes' if e['inherited'] else 'no'}")
        wrapped(" ".join(e["h"][i:i+8] for i in range(0,64,8)), CYAN)
    else:
        row("Awaiting monitored task")
    rule("LOOPBACK RECEIVERS")
    c = stream.counts
    row(f"APPROVED SERVICE (:19998)   {c['approved'] if c else '…'} pkts", GREEN)
    leaked_tag = "  [LEAKED]" if c and c.get("secret_leaked") else ""
    row(f"UNAPPROVED SINK  (:19999)   {c['bytes'] if c else '…'} bytes{leaked_tag}", RED if c and (c["bytes"] or c.get("secret_leaked")) else GREEN)
    row("↑/↓ scroll   End follow   Ctrl-b z zoom")
    lines.append((CYAN, "└" + "─" * (width - 2) + "┘"))
    slots = max(1, height - len(header) - len(lines))
    feed = []
    for event in stream.events:
        color, msg = summary(event)
        for part in textwrap.wrap(msg, inner, subsequent_indent="  "):
            feed.append((color, "│ " + part.ljust(inner) + " │"))
    scroll = min(scroll, max(0, len(feed) - slots))
    end = len(feed) - scroll
    visible = feed[max(0,end-slots):end]
    empty = (WHITE, "│ " + " " * inner + " │")
    return header + [empty] * (slots-len(visible)) + visible + lines, scroll


def live(screen, stream):
    curses.curs_set(0)
    curses.start_color()
    curses.use_default_colors()
    for i, color in enumerate((7,3,6,4,2,1), 1):
        curses.init_pair(i, color, -1)
    screen.timeout(150)
    scroll = 0
    while True:
        geometry = stream.run / "geometry"
        if geometry.exists():
            rows, cols, *_ = map(int, geometry.read_text().split())
            if (rows, cols) != screen.getmaxyx():
                curses.resizeterm(rows, cols)
        stream.poll()
        height, width = screen.getmaxyx()
        frame, scroll = render(stream, max(16,width), height, scroll)
        for y, (color, text) in enumerate(frame[:height]):
            try:
                screen.addnstr(y,0,text,width,curses.color_pair(color) | (curses.A_BOLD if color != WHITE else 0))
            except curses.error:
                pass  # ncurses reports ERR when the last cell is filled.
        screen.refresh()
        key = screen.getch()
        if key in (curses.KEY_UP, curses.KEY_PPAGE):
            scroll += 1 if key == curses.KEY_UP else 8
        elif key in (curses.KEY_DOWN, curses.KEY_NPAGE):
            scroll = max(0, scroll - (1 if key == curses.KEY_DOWN else 8))
        elif key in (curses.KEY_END, ord("G")):
            scroll = 0


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("run", type=Path)
    parser.add_argument("--snapshot", action="store_true")
    args = parser.parse_args()
    stream = Stream(args.run)
    if args.snapshot:
        stream.poll()
        frame, _ = render(stream,120,36,0)
        print("\n".join(line for _,line in frame))
    else:
        curses.wrapper(live,stream)