Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mcp/blob/main/gates/maintenance.py # omega-mcp aien-dev/omega-mcp Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mcp / gates / maintenance.py` 444 lines ยท 23539 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Independent stdio/file-state oracle. No builds, source inspection or live writes. 3 4 Run: python3 gates/maintenance.py --binary /absolute/maintenance 5 Optional --real-root performs inventory/read only (never --allow-write). 6 Optional --negative-control-binary supplies a parent-built guard-removal mutant: 7 the same default-readonly check must fail because the mutant actually writes. 8 All mutation clients use isolated TemporaryDirectory fixtures. 9 """ 10 import argparse 11 import hashlib 12 import json 13 import os 14 from pathlib import Path 15 import select 16 import subprocess 17 import tempfile 18 import time 19 20 21 def digest(value): 22 return hashlib.sha256(value if isinstance(value, bytes) else value.encode()).hexdigest() 23 24 25 class Client: 26 def __init__(self, binary, root, writable=False): 27 self.proc = subprocess.Popen( 28 [str(binary), '--root', str(root)] + (['--allow-write'] if writable else []), 29 stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 30 self.seq = 0 31 self.pending = b'' 32 33 def __enter__(self): 34 return self 35 36 def __exit__(self, *args): 37 self.proc.stdin.close() 38 try: 39 self.proc.wait(timeout=5) 40 except subprocess.TimeoutExpired: 41 self.proc.kill() 42 self.proc.wait() 43 self.proc.stdout.close() 44 self.proc.stderr.close() 45 46 def send(self, value): 47 self.raw(json.dumps(value, ensure_ascii=False, separators=(',', ':')).encode() + b'\n') 48 49 def raw(self, data): 50 self.proc.stdin.write(data) 51 self.proc.stdin.flush() 52 53 def receive(self): 54 deadline = time.monotonic() + 10 55 while b'\n' not in self.pending: 56 remaining = deadline - time.monotonic() 57 assert remaining > 0, 'server reply timeout' 58 ready, _, _ = select.select([self.proc.stdout], [], [], remaining) 59 assert ready, 'server reply timeout' 60 data = os.read(self.proc.stdout.fileno(), 65536) 61 assert data, f'server closed stdout (status {self.proc.poll()})' 62 self.pending += data 63 line, self.pending = self.pending.split(b'\n', 1) 64 reply = json.loads(line) 65 assert reply['jsonrpc'] == '2.0', reply 66 return reply 67 68 def rpc(self, method, params=None, identifier=None): 69 self.seq += 1 70 identifier = self.seq if identifier is None else identifier 71 request = {'jsonrpc': '2.0', 'id': identifier, 'method': method} 72 if params is not None: 73 request['params'] = params 74 self.send(request) 75 reply = self.receive() 76 assert reply['id'] == identifier and type(reply['id']) is type(identifier), reply 77 return reply 78 79 def tool(self, name, args, success=True): 80 reply = self.rpc('tools/call', {'name': name, 'arguments': args}) 81 assert 'error' not in reply, reply 82 result = reply['result'] 83 body = result['structuredContent'] 84 assert isinstance(body, dict), result 85 assert isinstance(result['content'][0]['text'], str) and result['content'][0]['text'], result 86 assert result['content'][0]['type'] == 'text', result 87 assert result['isError'] is (not success), result 88 assert body['ok'] is success, body 89 if not success: 90 assert isinstance(body['error'], str) and body['error'], body 91 return body 92 93 94 def fixture(root): 95 (root / 'agents').mkdir() 96 (root / 'RULES.md').write_text('Initial rules.\n') 97 (root / 'config.yml').write_text('{"model":"example:model"}\n') 98 (root / 'WATCHDOG.yml').write_text('{"advisors":[{"name":"fixture","model":"example:model"}]}\n') 99 (root / 'agents' / 'worker.md').write_text(agent('worker')) 100 101 102 def agent(name, extra=None): 103 meta = {'name': name, 'description': 'Isolated oracle fixture'} 104 meta.update(extra or {}) 105 return '---\n' + json.dumps(meta) + '\n---\nFixture instructions.\n' 106 107 108 def read(c, file='RULES.md'): 109 result = c.tool('read_file', {'file': file}) 110 assert result['sha256'] == digest(result['content']), result 111 assert result['size'] == len(result['content'].encode()), result 112 return result 113 114 115 def propose(c, file, content, before): 116 result = c.tool('propose', {'file': file, 'content': content, 117 'expected_sha256': digest(before)}) 118 assert isinstance(result['proposal_id'], str) and result['proposal_id'], result 119 assert result['changed'] is (before != content), result 120 assert result['before_content'] == before and result['after_content'] == content, result 121 assert result['before_sha256'] == digest(before), result 122 assert result['after_sha256'] == digest(content), result 123 return result 124 125 126 def readonly(binary): 127 with tempfile.TemporaryDirectory(prefix='maintenance-readonly-') as tmp: 128 root = Path(tmp) 129 fixture(root) 130 before = (root / 'RULES.md').read_text() 131 after = 'Must not be written in default mode.\n' 132 with Client(binary, root) as c: 133 p = propose(c, 'RULES.md', after, before) 134 assert p['apply_allowed'] is False, p 135 c.tool('apply', {'proposal_id': p['proposal_id']}, success=False) 136 assert (root / 'RULES.md').read_text() == before, 'default-readonly guard missing: actual mutation' 137 138 139 def protocol(binary): 140 with tempfile.TemporaryDirectory(prefix='maintenance-protocol-') as tmp: 141 root = Path(tmp) 142 fixture(root) 143 with Client(binary, root, True) as c: 144 for version in ('2024-11-05', '2025-03-26', '2025-06-18'): 145 reply = c.rpc('initialize', {'protocolVersion': version, 'capabilities': {}, 146 'clientInfo': {'name': 'oracle', 'version': '1'}}) 147 assert reply['result']['protocolVersion'] == version, reply 148 assert reply['result']['serverInfo']['name'] == 'omega-agent-maintenance', reply 149 reply = c.rpc('initialize', {'protocolVersion': 'unknown'}) 150 assert reply['result']['protocolVersion'] == '2025-06-18', reply 151 for identifier in ('escaped"\\\n\u2603', -17, 0, `18446744073709551616`): 152 assert c.rpc('ping', identifier=identifier)['result'] == {} 153 pending = propose(c, 'RULES.md', 'Notification must not apply\n', 'Initial rules.\n') 154 c.send({'jsonrpc': '2.0', 'method': 'tools/call', 155 'params': {'name': 'apply', 'arguments': {'proposal_id': pending['proposal_id']}}}) 156 assert c.rpc('ping')['result'] == {}, 'notification produced response' 157 assert (root / 'RULES.md').read_text() == 'Initial rules.\n', 'notification executed a mutation' 158 tools = c.rpc('tools/list')['result']['tools'] 159 expected = {'inventory': [], 'read_file': ['file'], 'validate': ['file', 'content'], 160 'propose': ['file', 'content', 'expected_sha256'], 161 'apply': ['proposal_id'], 'rollback': ['proposal_id']} 162 assert {t['name'] for t in tools} == set(expected) 163 for tool in tools: 164 schema = tool['inputSchema'] 165 assert schema['type'] == 'object' and schema['additionalProperties'] is False 166 assert set(schema['required']) == set(expected[tool['name']]) 167 assert set(schema['properties']) == set(expected[tool['name']]) 168 for request, code in [([], -32600), ({}, -32600), 169 ({'jsonrpc': '2.0', 'id': 1.5, 'method': 'ping'}, -32600), 170 ({'jsonrpc': '2.0', 'id': None, 'method': 'ping'}, -32600)]: 171 c.send(request) 172 assert c.receive()['error']['code'] == code 173 for wire in (b'{oops}\n', b'\xff\n', b'{"x":"\\ud800"}\n', 174 b'{"jsonrpc":"2.0","id":1,"method":"ping","method":"ping"}\n'): 175 c.raw(wire) 176 assert c.receive()['error']['code'] in (-32700, -32600) 177 for name, args in [('inventory', {'extra': True}), ('read_file', {}), 178 ('read_file', {'file': 3}), ('apply', {'proposal_id': 'x', 'file': 'RULES.md'}), 179 ('validate', {'file': 'RULES.md', 'content': 'x' * 65537}), 180 ('missing', {})]: 181 reply = c.rpc('tools/call', {'name': name, 'arguments': args}) 182 assert reply['error']['code'] == -32602, reply 183 c.raw(b'{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_file","arguments":{"file":"RULES.md","file":"config.yml"}}}\n') 184 assert c.receive()['error']['code'] == -32602 185 wire = json.dumps({'jsonrpc': '2.0', 'id': 'oversized', 'method': 'tools/call', 186 'params': {'name': 'apply', 'arguments': {'proposal_id': pending['proposal_id']}}}).encode() 187 c.raw(wire + b' ' * 524289 + b'\n') 188 assert c.receive()['error']['code'] == -32700 189 assert c.rpc('ping')['result'] == {}, 'oversize frame desynchronized transport' 190 assert (root / 'RULES.md').read_text() == 'Initial rules.\n' 191 192 193 def transactions(binary): 194 with tempfile.TemporaryDirectory(prefix='maintenance-transactions-') as tmp: 195 root = Path(tmp) 196 fixture(root) 197 target = root / 'RULES.md' 198 before = target.read_text() 199 after = 'Updated rules: caf\u00e9 \u2603.\n' 200 target.chmod(0o640) 201 with Client(binary, root, True) as c: 202 c.tool('inventory', {}) 203 assert read(c)['content'] == before 204 c.tool('propose', {'file': 'RULES.md', 'content': after, 205 'expected_sha256': '0' * 64}, success=False) 206 p = propose(c, 'RULES.md', after, before) 207 assert p['apply_allowed'] is True, p 208 assert target.read_text() == before, 'propose wrote target' 209 c.tool('apply', {'proposal_id': 'wrong'}, success=False) 210 c.tool('rollback', {'proposal_id': p['proposal_id']}, success=False) 211 c.tool('apply', {'proposal_id': p['proposal_id']}) 212 assert target.read_text() == after and target.stat().st_mode & 0o777 == 0o640 213 assert read(c)['sha256'] == digest(after) 214 c.tool('apply', {'proposal_id': p['proposal_id']}, success=False) 215 c.tool('rollback', {'proposal_id': 'wrong'}, success=False) 216 target.write_text('External edit\n') 217 c.tool('rollback', {'proposal_id': p['proposal_id']}, success=False) 218 assert target.read_text() == 'External edit\n' 219 target.write_text(after) 220 c.tool('rollback', {'proposal_id': p['proposal_id']}) 221 assert target.read_text() == before 222 c.tool('rollback', {'proposal_id': p['proposal_id']}, success=False) 223 p = propose(c, 'RULES.md', after, before) 224 target.write_text('Stale proposal\n') 225 c.tool('apply', {'proposal_id': p['proposal_id']}, success=False) 226 assert target.read_text() == 'Stale proposal\n' 227 target.write_text(before) 228 old = propose(c, 'RULES.md', after, before) 229 new = propose(c, 'RULES.md', 'Replacement\n', before) 230 c.tool('apply', {'proposal_id': old['proposal_id']}, success=False) 231 c.tool('apply', {'proposal_id': new['proposal_id']}) 232 assert target.read_text() == 'Replacement\n' 233 c.tool('rollback', {'proposal_id': new['proposal_id']}) 234 p = propose(c, 'RULES.md', after, before) 235 with Client(binary, root, True) as c: 236 c.tool('apply', {'proposal_id': p['proposal_id']}, success=False) 237 c.tool('rollback', {'proposal_id': p['proposal_id']}, success=False) 238 assert target.read_text() == before 239 240 241 def validation(binary): 242 with tempfile.TemporaryDirectory(prefix='maintenance-validation-') as tmp: 243 root = Path(tmp) 244 fixture(root) 245 with Client(binary, root, True) as c: 246 for file, content in [('RULES.md', 'Unicode \u2603\n'), ('RULES.md', 'x' * 65536), 247 ('config.yml', '{"nested":{"ok":true}}'), 248 ('WATCHDOG.yml', '{"advisors":[]}'), 249 ('agents/worker.md', agent('worker'))]: 250 c.tool('validate', {'file': file, 'content': content}) 251 original_agent = (root / 'agents' / 'worker.md').read_text() 252 replacement_agent = agent('worker', {'description': 'Changed saved definition'}) 253 p = propose(c, 'agents/worker.md', replacement_agent, original_agent) 254 c.tool('apply', {'proposal_id': p['proposal_id']}) 255 assert (root / 'agents' / 'worker.md').read_text() == replacement_agent 256 c.tool('rollback', {'proposal_id': p['proposal_id']}) 257 assert (root / 'agents' / 'worker.md').read_text() == original_agent 258 original_rules = (root / 'RULES.md').read_text() 259 large = '"' * 65536 260 p = propose(c, 'RULES.md', large, original_rules) 261 c.tool('apply', {'proposal_id': p['proposal_id']}) 262 assert (root / 'RULES.md').read_text() == large 263 c.tool('rollback', {'proposal_id': p['proposal_id']}) 264 assert (root / 'RULES.md').read_text() == original_rules 265 for file, content in [('RULES.md', 'NUL\x00'), ('config.yml', 'model: legacy-yaml\n'), 266 ('config.yml', '[]'), ('config.yml', '{"bad":}'), 267 ('WATCHDOG.yml', 'not json'), 268 ('agents/worker.md', '---\nname: worker\n---\nlegacy\n'), 269 ('agents/worker.md', agent('different')), 270 ('agents/worker.md', agent('worker', {'description': ''})), 271 ('agents/worker.md', agent('worker', {'model': 3})), 272 ('agents/worker.md', agent('worker', {'thinking-level': 'impossible'})), 273 ('config.yml', '{"defaultThinkingLevel":3}'), 274 ('config.yml', '{"defaultThinkingLevel":"impossible"}'), 275 ('config.yml', '{"model":"a","model":"b"}'), 276 ('WATCHDOG.yml', '{"advisors":[{"name":"same"},{"name":"same"}]}'), 277 ('WATCHDOG.yml', '{"advisors":[{"name":""}]}'), 278 ('WATCHDOG.yml', '{"advisors":[{"name":"valid","model":3}]}')]: 279 c.tool('validate', {'file': file, 'content': content}, success=False) 280 before = (root / file).read_text() 281 c.tool('propose', {'file': file, 'content': content, 282 'expected_sha256': digest(before)}, success=False) 283 assert (root / file).read_text() == before 284 (root / 'config.yml').write_text('model: readable-legacy-yaml\n') 285 assert read(c, 'config.yml')['content'] == 'model: readable-legacy-yaml\n' 286 legacy = (root / 'config.yml').read_text() 287 p = propose(c, 'config.yml', '{"model":"new:model"}\n', legacy) 288 c.tool('apply', {'proposal_id': p['proposal_id']}) 289 c.tool('rollback', {'proposal_id': p['proposal_id']}) 290 assert (root / 'config.yml').read_text() == legacy, 'legacy rollback must restore exact captured bytes' 291 (root / 'agents' / 'worker.md').write_text('---\nname: worker\n---\nLegacy\n') 292 read(c, 'agents/worker.md') 293 (root / 'RULES.md').write_bytes(b'bad\xff') 294 c.tool('read_file', {'file': 'RULES.md'}, success=False) 295 (root / 'RULES.md').write_bytes(b'x' * 65537) 296 c.tool('read_file', {'file': 'RULES.md'}, success=False) 297 298 299 def paths(binary): 300 with tempfile.TemporaryDirectory(prefix='maintenance-paths-') as tmp: 301 top = Path(tmp) 302 root = top / 'root' 303 root.mkdir() 304 fixture(root) 305 outside = top / 'outside.md' 306 outside.write_text('Outside must remain untouched\n') 307 with Client(binary, root, True) as c: 308 for file in ('../outside.md', '/etc/passwd', 'agents/../RULES.md', 'agents/a/b.md', 309 'agents/.hidden.md', 'agents/worker.sh', 'other.md', 'agents/missing.md'): 310 c.tool('read_file', {'file': file}, success=False) 311 c.tool('propose', {'file': file, 'content': 'unsafe\n', 312 'expected_sha256': digest(outside.read_text())}, success=False) 313 target = root / 'RULES.md' 314 target.unlink() 315 target.symlink_to(outside) 316 c.tool('read_file', {'file': 'RULES.md'}, success=False) 317 c.tool('propose', {'file': 'RULES.md', 'content': 'unsafe\n', 318 'expected_sha256': digest(outside.read_text())}, success=False) 319 target.unlink() 320 os.link(outside, target) 321 c.tool('read_file', {'file': 'RULES.md'}, success=False) 322 c.tool('propose', {'file': 'RULES.md', 'content': 'unsafe\n', 323 'expected_sha256': digest(outside.read_text())}, success=False) 324 target.unlink() 325 os.mkfifo(target) 326 c.tool('read_file', {'file': 'RULES.md'}, success=False) 327 target.unlink() 328 target.write_text('safe\n') 329 target.chmod(0o755) 330 c.tool('propose', {'file': 'RULES.md', 'content': 'unsafe\n', 331 'expected_sha256': digest('safe\n')}, success=False) 332 target.chmod(0o600) 333 p = propose(c, 'RULES.md', 'replacement\n', 'safe\n') 334 target.unlink() 335 target.symlink_to(outside) 336 c.tool('apply', {'proposal_id': p['proposal_id']}, success=False) 337 assert outside.read_text() == 'Outside must remain untouched\n' 338 target.unlink() 339 target.write_text('safe\n') 340 (root / 'config.yml').unlink() 341 inventory = c.tool('inventory', {}) 342 rows = {row['file']: row for row in inventory['files']} 343 assert rows['config.yml']['status'] == 'missing', rows 344 c.tool('read_file', {'file': 'config.yml'}, success=False) 345 agents = root / 'agents' 346 (agents / 'worker.md').unlink() 347 agents.rmdir() 348 agents.symlink_to(top, target_is_directory=True) 349 c.tool('read_file', {'file': 'agents/outside.md'}, success=False) 350 assert outside.read_text() == 'Outside must remain untouched\n' 351 link = top / 'link' 352 link.symlink_to(root, target_is_directory=True) 353 for candidate in (link, link / 'agents', Path('relative-root')): 354 proc = subprocess.run([str(binary), '--root', str(candidate)], input=b'', 355 capture_output=True, timeout=10) 356 assert proc.returncode != 0, ('unsafe root accepted', candidate) 357 # Pure boot refusal: no protected file is opened for writing or modified. 358 proc = subprocess.run([str(binary), '--root', '/srv/aien-keep', '--allow-write'], 359 input=b'', capture_output=True, timeout=10) 360 assert proc.returncode != 0, 'protected writable root accepted' 361 362 363 def write_failures(binary): 364 with tempfile.TemporaryDirectory(prefix='maintenance-failure-') as tmp: 365 root = Path(tmp) 366 fixture(root) 367 target = root / 'RULES.md' 368 before = target.read_text() 369 with Client(binary, root, True) as c: 370 p = propose(c, 'RULES.md', 'write must fail\n', before) 371 lock = root / '.agent-maintenance.lock' 372 lock.write_text('Other writer owns this lock\n') 373 c.tool('apply', {'proposal_id': p['proposal_id']}, success=False) 374 assert lock.read_text() == 'Other writer owns this lock\n', 'removed another writer lock' 375 assert target.read_text() == before 376 lock.unlink() 377 root.chmod(0o500) 378 try: 379 if os.geteuid() == 0: 380 raise AssertionError('permission failure fixture requires non-root execution') 381 c.tool('apply', {'proposal_id': p['proposal_id']}, success=False) 382 assert target.read_text() == before 383 finally: 384 root.chmod(0o700) 385 c.tool('apply', {'proposal_id': p['proposal_id']}) 386 assert target.read_text() == 'write must fail\n' 387 c.tool('rollback', {'proposal_id': p['proposal_id']}) 388 assert target.read_text() == before 389 expected = {'RULES.md', 'config.yml', 'WATCHDOG.yml', 'agents'} 390 assert {p.name for p in root.iterdir()} == expected, 'owned lock/stage leaked after failed write' 391 392 393 def real_smoke(binary, root): 394 with Client(binary, root) as c: 395 c.tool('inventory', {}) 396 for file in ('RULES.md', 'WATCHDOG.yml', 'config.yml'): 397 # Missing/unsupported existing data is reported individually, not hidden. 398 reply = c.rpc('tools/call', {'name': 'read_file', 'arguments': {'file': file}}) 399 assert 'result' in reply, reply 400 result = reply['result'] 401 assert result['isError'] is (not result['structuredContent']['ok']), result 402 403 404 def main(): 405 parser = argparse.ArgumentParser(description=__doc__) 406 parser.add_argument('--binary', type=Path, required=True) 407 parser.add_argument('--real-root', type=Path) 408 parser.add_argument('--negative-control-binary', type=Path) 409 args = parser.parse_args() 410 binary = args.binary.resolve(strict=True) 411 for name, check in [('protocol', protocol), ('default_readonly', readonly), 412 ('transactions', transactions), ('validation', validation), 413 ('path_boundaries', paths), ('failed_write_cleanup', write_failures)]: 414 check(binary) 415 print(json.dumps({'check': name, 'status': 'PASS'}), flush=True) 416 if args.real_root: 417 real_smoke(binary, args.real_root) 418 print(json.dumps({'check': 'real_root_readonly', 'status': 'PASS'}), flush=True) 419 if args.negative_control_binary: 420 mutant = args.negative_control_binary.resolve(strict=True) 421 with tempfile.TemporaryDirectory(prefix='maintenance-mutant-') as tmp: 422 root = Path(tmp) 423 fixture(root) 424 before = (root / 'RULES.md').read_text() 425 after = 'Mutant actually bypassed default readonly.\n' 426 with Client(mutant, root) as c: 427 p = propose(c, 'RULES.md', after, before) 428 # Deliberately inspect actual mutation rather than a response-only stub. 429 c.rpc('tools/call', {'name': 'apply', 'arguments': {'proposal_id': p['proposal_id']}}) 430 assert (root / 'RULES.md').read_text() == after, 'negative control did not expose missing guard' 431 try: 432 readonly(mutant) 433 except AssertionError: 434 pass 435 else: 436 raise AssertionError('oracle accepted the missing-readonly-guard mutant') 437 print(json.dumps({'check': 'missing_guard_negative_control', 'status': 'PASS'}), flush=True) 438 else: 439 print(json.dumps({'check': 'missing_guard_negative_control', 'status': 'NOT_RUN', 440 'reason': 'supply independently built --negative-control-binary'}), flush=True) 441 442 443 if __name__ == '__main__': 444 main()