interplane.Get Omega
Read in your language

omega-mcp

aien-dev/omega-mcp

Brought by drakestapleton

branch main Branches Tags History

omega-mcp / gates / qa.py

269 lines · 11771 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Independent stdio/file-state oracle for build/agent-qa-mcp. No builds or source reads.
3
4Run: python3 gates/qa.py --binary /absolute/agent-qa-mcp
5Every scenario uses a fresh TemporaryDirectory store and consent file. Prints one JSON line per
6check and exits nonzero on the first failure.
7"""
8import argparse
9import hashlib
10import json
11import os
12from pathlib import Path
13import subprocess
14import tempfile
15
16HEX = set('0123456789abcdef')
17
18
19class Server:
20 def __init__(self, binary, store, agent='tester', consent=None):
21 args = [str(binary), '--store', str(store), '--agent', agent]
22 if consent is not None:
23 args += ['--consent', str(consent)]
24 self.args = args
25 self.lines = []
26
27 def run(self, calls):
28 """Sends initialize then each (name, arguments) call; returns the replies after initialize."""
29 msgs = [{'jsonrpc': '2.0', 'id': 0, 'method': 'initialize',
30 'params': {'protocolVersion': '2025-06-18'}}]
31 for i, c in enumerate(calls, 1):
32 if isinstance(c, dict):
33 msgs.append(dict(c, id=i, jsonrpc='2.0'))
34 else:
35 name, arguments = c
36 params = {'name': name}
37 if arguments is not None:
38 params['arguments'] = arguments
39 msgs.append({'jsonrpc': '2.0', 'id': i, 'method': 'tools/call', 'params': params})
40 data = ''.join(json.dumps(m) + '\n' for m in msgs).encode()
41 p = subprocess.run(self.args, input=data, capture_output=True, timeout=60)
42 assert p.returncode == 0, (p.returncode, p.stderr[:300])
43 out = [json.loads(l) for l in p.stdout.decode().splitlines()]
44 assert len(out) == len(msgs), (len(out), len(msgs), p.stdout[-300:])
45 return out[1:]
46
47
48def ok(reply):
49 r = reply['result']
50 assert r['isError'] is False, r
51 assert r['structuredContent']['ok'] is True, r
52 return r['structuredContent']
53
54
55def refused(reply, words=None):
56 r = reply['result']
57 assert r['isError'] is True, r
58 sc = r['structuredContent']
59 assert sc['ok'] is False, r
60 if words:
61 assert words in sc['error'], (words, sc['error'])
62 return sc
63
64
65def bad_params(reply):
66 assert 'error' in reply and reply['error']['code'] == -32602, reply
67
68
69def entries(store):
70 return sorted(p.name for p in Path(store).iterdir() if not p.name.startswith('.'))
71
72
73def snapshot(store):
74 return {p.name: p.read_bytes() for p in Path(store).iterdir()}
75
76
77Q = {'title': 'omc error 12 on a long if', 'versions': 'omc (this pin), Linux arm64',
78 'body': 'An if with five ors fails with error 12.\n\tSmallest repro below.'}
79
80
81def env(tmp, lines=('allow tester',)):
82 store = Path(tmp) / 'store'
83 store.mkdir()
84 consent = Path(tmp) / 'consent'
85 consent.write_text(''.join(l + '\n' for l in lines))
86 return store, consent
87
88
89def check_protocol(binary):
90 with tempfile.TemporaryDirectory() as tmp:
91 store, consent = env(tmp)
92 s = Server(binary, store, consent=consent)
93 r = s.run([{'method': 'tools/list'}, ('nosuch', {}), ('search', {'words': 'x', 'extra': 'y'}),
94 ('search', {}), ('read', {'id': 7}), ('ask', {'title': 'a', 'versions': 'b'}),
95 ('search', {'words': 'x' * 257}), ('consent_status', None)])
96 tools = r[0]['result']['tools']
97 names = [t['name'] for t in tools]
98 assert names == ['search', 'read', 'consent_status', 'ask', 'answer', 'check'], names
99 for t in tools:
100 sch = t['inputSchema']
101 assert sch['additionalProperties'] is False
102 assert sorted(sch['required']) == sorted(sch['properties']), t
103 assert not [n for n in names if 'allow' in n or ('consent' in n and n != 'consent_status')]
104 for x in r[1:7]:
105 bad_params(x)
106 ok(r[7])
107
108
109def check_consent(binary):
110 with tempfile.TemporaryDirectory() as tmp:
111 store, consent = env(tmp, ['# allow tester', 'allow tester2', 'allow tester ', 'allowtester'])
112 before = consent.read_bytes()
113 s = Server(binary, store, consent=consent)
114 r = s.run([('consent_status', {}), ('ask', Q)])
115 st = ok(r[0])
116 assert st['may_contribute'] is False and st['agent'] == 'tester', st
117 assert 'allow tester' in st['how_to_enable'] and st['consent_file'] == str(consent), st
118 refused(r[1], 'Sharing is off')
119 assert entries(store) == []
120 # The first 65536 bytes end in `allow tester` and the line goes on `2\n`. That cut tail is not a line.
121 cut = b'allow tester'
122 consent.write_bytes(b'\n' * (65536 - len(cut)) + cut + b'2\n')
123 r = s.run([('consent_status', {}), ('ask', Q)])
124 assert ok(r[0])['may_contribute'] is False, ok(r[0])
125 refused(r[1], 'Sharing is off')
126 assert entries(store) == []
127 consent.write_text('allow other\nallow tester\n')
128 r = s.run([('consent_status', {}), ('ask', Q)])
129 assert ok(r[0])['may_contribute'] is True
130 qid = ok(r[1])['id']
131 assert entries(store) == [qid]
132 # A finished `allow tester` line inside the first 65536 bytes still counts when the file continues.
133 head = b'allow tester\n'
134 consent.write_bytes(head + b'z' * (65536 - len(head)) + b'continued\n')
135 r = s.run([('consent_status', {})])
136 assert ok(r[0])['may_contribute'] is True, ok(r[0])
137 consent.write_text('allow other\n')
138 r = s.run([('ask', dict(Q, title='second question'))])
139 refused(r[0], 'Sharing is off')
140 assert entries(store) == [qid]
141 # Without --consent: reading works, contributing is refused, the answer names --consent.
142 s2 = Server(binary, store)
143 r = s2.run([('consent_status', {}), ('ask', dict(Q, title='third')), ('read', {'id': qid}),
144 ('search', {'words': ''})])
145 st = ok(r[0])
146 assert st['may_contribute'] is False and st['consent_file'] is None and '--consent' in st['how_to_enable']
147 refused(r[1], 'Sharing is off')
148 ok(r[2])
149 assert ok(r[3])['matches'] == 1
150 assert consent.read_bytes() == b'allow other\n'
151 assert before != consent.read_bytes() # only this oracle wrote it
152
153
154def check_privacy(binary):
155 cases = [
156 ('body', 'key:\n-----BEGIN OPENSSH PRIVATE KEY-----\nabc', 'private key'),
157 ('body', 'it lives in /home/someone/project', 'home directory'),
158 ('versions', 'macOS, /Users/someone/x', 'home directory'),
159 ('title', 'root at /root/.config', 'home directory'),
160 ('body', 'use sk-ant-api03-AbCdEfGh1234567890abcdEFGH please', 'key or token'),
161 ('body', 'token ghp_A1b2C3d4E5f6G7h8I9j0K1l2M3n4', 'key or token'),
162 ('title', 'two\nlines', 'one-line field'),
163 ('body', 'bell \x07 here', 'control character'),
164 ]
165 with tempfile.TemporaryDirectory() as tmp:
166 store, consent = env(tmp)
167 s = Server(binary, store, consent=consent)
168 r = s.run([('ask', dict(Q, **{f: v})) for f, v, _ in cases])
169 for (f, v, why), x in zip(cases, r):
170 refused(x, why)
171 assert entries(store) == [], entries(store)
172 fine = dict(Q, body='sha256 ' + 'a' * 64 + ' in ~/project; OmegaCompilerBuild2 works')
173 r = s.run([('ask', fine)])
174 ok(r[0])
175
176
177def check_entries(binary):
178 with tempfile.TemporaryDirectory() as tmp:
179 store, consent = env(tmp)
180 s = Server(binary, store, consent=consent)
181 r = s.run([('ask', Q), ('ask', Q)])
182 a, b = ok(r[0]), ok(r[1])
183 assert a['id'] == b['id'] and a['created'] is True and b['created'] is False
184 qid = a['id']
185 assert entries(store) == [qid]
186 raw = (store / qid).read_bytes()
187 assert hashlib.sha256(raw).hexdigest() == qid
188 assert raw.startswith(b'agent-qa 1\nkind question\nagent tester\n'), raw[:60]
189 body = Q['body'].encode()
190 assert raw.endswith(b'body %d\n' % len(body) + body + b'\n'), raw[-80:]
191 ans = {'question': qid, 'versions': 'omc (this pin)', 'steps': 'Split the if.\nUse a temporary.',
192 'evidence': 'omc < a.om; echo $? prints 0', 'body': 'Each if takes one comparison chain.'}
193 r = s.run([('read', {'id': qid}), ('answer', ans), ('answer', dict(ans, question='0' * 64)),
194 ('answer', dict(ans, question='Z' * 64))])
195 assert ok(r[0])['text'] == raw.decode()
196 aid = ok(r[1])['id']
197 refused(r[2], 'No entry')
198 refused(r[3], '64 lowercase')
199 chk = {'answer': aid, 'result': 'works', 'evidence': 'omc exit 0', 'body': 'Reproduced.'}
200 r = s.run([('check', chk), ('check', dict(chk, result='maybe')), ('check', dict(chk, answer=qid)),
201 ('answer', dict(ans, question=aid))])
202 cid = ok(r[0])['id']
203 refused(r[1], 'works or fails')
204 refused(r[2], 'answer must be')
205 refused(r[3], 'question must be')
206 r = s.run([('search', {'words': 'TEMPORARY split'}), ('search', {'words': 'split nowhere'}),
207 ('read', {'id': cid})])
208 res = ok(r[0])
209 assert res['matches'] == 1 and res['results'][0]['id'] == aid and res['results'][0]['ref'] == qid, res
210 assert res['results'][0]['kind'] == 'answer'
211 assert ok(r[1])['matches'] == 0
212 assert 'result works\n' in ok(r[2])['text']
213
214
215def check_damage(binary):
216 with tempfile.TemporaryDirectory() as tmp:
217 store, consent = env(tmp)
218 s = Server(binary, store, consent=consent)
219 qid = ok(s.run([('ask', Q)])[0])['id']
220 good = ok(s.run([('ask', dict(Q, title='kept'))])[0])['id']
221 p = store / qid
222 p.write_bytes(p.read_bytes().replace(b'error 12', b'error 13'))
223 bad = b'agent-qa 1\nkind question\ntitle \xff\xfe\n'
224 bid = hashlib.sha256(bad).hexdigest()
225 (store / bid).write_bytes(bad)
226 (store / 'notes.txt').write_text('not an entry')
227 r = s.run([('read', {'id': qid}), ('read', {'id': bid}), ('search', {'words': ''}), ('read', {'id': good})])
228 refused(r[0], 'does not match')
229 refused(r[1], 'does not match')
230 res = ok(r[2])
231 assert res['matches'] == 1 and res['skipped'] == 2, res
232 ok(r[3])
233 # A temporary file left by an interrupted write blocks that entry with a plain message.
234 q3 = dict(Q, title='third')
235 r = s.run([('ask', q3)])
236 tid = ok(r[0])['id']
237 (store / tid).unlink()
238 (store / ('.qa-tmp-' + tid)).write_text('partial')
239 r = s.run([('ask', q3), ('search', {'words': 'third'})])
240 refused(r[0], 'interrupted write')
241 assert ok(r[1])['matches'] == 0
242
243
244def check_paging(binary):
245 with tempfile.TemporaryDirectory() as tmp:
246 store, consent = env(tmp)
247 s = Server(binary, store, consent=consent)
248 r = s.run([('ask', dict(Q, title='paged question %d' % i)) for i in range(57)]
249 + [('search', {'words': 'PAGED'})])
250 for x in r[:-1]:
251 ok(x)
252 res = ok(r[-1])
253 assert res['matches'] == 57 and res['shown'] == 50 and len(res['results']) == 50 and res['more'] is True, \
254 {k: v for k, v in res.items() if k != 'results'}
255
256
257def main():
258 ap = argparse.ArgumentParser(description=__doc__)
259 ap.add_argument('--binary', type=Path, required=True)
260 args = ap.parse_args()
261 binary = args.binary.resolve(strict=True)
262 for name, fn in [('protocol', check_protocol), ('consent', check_consent), ('privacy', check_privacy),
263 ('entries', check_entries), ('damage', check_damage), ('paging', check_paging)]:
264 fn(binary)
265 print(json.dumps({'check': name, 'status': 'PASS'}), flush=True)
266
267
268if __name__ == '__main__':
269 main()