aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / om / site / verify-mutations.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Negative-control runner for the Omega site verifier (verification only, never in production). |
| 3 | |
| 4 | Each row of om/site/verify-mutations.jsonl names the original oracle rule it exercises (`rule`, |
| 5 | the B/V/C/H/E/F/G ids of crates/site-builder plus O/D/L/Q/N1/R0 for the gates the oracle grew), |
| 6 | the mutation (`ops`) and what the Omega verifier must say (`expect`): a rule label that must appear |
| 7 | as `verify: FAIL <label> ` with exit 1, `EXIT70` for a fail-closed runtime refusal, `PASS` for a |
| 8 | control that must stay accepted, or `HASH` for the artifact-hash gate this runner itself performs |
| 9 | with the pinned external `sha256sum` (an oracle, not part of the site build). |
| 10 | |
| 11 | Usage (from the repository root, after a known-good dist exists): |
| 12 | python3 om/site/verify-mutations.py --verifier build/site-verify --dist dist \ |
| 13 | [--oracle target/release/site-builder] [--only ID,...] [--keep] |
| 14 | |
| 15 | Before any mutation the runner proves its setup: the unmodified dist, every source data file and |
| 16 | `--sources` must pass, and the artifact hashes must match. A mutation whose anchor text is absent is |
| 17 | INVALID (the control did not run), never a pass. Exit 0 only when every row behaved as expected. |
| 18 | """ |
| 19 | import argparse, hashlib, html, json, os, re, shutil, subprocess, sys, tempfile |
| 20 | |
| 21 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 22 | ROWS = os.path.join(HERE, "verify-mutations.jsonl") |
| 23 | QUOTES = "data/quotes.json" |
| 24 | ENGINEER = "public/data/engineer.json" |
| 25 | SOURCES = ["public/data/now.tsv", "facts.json", "public/data/agent-repos.json", |
| 26 | "crates/site-builder/data/machines.json", "crates/site-builder/data/omega.json", |
| 27 | "crates/site-builder/data/cudaplusplus.json", "crates/site-builder/data/research_status.json", |
| 28 | "crates/site-builder/data/status.json", "public/data/project-progress.json", QUOTES, ENGINEER] |
| 29 | # Artifact hashes (rule B8): (sidecar, dist copy). The sidecar names the source file it pins. |
| 30 | HASHES = [("om/hive-page/hive.js.sha256", "js/hive.js"), |
| 31 | ("om/hive-page/turing-look.js.sha256", "js/turing-look.js"), |
| 32 | ("public/wasm/hive-fresh.wasm.sha256", "wasm/hive-fresh.wasm"), |
| 33 | ("om/hive-page/main.html.sha256", None)] |
| 34 | BOX_CLASSES = ("mx-card mx-row glow-box lineage-card lineage-role status-row live-row receipt rs-card rs-step " |
| 35 | "rs-impl-item hub-card narr-card blog-card now-card now-queue-row now-tl now-usage om-part om-layer " |
| 36 | "om-receipt om-gap om-bar-row om-beyond cp-hop cp-card cp-row dash-card").split() |
| 37 | DESTS = ["/classic/", "/omega/", "/machine/", "/discoveries/", "/learn/", "/allen/"] |
| 38 | |
| 39 | |
| 40 | class Invalid(Exception): |
| 41 | pass |
| 42 | |
| 43 | |
| 44 | def rd(p): |
| 45 | with open(p, "rb") as f: |
| 46 | return f.read() |
| 47 | |
| 48 | |
| 49 | def wr(p, b): |
| 50 | os.makedirs(os.path.dirname(p) or ".", exist_ok=True) |
| 51 | with open(p, "wb") as f: |
| 52 | f.write(b) |
| 53 | |
| 54 | |
| 55 | def text(p): |
| 56 | return rd(p).decode("utf-8") |
| 57 | |
| 58 | |
| 59 | def jpath(obj, path, create=False): |
| 60 | keys = [k for k in path.split(".")] if path else [] |
| 61 | for k in keys[:-1]: |
| 62 | obj = obj[int(k)] if isinstance(obj, list) else obj[k] |
| 63 | return obj, (keys[-1] if keys else None) |
| 64 | |
| 65 | |
| 66 | def jkey(parent, k): |
| 67 | return int(k) if isinstance(parent, list) else k |
| 68 | |
| 69 | |
| 70 | def first_tag(s, pat): |
| 71 | m = re.search(pat, s) |
| 72 | if not m: |
| 73 | raise Invalid(f"anchor {pat!r} absent") |
| 74 | return m |
| 75 | |
| 76 | |
| 77 | def sha256sum(path): |
| 78 | out = subprocess.run(["sha256sum", path], capture_output=True, check=True, text=True).stdout |
| 79 | return out.split()[0] |
| 80 | |
| 81 | |
| 82 | def apply(op, root, files): |
| 83 | name, args = op[0], op[1:] |
| 84 | |
| 85 | def P(a): |
| 86 | return files.get(a) or os.path.join(root, a) |
| 87 | |
| 88 | if name in ("sub", "suball"): |
| 89 | p, old, new = P(args[0]), args[1], args[2] |
| 90 | s = text(p) |
| 91 | if old not in s: |
| 92 | raise Invalid(f"{args[0]}: {old!r} absent") |
| 93 | wr(p, (s.replace(old, new, 1) if name == "sub" else s.replace(old, new)).encode()) |
| 94 | elif name == "ins": |
| 95 | p, before, t = P(args[0]), args[1], args[2] |
| 96 | s = text(p) |
| 97 | if before not in s: |
| 98 | raise Invalid(f"{args[0]}: {before!r} absent") |
| 99 | wr(p, s.replace(before, t + before, 1).encode()) |
| 100 | elif name == "app": |
| 101 | p = P(args[0]) |
| 102 | if not os.path.exists(p): |
| 103 | raise Invalid(f"{args[0]} absent") |
| 104 | wr(p, rd(p) + args[1].encode()) |
| 105 | elif name == "put": |
| 106 | wr(P(args[0]), args[1].encode()) |
| 107 | elif name == "del": |
| 108 | p = P(args[0]) |
| 109 | if not os.path.lexists(p): |
| 110 | raise Invalid(f"{args[0]} absent") |
| 111 | os.remove(p) |
| 112 | elif name == "trunc": |
| 113 | p = P(args[0]) |
| 114 | wr(p, rd(p)[: -int(args[1])]) |
| 115 | elif name == "flipbyte": |
| 116 | p = P(args[0]) |
| 117 | b = bytearray(rd(p)) |
| 118 | if not b: |
| 119 | raise Invalid(f"{args[0]} empty") |
| 120 | b[-1] ^= 1 |
| 121 | wr(p, bytes(b)) |
| 122 | elif name == "symlink": |
| 123 | target, link = P(args[0]), P(args[1]) |
| 124 | if not os.path.exists(target): |
| 125 | raise Invalid(f"{args[0]} absent") |
| 126 | os.symlink(os.path.relpath(target, os.path.dirname(link)), link) |
| 127 | elif name in ("jset", "jdel", "jcopy", "jtrunc", "jappend"): |
| 128 | p = P(args[0]) |
| 129 | doc = json.loads(text(p)) |
| 130 | try: |
| 131 | if name == "jset": |
| 132 | par, k = jpath(doc, args[1]) |
| 133 | par[jkey(par, k)] = args[2] |
| 134 | elif name == "jdel": |
| 135 | par, k = jpath(doc, args[1]) |
| 136 | del par[jkey(par, k)] |
| 137 | elif name == "jcopy": |
| 138 | sp, sk = jpath(doc, args[1]) |
| 139 | dp, dk = jpath(doc, args[2]) |
| 140 | dp[jkey(dp, dk)] = sp[jkey(sp, sk)] |
| 141 | elif name == "jtrunc": |
| 142 | par, k = jpath(doc, args[1]) |
| 143 | lst = par[jkey(par, k)] |
| 144 | if len(lst) <= args[2]: |
| 145 | raise Invalid(f"{args[1]} already has {len(lst)} items") |
| 146 | del lst[args[2]:] |
| 147 | else: |
| 148 | par, k = jpath(doc, args[1]) |
| 149 | par[jkey(par, k)].append(args[2]) |
| 150 | except (KeyError, IndexError, TypeError) as e: |
| 151 | raise Invalid(f"{args[0]}: path {args[1]}: {e!r}") |
| 152 | wr(p, (json.dumps(doc, ensure_ascii=False, indent=1) + "\n").encode()) |
| 153 | elif name == "machines_above_ceiling": |
| 154 | p = P(args[0]) |
| 155 | doc = json.loads(text(p)) |
| 156 | ceil = {c["id"]: c["tok_s"] for c in doc["ceilings"]} |
| 157 | for sp in doc["speeds"]: |
| 158 | if sp.get("ceiling") in ceil: |
| 159 | sp["tok_s"] = ceil[sp["ceiling"]] * 2 |
| 160 | break |
| 161 | else: |
| 162 | raise Invalid("no speed with a ceiling") |
| 163 | wr(p, (json.dumps(doc, ensure_ascii=False, indent=1) + "\n").encode()) |
| 164 | elif name == "engineer_second_home": |
| 165 | p = P(args[0]) |
| 166 | doc = json.loads(text(p)) |
| 167 | others = [x for x in doc["pages"] if x.get("kind") != "home"] |
| 168 | if not others: |
| 169 | raise Invalid("no non-home engineer page") |
| 170 | others[0]["kind"] = "home" |
| 171 | wr(p, (json.dumps(doc, ensure_ascii=False, indent=1) + "\n").encode()) |
| 172 | elif name in ("unbox", "boxlink_off", "boxlink_drop"): |
| 173 | p = P(args[0]) |
| 174 | s = text(p) |
| 175 | if name == "unbox": |
| 176 | def strip_cls(m): |
| 177 | toks = [t for t in m.group(1).split() if t not in BOX_CLASSES] |
| 178 | return 'class="' + " ".join(toks) + '"' |
| 179 | t = re.sub(r'class="([^"]*)"', strip_cls, s) |
| 180 | if t == s: |
| 181 | raise Invalid("no box classes") |
| 182 | else: |
| 183 | m = first_tag(s, r'<a [^>]*class="[^"]*\bbox-link\b[^"]*"[^>]*>') |
| 184 | tag = m.group(0) |
| 185 | if name == "boxlink_off": |
| 186 | new = re.sub(r'href="[^"]*"', 'href="/now/"', tag, count=1) |
| 187 | else: |
| 188 | new = re.sub(r'\bbox-link\b', "box-lnk", tag, count=1) |
| 189 | t = s[: m.start()] + new + s[m.end():] |
| 190 | wr(p, t.encode()) |
| 191 | elif name == "ldgraph_trunc": |
| 192 | p = P(args[0]) |
| 193 | s = text(p) |
| 194 | o = '<script type="application/ld+json">' |
| 195 | a = s.index(o) + len(o) |
| 196 | b = s.index("</script>", a) |
| 197 | doc = json.loads(s[a:b]) |
| 198 | if len(doc.get("@graph", [])) <= args[1]: |
| 199 | raise Invalid("graph already small") |
| 200 | doc["@graph"] = doc["@graph"][: args[1]] |
| 201 | wr(p, (s[:a] + json.dumps(doc, ensure_ascii=False) + s[b:]).encode()) |
| 202 | elif name in ("quote_html", "quote_raw"): |
| 203 | p = P(args[0]) |
| 204 | q = {x["id"]: x["quote"] for x in json.loads(text(files["$QUOTES"]))["quotes"]}[args[1]] |
| 205 | s = text(p) |
| 206 | if name == "quote_html": |
| 207 | if "</main>" not in s: |
| 208 | raise Invalid("no </main>") |
| 209 | block = f'<blockquote data-quote-id="{args[1]}">{html.escape(q, quote=True)}</blockquote>' |
| 210 | s = s.replace("</main>", block + "</main>", 1) |
| 211 | else: |
| 212 | s = s + "\n" + q + "\n" |
| 213 | wr(p, s.encode()) |
| 214 | elif name == "hide_destinations": |
| 215 | p = P(args[0]) |
| 216 | s = text(p) |
| 217 | t = s |
| 218 | for h in DESTS: |
| 219 | t = t.replace(f'<a href="{h}"', f'<a aria-hidden="true" href="{h}"') |
| 220 | if t == s: |
| 221 | raise Invalid("no destination anchors in the <a href= form") |
| 222 | wr(p, t.encode()) |
| 223 | elif name == "x_after_main": |
| 224 | p = P(args[0]) |
| 225 | s = text(p) |
| 226 | cut = s.find("<main") |
| 227 | if cut < 0: |
| 228 | raise Invalid("no <main") |
| 229 | head = s[:cut].replace('href="https://x.com/drakestapleton"', 'href="https://x.com/drakestapleton/moved"') |
| 230 | if head == s[:cut]: |
| 231 | raise Invalid("no X link before <main") |
| 232 | wr(p, (head + s[cut:]).encode()) |
| 233 | elif name == "swap_ids": |
| 234 | p, a, b = P(args[0]), args[1], args[2] |
| 235 | s = text(p) |
| 236 | if a not in s or b not in s: |
| 237 | raise Invalid("ids absent") |
| 238 | wr(p, s.replace(a, "\0").replace(b, a).replace("\0", b).encode()) |
| 239 | elif name == "move_before_footer_into_footer": |
| 240 | p, needle = P(args[0]), args[1] |
| 241 | s = text(p) |
| 242 | cut = s.find("<footer") |
| 243 | if cut < 0 or needle not in s[:cut]: |
| 244 | raise Invalid("needle not before the footer") |
| 245 | body = s[:cut].replace(needle, needle.replace("href", "data-moved")) |
| 246 | rest = s[cut:] |
| 247 | if needle not in rest: |
| 248 | rest = rest.replace("</footer>", f"<a {needle}>moved</a></footer>", 1) |
| 249 | wr(p, (body + rest).encode()) |
| 250 | else: |
| 251 | raise Invalid(f"unknown op {name}") |
| 252 | |
| 253 | |
| 254 | def run(cmd, cwd=None): |
| 255 | r = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=1800) |
| 256 | return r.returncode, r.stderr.decode("utf-8", "replace") |
| 257 | |
| 258 | |
| 259 | def hash_gate(repo, dist): |
| 260 | bad = [] |
| 261 | for sidecar, copy in HASHES: |
| 262 | want, name = text(os.path.join(repo, sidecar)).split()[:2] |
| 263 | src = os.path.normpath(os.path.join(repo, os.path.dirname(sidecar), name)) |
| 264 | if sha256sum(src) != want: |
| 265 | bad.append(f"{src} != {sidecar}") |
| 266 | if copy and dist and sha256sum(os.path.join(dist, copy)) != want: |
| 267 | bad.append(f"dist/{copy} != {sidecar}") |
| 268 | return bad |
| 269 | |
| 270 | |
| 271 | def verdict(row, code, err): |
| 272 | e = row["expect"] |
| 273 | if e == "PASS": |
| 274 | return code == 0 |
| 275 | if e == "EXIT70": |
| 276 | return code == 70 |
| 277 | return code == 1 and f"verify: FAIL {e} " in err |
| 278 | |
| 279 | |
| 280 | def main(): |
| 281 | ap = argparse.ArgumentParser() |
| 282 | ap.add_argument("--verifier", required=True) |
| 283 | ap.add_argument("--dist", required=True) |
| 284 | ap.add_argument("--repo", default=".") |
| 285 | ap.add_argument("--oracle") |
| 286 | ap.add_argument("--only") |
| 287 | ap.add_argument("--keep", action="store_true") |
| 288 | a = ap.parse_args() |
| 289 | repo = os.path.abspath(a.repo) |
| 290 | bin_ = os.path.abspath(a.verifier) |
| 291 | good = os.path.abspath(a.dist) |
| 292 | rows = [json.loads(l) for l in open(ROWS, encoding="utf-8") if l.strip()] |
| 293 | if a.only: |
| 294 | keep = set(a.only.split(",")) |
| 295 | rows = [r for r in rows if r["id"] in keep] |
| 296 | quotes, engineer = os.path.join(repo, QUOTES), os.path.join(repo, ENGINEER) |
| 297 | setup = [] |
| 298 | code, err = run([bin_, good, quotes, engineer]) |
| 299 | if code != 0: |
| 300 | setup.append(f"unmodified dist refused ({code}):\n{err[-4000:]}") |
| 301 | code, err = run([bin_, "--sources"], cwd=repo) |
| 302 | if code != 0: |
| 303 | setup.append(f"--sources refused ({code}):\n{err[-4000:]}") |
| 304 | setup += hash_gate(repo, good) |
| 305 | if a.oracle: |
| 306 | code, err = run([os.path.abspath(a.oracle), "verify", good], cwd=repo) |
| 307 | if code != 0: |
| 308 | setup.append(f"Rust oracle refused the unmodified dist ({code})") |
| 309 | if setup: |
| 310 | print("MUTATIONS INVALID setup:\n" + "\n".join(setup)) |
| 311 | return 2 |
| 312 | counts = {"PASS": 0, "FAIL": 0, "INVALID": 0} |
| 313 | for row in rows: |
| 314 | tmp = tempfile.mkdtemp(prefix="svm-") |
| 315 | try: |
| 316 | files = {"$QUOTES": os.path.join(tmp, "quotes.json"), "$ENGINEER": os.path.join(tmp, "engineer.json")} |
| 317 | shutil.copy(quotes, files["$QUOTES"]) |
| 318 | shutil.copy(engineer, files["$ENGINEER"]) |
| 319 | if row["mode"] == "dist": |
| 320 | root = os.path.join(tmp, "dist") |
| 321 | shutil.copytree(good, root, symlinks=True) |
| 322 | elif row["mode"] == "data": |
| 323 | root = tmp |
| 324 | files["$F"] = os.path.join(tmp, os.path.basename(row["src"])) |
| 325 | shutil.copy(os.path.join(repo, row["src"]), files["$F"]) |
| 326 | else: |
| 327 | root = os.path.join(tmp, "repo") |
| 328 | for s in SOURCES: |
| 329 | if os.path.exists(os.path.join(repo, s)): |
| 330 | os.makedirs(os.path.dirname(os.path.join(root, s)) or root, exist_ok=True) |
| 331 | shutil.copy(os.path.join(repo, s), os.path.join(root, s)) |
| 332 | files["$F"] = os.path.join(root, row["src"]) |
| 333 | try: |
| 334 | for op in row["ops"]: |
| 335 | apply(op, root, files) |
| 336 | except (Invalid, OSError, ValueError, KeyError) as e: |
| 337 | counts["INVALID"] += 1 |
| 338 | print(f"INVALID\t{row['id']}\t{row['rule']}\t{e}") |
| 339 | continue |
| 340 | if row["expect"] == "HASH": |
| 341 | ok = bool(hash_gate(repo, root)) |
| 342 | code, err = (1 if ok else 0), "" |
| 343 | elif row["mode"] == "dist": |
| 344 | code, err = run([bin_, root, files["$QUOTES"], files["$ENGINEER"]]) |
| 345 | ok = verdict(row, code, err) |
| 346 | elif row["mode"] == "data": |
| 347 | code, err = run([bin_, "--data", row["kind"], files["$F"]]) |
| 348 | ok = verdict(row, code, err) |
| 349 | else: |
| 350 | code, err = run([bin_, "--sources"], cwd=root) |
| 351 | ok = verdict(row, code, err) |
| 352 | oracle = "n/a" |
| 353 | if a.oracle and row["mode"] == "dist" and row.get("oracle") == "yes": |
| 354 | ocode, _ = run([os.path.abspath(a.oracle), "verify", root], cwd=repo) |
| 355 | oracle = "agrees" if (ocode == 0) == (row["expect"] == "PASS") else "DISAGREES" |
| 356 | ok = ok and oracle == "agrees" |
| 357 | counts["PASS" if ok else "FAIL"] += 1 |
| 358 | first = next((l for l in err.splitlines() if l.startswith("verify: FAIL")), "") |
| 359 | print(f"{'PASS' if ok else 'FAIL'}\t{row['id']}\t{row['rule']}\texit={code}\toracle={oracle}\t{first[:200]}") |
| 360 | finally: |
| 361 | if not a.keep: |
| 362 | shutil.rmtree(tmp, ignore_errors=True) |
| 363 | print(f"MUTATIONS pass={counts['PASS']} fail={counts['FAIL']} invalid={counts['INVALID']} total={len(rows)}") |
| 364 | return 0 if counts["FAIL"] == 0 and counts["INVALID"] == 0 else 1 |
| 365 | |
| 366 | |
| 367 | if __name__ == "__main__": |
| 368 | sys.exit(main()) |