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

119 lines
7.9 KiB
Python

#!/usr/bin/env python3
"""Read original item APIs in an authenticated local native world.
Compare source identity and scalar stats; no item grants, equipment changes,
database writes, API overrides or claims about model/proc/gameplay equivalence.
"""
import argparse,json,secrets,time
from pathlib import Path
from client_session import Session
from console_report import parse
from native_engine_character_test import ROOT,Controller,local_listeners
from native_test_guard import require_authenticated_turtle_realm,require_local_turtle_ports
from native_source_artwork_test import indexed_entries
import client_ui as ui
STAT_NAMES={0:'ITEM_MOD_MANA_SHORT',1:'ITEM_MOD_HEALTH_SHORT',3:'ITEM_MOD_AGILITY_SHORT',4:'ITEM_MOD_STRENGTH_SHORT',5:'ITEM_MOD_INTELLECT_SHORT',6:'ITEM_MOD_SPIRIT_SHORT',7:'ITEM_MOD_STAMINA_SHORT'}
def expected_stats(proto):
result={}
for i in range(1,11):
value=proto['stat_value'+str(i)]
if value:
name=STAT_NAMES[proto['stat_type'+str(i)]];result[name]=result.get(name,0)+value
for field,name in [('armor','RESISTANCE0_NAME'),('block','ITEM_MOD_BLOCK_VALUE_SHORT')]+[(field,'RESISTANCE'+str(i)+'_NAME')for field,i in [('holy_res',1),('fire_res',2),('nature_res',3),('frost_res',4),('shadow_res',5),('arcane_res',6)]]:
if proto[field]:result[name]=proto[field]
return result
def source_level_matches(source_level,observed):
"""Keep raw source levels: original UI can show effective1 for base0."""
if 'baseLevel'in observed or 'effectiveLevel'in observed:
return (type(observed.get('baseLevel'))is int and type(observed.get('effectiveLevel'))is int
and observed['baseLevel']==source_level and observed['effectiveLevel']==observed.get('level'))
return type(observed.get('level'))is int and observed['level']==source_level
def persist_probe(session,controller,observed,*,world_ready=None):
"""A reload may complete while its outgoing chat acknowledgement times out.
Never replay ReloadUI. Only a caller's fresh nonce in saved data followed by
actual world readiness can confirm that the already submitted action ran.
"""
warning=None
try:session.macro('/run ReloadUI()')
except RuntimeError as error:
if str(error)!='Chat edit readiness/submission unconfirmed; no automatic replay':raise
warning=str(error)
data=controller.wait(observed,15)
if world_ready is None:
session.wait_world(timeout=15)
else:
world_ready()
return data,warning
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--source',type=Path,required=True)
p.add_argument('--items',type=int,nargs='+',required=True);p.add_argument('--output',type=Path,required=True)
p.add_argument('--bag-family',action='store_true',help='Also verify original item-family API against the reviewed source-category conversion');a=p.parse_args()
if not a.output.resolve().is_relative_to(ROOT/'runtime')or a.output.exists()or not 1<=len(a.items)<=12 or len(set(a.items))!=len(a.items):p.error('Fresh runtime evidence and1..12 distinct source IDs required')
source={r['entry']:r for r in json.loads(a.source.read_bytes())}
if not set(a.items)<=set(source):raise ValueError('Sample source missing')
expected={i:expected_stats(source[i])for i in a.items}
require_local_turtle_ports(local_listeners());c=Controller(int((ROOT/'runtime/native-client.pid').read_text()));require_authenticated_turtle_realm(c.rpc('inspect-wire-account'))
pipe=c.rpc('inspect-engine-pipe')
if pipe['error']or pipe['closed']or not pipe['world_auth']or not pipe['world']['self_create']:raise RuntimeError('Actual native world required')
run=secrets.token_hex(4);old=ui.KEY_DELAY;started=time.monotonic();reload_warnings=[]
# Keep protected/UI actions on the actual hardware-input macro path. A
# timer callback must never own ReloadUI or silently bypass its rejection.
commands=['/run GatewayDiagnosticsSaved.bulkMetadata={run="'+run+'",items={}}']
for offset in range(0,len(a.items),3):
ids=','.join(map(str,a.items[offset:offset+3]))
commands.append('/run for _,i in ipairs({'+ids+'}) do local n,l,q,v=C_Item.GetItemInfo(i);GatewayDiagnosticsSaved.bulkMetadata.items[i]={name=n,quality=q,level=v,stats=C_Item.GetItemStats("item:"..i)} end')
for offset in range(0,len(a.items),3):
ids=','.join(map(str,a.items[offset:offset+3]))
commands.append('/run for _,i in ipairs({'+ids+'}) do local f=C_Item.GetDetailedItemLevelInfo;if type(f)=="function" then local a,p,b=f(i);local t=GatewayDiagnosticsSaved.bulkMetadata.items[i];t.baseLevel=b;t.effectiveLevel=a end end')
if a.bag_family:
for offset in range(0,len(a.items),6):
ids=','.join(map(str,a.items[offset:offset+6]))
commands.append('/run for _,i in ipairs({'+ids+'}) do local f=C_Item.GetItemFamily;GatewayDiagnosticsSaved.bulkMetadata.items[i].family=type(f)=="function" and f(i) or false end')
if any(len(s)>255 for s in commands):raise ValueError('Read-only probe input bound')
saved=ROOT/'runtime/native-client/_classic_beta_/WTF/Account/SavedVariables/GatewayDiagnostics.lua'
try:
with Session(c.pid)as s:
s.wait_world();ui.KEY_DELAY=.03
def observed():
try:
value=parse(saved.read_text()).get('bulkMetadata',{})
return value if value.get('run')==run else None
except (OSError,ValueError):return None
for attempt in range(1,4):
if attempt>1:run=secrets.token_hex(4);commands[0]='/run GatewayDiagnosticsSaved.bulkMetadata={run="'+run+'",items={}}'
a.output.with_suffix('.plan.json').write_text(json.dumps(dict(run=run,pid=c.pid,items=a.items,attempt=attempt),indent=2)+'\n')
for index,command in enumerate(commands,1):
s.macro(command);print('Read-only item probe pass',attempt,'command',index,'/',len(commands),flush=True)
data,warning=persist_probe(s,c,observed)
if warning:reload_warnings.append(warning)
actual=dict(indexed_entries(data['items']))
ready=all(actual.get(i,{}).get('name')for i in a.items)
if ready:break
ui.key(s.d,'c');s.shot(a.output.with_suffix('.png'));ui.key(s.d,'c')
finally:ui.KEY_DELAY=old
actual=dict(indexed_entries(data['items']));samples=[]
for ident in a.items:
proto=source[ident];row=actual.get(ident,{})
valid=(row.get('name')==proto['name']and row.get('quality')==proto['quality']and source_level_matches(proto['item_level'],row)
and all((row.get('stats')or{}).get(k)==v for k,v in expected[ident].items()))
if a.bag_family:
from item_sparse_compat import bag_family_mask
valid=valid and type(row.get('family'))is int and row['family']==bag_family_mask(proto['bag_family'])
samples.append(dict(entry=ident,name=proto['name'],observed=row,expected_stats=expected[ident],expected_base_item_level=proto['item_level'],source_fields_match=valid))
report=dict(kind='actual-native-item-metadata-samples',pid=c.pid,local_only=True,external_gateway_running=False,
samples=samples,item_data_ready=ready,readiness_passes=attempt,all_samples_match=all(s['source_fields_match']for s in samples),elapsed_seconds=round(time.monotonic()-started,3),
character_or_database_modified=False,models_or_equipped_effects_verified=False,
saved_nonce=run,reload_acknowledgement_warnings=reload_warnings,
additional_saved_item_ids=sorted(set(actual)-set(a.items)))
if a.bag_family:report['expected_item_family_masks']={str(i):bag_family_mask(source[i]['bag_family'])for i in a.items}
a.output.write_text(json.dumps(report,indent=2)+'\n');print('Original item metadata samples:',sum(s['source_fields_match']for s in samples),'/',len(samples),'report:',a.output)
return 0 if report['all_samples_match']else 2
if __name__=='__main__':raise SystemExit(main())