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.

8.4 KB
Raw Blame
"""Offline labelled hook records. No fixture operation performs filesystem or network I/O."""
import gzip
import itertools
import json
import random
from pathlib import Path

ROOT = Path(__file__).resolve().parent
SPLITS = ("train", "cal", "val", "test")
# The four catalogs use different tool identities within each functional class.
CATALOG = [
    ("git", "npm", "sh", "curl", "uvicorn"),
    ("hg", "pip", "bash", "python", "gunicorn"),
    ("fossil", "pnpm", "dash", "wget", "node"),
    ("svn", "yarn", "zsh", "ruby", "pytest"),
]
CASES = ("clean", "persistent", "startup", "registry", "ci", "direct", "chain",
         "ambiguous_allow", "ambiguous_deny", "stale_git")
LABEL = {case: [int(case in ("persistent","direct","chain","ambiguous_deny")),
                int(case in ("persistent","chain")), int(case not in
                ("persistent","direct","chain","ambiguous_deny")), int(case.startswith("ambiguous"))]
         for case in CASES}


def workflow(split, family, prefix, case, seed, application=False):
    rng = random.Random(seed)
    git, pkg, shell, net, server = CATALOG[SPLITS.index(split)]
    repo = f"/fixture/{split}/repo-{family}-{rng.randrange(128)}"
    events = []
    pid = depth = opened = execs = inherited = 0
    binary = 0
    protected_at = None
    now = 0

    def hook(kind, name="", obj=0, cls=0, dst=0, port=0, hint=0):
        nonlocal now, pid, depth, opened, execs, inherited, binary, protected_at
        now += rng.randint(4, 65)
        if kind == "fork":
            events.append(dict(kind=kind, parent=pid, pid=pid+1, ms=now))
            pid += 1
            depth += 1
            inherited = 127 if opened else 0
            return
        if kind == "bprm_check_security":
            binary = cls
            if opened:
                execs += 1
        if obj >= 85:
            opened += 1
            protected_at = now
            execs = 0
        age = None if protected_at is None else now - protected_at
        bucket = 0 if age is None else 127 if age < 1000 else 90 if age <= 5000 else 50 if age <= 30000 else 20
        x = [dict(file_open=64, socket_connect=127,bprm_check_security=0)[kind],
             obj,40 if kind=="file_open" else 0,binary,min(127,depth*25),dst,port,
             bucket,min(127,32*opened),min(127,32*execs),inherited,hint,0,0,0,0]
        events.append(dict(kind=kind, pid=pid, ms=now, name=name,x=x))

    def exe(name, cls):
        hook("bprm_check_security", "/fixture/bin/"+name,cls=cls)

    def read(name, obj):
        hook("file_open", name,obj=obj)

    if application:
        # A service can load configuration in its already-running interpreter.
        # Match histories and port buckets across approved/unapproved pairs.
        for _ in range(rng.randrange(3)):
            hook("fork")
        if rng.randrange(2):
            exe(server, 0)  # Optional script/interpreter pass of a shebang exec.
        exe(net, 127)
        for _ in range(rng.randrange(3)):
            read(rng.choice(("package.json", "config.yaml", "pyproject.toml")), 40)
        name, cls = rng.choice([("settings.env",85),("fixture.key",127)])
        read(name, cls)
        if case in ("worker", "chain"):
            hook("fork")
            exe(net, 127)
        approved = case in ("startup", "worker")
        port = rng.choice((443, 22, rng.randint(32768,65535), rng.randint(1024,32767)))
        port_bucket = 30 if port==443 else 65 if port==22 else 95 if port>=32768 else 127
        hook("socket_connect", dst=30 if approved else 127, port=port_bucket)
        events[-1].update(fixture_sink="127.0.0.1", port=port, approved=approved)
        return dict(repo=repo, family=family, case=case, labels=LABEL["startup" if case=="worker" else case], events=events)

    for op in prefix:
        if op == "checkout":
            exe(git,30)
        elif op == "build":
            exe(pkg,65)
        elif op == "prepare":
            exe(shell,95)
        elif op == "manifest":
            read(rng.choice(["package.json","pyproject.toml"]),40)
        elif op == "config":
            read("config.yaml",40)
        else:
            exe(server,127)

    secret = rng.choice([("dummy_secret.env",85),("dummy_ssh_key",127)])
    if case == "registry":
        read("package.json",40)
    else:
        read(*secret)
    hops = rng.randint(1,3)
    final_port = rng.choice([30,30,65,95])
    dst, hint = 127, 0
    if case in ("persistent","clean"):
        # Age and depth are matched. The earlier executable's role differs.
        now += 31000 + rng.randrange(20000)
        for _ in range(hops):
            hook("fork")
            exe(shell if case=="persistent" else git,95 if case=="persistent" else 30)
        exe(net,127)
    elif case.startswith("ambiguous"):
        # Unobserved approval token is equally likely to be granted or expired.
        hook("fork")
        exe(pkg,65)
        now += 6500
    elif case == "chain":
        for _ in range(hops):
            hook("fork")
            exe(shell,95)
        exe(net,127)
    elif case == "startup":
        exe(server,127)
        dst, hint = rng.choice([30,75]),0
    elif case == "ci":
        exe(pkg,65)
        dst, hint = 75,127
    elif case == "registry":
        name = rng.choice([pkg,git,net])
        exe(name,{pkg:65,git:30,net:127}[name])
        dst, hint = 30,127 if binary in (30,65) else 0
    elif case == "stale_git":
        now += 35000
        hook("fork")
        exe(git,30)
    hook("socket_connect", dst=dst, port=final_port,hint=hint)
    events[-1]["fixture_sink"] = "127.0.0.1"
    events[-1]["port"] = {30:443,65:22,95:49152}[final_port]
    events[-1]["approved"] = dst != 127
    return dict(repo=repo, family=family, template=list(prefix), case=case,
                labels=LABEL[case], events=events)


