"""Reuse the approved apply/restore and bounded observers; exactly two fresh runs."""
from pathlib import Path

source=Path('/tmp/codex/ltb1021/2026-09-13_contextra-intrusion-live_r01/runtime.py').read_text()
window=r'''
def comparison_window(mode):
    global started, events, matches
    events, matches = {}, set()
    flag.unlink(missing_ok=True)
    state['mode']=mode
    state['cleanup_verified']=False
    state['runtime_windows']+=1
    win=dict(mode=mode, samples=[], cleanup=False)
    state.setdefault('windows',[]).append(win)
    started=True
    r.command('start')
    deadline=time.monotonic()+60
    first=None
    while time.monotonic()<deadline:
        item=r.sample()
        assert log.error is None and not item.get('last_error') and not item.get('cleanup_error'), 'PIPELINE_ERROR'
        if item['state']=='running' and item.get('metadata_path',{}).get('processed',0):
            first=item
            break
        time.sleep(.2)
    assert first is not None, 'FIRST_RESULT_TIMEOUT'
    state['run_id']=first['run_id']
    win['first_result_ns']=time.monotonic_ns()
    assert first['metadata_path']['visual']['preparation']['ready'], 'CAPTURE_PREPARATION_FAILED'
    win['preparation']=first['metadata_path']['visual']['preparation']
    r.api(r.path+'/metrics','POST',dict(run_generation=first['run_generation'],enabled=True,seconds=60))
    deadline=time.monotonic()+35
    last_seq=-1
    while time.monotonic()<deadline:
        item=r.sample()
        assert item['state']=='running' and not item.get('last_error') and not item.get('cleanup_error'), 'PIPELINE_ERROR'
        perf=item['metadata_path']['performance']
        key=perf.get('last_frame',{}).get('result')
        if key and key[0]!=last_seq:
            last_seq=key[0]
            if 20<=last_seq<=125:
                win['samples'].append(dict(frame=last_seq,pts_ns=key[1],performance=perf,
                    processed=item['metadata_path'].get('processed'),stale=item['metadata_path'].get('stale',0),
                    queue_drop=item['metadata_path'].get('queue_drop',0),
                    publisher=state['observations'][-1]['publisher']['metrics']))
        if mode=='on' and last_seq>=30 and not flag.exists():
            flag.touch(mode=0o600,exist_ok=False)
            win['capture_enabled_after_frame']=last_seq
        readback_frames()
        win['visual']=item['metadata_path'].get('visual')
        if last_seq>=125:
            break
        time.sleep(.15)
    assert last_seq>=125, 'MEASUREMENT_FRAME_TIMEOUT'
    readback_frames()
    win.update(events_observed=len(events),events_created=item['metadata_path'].get('events_created',0),
               matched_frames=sorted(matches),last_frame=last_seq)
    if mode=='off':
        assert win['visual']['captures']==0
    else:
        assert matches, 'VISUAL_FRAME_UNAVAILABLE'
    r.api(r.path+'/metrics','POST',dict(run_generation=first['run_generation'],enabled=False,seconds=60))
    started=False
    r.command('stop')
    deadline=time.monotonic()+60
    while time.monotonic()<deadline:
        item=r.sample()
        assert not item.get('last_error') and not item.get('cleanup_error'), 'PIPELINE_ERROR'
        if item['state']=='stopped' and not item.get('cleanup_pending'):
            assert item['last_cleanup']['completed']
            win['cleanup']=item['last_cleanup']
            state['cleanup_verified']=True
            break
        time.sleep(.2)
    assert state['cleanup_verified'], 'CLEANUP_TIMEOUT'
    flag.unlink(missing_ok=True)
    save()

'''
source=source.replace('def main():',window+'\ndef main():',1)
start=source.index('        started=True\n        state[\'runtime_windows\']=1')
end=source.index('\n    except Exception as e:',start)
source=source[:start]+'''        state['runtime_windows']=0
        for mode in ('off','on'):
            comparison_window(mode)
        state['window_result']='OFF_ON_COMPLETE'
        save()
'''+source[end:]
source=source.replace("measurement_seconds=8", "measurement_source_frames=[20,125]")
source=source.replace("'MEASUREMENT_FRAME_TIMEOUT'", "'MEASUREMENT_FRAME_TIMEOUT'")
exec(compile(source,'bounded_off_on_runtime','exec'))
