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

245 lines
23 KiB
Python

#!/usr/bin/env python3
"""One real original targeted cast on a matched temporary local creature.
GM prepares rage/temporary summon only; original /cast tests the action. No SQL
writes, persistent spawn, template change, spell grant, raw request or retries.
Cleanup guards the actual source entry and restores original rage/max and gear.
"""
import argparse,json,math,re,threading,time
from pathlib import Path
from client_session import Session
import client_ui as ui
from local_tortoise import db
from native_engine_character_test import ROOT,Controller,local_listeners
from native_test_guard import require_local_turtle_ports,require_authenticated_turtle_realm,require_native_gameplay_policy,require_solo_test_character,require_supported_pve_creature
from native_world_trace import WorldTrace
from native_entity_catalog import read_catalog
from native_vendor_buy_test import inventory
TARGET_STATE_PROBE='/run GWTargetStateProbe=function()print("GW targetstate",UnitGUID("targettarget"),UnitIsUnit("targettarget","player"));SendChatMessage(".debug fields show 16 uint","SAY");SendChatMessage(".debug fields show 17 uint","SAY")end'
def prepared_melee_invariants(before,after,inventory_unchanged):
"""Allow real combat HP/rage changes; preserve level, money, flags and gear."""
if inventory_unchanged is not True:return False
rows=[]
for text in (before,after):
if not isinstance(text,str):return False
fields=text.split('\t')
if len(fields)!=5 or any(not re.fullmatch(r'[0-9]{1,10}',v) for v in fields):return False
level,health,rage,money,flags=map(int,fields)
if level!=60 or health>=2**32 or rage>1000 or money>=2**32 or flags>=2**32 or flags&17:return False
rows.append((level,health,rage,money,flags))
return all(rows[0][index]==rows[1][index] for index in (0,3,4))
def new_chase_stop(row,guid,previous_ids):
"""A new accepted source STOP for the exact summoned actor, never a guess."""
if str(row.get('legacy_guid'))!=str(guid) or type(row.get('id')) is not int or row['id'] in previous_ids:return None
if row.get('facing')!=1 or row.get('points')!=0 or row.get('duration')!=0:return None
start=row.get('start');destination=row.get('destination')
if not isinstance(start,(list,tuple)) or len(start)!=3 or start!=destination:return None
if any(type(v) not in (int,float) or not math.isfinite(v) or abs(v)>100000 for v in start):return None
return row
def main():
p=argparse.ArgumentParser(description=__doc__)
for n in ('character','entry'):p.add_argument('--'+n,type=int,required=True)
p.add_argument('--spell',type=int)
p.add_argument('--melee',action='store_true',help='Bounded original autoattack observation, distinct from a cast; actual damage/animation require combat-log/UI review')
p.add_argument('--prepared-melee',action='store_true',help='Reuse normal visible4509 Warrior session; retain genuine HP/rage and combat logging for the next test')
p.add_argument('--sample-seconds',type=float,default=0,help='Melee only: measured consecutive visual sampling0..8seconds; no added input')
p.add_argument('--observe-chase',action='store_true',help='Melee only: bounded ordinary backwards input and source-confirmed same-actor STOP observation')
p.add_argument('--observe-target-state',action='store_true',help='Melee only: original targettarget API and read-only source target GUID halves; screenshot requires manual review')
p.add_argument('--combat-log',type=Path,help='Existing standard client log enabled with its original LoggingCombat baseline retained in GWCombatLoggingBefore')
p.add_argument('--health-max',type=int,help='Explicit reviewed maximum for restoring controlled NPC combat damage; no stat feature')
p.add_argument('--observe-aura',action='store_true',help='Capture original target debuff UI immediately; combat aura APIs reject tainted macro access')
p.add_argument('--observe-range',action='store_true',help='Collect genuine source distance and original client range/usability/error diagnostics; no position changes')
p.add_argument('--output',type=Path,required=True);a=p.parse_args();out=a.output.resolve()
if not out.is_relative_to(ROOT/'runtime') or out.exists() or not out.parent.is_dir() or not 0<a.entry<65536 or not 0<a.character<2**32:p.error('Require bounded source IDs and new runtime report')
if (a.melee and a.spell is not None) or (not a.melee and (a.spell is None or not 0<a.spell<65536)):p.error('Cast requires genuine spell ID; melee takes no spell')
if a.prepared_melee and (not a.melee or a.character!=4509 or a.health_max is not None):p.error('Prepared melee requires designated4509 melee and no automatic health restoration')
if a.observe_chase and not a.melee:p.error('Chase observation requires melee')
if a.observe_target_state and not a.melee:p.error('Target-state observation requires melee')
if not math.isfinite(a.sample_seconds) or not 0<=a.sample_seconds<=8 or (a.sample_seconds>0 and not a.melee):p.error('Visual sampling requires melee and finite0..8seconds')
log=a.combat_log.resolve() if a.combat_log else None
if a.melee and (not log or not log.is_relative_to(ROOT/'runtime/native-client/_classic_beta_/Logs') or not log.name.startswith('WoWCombatLog') or not log.is_file() or log.is_symlink()):p.error('Melee requires an existing owned standard combat log')
log_offset=log.stat().st_size if log else 0
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'));require_native_gameplay_policy(c.rpc('inspect-native-channel-policy'));require_solo_test_character(a.character,db('SELECT guid FROM tw_char.characters WHERE online<>0 ORDER BY guid;'))
creature_row=db(f'SELECT name,level_min,level_max,rank,npc_flags,unit_class FROM tw_world.creature_template WHERE entry={a.entry};')
spell=db(f'SELECT name,powerType,manaCost FROM tw_world.spell_template WHERE entry={a.spell};').split('\t') if not a.melee else []
before=db(f'SELECT level,health,power2,money,extra_flags FROM tw_char.characters WHERE guid={a.character};');level=int(before.split('\t')[0])
creature=require_supported_pve_creature(creature_row,level)
if a.prepared_melee:
if not prepared_melee_invariants(before,before,True) or int(before.split('\t')[1])==0 or db(f'SELECT class FROM tw_char.characters WHERE guid={a.character};')!='1':raise RuntimeError('Prepared melee requires saved normal-visible level60 source Warrior baseline')
elif before.split('\t')[2]!='0':raise RuntimeError('Require original zero rage')
if not a.melee and (len(spell)!=3 or spell[1]!='1' or not 0<int(spell[2])<=1000 or not re.fullmatch(r'[A-Za-z -]{1,100}',spell[0])):raise RuntimeError('Require real source rage spell')
if not a.melee and db(f'SELECT active,disabled FROM tw_char.character_spell WHERE guid={a.character} AND spell={a.spell};')!='1\t0':raise RuntimeError('Require genuinely learned saved test spell')
if a.health_max is not None and not int(before.split('\t')[1])<=a.health_max<1000000:p.error('Invalid reviewed maximum health')
actors=lambda:[x for x in read_catalog(c)['actors'] if x['entry']==a.entry and x['kind']==3]
if actors():raise RuntimeError('Same-entry creature already visible; preserve it')
baseline=inventory(a.character);spawns=db('SELECT COUNT(*) FROM tw_world.creature;')
report=dict(pid=c.pid,external_gateway_running=False,character=a.character,entry=a.entry,spell=a.spell,source_creature=creature,source_spell=spell,before_state=before,fixture_cleanup_pending=False,rage_restoration_pending=False,cast_attempted=False,cast_pipeline_verified=False,melee_pipeline_verified=False,gameplay_effect_verified=False,ui_review_required=True);failure=None;old=ui.KEY_DELAY
if a.observe_target_state:report['target_state_helper_pending']=False
if a.prepared_melee:report.update(prepared_melee=True,state_deltas_allowed=True,persisted=False,save_requested=False,own_damage_verified=False,persistence_note='No explicit save requested; ordinary server autosaving is not disabled or assessed.')
with WorldTrace(c) as trace:
try:
with Session(c.pid) as s:
s.wait_world()
ui.KEY_DELAY=.03;ui.click_at(s.d,s.win,60,750);ui.key(s.d,'F1');report['rage_restoration_pending']=not a.prepared_melee
if a.observe_target_state:
# Define before summoning: the diagnostic itself remains
# short after combat starts. These source commands only read.
report['target_state_helper_pending']=True;s.macro(TARGET_STATE_PROBE)
if a.observe_range:
# Prepare diagnostics before summoning, so typing them does
# not leave a hostile actor active for many extra seconds.
command=f'print("GW range",C_Spell.IsSpellInRange({a.spell},"target"));print("GW usable",C_Spell.IsSpellUsable({a.spell}));' if not a.melee else ''
s.macro('/run GWTargetRangeProbe=function()'+command+'print("GW target",UnitHealth("target"),UnitPower("player"))end')
s.macro('/run GWTargetErrorProbe=CreateFrame("Frame");GWTargetErrorProbe:RegisterEvent("UI_ERROR_MESSAGE");GWTargetErrorProbe:SetScript("OnEvent",function(_,_,id,text)print("GW cast UI error",id,text)end)')
if not a.melee:s.macro('/s .mod rage 100 100')
report['fixture_cleanup_pending']=True;s.macro(f'/s .npc summon {a.entry}')
report['actor']=c.wait(lambda:(r[0] if len(r:=actors())==1 and r[0]['sent'] else False),8)
s.macro('/targetexact '+creature[0])
if not a.melee:
if a.observe_range:
s.macro('/s .distance');s.macro('/run GWTargetRangeProbe()')
else:s.macro('/run print("GW target before",UnitGUID("target"),UnitLevel("target"),UnitHealth("target"),UnitHealthMax("target"),UnitPower("player"))')
s.shot(out.with_name(out.stem+'-before.png'))
if a.melee:
anchor=trace.bookmark()
report['attack_attempted']=True;s.macro('/startattack')
report['native_request']=trace.wait(2,0x3e011e,5,after_index=anchor);index=report['native_request']['index']
report['native_attack_start']=trace.wait(3,0x4d0017,5,after_index=index);report['source_attack_start']=trace.source_before(report['native_attack_start'],0x143,after_index=index)
if a.observe_target_state:
path=out.with_name(out.stem+'-target-state.png')
if path.exists() or path.is_symlink():raise RuntimeError('Preserve existing target-state frame')
s.macro('/run GWTargetStateProbe()');s.shot(path)
report['target_state_observation']=dict(frame=str(path),source_fields=[16,17],target_state_verified=False,ui_review_required=True)
if a.sample_seconds>0:
visual=dict(requested_seconds=a.sample_seconds,frames=[],model_animation_verified=False,ui_review_required=True)
report['melee_visual_sample']=visual;started=time.monotonic()
# Independent of damage-triggered shots. The existing
# concurrent WorldTrace keeps the genuine damage rows.
while len(visual['frames'])<3 or time.monotonic()-started<a.sample_seconds:
if len(visual['frames'])>=20:visual['sample_bound_reached']=True;break
path=out.with_name(out.stem+'-melee-frame-'+str(len(visual['frames']))+'.png')
if path.exists() or path.is_symlink():raise RuntimeError('Preserve existing melee visual frame')
at=time.monotonic();s.shot(path);finished=time.monotonic()
visual['frames'].append(dict(path=str(path),relative_seconds=round(at-started,3),capture_seconds=round(finished-at,3)))
visual['elapsed_seconds']=round(time.monotonic()-started,3)
if a.observe_chase:
chase=dict(movement_started=False,stop_observed=False,chase_visual_verified=False,ui_review_required=True,frames=[])
report['chase_observation']=chase;guid=report['actor']['legacy_guid']
previous=trace.track_motion(guid)
with trace.lock:chase['motion_before']=trace.motion_latest
chase['actor_previous_ids']=sorted(previous);s.focus();code=s.d.keysym_to_keycode(ui.XK.string_to_keysym('s'))
if not code:raise RuntimeError('Ordinary backwards key is unavailable')
released=threading.Event();release_errors=[];started=time.monotonic()
def release():
released.set();chase.setdefault('key_release_monotonic',time.monotonic())
try:ui.fake(s.d,ui.X.KeyRelease,code)
except Exception as error:release_errors.append(type(error).__name__+': '+str(error))
watchdog=threading.Timer(2,release);watchdog.daemon=True;watchdog.start()
try:
ui.fake(s.d,ui.X.KeyPress,code);chase.update(movement_started=True,movement_started_monotonic=started)
for frame in range(3):
if released.is_set():break
path=out.with_name(out.stem+'-chase-moving-'+str(frame)+'.png')
if path.exists() or path.is_symlink():raise RuntimeError('Preserve existing chase frame')
at=time.monotonic();s.shot(path);finished=time.monotonic()
chase['frames'].append(dict(path=str(path),relative_seconds=round(at-started,3),capture_seconds=round(finished-at,3),completed_while_held=not released.is_set()))
released.wait(max(0,2-(time.monotonic()-started)))
finally:
watchdog.cancel();release();watchdog.join(1);s.d.sync()
chase['movement_input_seconds']=round(chase['key_release_monotonic']-started,3)
if release_errors:chase['key_release_errors']=release_errors
if release_errors or watchdog.is_alive():raise RuntimeError('Backwards key release requires inspection')
if sum(frame['completed_while_held'] for frame in chase['frames'])<2:raise RuntimeError('Fewer than two fresh frames completed within bounded backwards input; no movement retry')
def stopped():
if trace.error:raise RuntimeError('Actor motion observation failed: '+trace.error)
with trace.lock:chase['motion_after']=trace.motion_latest
retained=trace.motion_rows();chase['retained_actor_motion_rows']=len(retained)
return next((match for row in reversed(retained) if row['seen_monotonic']>=started and (match:=new_chase_stop(row,guid,previous)) is not None),None)
try:chase['stop_row']=c.wait(stopped,5);chase['stop_observed']=True
except RuntimeError as error:
chase['stop_wait_error']=str(error)
if str(error)=='Bounded native readiness wait expired':
try:
current=actors()
if len(current)!=1 or str(current[0]['legacy_guid'])!=str(guid):raise RuntimeError('Exact summoned fixture is no longer present; no target diagnostics')
s.macro('/s .distance');s.macro('/s .gps')
s.macro('/run if UnitPosition then for _,u in ipairs({"target","player"})do local x,y,z,m=UnitPosition(u);print("GW chase position",u,UnitGUID(u),UnitIsDead(u),x,y,z,m)end else print("GW chase UnitPosition unavailable")end')
path=out.with_name(out.stem+'-chase-stop-timeout.png')
if path.exists() or path.is_symlink():raise RuntimeError('Preserve existing chase timeout frame')
s.shot(path);chase['timeout_diagnostics_frame']=str(path)
except Exception as diagnostic:chase['timeout_diagnostic_error']=type(diagnostic).__name__+': '+str(diagnostic)
raise
s.macro('/s .distance');s.shot(out.with_name(out.stem+'-chase-distance-after-stop.png'))
# Do not leave a newly summoned hostile idle while typing
# several diagnostics: it can chase guards before attack.
# Post-start distance is labelled honestly, not a precondition.
if a.observe_range and not a.observe_chase:
s.macro('/s .distance');s.macro('/run GWTargetRangeProbe()')
s.shot(out.with_name(out.stem+'-range-after-start.png'))
report['source_damage_events']=[];last=index
for step in range(3):
event=trace.wait(1,0x14a,6,after_index=last);last=event['index'];report['source_damage_events'].append(event);s.shot(out.with_name(out.stem+f'-swing-{step+1}.png'))
s.macro('/stopattack');report['melee_pipeline_verified']=True
# Source damage metadata can be either actor. Standard log
# and actual images must prove OWN swings and animation.
else:
report['cast_attempted']=True;s.macro('/cast '+spell[0]);s.macro('/stopattack')
report['native_request']=trace.wait(2,0x3e0176,5);index=report['native_request']['index']
report['native_start']=trace.wait(3,0x69002d,5,after_index=index);report['source_start']=trace.source_before(report['native_start'],0x131,after_index=index)
report['native_go']=trace.wait(3,0x69002c,5,after_index=index);report['source_go']=trace.source_before(report['native_go'],0x132,after_index=index)
if a.observe_aura:s.shot(out.with_name(out.stem+'-debuff.png')) # Original UI; no tainted combat aura query.
s.macro('/s .list auras')
s.macro('/run print("GW target after",UnitGUID("target"),UnitHealth("target"),UnitPower("player"))');s.shot(out.with_suffix('.png'))
pipe=c.rpc('inspect-engine-pipe');report.update(request=pipe['spell_request'],pipe_error=pipe['error'],pipe_closed=pipe['closed'],cast_pipeline_verified=not a.melee and not pipe['error'] and not pipe['closed'] and not pipe['spell_request']['result'])
except Exception as error:
failure=type(error).__name__+': '+str(error)
if a.observe_range:
try:
with Session(c.pid) as s:
s.wait_world();s.shot(out.with_name(out.stem+'-failure.png'))
except Exception as capture_error:report['failure_capture_error']=str(capture_error)
finally:
try:
with Session(c.pid) as s:
s.wait_world()
ui.KEY_DELAY=.03
if report.get('target_state_helper_pending'):
s.macro('/run GWTargetStateProbe=nil');report['target_state_helper_pending']=False
s.macro('/stopattack')
if report['fixture_cleanup_pending']:
s.macro('/targetexact '+creature[0]);s.macro(f'/run local g=UnitGUID("target");if g and g:find("-{a.entry}-",1,true) then SendChatMessage(".npc delete","SAY") end')
c.wait(lambda:not actors(),8);report['fixture_cleanup_pending']=False
if report['rage_restoration_pending']:
ui.key(s.d,'F1');s.macro('/s .mod rage 0 100');s.macro('/s .save')
c.wait(lambda:db(f'SELECT power2 FROM tw_char.characters WHERE guid={a.character};')=='0',8);report['rage_restoration_pending']=False
if a.health_max is not None:
current=int(db(f'SELECT health FROM tw_char.characters WHERE guid={a.character};'));original=int(before.split('\t')[1])
report['health_after_combat']=current
if current<original:
report['health_restoration_pending']=True;s.macro(f'/s .mod hp {original} {a.health_max}');s.macro('/s .save')
c.wait(lambda:int(db(f'SELECT health FROM tw_char.characters WHERE guid={a.character};'))==original,8);report['health_restoration_pending']=False
report.update(after_state=db(f'SELECT level,health,power2,money,extra_flags FROM tw_char.characters WHERE guid={a.character};'),inventory_unchanged=inventory(a.character)==baseline,persistent_spawn_count_unchanged=db('SELECT COUNT(*) FROM tw_world.creature;')==spawns)
if a.observe_range:s.macro('/run if GWTargetErrorProbe then GWTargetErrorProbe:UnregisterAllEvents();GWTargetErrorProbe:SetScript("OnEvent",nil);GWTargetErrorProbe=nil end;GWTargetRangeProbe=nil')
if a.melee and not a.prepared_melee:s.macro('/run LoggingCombat(GWCombatLoggingBefore or false)')
if not a.prepared_melee:s.macro('/run print("GW restored rage",UnitPower("player"),UnitPowerMax("player"))')
s.shot(out.with_name(out.stem+('-prepared-after.png' if a.prepared_melee else '-restored.png')))
except Exception as error:report['restoration_error']=type(error).__name__+': '+str(error)
ui.KEY_DELAY=old
report.update(trace.report())
state_matches=prepared_melee_invariants(before,report.get('after_state'),report.get('inventory_unchanged')) if a.prepared_melee else report.get('after_state')==before and report.get('inventory_unchanged')
if not state_matches or not report.get('persistent_spawn_count_unchanged'):report['cast_pipeline_verified']=report['melee_pipeline_verified']=False
if log:
if log.stat().st_size<log_offset or log.stat().st_size-log_offset>131072:report['combat_log_error']='Log rotated or exceeded bounded fixture delta'
else:
with log.open('rb') as stream:stream.seek(log_offset);delta=stream.read(131073)
target=out.with_suffix('.combat.log');target.write_bytes(delta);target.chmod(0o600);report['combat_log_delta']=str(target.relative_to(ROOT));report['combat_log_requires_review']=True
if failure:report['failure']=failure
out.write_text(json.dumps(report,indent=2)+'\n');out.chmod(0o600)
print(json.dumps({k:report.get(k) for k in ('pid','native_request','source_start','source_go','native_go','cast_pipeline_verified','melee_pipeline_verified','combat_log_delta','combat_log_error','fixture_cleanup_pending','rage_restoration_pending','inventory_unchanged','persistent_spawn_count_unchanged','lost_metadata_rows','observer_error','failure','restoration_error')}))
return 0 if (report['cast_pipeline_verified'] or report['melee_pipeline_verified']) and not trace.error and not report.get('combat_log_error') and not report['fixture_cleanup_pending'] and not report['rage_restoration_pending'] and not report.get('health_restoration_pending',False) and not report.get('target_state_helper_pending',False) else 2
if __name__=='__main__':raise SystemExit(main())