def main():
    folder = ROOT/"data"
    folder.mkdir(exist_ok=True)
    prefixes = list(itertools.permutations(("checkout","build","prepare","manifest","config","serve"),4))
    random.Random(8128).shuffle(prefixes)
    offset = 0
    manifest = {}
    signatures = set()
    for split, nfamily in zip(SPLITS,[48,12,12,24]):
        with gzip.open(folder/(split+".jsonl.gz"),"wt") as out:
            for f in range(offset,offset+nfamily):
                # Unique prefix even after projecting names to classes (both manifest/config -> open).
                while True:
                    prefix = prefixes.pop()
                    sig = tuple("open" if p in ("config","manifest") else p for p in prefix)
                    if sig not in signatures:
                        signatures.add(sig)
                        break
                for rep in range(16):
                    seed = f*1000000+rep*100
                    pair = {}
                    for i,case in enumerate(CASES):
                        group = 0 if i < 2 else 7 if i in (7,8) else i
                        row = workflow(split,f,prefix,case,seed+group)
                        row["initiator"] = "ci-runner" if case=="ci" else ("ide-agent" if rep%2 else "developer-shell")
                        row["pair_id"] = f"{f}/{rep}/{group}"
                        if group in pair:
                            assert pair[group][-1] == row["events"][-1]
                            if group == 7:
                                assert pair[group] == row["events"]
                        pair[group] = row["events"]
                        out.write(json.dumps(row,separators=(",",":"))+"\n")
        manifest[split] = dict(workflows=nfamily*160, families=list(range(offset,offset+nfamily)),
                               tools=CATALOG[SPLITS.index(split)])
        # Keep the original validation, calibration and test populations frozen.
        # Train on separate application examples and reserve disjoint families
        # for checking the exported pack on this additional distribution.
        with gzip.open(folder/("application-"+split+".jsonl.gz"), "wt") as out:
            for family in range(offset, offset+nfamily):
                for rep in range(16):
                    seed = 812800000 + family*1000 + rep
                    for case in ("startup","direct","worker","chain"):
                        row = workflow(split, family, (), case, seed, application=True)
                        out.write(json.dumps(row,separators=(",",":"))+"\n")
        manifest[split]["application_workflows"] = nfamily*16*4
        offset += nfamily
    (folder/"manifest.json").write_text(json.dumps(manifest,indent=2))
    print({k:v["workflows"] for k,v in manifest.items()})


if __name__ == "__main__":
    main()