Files
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

108 lines
8.6 KiB
Python

#!/usr/bin/env python3
"""Reversible Wine in-process backend experiment; NOT Forever engine compatibility.
Only the designated local test session and exact gateway PID are controlled.
"""
import argparse,json,os,signal,subprocess,time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
COPY=ROOT/'runtime/native-client'
CONFIG=ROOT/'secrets/native-local-bootstrap.json'
def prepare(engine_bridge=False,registration_trace=False,native_registration=False):
from client_installation import clone,inspect_installation
clone();identity=inspect_installation(COPY)
if engine_bridge:
import hashlib
manifest=json.loads((ROOT/'runtime/native-engine-pe.json').read_text())
if manifest.get('restored'):raise RuntimeError('Prepare the private PE observer before using it')
private_system=ROOT/'runtime/native-wine-prefix/drive_c/windows/system32'
if hashlib.sha256((private_system/'GWNativeBridge.dll').read_bytes()).hexdigest()!=manifest['dll_sha256']:raise RuntimeError('Private Windows observer identity mismatch')
if hashlib.sha256((private_system/'d3d11.dll').read_bytes()).hexdigest()!=manifest['dependency_patched_sha256']:raise RuntimeError('Private dependency identity mismatch')
if identity['files']['_classic_beta_/WowB.exe']['sha256']!=manifest['patched_sha256']:raise RuntimeError('Require the exact reproducible70334 import patch; changed copy preserved')
exe=COPY/'_classic_beta_/WowB.exe'
# Only the disposable copy's frontend endpoint is changed. Its original
# configuration and complete archive remain in the pristine extraction.
import re
config=exe.parent/'WTF/Config.wtf'
original=config.read_text()
original=re.sub(r'^SET portal .*$', 'SET portal "trinity.actual.battle.net"',original,flags=re.M)
if not re.search(r'^SET portal ',original,re.M):original+='\nSET portal "trinity.actual.battle.net"\n'
config.write_text(original);config.chmod(0o600)
directories=[p for p in (ROOT/'secrets').glob('GW*') if (p/'account.json').exists()]
if len(directories)!=1:raise RuntimeError('Require single authorized disposable backend binding')
CONFIG.write_text(json.dumps({'workspace':str(ROOT),'account_directory':str(directories[0]),'character_guid':4509,'discover_realms':True,'engine_bridge_probe':engine_bridge,'engine_registration_trace':registration_trace,'native_registration':native_registration,'evidence':str(ROOT/'runtime/native-backend-evidence.json')}));CONFIG.chmod(0o600)
print('Prepared complete private client and opt-in module configuration; credentials omitted.')
def run(engine_bridge=False,registration_trace=False,native_registration=False):
prepare(engine_bridge,registration_trace,native_registration)
from client_installation import close_test_client
close_test_client()
pid=int((ROOT/'runtime/relay.pid').read_text());proc=Path('/proc')/str(pid)
if proc.exists():
if os.readlink(proc/'exe').removesuffix(' (deleted)')!=str(ROOT/'build/gateway-relay'):raise RuntimeError('Gateway PID identity mismatch')
flags={}
for item in (proc/'environ').read_bytes().split(b'\0'):
if item.startswith(b'GATEWAY_'):
k,v=item.decode().split('=',1);flags[k]=v
(ROOT/'runtime/native-fallback-flags.json').write_text(json.dumps(flags));(ROOT/'runtime/native-fallback-flags.json').chmod(0o600)
os.kill(pid,signal.SIGTERM)
until=time.monotonic()+5
while proc.exists() and time.monotonic()<until:time.sleep(.05)
if proc.exists():raise RuntimeError('Gateway did not stop; no native test launched')
elif not (ROOT/'runtime/native-fallback-flags.json').exists():raise RuntimeError('Gateway already absent without a recorded fallback; preserve environment')
for other in Path('/proc').iterdir():
try:
if other.name.isdigit() and (other/'comm').read_text().strip()=='gateway-relay' and os.readlink(other/'exe').removesuffix(' (deleted)')==str(ROOT/'build/gateway-relay'):raise RuntimeError('Another workspace gateway is still running; no native test launched')
except OSError:pass
for name in ('native-engine-plan.json','native-engine-lua-bound.json','native-engine-probe-result.json','native-engine-registration.json'):(ROOT/'runtime'/name).unlink(missing_ok=True)
evidence=ROOT/'runtime/native-backend-evidence.json';evidence.unlink(missing_ok=True)
env=dict(os.environ)
with (ROOT/'runtime/native-client.log').open('wb')as log:
child=subprocess.Popen(['python3','-u',str(ROOT/'ops/debug_client_owner.py'),'serve-copy'],cwd=ROOT,env=env,stdout=log,stderr=log,start_new_session=True)
(ROOT/'runtime/native-debug-owner.pid').write_text(str(child.pid))
print('Started experimental WowB diagnostic parent; external gateway stopped. Owner PID',child.pid)
until=time.monotonic()+45
while time.monotonic()<until:
if evidence.exists():
report=json.loads(evidence.read_text());host=Path('/proc')/str(report['pid'])
# Boost property_tree emits scalar strings. Normalize the evidence
# so the string "false" can never be mistaken for a true boolean.
for field in ('engine_world_entry','external_gateway_used'):
if report[field] not in ('true','false'):raise RuntimeError('Native evidence boolean schema mismatch')
report[field]=report[field]=='true'
if 'backend_session_retained' in report:report['backend_session_retained']=report['backend_session_retained']=='true'
for field in ('pid','backend_auth_result','backend_discovery_result','backend_world_auth_result','selected_realm_index','realm_count','character_count','character_guid','character_level','backend_world_result','backend_map','backend_packets','backend_objects'):
if field in report:report[field]=int(report[field])
for field in ('backend_x','backend_y','backend_z'):
if field in report:report[field]=float(report[field])
if 'selection_required' in report:report['selection_required']=report['selection_required']=='true'
for realm in report.get('realms',[]):
for field in ('index','type','flags','characters','category','wire_id'):realm[field]=int(realm[field])
realm['population']=float(realm['population'])
if (host/'comm').read_text().strip()!='WowB.exe':raise RuntimeError('Evidence host identity mismatch')
maps=(host/'maps').read_text();report['module_mapped_in_host']='libgateway_native_bootstrap.so' in maps and 'libgateway_native.so' in maps
report['external_gateway_pid_absent']=not proc.exists();evidence.write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report));return
if child.poll() is not None:raise RuntimeError('Experimental client exited; inspect private runtime/native-client.log')
time.sleep(.1)
raise RuntimeError('Bounded native proof timed out; experimental client preserved for inspection')
def restore():
# Do not kill an unverified process. Only close an exact experimental path.
pid_path=ROOT/'runtime/native-client.pid'
if pid_path.exists():
pid=int(pid_path.read_text());proc=Path('/proc')/str(pid)
if proc.exists():
command=(proc/'cmdline').read_bytes().split(b'\0')
expected=str(COPY/'_classic_beta_/WowB.exe');wine_path=('Z:'+expected.replace('/','\\')).encode()
if expected.encode() not in command and wine_path not in command:raise RuntimeError('Experimental PID identity mismatch; inspect before restoring')
os.kill(pid,signal.SIGTERM)
pid=int((ROOT/'runtime/relay.pid').read_text())
if (Path('/proc')/str(pid)).exists():raise RuntimeError('Existing gateway preserved; no duplicate started')
env=dict(os.environ);env.update(json.loads((ROOT/'runtime/native-fallback-flags.json').read_text()))
subprocess.run(['python3',str(ROOT/'ops/run_relay.py')],env=env,check=True)
print('Restored gateway fallback. Original client can be launched with ops/client_ui.py launch.')
if __name__=='__main__':
os.umask(0o077);p=argparse.ArgumentParser();p.add_argument('action',choices=('prepare','run','restore'));p.add_argument('--engine-bridge',action='store_true');p.add_argument('--trace-registration',action='store_true');p.add_argument('--native-registration',action='store_true');a=p.parse_args()
if a.native_registration and a.trace_registration:p.error('The in-process hook and external hardware trace cannot share debug registers')
if a.action=='restore':restore()
else:globals()[a.action](a.engine_bridge or a.trace_registration or a.native_registration,a.trace_registration,a.native_registration)