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

169 lines
12 KiB
Python

#!/usr/bin/env python3
"""Capture original C_Spell metadata in a local native world, without learning/casting.
Reuses the installed bounded diagnostics command and preserves its previous
spell-definition samples. Loaded metadata is not spell/gameplay verification.
"""
import argparse
import hashlib
import json
import re
import secrets
import time
from pathlib import Path
from client_session import Session
from console_report import parse
from native_engine_character_test import Controller,ROOT,local_listeners
from native_test_guard import require_authenticated_turtle_realm,require_local_turtle_ports
from native_item_metadata_test import persist_probe
SPELL_QUERY_HANDLER_SHA256='5fb8f372838c6883201db692ac9374cbe2913a3a6df4daf3c29b14946af0701c'
# One complete source set-bonus absence inventory fits in one persisted probe.
# Keep each diagnostics table at16 entries and every input at255 characters;
# this aggregate bound does not change the addon's per-query/sample guards.
MAX_PROBE_SPELLS=256
def api_probe_attestation(macros,source_path=None):
"""Attest this probe's direct read path, not session-wide API integrity.
The reviewed handler queries current C_Spell methods via pcall and has no
source-provider fallback. Other loaded code's function identity is outside
this source-level attestation; do not rename it to no_api_overrides.
"""
path=source_path or ROOT/'client_addons/GatewayDiagnostics/GatewayDiagnostics.lua'
raw=Path(path).read_bytes();text=raw.decode()
try:handler=text[text.index('local function spellInfo(command)'):text.index('local function itemInfo(command)')]
except ValueError as error:raise ValueError('Pinned direct C_Spell query handler missing')from error
if hashlib.sha256(handler.encode()).hexdigest()!=SPELL_QUERY_HANDLER_SHA256:
raise ValueError('Pinned direct C_Spell query handler changed')
if not isinstance(macros,list)or not macros or any(not isinstance(c,str)for c in macros):
raise ValueError('Actual generated probe commands required')
if any(re.search(r'\bC_Spell\s*(?:\.[A-Za-z_][A-Za-z_0-9]*\s*)?=',c)for c in macros):
raise ValueError('Spell API assignment is outside direct read probe')
return dict(policy='source-pinned-direct-c-spell-read-probe-v1',
query_methods=['GetSpellName','GetSpellInfo','GetSpellDescription'],
query_source_path=str(Path(path).resolve()),query_source_sha256=hashlib.sha256(raw).hexdigest(),
query_handler_sha256=SPELL_QUERY_HANDLER_SHA256,
probe_commands_sha256=hashlib.sha256(json.dumps(macros,separators=(',',':')).encode()).hexdigest(),
probe_overrides_c_spell_api=False,source_provider_fallbacks_used=False,
whole_session_api_identity_verified=False,
scope='This probe reads current C_Spell methods directly; it neither replaces them nor uses source-provider fallback values. Other loaded code is outside this attestation.')
def loop_commands(ids,body):
"""Pack read-only Lua iterations within both actual input/sample bounds."""
def render(values):return '/run for _,i in ipairs({'+','.join(map(str,values))+'})do '+body+' end'
result=[];chunk=[]
for ident in ids:
if chunk and (len(chunk)==16 or len(render(chunk+[ident]))>255):
result.append(render(chunk));chunk=[]
chunk.append(ident)
if len(render(chunk))>255:raise ValueError('One diagnostic iteration exceeds client edit bound')
if chunk:result.append(render(chunk))
return result
def commands(ids,nonce,request_load=False):
if (not isinstance(ids,list)or not 1<=len(ids)<=MAX_PROBE_SPELLS or len(set(ids))!=len(ids)
or any(type(i)is not int or not 0<i<2**31 for i in ids)):
raise ValueError('Bounded distinct source spell IDs required')
if len(nonce)!=8 or any(c not in'0123456789abcdef'for c in nonce):raise ValueError('Diagnostic nonce required')
if type(request_load)is not bool:raise ValueError('Explicit native data-load option required')
pre=[];cleanup=[]
if request_load:
pre=['/run GWPreviousSpellLoads=GatewayDiagnosticsSaved.spellLoadRequests;GatewayDiagnosticsSaved.spellLoadRequests={};GWRequest=C_Spell and C_Spell.RequestLoadSpellData']
pre+=loop_commands(ids,'local r={available=type(GWRequest)=="function"};if r.available then r.callOK=pcall(GWRequest,i)end;GatewayDiagnosticsSaved.spellLoadRequests[i]=r')
pre+=['/run GWRequest=nil']
cleanup=['/run GatewayDiagnosticsSaved.spellLoadRequests=GWPreviousSpellLoads;GWPreviousSpellLoads=nil']
capture='/run GatewayDiagnosticsSaved.spellMetadataProbe={run="'+nonce+'",spells=GatewayDiagnosticsSaved.spellDefinitions'
capture+=',requests=GatewayDiagnosticsSaved.spellLoadRequests'if request_load else''
result=['/run GWPreviousSpellDefinitions=GatewayDiagnosticsSaved.spellDefinitions;GatewayDiagnosticsSaved.spellDefinitions={}',*pre]
if len(ids)<=16:
result.extend(loop_commands(ids,'SlashCmdList.GATEWAYDIAGNOSTICS("spell-info "..i)'))
result.append(capture+'}')
else:
# Preserve the addon's16-entry bound. Collect several bounded captures
# in one authenticated session and persist once, rather than relogging
# or reloading the entire UI for each chunk.
result.append('/run GatewayDiagnosticsSaved.spellMetadataProbe={run="'+nonce+'",spells={}}')
if request_load:result.append('/run GatewayDiagnosticsSaved.spellMetadataProbe.requests=GatewayDiagnosticsSaved.spellLoadRequests')
for start in range(0,len(ids),16):
# This is the exact handler registered for /gwdiag by our existing
# diagnostics module, not an inferred engine callback. It performs
# the same original API queries and retains its16-entry guard.
result.extend(loop_commands(ids[start:start+16],'SlashCmdList.GATEWAYDIAGNOSTICS("spell-info "..i)'))
result.append('/run for i,r in pairs(GatewayDiagnosticsSaved.spellDefinitions)do GatewayDiagnosticsSaved.spellMetadataProbe.spells[i]=r end;GatewayDiagnosticsSaved.spellDefinitions={}')
# Use the original API directly. A captured native session accepted all
# queries but treated the /reload alias as unknown, leaving them unpersisted.
return [*result,*cleanup,'/run GatewayDiagnosticsSaved.spellDefinitions=GWPreviousSpellDefinitions;GWPreviousSpellDefinitions=nil','/run ReloadUI()']
def matches(samples, ids, *, loaded=False, unavailable=False, description=None):
"""Loading and source-value acceptance are separate assertions."""
if loaded and unavailable or description is not None and (not loaded or len(ids)!=1):
raise ValueError('A source description requires one loaded spell')
if description is not None and (not isinstance(description,str)or not description or len(description)>4096):
raise ValueError('Bounded exact source description required')
present=all(samples.get(i,{}).get('spellID')==i and all(samples.get(i,{}).get(k)=='ok'for k in('infoStatus','nameStatus','descriptionStatus'))for i in ids)
missing=all(all(samples.get(i,{}).get(k)=='nil'for k in('infoStatus','nameStatus','descriptionStatus'))for i in ids)
accepted=present if loaded else missing if unavailable else len(samples)==len(ids)
if description is not None:accepted=accepted and samples.get(ids[0],{}).get('description')==description
return present,missing,accepted
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--spells',nargs='+',type=int,required=True);p.add_argument('--output',type=Path,required=True)
expectations=p.add_mutually_exclusive_group();expectations.add_argument('--expect-loaded',action='store_true');expectations.add_argument('--expect-unavailable',action='store_true')
p.add_argument('--expect-description',help='Exact independently verified source description; requires one spell and --expect-loaded')
p.add_argument('--request-load',action='store_true',help='Use documented original70334 C_Spell.RequestLoadSpellData before sampling; no learning or casting');a=p.parse_args()
matches({},a.spells,loaded=a.expect_loaded,unavailable=a.expect_unavailable,description=a.expect_description)
out=a.output.resolve()
if not out.is_relative_to(ROOT/'runtime')or out.exists():p.error('Fresh runtime evidence path required')
nonce=secrets.token_hex(4);macros=commands(a.spells,nonce,a.request_load)
if any(len(v)>255 or any(x in v for x in'`~')for v in macros):raise ValueError('Macro bound')
query_attestation=api_probe_attestation(macros)
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 authenticated native world required')
saved=ROOT/'runtime/native-client/_classic_beta_/WTF/Account/SavedVariables/GatewayDiagnostics.lua';started=time.monotonic()
out.with_suffix('.plan.json').write_text(json.dumps(dict(pid=c.pid,run=nonce,spell_ids=a.spells,native_load_requested=a.request_load),indent=2)+'\n')
with Session(c.pid)as s:
s.wait_world()
groups_submitted=0
# Reuse the existing item-probe persistence contract: a ReloadUI edit
# acknowledgement can time out after the genuine reload succeeded.
# Only the exact fresh saved nonce plus world readiness confirms it;
# never replay the queries or reload on that ambiguous acknowledgement.
assert macros[-1]=='/run ReloadUI()'
for command in macros[:-1]:
s.macro(command)
if command.startswith('/run for i,r in pairs('):
groups_submitted+=1
print('Original-API query group submitted:',groups_submitted,'; persisted results not yet verified.',flush=True)
def observed():
try:
r=parse(saved.read_text()).get('spellMetadataProbe',{})
return r if r.get('run')==nonce else None
except(OSError,ValueError):return None
data,reload_warning=persist_probe(s,c,observed)
# Preserve the completed original-API observation even when the
# post-reload world-label detector cannot confirm readiness. This
# remains a failed UI test and must not authorize further input.
readiness_error=None
try:s.wait_world(timeout=15)
except RuntimeError as error:readiness_error=str(error)
samples=data.get('spells',{});loaded,missing,matched=matches(samples,a.spells,loaded=a.expect_loaded,unavailable=a.expect_unavailable,description=a.expect_description)
requests=data.get('requests',{});requests_ok=all(requests.get(i,{}).get('available')is True and requests.get(i,{}).get('callOK')is True for i in a.spells)if a.request_load else None
if a.request_load:matched=matched and requests_ok
if api_probe_attestation(macros)!=query_attestation:raise RuntimeError('Spell query source changed during probe')
report=dict(kind='actual-native-original-spell-api-probe',pid=c.pid,local_only=True,external_gateway_running=False,character_modified=False,
spells=samples,all_loaded=loaded,all_unavailable=missing,expected_description=a.expect_description,source_description_verified=a.expect_description is not None and matched,
expectation_matched=matched,native_load_requested=a.request_load,load_requests=requests,all_load_requests_succeeded=requests_ok,
gameplay_verified=False,world_readiness_confirmed=readiness_error is None,
api_probe_attestation=query_attestation,
readiness_error=readiness_error,saved_nonce=nonce,reload_acknowledgement_warning=reload_warning,
elapsed_seconds=round(time.monotonic()-started,3))
out.write_text(json.dumps(report,indent=2)+'\n');print('Original spell metadata:',len(samples),'loaded:',loaded,'unavailable:',missing,'expectation:',matched,'report:',out)
return 0 if matched and readiness_error is None else 2
if __name__=='__main__':raise SystemExit(main())