interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / seed / agent / tests / check.py

538 lines · 23707 bytes Raw Blame History
1#!/usr/bin/env python3
2"""seed/agent/tests/check.py -- host check of seed/agent/agent.om (omagent).
3
4TEST-ONLY. Python is only the referee: it plays a scripted OpenAI-compatible model server
5(chat completions, SSE and plain JSON) on a kernel-chosen 127.0.0.1 port, runs the compiled
6Omega binary against it, and compares exit codes, stdout, stderr, the requests the server saw,
7the session file and the workspace. Every implementation byte under test is compiled .om.
8
9Usage: nice -n 19 ionice -c3 python3 seed/agent/tests/check.py [--omc PATH] [--bin PATH] [--keep DIR]
10Stages: build, cases (one scripted conversation each), controls (a wrong expectation must
11fail; source mutants of agent.om must each be caught by the cases).
12Exit 0 = PASS, 1 = FAIL, 3 = NOT_RUN (the compiler is missing).
13Never touches port 18091; never reaches outside 127.0.0.1.
14"""
15import http.server
16import json
17import os
18import shutil
19import socketserver
20import subprocess
21import sys
22import tempfile
23import threading
24import time
25
26HERE = os.path.dirname(os.path.abspath(__file__))
27AGENT = os.path.dirname(HERE)
28ROOT = os.path.dirname(os.path.dirname(AGENT))
29SOURCES = ["seed/json/json.om", "seed/json/jsonw.om", "seed/net/http.om", "seed/net/notls.om", "seed/agent/path.om", "seed/agent/agent.om"]
30KEY = "sk-omagent-test-7f3a9c41d2e8b605"
31LOG = []
32
33
34def log(s):
35 print(s, flush=True)
36
37
38# ---------------------------------------------------------------- scripted model server
39
40class Mock:
41 """One response script per request: entries are consumed in order."""
42
43 def __init__(self):
44 self.script = []
45 self.requests = []
46 self.lock = threading.Lock()
47
48
49MOCK = Mock()
50
51
52def sse_event(obj):
53 if isinstance(obj, str):
54 return ("data: %s\n\n" % obj).encode()
55 return ("data: %s\n\n" % json.dumps(obj)).encode()
56
57
58def delta_text(t):
59 return {"choices": [{"index": 0, "delta": {"content": t}}]}
60
61
62def delta_call(i, cid, name, args):
63 fn = {}
64 if name is not None:
65 fn["name"] = name
66 if args is not None:
67 fn["arguments"] = args
68 tc = {"index": i, "function": fn}
69 if cid is not None:
70 tc["id"] = cid
71 tc["type"] = "function"
72 return {"choices": [{"index": 0, "delta": {"tool_calls": [tc]}}]}
73
74
75def finish(reason):
76 return {"choices": [{"index": 0, "delta": {}, "finish_reason": reason}]}
77
78
79def sse_text(*parts):
80 ev = [delta_text(p) for p in parts] + [finish("stop"), "[DONE]"]
81 return ("sse", ev)
82
83
84def sse_calls(calls):
85 """calls: list of (name, arguments-json-string); arguments are split in two deltas."""
86 ev = []
87 for i, (name, args) in enumerate(calls):
88 h = len(args) // 2
89 ev.append(delta_call(i, "c%d" % i, name, args[:h]))
90 ev.append(delta_call(i, None, None, args[h:]))
91 ev += [finish("tool_calls"), "[DONE]"]
92 return ("sse", ev)
93
94
95class Handler(http.server.BaseHTTPRequestHandler):
96 protocol_version = "HTTP/1.0"
97
98 def log_message(self, *a):
99 pass
100
101 def do_GET(self):
102 with MOCK.lock:
103 MOCK.requests.append({"method": "GET", "path": self.path, "headers": dict(self.headers), "body": None})
104 body = b"hello from the fetch page\n"
105 self.send_response(200)
106 self.send_header("Content-Type", "text/plain")
107 self.send_header("Content-Length", str(len(body)))
108 self.end_headers()
109 self.wfile.write(body)
110
111 def do_POST(self):
112 n = int(self.headers.get("Content-Length", "0"))
113 raw = self.rfile.read(n)
114 try:
115 body = json.loads(raw)
116 except Exception:
117 body = {"_unparsed": raw.decode("latin-1")}
118 with MOCK.lock:
119 MOCK.requests.append({"method": "POST", "path": self.path, "headers": dict(self.headers), "body": body})
120 step = MOCK.script.pop(0) if MOCK.script else ("status", 500, "script exhausted")
121 kind = step[0]
122 if kind == "sse":
123 self.send_response(200)
124 self.send_header("Content-Type", "text/event-stream")
125 self.end_headers()
126 for ev in step[1]:
127 self.wfile.write(sse_event(ev))
128 self.wfile.flush()
129 elif kind == "rawsse":
130 self.send_response(200)
131 self.send_header("Content-Type", "text/event-stream")
132 self.end_headers()
133 self.wfile.write(step[1])
134 elif kind == "json":
135 b = json.dumps(step[1]).encode()
136 self.send_response(200)
137 self.send_header("Content-Type", "application/json")
138 self.send_header("Content-Length", str(len(b)))
139 self.end_headers()
140 self.wfile.write(b)
141 elif kind == "status":
142 b = step[2].encode()
143 self.send_response(step[1])
144 self.send_header("Content-Type", "text/plain")
145 self.send_header("Content-Length", str(len(b)))
146 self.end_headers()
147 self.wfile.write(b)
148 elif kind == "stall":
149 self.send_response(200)
150 self.send_header("Content-Type", "text/event-stream")
151 self.end_headers()
152 self.wfile.write(sse_event(delta_text("partial ")))
153 self.wfile.flush()
154 time.sleep(step[1])
155
156
157class Server(socketserver.ThreadingMixIn, http.server.HTTPServer):
158 daemon_threads = True
159 allow_reuse_address = True
160
161
162# ---------------------------------------------------------------- cases
163
164def run(binp, port, work, args, stdin=None, env_key=True, timeout=30):
165 env = {"PATH": "/usr/bin:/bin"}
166 if env_key:
167 env["OMAGENT_API_KEY"] = KEY
168 argv = [binp, "--url", "http://127.0.0.1:%d/v1/chat/completions" % port, "--model", "mock-1",
169 "--workdir", work] + [os.path.join(work, x) if x == "s.jsonl" else x for x in args]
170 t0 = time.monotonic()
171 p = subprocess.run(argv, input=stdin, capture_output=True, env=env, timeout=timeout)
172 return p.returncode, p.stdout.decode("utf-8", "replace"), p.stderr.decode("utf-8", "replace"), time.monotonic() - t0
173
174
175def tool_msgs(req):
176 return [m for m in req["body"].get("messages", []) if m.get("role") == "tool"]
177
178
179def C(name, script, args, expect_rc, checks, stdin=None, prep=None, env_key=True, timeout=30):
180 return {"name": name, "script": script, "args": args, "rc": expect_rc, "checks": checks,
181 "stdin": stdin, "prep": prep, "env_key": env_key, "timeout": timeout}
182
183
184def has(s):
185 return lambda o: s in o["out"]
186
187
188def err_has(s):
189 return lambda o: s in o["err"]
190
191
192def last_tool_has(s):
193 def f(o):
194 posts = [r for r in o["reqs"] if r["method"] == "POST"]
195 t = tool_msgs(posts[-1]) if posts else []
196 return bool(t) and s in t[-1]["content"]
197 return f
198
199
200def nposts(n):
201 return lambda o: len([r for r in o["reqs"] if r["method"] == "POST"]) == n
202
203
204def file_is(rel, content):
205 def f(o):
206 p = os.path.join(o["work"], rel)
207 return os.path.isfile(p) and open(p, "rb").read() == content.encode()
208 return f
209
210
211def no_file(rel):
212 return lambda o: not os.path.exists(os.path.join(o["work"], rel))
213
214
215def no_survivor(marker):
216 """No process whose argv contains marker is alive (zombies have an empty cmdline). Polls up to
217 1 s for SIGKILL delivery; any survivor found is killed so it cannot leak into later cases."""
218 def f(o):
219 found = []
220 for _ in range(20):
221 found = []
222 for d in os.listdir("/proc"):
223 if not d.isdigit():
224 continue
225 try:
226 with open("/proc/%s/cmdline" % d, "rb") as fh:
227 if marker.encode() in fh.read().split(b"\0"):
228 found.append(int(d))
229 except OSError:
230 pass
231 if not found:
232 return True
233 time.sleep(0.05)
234 for p in found:
235 try:
236 os.kill(p, 9)
237 except OSError:
238 pass
239 return False
240 return f
241
242
243def no_key_leak(o):
244 blob = o["out"] + o["err"]
245 sess = os.path.join(o["work"], "s.jsonl")
246 if os.path.exists(sess):
247 blob += open(sess, encoding="utf-8", errors="replace").read()
248 return KEY not in blob
249
250
251def bearer_sent(o):
252 posts = [r for r in o["reqs"] if r["method"] == "POST"]
253 return bool(posts) and all(r["headers"].get("Authorization") == "Bearer " + KEY for r in posts)
254
255
256def request_shape(o):
257 r = [r for r in o["reqs"] if r["method"] == "POST"][0]
258 b = r["body"]
259 names = [t["function"]["name"] for t in b.get("tools", [])]
260 return (r["path"] == "/v1/chat/completions" and b.get("model") == "mock-1" and b.get("stream") is True
261 and names == ["read_file", "write_file", "run_command", "http_fetch"]
262 and b["messages"][0]["role"] == "system" and b["messages"][-1] == {"role": "user", "content": "hi"})
263
264
265def session_lines(n):
266 def f(o):
267 p = os.path.join(o["work"], "s.jsonl")
268 if not os.path.exists(p):
269 return False
270 ls = open(p, encoding="utf-8").read().splitlines()
271 return len(ls) == n and all(isinstance(json.loads(x), dict) for x in ls)
272 return f
273
274
275def prep_file(rel, content):
276 def f(work):
277 with open(os.path.join(work, rel), "w") as fh:
278 fh.write(content)
279 return f
280
281
282def prep_symlink(work):
283 os.symlink("/etc", os.path.join(work, "lnk"))
284
285
286def prep_bad_session(work):
287 with open(os.path.join(work, "s.jsonl"), "w") as fh:
288 fh.write('{"role":"user","content":"a"}\nnot json\n')
289
290
291def prep_good_session(work):
292 with open(os.path.join(work, "s.jsonl"), "w") as fh:
293 fh.write('{"role":"user","content":"earlier question"}\n{"role":"assistant","content":"earlier answer"}\n')
294
295
296def resent_history(o):
297 b = [r for r in o["reqs"] if r["method"] == "POST"][0]["body"]
298 ms = b["messages"]
299 return (ms[1] == {"role": "user", "content": "earlier question"}
300 and ms[2] == {"role": "assistant", "content": "earlier answer"}
301 and ms[3] == {"role": "user", "content": "hi"})
302
303
304def cases(port):
305 fetch = "127.0.0.1:%d" % port
306 S = ["-p", "hi", "--session", "s.jsonl"]
307 return [
308 C("plain-sse", [sse_text("Hello", ", world")], S, 0,
309 [has("Hello, world"), nposts(1), request_shape, bearer_sent, no_key_leak, session_lines(2)]),
310 C("plain-json", [("json", {"choices": [{"index": 0, "message": {"role": "assistant", "content": "json reply"},
311 "finish_reason": "stop"}]})], S, 0, [has("json reply"), nposts(1)]),
312 C("read-file", [sse_calls([("read_file", '{"path":"notes.txt"}')]), sse_text("done")], S, 0,
313 [has("done"), nposts(2), last_tool_has("secret plan 42"), err_has("tool read_file: ok"), session_lines(4)],
314 prep=prep_file("notes.txt", "secret plan 42\n")),
315 C("write-file", [sse_calls([("write_file", '{"path":"out/x.txt","content":"written by agent"}')]), sse_text("ok")],
316 S + ["--allow-write"], 0, [file_is("out/x.txt", "written by agent"), last_tool_has("ok: wrote 16 bytes")],
317 prep=lambda w: os.mkdir(os.path.join(w, "out"))),
318 C("run-echo", [sse_calls([("run_command", '{"argv":["/bin/echo","hi","there"]}')]), sse_text("ran")],
319 S + ["--allow-cmd", "/bin/echo"], 0, [last_tool_has("hi there\n"), last_tool_has("[exit status 0]")]),
320 # end of file is not exit: a child that closes its output and exits later (as /bin/echo
321 # does, closing stdout before it exits) must be reaped, not killed with its group
322 C("cmd-closes-output-early", [sse_calls([("run_command", '{"argv":["/bin/sh","-c","echo hi; exec >&- 2>&-; sleep 0.3; exit 3"]}')]), sse_text("ok")],
323 S + ["--allow-cmd", "/bin/sh", "--cmd-timeout", "10"], 0,
324 [last_tool_has("hi\n"), last_tool_has("[exit status 3]")]),
325 C("run-exit-code", [sse_calls([("run_command", '{"argv":["/bin/false"]}')]), sse_text("ran")],
326 S + ["--allow-cmd", "/bin/false"], 0, [last_tool_has("[exit status 1]")]),
327 C("fetch", [sse_calls([("http_fetch", '{"url":"http://%s/page"}' % fetch)]), sse_text("fetched")],
328 S + ["--allow-fetch", fetch], 0, [last_tool_has("status=200\nhello from the fetch page")]),
329 C("two-calls-one-turn", [sse_calls([("read_file", '{"path":"a"}'), ("read_file", '{"path":"b"}')]), sse_text("both")],
330 S, 0, [lambda o: [m["content"] for m in tool_msgs([r for r in o["reqs"] if r["method"] == "POST"][-1])] == ["A", "B"],
331 lambda o: [m["tool_call_id"] for m in tool_msgs([r for r in o["reqs"] if r["method"] == "POST"][-1])] == ["c0", "c1"]],
332 prep=lambda w: (prep_file("a", "A")(w), prep_file("b", "B")(w))),
333 # refusals: the tool result says refused, the agent continues, nothing is executed
334 C("refuse-cmd-not-allowed", [sse_calls([("run_command", '{"argv":["/bin/rm","-rf","x"]}')]), sse_text("ok")],
335 S + ["--allow-cmd", "/bin/echo"], 0, [last_tool_has("refused: the program is not on the --allow-cmd list: /bin/rm"),
336 err_has("tool run_command: refused")]),
337 C("refuse-cmd-disabled", [sse_calls([("run_command", '{"argv":["/bin/echo","x"]}')]), sse_text("ok")],
338 S, 0, [last_tool_has("refused: run_command is disabled")]),
339 C("refuse-dotdot", [sse_calls([("read_file", '{"path":"../etc/passwd"}')]), sse_text("ok")],
340 S, 0, [last_tool_has("refused: the path must be relative")]),
341 C("refuse-absolute", [sse_calls([("read_file", '{"path":"/etc/passwd"}')]), sse_text("ok")],
342 S, 0, [last_tool_has("refused: the path must be relative")]),
343 C("refuse-symlink", [sse_calls([("read_file", '{"path":"lnk/passwd"}')]), sse_text("ok")],
344 S, 0, [last_tool_has("refused: the path must be relative")], prep=prep_symlink),
345 C("refuse-write-disabled", [sse_calls([("write_file", '{"path":"y.txt","content":"x"}')]), sse_text("ok")],
346 S, 0, [last_tool_has("refused: write_file is disabled"), no_file("y.txt")]),
347 C("refuse-unknown-tool", [sse_calls([("format_disk", '{}')]), sse_text("ok")],
348 S, 0, [last_tool_has("refused: unknown tool format_disk")]),
349 C("refuse-fetch-host", [sse_calls([("http_fetch", '{"url":"http://10.1.2.3:80/"}')]), sse_text("ok")],
350 S + ["--allow-fetch", fetch], 0, [last_tool_has("refused: the host:port is not on the --allow-fetch list: 10.1.2.3:80")]),
351 C("refuse-https-fetch", [sse_calls([("http_fetch", '{"url":"https://%s/page"}' % fetch)]), sse_text("ok")],
352 S + ["--allow-fetch", fetch], 0, [last_tool_has("refused: only http:// URLs")]),
353 C("bad-tool-args", [sse_calls([("read_file", '[1,2]')]), sse_text("ok")],
354 S, 0, [last_tool_has("error: tool arguments are not a JSON object")]),
355 # malformed model output
356 C("malformed-event", [("rawsse", b"data: {not json\n\n")], S, 6, [err_has("malformed model output")]),
357 C("truncated-stream", [("rawsse", b'data: {"choices":[{"index":0,"delta":{"content":"cut"}}]}\n\n')], S, 6,
358 [err_has("the stream ended before [DONE]")]),
359 C("server-error-object", [("sse", [{"error": {"message": "boom"}}])], S, 6, [err_has("error object")]),
360 C("too-many-calls", [("sse", [delta_call(9, "c9", "read_file", "{}"), finish("tool_calls"), "[DONE]"])], S, 6,
361 [err_has("more than 8 tool calls")]),
362 C("http-500", [("status", 500, "internal oops")], S, 4, [err_has("status"), err_has("internal oops")]),
363 # timeouts
364 C("model-timeout", [("stall", 6)], S + ["--timeout", "2"], 5, [err_has("timed out"), lambda o: o["dt"] < 5.5]),
365 C("cmd-timeout", [sse_calls([("run_command", '{"argv":["/bin/sleep","30"]}')]), sse_text("ok")],
366 S + ["--allow-cmd", "/bin/sleep", "--cmd-timeout", "1"], 0,
367 [last_tool_has("[killed: timeout after 1 s]"), lambda o: o["dt"] < 10]),
368 # a tool's grandchild: the call returns when the direct child exits, and the group is killed
369 C("cmd-grandchild", [sse_calls([("run_command", '{"argv":["/bin/sh","-c","sleep 31.7 & echo hi"]}')]), sse_text("ok")],
370 S + ["--allow-cmd", "/bin/sh", "--cmd-timeout", "10"], 0,
371 [last_tool_has("hi"), last_tool_has("[exit status 0]"), lambda o: o["dt"] < 5, no_survivor("31.7")]),
372 C("cmd-timeout-group", [sse_calls([("run_command", '{"argv":["/bin/sh","-c","sleep 32.3 & sleep 32.4"]}')]), sse_text("ok")],
373 S + ["--allow-cmd", "/bin/sh", "--cmd-timeout", "1"], 0,
374 [last_tool_has("[killed: timeout after 1 s]"), lambda o: o["dt"] < 10,
375 no_survivor("32.3"), no_survivor("32.4")]),
376 C("round-limit", [sse_calls([("read_file", '{"path":"a"}')])] * 3, S + ["--max-rounds", "2"], 7,
377 [err_has("round limit"), nposts(2)], prep=prep_file("a", "A")),
378 # sessions and configuration
379 C("session-reload", [sse_text("again")], S, 0, [resent_history, session_lines(4)], prep=prep_good_session),
380 C("session-bad-line", [sse_text("never")], S, 8, [nposts(0), err_has("session file line")], prep=prep_bad_session),
381 C("https-model-refused", [], ["-p", "hi", "--url", "https://127.0.0.1:1/x"], 2, [nposts(0)]),
382 C("no-key-no-header", [sse_text("anon")], S, 0,
383 [lambda o: "Authorization" not in [r for r in o["reqs"] if r["method"] == "POST"][0]["headers"]], env_key=False),
384 C("repl-two-lines", [sse_text("one"), sse_text("two")], ["--session", "s.jsonl"], 0,
385 [has("one"), has("two"), nposts(2), session_lines(4)], stdin=b"first\nsecond\n"),
386 C("connect-refused", [], ["-p", "hi", "--url", "http://127.0.0.1:1/v1"], 3, [err_has("cannot connect")]),
387 ]
388
389
390def run_case(binp, port, base, c):
391 work = tempfile.mkdtemp(prefix=c["name"] + "-", dir=base)
392 if c["prep"]:
393 c["prep"](work)
394 with MOCK.lock:
395 MOCK.script = list(c["script"])
396 MOCK.requests = []
397 rc, out, err, dt = run(binp, port, work, c["args"], c["stdin"], c["env_key"], c["timeout"])
398 o = {"out": out, "err": err, "work": work, "reqs": list(MOCK.requests), "dt": dt}
399 fails = []
400 if rc != c["rc"]:
401 fails.append("rc=%d want %d" % (rc, c["rc"]))
402 for i, chk in enumerate(c["checks"]):
403 try:
404 ok = chk(o)
405 except Exception as e:
406 ok = False
407 if not ok:
408 fails.append("check %d" % i)
409 if c["name"] != "no-key-no-header" and not no_key_leak(o):
410 fails.append("key leaked")
411 return fails, o, rc, dt
412
413
414def build(omc, out):
415 src = b"om2\n" + b"".join(open(os.path.join(ROOT, s), "rb").read() for s in SOURCES)
416 p = subprocess.run([omc], input=src, capture_output=True)
417 if p.returncode != 0:
418 raise RuntimeError("build failed: " + p.stderr.decode()[:400])
419 with open(out, "wb") as fh:
420 fh.write(p.stdout)
421 os.chmod(out, 0o700)
422
423
424# source mutants: each weakens one safety or protocol rule; the cases must catch every one
425MUTANTS = [
426 ("allowlist-bypass", "if eq k 0\nif or eq m 0 not agallowed ICMD get gnum QNCMD view part e1 0 m", "if eq k 1\nif or eq m 0 not agallowed ICMD get gnum QNCMD view part e1 0 m"),
427 ("dotdot-allowed", "if eq cl 2\nif eq get p add s 1 46\nret false", "if eq cl 2\nif eq get p add s 1 47\nret false"),
428 ("symlink-followed", "ret ne and md 61440 40960", "ret true"),
429 ("fetch-allowlist-bypass", "if not agallowed IFET nf view part cn 0 cl", "if eq nf 999"),
430 ("write-flag-ignored", "if eq get gnum QWRITE 0", "if eq get gnum QWRITE 7"),
431 ("no-done-accepted", "if eq get gst SFIN 0\nagerr enodone\nret 6", "if eq get gst SFIN 7\nagerr enodone\nret 6"),
432 ("exit-kills-child-only", "r = killpid neg pid 9", "r = killpid pid 9"),
433 ("timeout-kills-child-only", "r = killpid neg int pid 9\nif eq get gnum 23 0", "r = killpid int pid 9\nif eq get gnum 23 0"),
434 ("eof-taken-as-exit", "if eq n 0\nret agwaitc dl\nend", "if eq n 0\nret false\nend"),
435]
436
437
438def run_mutants(omc, port, base):
439 texts = [open(os.path.join(ROOT, s)).read() for s in SOURCES]
440 own = [i for i, s in enumerate(SOURCES) if s.startswith("seed/agent/")]
441 killed = 0
442 for name, a, b in MUTANTS:
443 n = sum(texts[i].count(a) for i in own)
444 if n != 1:
445 raise RuntimeError("mutant %s: anchor found %d times" % (name, n))
446 mt = [t.replace(a, b) if i in own else t for i, t in enumerate(texts)]
447 src = ("om2\n" + "".join(mt)).encode()
448 p = subprocess.run([omc], input=src, capture_output=True)
449 if p.returncode != 0:
450 raise RuntimeError("mutant %s does not compile" % name)
451 mb = os.path.join(base, "mut-" + name)
452 with open(mb, "wb") as fh:
453 fh.write(p.stdout)
454 os.chmod(mb, 0o700)
455 caught = []
456 for c in cases(port):
457 f, _, _, _ = run_case(mb, port, base, c)
458 if f:
459 caught.append(c["name"])
460 if caught:
461 killed += 1
462 log("AGENT-MUTANT %s KILLED by %s" % (name, ",".join(caught[:3])))
463 else:
464 log("AGENT-MUTANT %s SURVIVED" % name)
465 return killed
466
467
468def main():
469 a = sys.argv[1:]
470 omc = os.path.join(ROOT, "seed/out/omc")
471 binp = None
472 keep = None
473 while a:
474 k = a.pop(0)
475 if k == "--omc":
476 omc = a.pop(0)
477 elif k == "--bin":
478 binp = a.pop(0)
479 elif k == "--keep":
480 keep = a.pop(0)
481 if not os.access(omc, os.X_OK):
482 log("AGENT-CHECK NOT_RUN no compiler at %s" % omc)
483 return 3
484 base = keep or tempfile.mkdtemp(prefix="omagent-check-")
485 os.makedirs(base, exist_ok=True)
486 srv = Server(("127.0.0.1", 0), Handler)
487 port = srv.server_address[1]
488 assert port != 18091
489 threading.Thread(target=srv.serve_forever, daemon=True).start()
490 try:
491 if binp is None:
492 binp = os.path.join(base, "omagent")
493 build(omc, binp)
494 log("AGENT-BUILD PASS bytes=%d" % os.path.getsize(binp))
495 bad = 0
496 cs = cases(port)
497 for c in cs:
498 f, o, rc, dt = run_case(binp, port, base, c)
499 if f:
500 bad += 1
501 log("AGENT-CASE %s FAIL %s rc=%d dt=%.2f\n stdout=%r\n stderr=%r" % (c["name"], "; ".join(f), rc, dt, o["out"][:300], o["err"][:300]))
502 else:
503 log("AGENT-CASE %s PASS rc=%d dt=%.2f" % (c["name"], rc, dt))
504 if bad:
505 log("AGENT-CHECK FAIL failed=%d/%d" % (bad, len(cs)))
506 return 1
507 # negative control: a deliberately wrong expectation must fail
508 wrong = dict(cs[0])
509 wrong["rc"] = 6
510 f, _, _, _ = run_case(binp, port, base, wrong)
511 if not f:
512 log("AGENT-CONTROL FAIL a wrong expectation passed")
513 return 1
514 wrong = dict(cs[0])
515 wrong["checks"] = [has("text the model never sent")]
516 f, _, _, _ = run_case(binp, port, base, wrong)
517 if not f:
518 log("AGENT-CONTROL FAIL a wrong output expectation passed")
519 return 1
520 log("AGENT-CONTROL PASS wrong expectations fail")
521 k = run_mutants(omc, port, base)
522 if k != len(MUTANTS):
523 log("AGENT-MUTANTS FAIL killed=%d/%d" % (k, len(MUTANTS)))
524 return 1
525 log("AGENT-MUTANTS PASS killed=%d/%d" % (k, len(MUTANTS)))
526 log("AGENT-CHECK PASS cases=%d mutants=%d" % (len(cs), len(MUTANTS)))
527 return 0
528 except Exception as e:
529 log("AGENT-CHECK FAIL %s" % e)
530 return 1
531 finally:
532 srv.shutdown()
533 if keep is None:
534 shutil.rmtree(base, ignore_errors=True)
535
536
537if __name__ == "__main__":
538 sys.exit(main())