interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / allen / e2e_calculator.py

148 lines · 6297 bytes Raw Blame History
1#!/usr/bin/env python3
2"""End-to-end build loop against the real aien-dev/omega-projects (test-labelled).
3
4A throwaway loopback gateway (this directory's code, a test visitor secret, no model calls)
5compiles calc.om to WebAssembly through /allen/api/omega, gives the test visitor a home,
6takes two saves and one publish; the real pusher program files each one with the
7fine-grained OMEGA_PROJECTS_TOKEN from the atlas vault (never printed). Expected: two
8commits on u/<handle>, one pull request to main left open for Drake, main untouched.
9
10Usage: e2e_calculator.py --omc PATH --irwasm PATH --system-prompt PATH --calc FILE --out DIR
11"""
12
13import argparse
14import base64
15import json
16import os
17import subprocess
18import sys
19
20HERE = os.path.dirname(os.path.abspath(__file__))
21sys.path.insert(0, HERE)
22from test_gateway import Gateway # noqa: E402
23
24KEY = "e2" * 16 # the test visitor's Aien key (X-Allen-Key header)
25
26
27def page(wasm_b64):
28 return """<!doctype html>
29<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
30<title>Calculator</title>
31<style>body{font:18px/1.5 system-ui,sans-serif;max-width:28rem;margin:2rem auto;padding:0 1rem}
32input,select,button{font:inherit;padding:.3rem}</style>
33<h1>Calculator</h1>
34<p>Whole numbers, computed by Omega compiled to WebAssembly.</p>
35<p><input id=a type=number value=12> <select id=op><option value=plus>+</option><option value=minus>-</option>
36<option value=times>&times;</option><option value=quot>&divide;</option></select> <input id=b type=number value=3>
37<button id=go>=</button> <output id=out></output></p>
38<script>
39const bytes = Uint8Array.from(atob("%s"), c => c.charCodeAt(0));
40WebAssembly.instantiate(bytes, {}).then(({ instance }) => {
41 const run = () => {
42 const f = instance.exports[document.getElementById('op').value];
43 const a = BigInt(document.getElementById('a').value || 0), b = BigInt(document.getElementById('b').value || 0);
44 document.getElementById('out').textContent = String(f(a, b));
45 };
46 document.getElementById('go').addEventListener('click', run);
47 run();
48});
49</script>
50</html>
51""" % wasm_b64
52
53
54README = """# Calculator
55
56A four-function calculator for whole numbers. The arithmetic is written in Omega (`calc.om`),
57compiled to WebAssembly by Aien's Omega compiler, and run by `index.html` in the browser with
58nothing loaded from elsewhere.
59
60Who it helps: anyone who wants a tiny, readable example of an Omega program running on a web
61page, and students checking quick sums. Division by zero returns 0.
62
63Built with Aien at https://www.aienos.com/aien/ (end-to-end test of the build loop).
64"""
65
66
67def main():
68 ap = argparse.ArgumentParser()
69 ap.add_argument("--omc", required=True)
70 ap.add_argument("--irwasm", required=True)
71 ap.add_argument("--system-prompt", required=True)
72 ap.add_argument("--calc", required=True)
73 ap.add_argument("--out", required=True)
74 ap.add_argument("--pusher-dir", default="/tmp/allenchat/pusher")
75 a = ap.parse_args()
76 os.makedirs(a.out, exist_ok=True)
77 log = open(os.path.join(a.out, "e2e-calculator.log"), "a")
78
79 def say(*parts):
80 line = " ".join(str(p) for p in parts)
81 print(line, flush=True)
82 log.write(line + "\n")
83 log.flush()
84
85 g = Gateway(a, env={"ALLEN_VISITOR_SECRET": "e2e-test-visitor-secret-" + "0" * 20})
86 state = os.path.join(a.out, "pusher-state")
87 os.makedirs(state, mode=0o700, exist_ok=True)
88 H = {"X-Allen-Key": KEY}
89
90 def post(path, body, ip):
91 c, r = g.post(path, body, headers=H, ip=ip)
92 return r.status, json.loads(r.read())
93
94 def pusher():
95 cmd = ("exec python3 %s --spool-in %s --spool-status %s --state-dir %s --areas /nonexistent "
96 "--spool-module-dir %s --token-file <(printf %%s \"$OMEGA_PROJECTS_TOKEN\") --test-label "
97 "--idle-delay 0" % (os.path.join(a.pusher_dir, "omega_projects_pusher.py"), g.dirs["in"],
98 g.dirs["status"], state, HERE))
99 r = subprocess.run(["atlas-vault", "run", "OMEGA_PROJECTS_TOKEN", "--", "bash", "-c", cmd],
100 capture_output=True, text=True, timeout=180)
101 say("pusher rc=%d" % r.returncode, r.stderr.strip().replace("\n", " | ")[-800:])
102
103 def status(iid):
104 c, r = g.get("/allen/api/status/" + iid)
105 return json.loads(r.read())
106
107 try:
108 src = open(a.calc).read()
109 st, j = post("/allen/api/omega", {"source": src}, "198.51.100.60")
110 wasm = j.get("wasm") or j.get("wasm_b64") or ""
111 say("compile calc.om:", st, "wasm bytes:", len(base64.b64decode(wasm)) if wasm else 0,
112 "keys:", sorted(j))
113 if st != 200 or not wasm:
114 return 1
115 st, h = post("/allen/api/projects/handle", {"name": "calc-tester"}, "198.51.100.61")
116 handle = h["handle"]
117 say("handle:", st, handle)
118 base = {"handle": handle, "project": "calculator", "title": "Calculator",
119 "description": "A four-function calculator: Omega arithmetic compiled to WebAssembly."}
120 v1 = dict(base, files=[{"name": "calc.om", "content": src}, {"name": "README.md", "content": README}])
121 st, s1 = post("/allen/api/projects/save", v1, "198.51.100.62")
122 say("save 1:", st, s1)
123 pusher()
124 r1 = status(s1["id"])
125 say("save 1 status:", r1)
126 v2 = dict(base, files=v1["files"] + [{"name": "index.html", "content": page(wasm)}])
127 st, s2 = post("/allen/api/projects/save", v2, "198.51.100.63")
128 say("save 2:", st, s2)
129 pusher()
130 r2 = status(s2["id"])
131 say("save 2 status:", r2)
132 st, p = post("/allen/api/projects/publish", v2, "198.51.100.64")
133 say("publish:", st, p)
134 pusher()
135 rp = status(p["id"])
136 say("publish status:", rp)
137 with open(os.path.join(a.out, "e2e-calculator.json"), "w") as f:
138 json.dump({"handle": handle, "branch": "u/" + handle, "save1": r1, "save2": r2, "publish": rp,
139 "view": s2.get("view")}, f, indent=2)
140 ok = r1["state"] == r2["state"] == rp["state"] == "filed"
141 say("RESULT", "PASS" if ok else "FAIL")
142 return 0 if ok else 1
143 finally:
144 g.close()
145
146
147if __name__ == "__main__":
148 sys.exit(main())