Files

149 lines
8.2 KiB
Python

#!/usr/bin/env python3
"""Launch the isolated LOCAL editor with read-only rolling database captures."""
import argparse
import datetime
import json
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
import session_capture
import spawn_export
ROOT=Path(__file__).resolve().parents[2]
LOCAL=Path('/mnt/Games/OctoWoW-LOCAL-Client')
HARNESS=Path('/mnt/Games/@project/client-repack-20261124/play-visible-capture.sh')
LOGIN=Path('/home/praxis/.claude/jobs/8f9a0552/tmp/login514/login_as.py')
FORBIDDEN={'PROXYONE','BLESISI'}
def editor_identity(reader=spawn_export.query):
# Existing LOCAL schema. Only EDITOR is selected; no account creation/rank changes.
rows=reader("SELECT a.username,a.rank,c.guid,(SELECT COUNT(*) FROM tw_char.characters c2 WHERE c2.account=c.account) "
"FROM tw_char.characters c JOIN tw_logon.account a ON a.id=c.account WHERE UPPER(c.name)='EDITOR';").splitlines()
if len(rows)!=1:raise ValueError('LOCAL EDITOR character/account is missing or ambiguous; ask Claude to provision it')
account,rank,guid,count=rows[0].split('\t')
if account.upper() in FORBIDDEN or not re.fullmatch(r'[A-Za-z0-9_]{1,32}',account):raise ValueError('Refusing protected or unsupported account')
if int(rank)<3:raise ValueError('EDITOR needs existing developer rank 3 or higher')
if int(count)!=1:raise ValueError('Automatic EDITOR login requires a dedicated one-character account; no other character will be entered')
return {'account':account,'rank':int(rank),'guid':guid,'character':'EDITOR'}
def install_addon(client, source):
addon=Path(client)/'_classic_beta_/Interface/AddOns/OctoEditor'
marker=addon/'.local-editor-owned'
if addon.exists() and not marker.exists():raise ValueError('Existing unowned OctoEditor directory preserved')
addon.mkdir(parents=True,exist_ok=True)
for name in ['OctoEditor.toc','Capture.lua','EditorCore.lua','EditorUI.lua']:
session_capture.atomic(addon/name,(Path(source)/name).read_bytes())
session_capture.atomic(marker,b'LOCAL editor launcher only; never publish\n')
return addon
def session_setup(out, addon, identity, baseline, names, session=None):
out=Path(out);out.mkdir(parents=True,exist_ok=False,mode=0o700)
session=session or uuid.uuid4().hex
meta={'session':session,'character':identity['character'],'character_guid':identity['guid'],
'local_only':True,'interval_seconds':15,'started_utc':datetime.datetime.now(datetime.timezone.utc).isoformat()}
(out/'session.json').write_text(json.dumps(meta,indent=2)+'\n')
spawn_export.validate(baseline)
(out/'baseline.json').write_text(json.dumps(baseline,separators=(',',':'))+'\n')
session_capture.capture(out/'snapshots',addon,session,identity['character'],names,baseline)
return meta
def local_client_running():
for proc in Path('/proc').iterdir():
if not proc.name.isdigit():continue
try:
if (proc/'comm').read_text().strip().lower()=='wowb.exe' and (proc/'cwd').resolve().is_relative_to(LOCAL):return True
except (OSError,ValueError):pass
return False
def login_editor(display_name, out, account, timeout=180):
# Reuse the approved login helper; use only its own nested display for UI observation.
from Xlib import display, X
from PIL import Image
sys.path.insert(0,str(ROOT/'ops'));import client_ui as ui
d=display.Display(display_name)
row=ui.choose_main_window(ui.window_rows(d),expected_pid=None)
win=d.create_resource_object('window',row['id'])
ui.ensure_focus(d,win)
def submit():
subprocess.run([sys.executable,str(LOGIN),display_name,account],check=True,stdout=subprocess.DEVNULL)
def screen():
ui.ensure_focus(d,win);g=win.get_geometry()
pixels=win.get_image(0,0,g.width,g.height,X.ZPixmap,0xffffffff)
image=Image.frombytes('RGB',(g.width,g.height),pixels.data,'raw','BGRX')
path=out/'private-editor-screen.png';image.save(path)
result=subprocess.run(['tesseract',str(path),'stdout','--psm','11'],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,check=True,text=True)
return result.stdout
retry=0;entered=False;submitted=False;deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
time.sleep(2);text=screen();words=re.sub(r'[^a-z0-9]','',text.lower())
if '51900319' in words and retry<1:
ui.click_at(d,win,960,573);submitted=False;retry+=1;continue
if not submitted and ui.is_login_screen(text) and 'disconnected' not in text.lower():
submit();submitted=True;continue
if ui.is_character_select_screen(text) and not entered:
if not submitted:raise RuntimeError('Unexpected pre-authenticated account preserved')
if not re.search(r'\beditor\b',text,re.IGNORECASE):continue
# Identity lookup proved that EDITOR is the account's only character.
ui.key(d,'Return');d.sync();entered=True;continue
if entered and 'localeditor' in words:
(out/'login-result.json').write_text(json.dumps({'character':'EDITOR','editor_ui_observed':True,'retry_count':retry})+'\n');return
raise RuntimeError('EDITOR UI was not observed; client preserved for Claude inspection')
def main():
ap=argparse.ArgumentParser(description=__doc__)
ap.add_argument('--out',type=Path,default=ROOT/'runtime/editor'/datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
ap.add_argument('--prepare-only',action='store_true',help='Prepare LOCAL addon and baseline without launching')
args=ap.parse_args();os.umask(0o077)
args.out=args.out.resolve()
if not re.fullmatch(r'[/A-Za-z0-9_.@-]+',str(args.out)):
raise ValueError('Use a plain session path: the approved shell harness does not quote arbitrary paths')
if args.out.exists():raise ValueError('Session output already exists; choose a new directory')
if local_client_running():raise ValueError('Existing LOCAL client preserved; close it before starting an editor session')
identity=editor_identity()
if not HARNESS.is_file() or not LOGIN.is_file():raise ValueError('Approved LOCAL launch/login harness is unavailable')
baseline=spawn_export.snapshot();names=session_capture.catalog()
addon=install_addon(LOCAL,ROOT/'client_addons/OctoEditor')
meta=session_setup(args.out,addon,identity,baseline,names)
# Preserve the prior SavedVariables export before the new session initializes it.
account_root=LOCAL/'_classic_beta_/WTF/Account'/identity['account'].upper()
for previous in account_root.glob('SavedVariables/OctoEditor.lua'):
shutil.copyfile(previous,args.out/'previous-OctoEditor.lua')
print('LOCAL editor session prepared:',args.out)
if args.prepare_only:return
stop=threading.Event();worker=threading.Thread(target=session_capture.watch,args=(args.out/'snapshots',addon,meta['session'],'EDITOR',names,stop),daemon=True);worker.start()
process=None
try:
with (args.out/'launcher.log').open('w') as log:
process=subprocess.Popen([str(HARNESS),str(args.out)],stdout=log,stderr=subprocess.STDOUT)
end=time.monotonic()+45;display_file=args.out/'display.txt'
while not display_file.exists() and time.monotonic()<end:
if process.poll() is not None:raise RuntimeError('LOCAL client exited during launch')
time.sleep(0.5)
if not display_file.exists():raise RuntimeError('LOCAL nested display was not published')
display_name=display_file.read_text().strip()
if not re.fullmatch(r':\d+(?:\.\d+)?',display_name):raise ValueError('Unexpected LOCAL display identifier')
time.sleep(5);login_editor(display_name,args.out,identity['account'])
print('EDITOR ready. Host snapshots refresh every 15 seconds. Close the client to finish.')
process.wait()
finally:
stop.set();worker.join(timeout=30)
# Do not terminate a client on a login/observation failure.
if process is not None and process.poll() is not None:
for saved in account_root.glob('SavedVariables/OctoEditor.lua'):
shutil.copyfile(saved,args.out/'OctoEditorUndo.lua')
if __name__=='__main__':main()