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 / om / hive-render / test-render.py

208 lines · 8925 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Independent Python/HTML parser oracle; never part of the serving path."""
3import copy
4import datetime
5import html
6from html.parser import HTMLParser
7import json
8from pathlib import Path
9import subprocess
10import sys
11
12BINARY, OMC, SCRATCH = map(Path, sys.argv[1:])
13BINARY, OMC = BINARY.resolve(), OMC.resolve()
14
15
16def canonical(value):
17 return (json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(',', ':')) + '\n').encode()
18
19
20def agent(identity='a1', parent=None):
21 return dict(id=identity, parent_id=parent, name='Worker', runtime='OMP', provider='provider',
22 model='model', role='worker', task='A public task', status='working', activity='A public action',
23 activity_state='running', started_at='2026-10-25T23:59:59.900Z',
24 updated_at=None, observed_at='2026-10-26T00:00:00.100Z')
25
26
27def snapshot():
28 return dict(schema_version=1, generated_at='2026-10-26T00:00:01.100Z', sequence='snapshot',
29 poll_ms=1000, stale_after_ms=15000,
30 coverage=dict(label='OMP', roots=1, agents=1, complete=False, notice='Partial observation'),
31 agents=[agent()], interactions=[])
32
33
34def run(raw, good=True):
35 result = subprocess.run([BINARY], input=raw, capture_output=True, timeout=30)
36 if good:
37 assert result.returncode == 0, (result.returncode, result.stderr)
38 assert result.stdout.startswith(b'<!doctype html>')
39 assert result.stdout.endswith(b'</html>\n')
40 else:
41 assert result.returncode != 0, 'invalid input was accepted'
42 assert result.stdout == b'', 'refusal leaked partial output'
43 return result.stdout
44
45
46class Document(HTMLParser):
47 def __init__(self, value):
48 super().__init__(convert_charrefs=True)
49 self.ids, self.tags, self.text, self.attrs = [], [], [], []
50 self.feed(value.decode())
51
52 def handle_starttag(self, tag, attrs):
53 attrs = dict(attrs)
54 self.tags.append(tag)
55 self.attrs.append(attrs)
56 if 'id' in attrs:
57 self.ids.append(attrs['id'])
58 assert not any(key.startswith('on') for key in attrs), attrs
59 assert not any('javascript:' in value for value in attrs.values() if value), attrs
60
61 def handle_data(self, data):
62 self.text.append(data)
63
64
65base = snapshot()
66raw = canonical(base)
67first = run(raw)
68assert first == run(raw), 'render depends on wall clock or mutable state'
69# Receiver sequence is arbitrary text: encode it, never widen attribute grammar.
70for sequence in ['', '\"><script>alert(1)</script>', 'é' * 64]:
71 value = snapshot()
72 value['sequence'] = sequence
73 parsed = Document(run(canonical(value)))
74 root = next(a for a in parsed.attrs if a.get('id') == 'hive-board')
75 assert root['data-sequence'] == 's-' + sequence.encode().hex()
76doc = Document(first)
77assert len(doc.ids) == len(set(doc.ids)), 'duplicate DOM id'
78assert '1s' in ''.join(doc.text) # Subsecond timestamps must not round up.
79assert 'script' not in doc.tags
80assert next(a for a in doc.attrs if a.get('id') == 'hive-board')['data-generated'] == base['generated_at']
81
82# Every byte is tested through the exact production escaper, without the JSON
83# parser (which correctly refuses invalid UTF-8 and disallowed controls).
84source = Path('render.om').read_text().split('fn main to int\n')[0]
85escape_main = '''fn main to int
86n = ulong 0
87while lt n 16000
88r = read 0 dec n sub ulong 16000 n
89if lt r 0
90ret 1
91end
92if eq r 0
93break
94end
95n = add n ulong r
96end
97escape 0 n
98r = write 1 out 0 get st 5
99if ne r long get st 5
100ret 2
101end
102ret 0
103end
104'''
105probe = SCRATCH / 'escape'
106compiled = subprocess.run([OMC], input=(source + escape_main).encode(), capture_output=True)
107assert compiled.returncode == 0, compiled.stderr
108probe.write_bytes(compiled.stdout)
109probe.chmod(0o700)
110for value in [bytes([i]) for i in range(256)] + [bytes(range(256)), b"&<>\"'" * 144, b"&<>\"'" * 3200]:
111 escaped = subprocess.run([probe], input=value, capture_output=True, check=True).stdout
112 expected = html.escape(value.decode('latin1'), quote=True).encode('latin1')
113 assert escaped == expected, (value[:20], escaped[:100], expected[:100])
114 if b'<' in value:
115 assert escaped != expected.replace(b'&lt;', b'<'), 'negative escaper oracle did not discriminate'
116
117probes = ['<img src=x onerror=alert(1)>', '</li><script>alert(1)</script>',
118 '\"><a href="javascript:alert(1)">', '</details>']
119for payload in probes + ['\b\f\n\r\t\\"', 'é 🐝 漢字', "&<>\"'" * 3200]:
120 value = snapshot()
121 value['agents'][0]['activity'] = payload
122 value['interactions'] = [dict(id='m1', agent_id='a1', role='assistant', text=payload,
123 at=value['generated_at'], runtime='OMP', provider='provider', model='model')]
124 output = run(canonical(value))
125 assert html.escape(payload).encode() in output
126 parsed = Document(output)
127 assert not {'img', 'script'} & set(parsed.tags)
128 assert payload in parsed.text
129 if payload in probes:
130 (SCRATCH / ('xss-' + str(probes.index(payload)) + '.html')).write_bytes(output)
131
132# Agent replies only: any human role is a schema refusal with no partial output.
133for role in ('drake', 'user', 'guest', 'Assistant'):
134 value = snapshot()
135 value['interactions'] = [dict(id='m1', agent_id='a1', role=role, text='HUMAN_MESSAGE_CANARY',
136 at=value['generated_at'], runtime='OMP', provider='provider', model='model')]
137 run(canonical(value), False)
138value = snapshot()
139value['interactions'] = [dict(id='m1', agent_id='a1', role='assistant', text='Agent reply',
140 at=value['generated_at'], runtime='OMP', provider='provider', model='model')]
141output = run(canonical(value))
142assert b'<h2>What the agents are saying, live</h2><ol class="hive-chat"' in output
143assert b'Drake' not in output
144
145for field, size in [('name', 720), ('task', 16000), ('activity', 16000)]:
146 value = snapshot()
147 value['agents'][0][field] = 'x' * size
148 run(canonical(value))
149 value['agents'][0][field] += 'x'
150 run(canonical(value), False)
151
152bad = [raw[:-2], raw.replace(b'"Worker"', b'"unterminated'), b'x' * (2097152 + 1),
153 raw.replace(b'"Worker"', b'"\\u0001"'), raw.replace(b'"Worker"', b'"\\q"'),
154 raw.replace(b'"Worker"', b'"\\u0041"'), raw.replace(b'"Worker"', b'"\xc0\xbc"'),
155 raw.replace(b'"agents":[', b'"agents":[],"agents":['),
156 raw.replace(b'"coverage":{', b'"unknown":0,"coverage":{')]
157for encoded in bad:
158 run(encoded, False)
159for mutation in ['bad-id', 'parent', 'cycle', 'count', 'date', 'enum', 'fraction', 'duplicate-id']:
160 value = snapshot()
161 if mutation == 'bad-id': value['agents'][0]['id'] = 'a" onclick="x'
162 if mutation == 'parent': value['agents'][0]['parent_id'] = 'missing'
163 if mutation == 'cycle':
164 value['agents'][0]['parent_id'] = 'a1'
165 value['coverage']['roots'] = 0
166 if mutation == 'count': value['coverage']['agents'] = 2
167 if mutation == 'date': value['generated_at'] = '2026-02-29T00:00:01Z'
168 if mutation == 'enum': value['agents'][0]['status'] = 'invented'
169 if mutation == 'fraction': value['generated_at'] = '2026-10-26T00:00:01.Z'
170 if mutation == 'duplicate-id':
171 value['agents'].append(agent())
172 value['coverage'].update(agents=2, roots=2)
173 run(canonical(value), False)
174
175# Deep valid trees are traversed iteratively, not via the process stack.
176value = snapshot()
177value['agents'] = [agent('a' + str(i), 'a' + str(i - 1) if i else None) for i in range(500)]
178value['coverage']['agents'] = 500
179output = run(canonical(value))
180assert output.count(b'<summary class="hive-record">') == 500
181assert output.count(b'</ul></details></li>') == 500
182
183# Receiver maximum byte budget with worst-case escaping can exceed one output
184# pool. This fixture exercises both pools rather than silently reducing scope.
185value = snapshot()
186value['agents'] = [agent('a' + str(i)) for i in range(60)]
187for item in value['agents']:
188 item['activity'] = "'" * 16000
189 item['task'] = "'" * 16000
190value['coverage'].update(agents=60, roots=60)
191encoded = canonical(value)
192assert len(encoded) < 2097152
193output = run(encoded)
194assert len(output) > 16777216
195Document(output)
196
197# Date arithmetic independently compared with Python's datetime oracle.
198for year in [1900, 2000, 2024, 2026]:
199 value = snapshot()
200 value['generated_at'] = f'{year}-03-01T00:00:00Z'
201 value['agents'][0]['started_at'] = f'{year}-02-28T00:00:00Z'
202 value['agents'][0]['observed_at'] = value['generated_at']
203 expected = int((datetime.datetime(year, 3, 1) - datetime.datetime(year, 2, 28)).total_seconds())
204 assert f'>{expected}s</span>'.encode() in run(canonical(value))
205
206(SCRATCH / 'fixture.json').write_bytes(raw)
207(SCRATCH / 'fixture.html').write_bytes(first)
208print('renderer oracle checks passed (byte escaper, Unicode, XSS, limits, negative controls, dates, deep tree, two output pools)')