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

284 lines
19 KiB
Python

#!/usr/bin/env python3
"""Publish one reviewed original ActionBarController branch into a fresh client.
No loose-file priority assumption: preserve the original FileDataID, ROOT names,
all prior TVFS paths/spans and all registered6760 asset payloads. This is a build
helper only; no auth, running client or original storage is changed.
"""
from pathlib import Path
from collections import defaultdict
import bisect,hashlib,json,struct,re
import casc_asset_package as c
import casc_tvfs as t
from casc_local_archive import lookup3_api,encoding_bucket,extend_index,archive_span,parse_index,verified_existing_spans
BASELINE=Path('runtime/all-source-set-bonus-definitions-20261021/spaced-icon-framed-publication')
SOURCE=Path('client_ui/warrior_action_bar/original-ActionBarController.lua')
PATCH=Path('client_ui/warrior_action_bar/ActionBarController.lua')
FID=7430847
OLD_CKEY='9da3c2deb5c0c2d8439f9a4f35f93bd7'
OLD_ROOT='660a3c0452cbb490bb7ce79ed29a9f1c'
SOURCE_SHA='d6edf1e5a09737151c47677c44876bc7c95a84fdd700094570d02dc281db0710'
PATCH_SHA='7fbc7cff6dae842131d3698840c11e0b4b9a23bd44b22e671e635506ecd0e477'
ORIGINAL_BRANCH='elseif (C_ActionBar.HasBonusActionBar() and C_ActionBar.GetActionBarPage() == 1) then'
PATCHED_BRANCH='elseif (C_ActionBar.HasBonusActionBar() and C_ActionBar.GetActionBarPage() == 1 and select(2, UnitClass("player")) ~= "WARRIOR") then'
def validate_patch(original,patched):
if hashlib.sha256(original).hexdigest()!=SOURCE_SHA or hashlib.sha256(patched).hexdigest()!=PATCH_SHA:
raise ValueError('Exact original and reviewed Warrior controller required')
a,b=ORIGINAL_BRANCH.encode(),PATCHED_BRANCH.encode()
if original.count(a)!=1 or patched!=original.replace(a,b,1):
raise ValueError('Only the reviewed original Warrior bonus-bar branch may change')
def md5(b):return hashlib.md5(b).hexdigest()
def sha(b):return hashlib.sha256(b).hexdigest()
def patch_root(raw,key):
if md5(raw)!=OLD_ROOT:raise ValueError('Exact6760ROOT required')
groups=c.root_groups(raw);controls=c.root_controls(raw,groups,{FID})[FID]
if len(controls)!=1 or controls[0]['content_key']!=OLD_CKEY:raise ValueError('Exact unique original ActionBarController resource required')
out=bytearray(raw);matches=[]
for g in groups['groups']:
ident=0
for i,(delta,)in enumerate(struct.iter_unpack('<I',raw[g['ids_offset']:g['ckeys_offset']])):
ident+=delta
if ident==FID:
at=g['ckeys_offset']+16*i;out[at:at+16]=bytes.fromhex(key);matches.append(at)
ident+=1
if len(matches)!=1:raise ValueError('Unique ROOT offset required')
at=matches[0];result=bytes(out)
if result[:at]!=raw[:at]or result[at+16:]!=raw[at+16:]:raise ValueError('Unrelated ROOT bytes changed')
return result,{'file_data_id':FID,'old_content_key':OLD_CKEY,'new_content_key':key,'offset':at,'changed_bytes':16,'all_other_root_bytes_identical':True}
def encoding_keys(raw,key):
sections=c.encoding_layout(raw)['sections']['content'];needle=bytes.fromhex(key);i=bisect.bisect_right([x[0]for x in sections],needle)-1
if i<0:raise ValueError('Original content missing from ENCODING')
row=next(v for k,v in c._encoding_entries(sections[i][1],'content')if k==needle)
return [row[22+j*16:38+j*16]for j in range(row[0])]
def verified_sources(source_root):
root=Path(source_root).resolve()
payloads=[]
for relative in (SOURCE,PATCH):
path=root/relative
if path.is_symlink() or not path.is_file() or not path.resolve().is_relative_to(root) or path.stat().st_size>262144:
raise ValueError('Regular source-bound Warrior UI file required')
if any(p.is_symlink() for p in path.parents if p!=root and p.is_relative_to(root)):
raise ValueError('Warrior UI source parent is a symlink')
payloads.append(path.read_bytes())
validate_patch(*payloads)
return tuple(payloads)
def stage_ui_assets(source_root,output):
ROOT=Path(source_root).resolve();BASE=ROOT/BASELINE;ORIGINAL=ROOT/SOURCE;PATCHED=ROOT/PATCH
out=Path(output).resolve()
if out.exists():raise ValueError('Fresh probe stage required')
original,payload=verified_sources(ROOT)
if sha(original)!=SOURCE_SHA or md5(original)!=OLD_CKEY:raise ValueError('Original Glue source differs')
old=json.loads((BASE/'manifest.json').read_text());inputs={};rows=[]
def read(label,path=None):
path=path or BASE/label;b=path.read_bytes();inputs[str(path.relative_to(ROOT))]=sha(b);return b
root_old=read(old['root']['decoded_file']);encoding_old=read(old['encoding']['decoded_file']);download_old=read(old['download']['decoded_file']);child_old=read(old['tvfs']['child']['decoded_file']);parent_old=read(old['tvfs']['root']['decoded_file'])
if md5(root_old)!=OLD_ROOT or old['registered_asset_count']!=6760:raise ValueError('Exact6760framed baseline required')
validate_patch(original,payload)
root_new,root_audit=patch_root(root_old,md5(payload))
out.mkdir();(out/'decoded').mkdir()
def publish(raw,label,method='Z'):
chunks=[(raw,'N')]if method=='N'else[(raw[i:i+262144],'Z')for i in range(0,len(raw),262144)]
encoded,r=c.blte_framed(chunks);r.update(file=r['encoding_key']+'.blte',decoded_file='decoded/'+label,source_file=label,source_files=[label],encoding_spec=c.blte_frame_spec(chunks));(out/r['file']).write_bytes(encoded);(out/r['decoded_file']).write_bytes(raw);rows.append(r);return r
ui=publish(payload,'ActionBarController.lua','N');root=publish(root_new,'root.bin')
layout=c.download_layout(download_old);keys=encoding_keys(encoding_old,OLD_CKEY);found=c.download_controls(download_old,layout,set(keys))
if not found:raise ValueError('Original exact UI DOWNLOAD control absent')
control=next(k for k in keys if k in found).hex()
download_raw,download_audit=c.extend_download(download_old,[dict(encoding_key=ui['encoding_key'],encoded_size=ui['encoded_size'],native_control_ekey=control),dict(encoding_key=root['encoding_key'],encoded_size=root['encoded_size'],native_control_ekey=old['root']['encoding_key'])],expected_download_md5=md5(download_old));download=publish(download_raw,'download.bin')
h=t.layout(child_old);paths=t.paths(child_old,h);old_name=f'{FID:08X}'+OLD_CKEY.upper();new_name=f'{FID:08X}'+ui['content_key'].upper()
if old_name not in paths or new_name in paths or sum(n[:8]==f'{FID:08X}'for n in paths)!=1:raise ValueError('Exact unique existing UI TVFS identity required')
# Explicit reviewed same-ID new-content diagnostic; preserve the old path too.
fields=('content_key','encoding_key','decoded_size','encoded_size','encoding_spec')
child_raw,child_audit=t._stage_references(child_old,{new_name:{k:ui[k]for k in fields}},h,paths)
new_h=t.layout(child_raw);new_paths=t.paths(child_raw,new_h)
if len(new_paths)!=len(paths)+1 or any(n not in new_paths for n in paths):raise ValueError('Old TVFS paths were lost')
for n in paths:
if t.spans(child_old,paths[n],h)!=t.spans(child_raw,new_paths[n],new_h):raise ValueError('Old TVFS span changed')
child=publish(child_raw,'tvfs-default.bin');ph=t.layout(parent_old);pindex=t.paths(parent_old,ph);refs={}
for name,row in ((old['tvfs']['child_name'],child),('.root',root)):
spec=t.container_record(parent_old,t.spans(parent_old,pindex[name],ph)[0],ph)['encoding_spec'];refs[name]={k:row[k]for k in fields if k!='encoding_spec'};refs[name]['encoding_spec']=spec
parent_raw,parent_audit=t.replace_references(parent_old,refs,expected_md5=md5(parent_old));parent=publish(parent_raw,'tvfs-root.bin')
encoded_raw,encoding_audit=c.extend_encoding(encoding_old,[{k:r[k]for k in fields}for r in rows],expected_encoding_md5=md5(encoding_old))
encoded_body,encoded,encoding=c.frame_encoding(encoded_raw);encoding.update(file=encoding['encoding_key']+'.blte',decoded_file='encoding.bin');(out/encoding['file']).write_bytes(encoded);(out/'encoding.bin').write_bytes(encoded_body)
report={'kind':'exact-original-warrior-action-bar-casc-stage','patched_source_sha256':PATCH_SHA,'assets':rows,'root':root,'download':download,'encoding':encoding,'tvfs':{'root':parent,'child':child,'child_number':old['tvfs']['child_number'],'child_name':old['tvfs']['child_name']},'registered_asset_count':6760,'reviewed_ui_payload_count':1,'baseline_manifest':str((BASE/'manifest.json').relative_to(ROOT)),'baseline_manifest_sha256':sha((BASE/'manifest.json').read_bytes()),'root_audit':root_audit,'download_audit':download_audit,'encoding_audit':encoding_audit,'tvfs_child_audit':child_audit,'tvfs_parent_audit':parent_audit,'all_old_tvfs_paths_and_spans_preserved':True,'old_tvfs_paths':len(paths),'source_sha256':SOURCE_SHA,'input_sha256':inputs,'installed':False,'engine_loaded':False,'presentation_changed':True,'authentication_performed':False,'limits':['Only the original Warrior bonus-bar branch changes.','Actual native controller loading and stance behavior require fresh-candidate acceptance.','Druid, vehicle, override, temporary shapeshift and manual-page branches are preserved.']}
(out/'manifest.json').write_text(json.dumps(report,indent=2)+'\n');return report
def apply_to_fresh_client(source_root,client_target,stage_directory,*,running_check):
target_argument=Path(client_target).absolute()
if target_argument.is_symlink() or any(p.is_symlink() for p in target_argument.parents):
raise ValueError('Fresh client path may not contain symlinks')
ROOT = Path(source_root).resolve()
source = ROOT / 'runtime/native-client'
package = Path(stage_directory).resolve()
manifest = json.loads((package / 'manifest.json').read_text())
output = Path(client_target).resolve()
if not (output.is_dir() and (not output.is_symlink())):
raise ValueError('Strict fresh-client CASC assembly guard failed')
if not (output / '.build.info').read_bytes() == (source / '.build.info').read_bytes():
raise ValueError('Strict fresh-client CASC assembly guard failed')
if not not running_check(output):
raise ValueError('Strict fresh-client CASC assembly guard failed')
if not source != output:
raise ValueError('Strict fresh-client CASC assembly guard failed')
if not (source == ROOT / 'runtime/native-client' and not output.is_relative_to(source)):
raise ValueError('Strict fresh-client CASC assembly guard failed')
rows = (source / '.build.info').read_text().splitlines()
headers = [x.split('!')[0] for x in rows[0].split('|')]
active = [dict(zip(headers, x.split('|'))) for x in rows[1:] if x]
active = [x for x in active if x.get('Active') == '1' and x.get('Product') == 'wow_classic_beta']
if not (len(active) == 1 and active[0]['Version'] == '1.60.1.70334'):
raise ValueError('Strict fresh-client CASC assembly guard failed')
identity = dict(build_key=active[0]['Build Key'], version=active[0]['Version'])
_key = identity['build_key']
_config = (source / 'Data/config' / _key[:2] / _key[2:4] / _key).read_text()
if not re.search('^root = ([0-9a-f]{32})$', _config, re.M)[1] == '660a3c0452cbb490bb7ce79ed29a9f1c':
raise ValueError('Strict fresh-client CASC assembly guard failed')
source_build_info_sha256 = hashlib.sha256((source / '.build.info').read_bytes()).hexdigest()
_helper = ROOT / 'build/casc-package-helpers'
_src = ROOT.parent / 'tools/casc-tool/vendor/CascLib/src/jenkins'
if not ((_helper / 'liblookup3.so').is_file() and (_helper / 'source.sha256').read_text().strip() == hashlib.sha256((_src / 'lookup3.c').read_bytes() + (_src / 'lookup.h').read_bytes()).hexdigest()):
raise ValueError('Existing verified lookup3 helper required; no builds permitted')
api, pin = lookup3_api()
srcdata = source / 'Data/data'
destdata = output / 'Data/data'
segment = max((int(p.name[5:]) for p in srcdata.glob('data.[0-9][0-9][0-9]'))) + 1
if not not (destdata / f'data.{segment:03d}').exists():
raise ValueError('Strict fresh-client CASC assembly guard failed')
new_entries = defaultdict(list)
spans = []
offset = 0
with (destdata / f'data.{segment:03d}').open('xb') as f:
for row in manifest['assets'] + [manifest['encoding']]:
if not re.fullmatch('[0-9a-f]{32}\\.blte', row['file']):
raise ValueError('Strict fresh-client CASC assembly guard failed')
b = (package / row['file']).read_bytes()
from casc_asset_package import blte_encoding_key
if not blte_encoding_key(b).hex() == row['encoding_key']:
raise ValueError('Strict fresh-client CASC assembly guard failed')
if not hashlib.md5((package / row['decoded_file']).read_bytes()).hexdigest() == row['content_key']:
raise ValueError('Strict fresh-client CASC assembly guard failed')
pad = -offset % 16
f.write(bytes(pad))
offset += pad
span, key = archive_span(b, offset, api)
f.write(span)
bucket = encoding_bucket(key)
record = dict(encoding_key=key, segment=segment, offset=offset, span_size=len(span))
new_entries[bucket].append(record)
spans.append(dict(record, encoding_key=key.hex()))
offset += len(span)
latest = {}
for p in srcdata.glob('*.idx'):
bucket = int(p.name[:2], 16)
generation = int(p.name[2:10], 16)
if bucket not in latest or generation > latest[bucket][0]:
latest[bucket] = (generation, p)
if not len(latest) == 16:
raise ValueError('Strict fresh-client CASC assembly guard failed')
audits = []
reused = []
encoded_by_key = {r['encoding_key']: (package / r['file']).read_bytes() for r in manifest['assets'] + [manifest['encoding']]}
def read_existing(segment, offset, size):
path = srcdata / f'data.{segment:03d}'
if not (path.is_file() and (not path.is_symlink()) and (path.stat().st_size >= offset + size)):
raise ValueError('Strict fresh-client CASC assembly guard failed')
with path.open('rb') as stream:
stream.seek(offset)
return stream.read(size)
for bucket, (generation, p) in sorted(latest.items()):
raw = p.read_bytes()
parse_index(raw, bucket, api)
if bucket not in new_entries:
continue
pending = []
additions = new_entries.pop(bucket)
checked_spans = verified_existing_spans(raw, bucket, [encoded_by_key[a['encoding_key'].hex()] for a in additions], read_existing, api)
for addition, checked in zip(additions, checked_spans):
if checked is None:
pending.append(addition)
else:
reused.append(checked)
if not pending:
continue
updated, audit = extend_index(raw, bucket, pending, api)
name = f'{bucket:02x}{generation + 1:08x}.idx'
path = destdata / name
if not not path.exists():
raise ValueError('Strict fresh-client CASC assembly guard failed')
path.write_bytes(updated)
audits.append(dict(old_file=p.name, new_file=name, **audit))
if not not new_entries:
raise ValueError('Strict fresh-client CASC assembly guard failed')
cache = output / 'preserved-derived-mappings'
cache.mkdir()
preserved = []
for relative in ('data/shmem', 'ecache/shmem', 'wow_classic_beta/shmem'):
p = output / 'Data' / relative
if p.exists():
dst = cache / relative
dst.parent.mkdir(parents=True, exist_ok=True)
p.rename(dst)
preserved.append(relative)
lines = (source / '.build.info').read_text().splitlines()
head = lines[0].split('|')
ki = next((i for i, k in enumerate(head) if k.startswith('Build Key!')))
pi = next((i for i, k in enumerate(head) if k.startswith('Product!')))
matched = 0
for i, line in enumerate(lines[1:], 1):
row = line.split('|')
if row[pi] != 'wow_classic_beta':
continue
matched += 1
old = row[ki]
if not old == identity['build_key']:
raise ValueError('Strict fresh-client CASC assembly guard failed')
raw = (source / 'Data/config' / old[:2] / old[2:4] / old).read_bytes()
if not hashlib.md5(raw).hexdigest() == old:
raise ValueError('Strict fresh-client CASC assembly guard failed')
text = raw.decode()
enc = manifest['encoding']
for field, value in [('root', manifest['root']['content_key']), ('encoding', enc['content_key'] + ' ' + enc['encoding_key']), ('encoding-size', str(enc['decoded_size']) + ' ' + str(enc['encoded_size'])), ('download', manifest['download']['content_key'] + ' ' + manifest['download']['encoding_key']), ('download-size', str(manifest['download']['decoded_size']) + ' ' + str(manifest['download']['encoded_size']))]:
text, n = re.subn('^' + re.escape(field) + ' = [^\\r\\n]*$', field + ' = ' + value, text, flags=re.M)
if not n == 1:
raise ValueError('Strict fresh-client CASC assembly guard failed')
for field, obj in [('vfs-root', manifest['tvfs']['root']), ('vfs-1', manifest['tvfs']['root']), ('vfs-820', manifest['tvfs']['child'])]:
for suffix, value in [('', obj['content_key'] + ' ' + obj['encoding_key']), ('-size', str(obj['decoded_size']) + ' ' + str(obj['encoded_size']))]:
text, n = re.subn('^' + re.escape(field + suffix) + ' = [^\\r\\n]*$', field + suffix + ' = ' + value, text, flags=re.M)
if not n == 1:
raise ValueError('Strict fresh-client CASC assembly guard failed')
updated = text.encode()
new = hashlib.md5(updated).hexdigest()
p = output / 'Data/config' / new[:2] / new[2:4] / new
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(updated)
row[ki] = new
lines[i] = '|'.join(row)
if not matched == 1:
raise ValueError('Strict fresh-client CASC assembly guard failed')
(output / '.build.info').write_text('\n'.join(lines) + '\n')
report = dict(kind='independent-cow-native-casc-candidate', original_build_config=old, new_build_config=new, actual_version=identity['version'], independent_cow_data=True, existing_index_generations_preserved=True, new_index_generations=audits, exact_existing_payloads_reused=reused, preserved_candidate_derived_mappings=preserved, new_segment=segment, lookup3_source_sha256=pin, spans=spans, root_group_order_preserved=True, download_publication_complete=True, native_seven_section_encoding_framing=True, all_objects_explicitly_framed=True, size_manifest_preserved_unmodified=True, native_tvfs_registered=True, installed=False, engine_verified=False)
(output / 'warrior-action-bar-casc.json').write_text(json.dumps(report, indent=2) + '\n')
if not hashlib.sha256((source / '.build.info').read_bytes()).hexdigest() == source_build_info_sha256:
raise ValueError('Strict fresh-client CASC assembly guard failed')
if not not running_check(output):
raise ValueError('Strict fresh-client CASC assembly guard failed')
report['kind']='fresh-client-warrior-original-actionbar-casc'
report['original_file_data_id']=FID
report['source_sha256']=SOURCE_SHA
report['patched_source_sha256']=PATCH_SHA
report['registered_asset_count']=6760
report['native_engine_acceptance_verified']=False
created={'.build.info':sha((output/'.build.info').read_bytes())}
for path in (output/'Data').rglob('*'):
if path.is_file() and not (source/path.relative_to(output)).exists():
if path.is_symlink():raise ValueError('Fresh CASC payload path is a symlink')
created[str(path.relative_to(output))]=sha(path.read_bytes())
report['published_files_sha256']=created
(output/'warrior-action-bar-casc.json').write_text(json.dumps(report,indent=2)+'\n')
return report