import datetime,json,os,pathlib
os.umask(0o077);R=pathlib.Path(__file__).parent
assert json.loads((R/'image-verify.json').read_text())=={'loader':0,'sdk_copy':0}
(R/'image-gate.json').write_text(json.dumps(dict(errors=0,failures=0,sdk=0)))
plan=json.loads((R/'plan.json').read_text());plan['controls']='/workspace/contextra-runtime-config/metadata-active'
(R/'plan.json').write_text(json.dumps(plan,indent=2))
budget=json.loads((R/'budget.json').read_text())
elapsed=(datetime.datetime.now(datetime.timezone.utc)-datetime.datetime.fromisoformat(budget['started_at'])).total_seconds()
assert budget['failed_groups']<(5 if elapsed<1200 else 4 if elapsed<2100 else 3)
assert budget['live_windows']==0
budget.update(live_windows=1,elapsed_before_live_s=elapsed)
budget['groups'].append(dict(id=3,hypothesis='Corrected source hook plus Flow substage and independent live observation',status='running',signature='instrumented-live'))
(R/'budget.json').write_text(json.dumps(budget,indent=2))
source=pathlib.Path('/tmp/codex/ltb1021/2026-09-12_contextra-rtp-anchor_r01/runtime-derived.py').read_text()
source=source.replace("R/'image-verify.json'", "R/'image-gate.json'")
source=source.replace('log=None;started=False;overlay_after=None;active_after=None','log=None;started=False;overlay_after=None;active_after=None;live_process=None')
source=source.replace("  started=True;state['runtime_windows']=1;command('start')", "  live_process=subprocess.Popen(['python3',str(R/'live_observer.py'),env['FASTAPI_HOST_PORT']])\n  time.sleep(.6)\n  started=True;state['runtime_windows']=1;command('start')")
source=source.replace(",\n   {'type':'bind','source':str(R/'anchor.json'),'target':'/run/contextra-test-anchor.json','read_only':True}", '')
source=source[:source.index('  try:\n   if not success:')]+'''
  try:
   if live_process:
    live_process.terminate()
    try:live_process.wait(5)
    except subprocess.TimeoutExpired:live_process.kill();live_process.wait(5)
   if not success and state.get('analytics_reflected'):
    state['failed_state']=g.inspect()['State'];save()
    cmd(['docker','stop','--timeout','20',g.NAME],40)
    cmd(['docker','update','--restart=no',g.NAME])
    assert g.sha(active)==active_after
    cfg=g.yaml.safe_load(active.read_text());cfg['services']['analytics']['restart']='no'
    state['active_after']=a.atomic(active,g.yaml.safe_dump(cfg).encode(),active_after)
    state['recovery']='RETAIN_SAFE_STOPPED_IMAGE'
   elif success:
    cmd(['docker','update','--restart='+a.restart_arg(plan['analytics']['HostConfig']['RestartPolicy']),g.NAME])
   if log:log.close();state['log_bytes']=log.bytes;state['log_error']=log.error
   c=g.inspect()
   if success:
    assert c['State']['Health']['Status']=='healthy' and api(path)[1]['state']=='stopped'
   elif state.get('analytics_reflected'):
    assert c['State']['Status']=='exited' and c['HostConfig']['RestartPolicy']['Name']=='no'
   assert g.others()==plan['other_containers'] and g.sha(g.CFG)==plan['config_hash']
   assert g.sha(g.CFG.parent/'2/model.plan')==plan['plan_hash']
   state['final']=dict(analytics='healthy' if success else c['State']['Status'],stream='stopped' if success else 'not_executing',image=c['Image'],success=success,display_score=.25,metadata_auth_preserved=True,model_non_targets_unchanged=True,capture_off=True,restart_policy=c['HostConfig']['RestartPolicy'],diagnostics='RETAIN task override until next approved recreate',test_anchor='RETAIN explicit camera setting; no autostart')
  except Exception as e:
   state['restore_error']=type(e).__name__
   try:cmd(['docker','stop','--timeout','20',g.NAME],40);state['safety_stopped']=True
   except Exception:state['safety_stop_failed']=True
  finally:
   if log:log.close()
  state['stage']='completed';save()
  budget=json.loads((R/'budget.json').read_text())
  budget['groups'][-1]['status']='passed' if success else 'failed'
  if not success:budget['failed_groups']+=1
  budget['elapsed_after_live_s']=time.time()-__import__('datetime').datetime.fromisoformat(budget['started_at']).timestamp()
  (R/'budget.json').write_text(json.dumps(budget,indent=2))
  print(json.dumps({k:state.get(k) for k in ('stage','window_result','anchor_transport','redis_visual_matches','cleanup_verified','error','error_code','final','restore_error')}))

if __name__=='__main__':main()
'''
(R/'runtime-derived.py').write_text(source)
exec(compile(source,str(R/'runtime-derived.py'),'exec'),globals())
