Files
WoW-Hybrid-gateway/ops/install_console_diagnostics.py
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

172 lines
13 KiB
Python

#!/usr/bin/env python3
"""Install the removable local addon without overwriting existing client files."""
import datetime
import argparse
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
ROOT = Path(__file__).resolve().parents[1]
CLIENT = Path('/mnt/Games/Games/WoW-Forever/_classic_beta_')
source = ROOT/'client_addons/GatewayDiagnostics'
def addon_files(include_turtle=False, weapon_payload=None):
"""Compose existing modules in dependency order, without touching a client."""
files={p.name:p.read_bytes() for p in source.iterdir() if p.is_file()}
if include_turtle:
files['TurtleData.lua']=(ROOT/'build/turtle-data/TurtleData.lua').read_bytes()
# Original base OnLoad is the verified pre-configuration boundary.
files['GatewayDiagnostics.toc']+=b'\n## Dependencies: Blizzard_SharedTalentUI\n'
files['GatewayDiagnostics.toc']+=b'\nTurtleData.lua\nTurtleTalentProvider.lua\nTurtleTalents.lua\n'
files['GatewayDiagnostics.toc']=files['GatewayDiagnostics.toc'].replace(b'no networking or character mutations.',b'optional Turtle talent provider uses authenticated compatibility-session state.')
if weapon_payload is not None:
if not isinstance(weapon_payload,bytes) or not 0<len(weapon_payload)<=1048576:
raise ValueError('Weapon presentation payload bound')
files['SourceWeaponDamageData.lua']=weapon_payload
files['GatewayDiagnostics.toc']+=b'\nSourceWeaponDamageData.lua\nSourceWeaponDamage.lua\n'
return files
def weapon_only_files(target, previous, payload):
"""Update only already-owned weapon files; retain later talent diagnostics.
Unrelated installed modules are not regenerated from older repository or
build outputs. Their exact bytes and hashes are retained in the new recovery.
Changes to the two owned files or load order still require separate review.
"""
replacements=addon_files(weapon_payload=payload)
owned=('SourceWeaponDamageData.lua','SourceWeaponDamage.lua')
required=owned+('GatewayDiagnostics.toc',)
files={p.name:p.read_bytes() for p in target.iterdir() if p.is_file() and not p.is_symlink()}
if set(files)!=set(previous['files']):raise RuntimeError('Unexpected addon files; preserve and review')
for name in required:
if name not in files or hashlib.sha256(files[name]).hexdigest()!=previous['files'].get(name):
raise RuntimeError('Owned weapon file/load order changed; preserve and review: '+name)
toc=files['GatewayDiagnostics.toc'].decode().splitlines()
if any(toc.count(name)!=1 for name in owned) or toc.index(owned[0])>=toc.index(owned[1]):
raise RuntimeError('Weapon provider load order differs')
for name in owned:files[name]=replacements[name]
return files
def talent_only_files(target,previous,profile):
"""Preserve all installed modules while replacing one staged data/provider group."""
from console_report import parse
profile=profile.resolve()
if not profile.is_relative_to(ROOT/'runtime'):raise ValueError('Require staged private talent profile')
manifest=json.loads((profile/'manifest.json').read_text())
if (manifest.get('kind')!='staged-talent-presentation'or manifest.get('schema_version')!=1 or
manifest.get('installed')is not False or manifest.get('engine_loaded')is not False or manifest.get('server_changed')is not False or
set(manifest.get('files',{}))!={'TurtleData.lua','talent-data.json','report.json'}):raise ValueError('Require complete staged talent manifest')
for name,expected in manifest['files'].items():
path=profile/name
if path.is_symlink()or not path.is_file()or path.stat().st_size>4194304 or hashlib.sha256(path.read_bytes()).hexdigest()!=expected:raise ValueError('Talent profile artifact differs: '+name)
report=json.loads((profile/'report.json').read_text())
if (report.get('kind')!='octo-talent-presentation-refresh'or report.get('schema_version')!=1 or
report.get('engine_loaded')is not False or report.get('gameplay_verified')is not False or report.get('relationships_or_server_state_changed')is not False or
report.get('converter_sha256')!=hashlib.sha256((ROOT/'ops/turtle_data.py').read_bytes()).hexdigest()):raise ValueError('Talent converter/report context differs')
def read_data(raw):
text=raw.decode();header,body=text.split('\n',1)
if not header.startswith('-- Generated from '):raise ValueError('Talent data header differs')
return parse(body,variable='GatewayTurtleData',max_tokens=500000)
payload=(profile/'TurtleData.lua').read_bytes();new=read_data(payload)
files={p.name:p.read_bytes()for p in target.iterdir()if p.is_file()and not p.is_symlink()}
if set(files)!=set(previous['files']):raise RuntimeError('Unexpected installed addon files; preserve and review')
if any(hashlib.sha256(raw).hexdigest()!=previous['files'][name]for name,raw in files.items()):raise RuntimeError('Installed addon differs from recovery; preserve and review')
owned=('TurtleData.lua','TurtleTalentProvider.lua','TurtleTalents.lua')
if any(name not in files for name in owned):raise RuntimeError('Require existing native talent provider group')
toc=files['GatewayDiagnostics.toc'].decode().splitlines()
if any(toc.count(name)!=1 for name in owned)or not toc.index(owned[0])<toc.index(owned[1])<toc.index(owned[2]):raise RuntimeError('Talent provider load order differs')
def relationships(value):
shape=dict(tabs=value['tabs'],talents=[dict({k:v for k,v in t.items()if k!='ranks'},ranks=[r['id']for r in t['ranks']])for t in value['talents']])
return hashlib.sha256(json.dumps(shape,sort_keys=True,separators=(',',':'),ensure_ascii=False,allow_nan=False).encode()).hexdigest()
if relationships(new)!=report.get('relationship_sha256')or relationships(read_data(files['TurtleData.lua']))!=report['relationship_sha256']:
raise ValueError('Talent baseline/tree identity differs; preserve installed state')
files['TurtleData.lua']=payload
for name in owned[1:]:files[name]=(source/name).read_bytes()
return files,dict(directory=str(profile),manifest_sha256=hashlib.sha256((profile/'manifest.json').read_bytes()).hexdigest(),report_sha256=manifest['files']['report.json'])
def main():
parser=argparse.ArgumentParser();parser.add_argument('--update',action='store_true');parser.add_argument('--turtle-talents',action='store_true')
parser.add_argument('--weapon-presentation-only',action='store_true',help='Preserve all other installed addon files; update only the two manifest-owned weapon files')
parser.add_argument('--talent-presentation-only',type=Path,help='Install a validated staged talent data/provider group; preserve every unrelated installed module')
parser.add_argument('--client-root',type=Path,default=CLIENT,help='Explicit original or disposable _classic_beta_ directory; no other client installations')
parser.add_argument('--source-weapon-damage-profile',type=Path,help='Enable verified generated secondary weapon tooltip metadata; never changes engine damage')
parser.add_argument('--source-snapshot',type=Path,default=ROOT/'runtime/all-item-templates-20261017')
parser.add_argument('--spell-defines',type=Path,default=Path('/home/praxis/Servers/tortoise-wow/src/game/Spells/SpellDefines.h'))
args=parser.parse_args();selected=args.client_root.resolve()
if selected!=CLIENT.resolve():
from client_installation import COPY,inspect_installation
if selected!=COPY.resolve()/'_classic_beta_':raise RuntimeError('Only the journaled disposable client or original development installation is allowed')
inspect_installation(COPY)
target=selected/'Interface/AddOns/GatewayDiagnostics'
include_turtle=args.turtle_talents;previous=None
if target.exists():
if not args.update:raise RuntimeError('Diagnostic addon already exists; use --update after review')
histories=[p for p in sorted((ROOT/'recovery').glob('console-addon-*/manifest.json'))
if json.loads(p.read_text()).get('added_directory')==str(target)]
if not histories:raise RuntimeError('Addon ownership manifest missing')
previous=json.loads(histories[-1].read_text())
include_turtle|='TurtleData.lua' in previous['files']
if set(p.name for p in target.iterdir())!=set(previous['files']):raise RuntimeError('Unexpected client addon files; preserve and review')
if not args.weapon_presentation_only:
for name,expected in previous['files'].items():
if hashlib.sha256((target/name).read_bytes()).hexdigest()!=expected:raise RuntimeError('Installed addon changed; preserve and review')
if args.weapon_presentation_only and (not args.update or previous is None or args.turtle_talents):
raise ValueError('Weapon-only update requires an existing recovery and --update, without talent regeneration')
if args.talent_presentation_only and (not args.update or previous is None or args.turtle_talents or args.weapon_presentation_only or args.source_weapon_damage_profile):
raise ValueError('Talent-only update requires existing recovery and --update, without other presentation regeneration')
if previous and 'source_talent_presentation_profile'in previous and not(args.talent_presentation_only or args.weapon_presentation_only):
raise ValueError('Preserve installed Octo talent profile; select a focused presentation update instead of regenerating older talent data')
weapon_payload=None;weapon_manifest=None
profile=args.source_weapon_damage_profile
if profile is None and previous and 'SourceWeaponDamageData.lua' in previous['files']:
prior=previous.get('source_weapon_damage_profile')
if not isinstance(prior,dict):raise RuntimeError('Enabled weapon profile provenance missing; preserve and review')
profile=Path(prior['directory']);args.source_snapshot=Path(prior['source_snapshot']);args.spell_defines=Path(prior['spell_defines'])
if profile is not None:
if not profile.resolve().is_relative_to(ROOT/'runtime'):raise ValueError('Weapon profile must be staged in private runtime')
from item_damage_profile import verified_payload
weapon_payload,weapon_manifest=verified_payload(profile,args.source_snapshot,args.spell_defines)
talent_manifest=None
if args.talent_presentation_only:
files,talent_manifest=talent_only_files(target,previous,args.talent_presentation_only)
elif args.weapon_presentation_only:
files=weapon_only_files(target,previous,weapon_payload)
else:files=addon_files(include_turtle,weapon_payload)
for name in files:
if name.endswith('.lua'):
checked=subprocess.run(['luac','-p','-'],input=files[name],capture_output=True)
if checked.returncode:raise RuntimeError('Addon Lua syntax validation failed: '+name)
# All inputs are validated before creating the recoverable update.
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
recovery = ROOT/'recovery'/('console-addon-'+stamp)
recovery.mkdir(mode=0o700)
shutil.copy2(selected/'WTF/Config.wtf', recovery/'Config.wtf')
(recovery/'Config.wtf').chmod(0o600)
manifest = {'added_directory': str(target), 'files': {name: hashlib.sha256(data).hexdigest() for name,data in files.items()}}
if args.weapon_presentation_only:
manifest['update_scope']='existing-owned-weapon-presentation-only'
manifest['preserved_installed_changes']=[name for name,raw in files.items()
if name not in ('SourceWeaponDamageData.lua','SourceWeaponDamage.lua') and hashlib.sha256(raw).hexdigest()!=previous['files'][name]]
if weapon_manifest is not None:manifest['source_weapon_damage_profile']=weapon_manifest
if talent_manifest is not None:
manifest['update_scope']='existing-native-talent-presentation-only'
manifest['source_talent_presentation_profile']=talent_manifest
elif previous and 'source_talent_presentation_profile'in previous:
manifest['source_talent_presentation_profile']=previous['source_talent_presentation_profile']
(recovery/'manifest.json').write_text(json.dumps(manifest, indent=2)+'\n')
(recovery/'RESTORE.txt').write_text('Stop only the local WowB test client. Remove only the added GatewayDiagnostics addon directory after checking its manifest; optionally remove its SavedVariables file. Existing addons and executable are untouched. Config.wtf backup is available here. For an update rollback, restore previous-addon to the added directory instead of removing the addon.\n')
if target.exists():
shutil.copytree(target,recovery/'previous-addon')
else:target.mkdir()
for name,data in files.items():(target/name).write_bytes(data)
print('Installed removable local GatewayDiagnostics addon; recovery:', recovery)
if __name__=='__main__':main()