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

301 lines
19 KiB
Python

"""Source-owned finite school reflection definitions; no client-side execution.
Charged incoming-spell reflection and uncharged timed reflectors retain distinct
proc metadata. Existing source/target definitions, server filters and visuals
remain authoritative; this module neither rolls procs nor changes item state.
"""
from copy import deepcopy
import hashlib, math, re
from pathlib import Path
from octo_client_data import canonical_sha256
from spell_result_profile import enum
from spell_item_haste_compat import HEADERS
from spell_family_compat import validate_family
from spell_passive_compat import (BUILD, SCHEMA, TABLES, SUPPLEMENTAL_TABLES,
CONDITIONS, CHILD_NEUTRAL, NEW_EFFECT_NEUTRAL, encode, integer,
new_registry_values, verified_spell_icon)
from spell_definition_common import (REQUIRED_REFERENCE_TABLES,
NEW_DEFINITION_CHILD_TABLES, checked_constant_source, review_effect_shape,
review_new_timing, review_duration_reference, new_definition_records,
review_proc_conditions, review_proc_override_snapshot,
validate_spell_category_namespace)
from item_batch_stage import available_index
POLICY = 'new-finite-self-school-reflection-definition-v1'
NAMESPACE = 'named-self-school-reflection-v1'
MAPPINGS = (
('aura', 'AuraType', 'AuraType', 'SPELL_AURA_REFLECT_SPELLS_SCHOOL', 'SPELL_AURA_REFLECT_SPELLS_SCHOOL', 74),
('effect', 'SpellEffects', 'SpellEffects', 'SPELL_EFFECT_APPLY_AURA', 'SPELL_EFFECT_APPLY_AURA', 6),
('target', 'SpellTarget', 'Targets', 'TARGET_UNIT_CASTER', 'TARGET_UNIT_CASTER', 1),
('dispel', 'DispelType', 'DispelType', 'DISPEL_NONE', 'DISPEL_NONE', 0),
('dispel', 'DispelType', 'DispelType', 'DISPEL_MAGIC', 'DISPEL_MAGIC', 1),
('defense', 'SpellDmgClass', 'SpellDmgClass', 'SPELL_DAMAGE_CLASS_NONE', 'SPELL_DAMAGE_CLASS_NONE', 0),
('defense', 'SpellDmgClass', 'SpellDmgClass', 'SPELL_DAMAGE_CLASS_MAGIC', 'SPELL_DAMAGE_CLASS_MAGIC', 1),
*tuple(('school', 'SpellSchools', 'SpellSchools', 'SPELL_SCHOOL_'+n, 'SPELL_SCHOOL_'+n, v)
for n, v in (('FIRE', 2), ('NATURE', 3), ('ARCANE', 6))),
)
def _contract():
return dict(policy=NAMESPACE, header_sha256=dict(HEADERS), mappings=[
dict(kind=k, source_name=a, target_name=b, source_value=v, target_value=v)
for k, _, _, a, b, v in MAPPINGS])
def namespace(paths):
if not isinstance(paths, dict) or set(paths) != set(HEADERS):
raise ValueError('Four pinned reflection enum headers required')
for role, path in paths.items():
if hashlib.sha256(Path(path).read_bytes()).hexdigest() != HEADERS[role]:
raise ValueError('Pinned reflection enum header changed')
for kind, source_enum, target_enum, old, new, value in MAPPINGS:
a = Path(paths['source_aura' if kind == 'aura' else 'source'])
b = Path(paths['target_aura' if kind == 'aura' else 'target'])
if enum(a, source_enum)[0].get(old) != value or enum(b, target_enum)[0].get(new) != value:
raise ValueError('Named reflection semantics differ')
return _contract()
def validate_namespace(proof):
if proof != _contract() or any(type(r.get(k)) is not int
for r in proof.get('mappings', []) for k in ('source_value', 'target_value')):
raise ValueError('Pinned named school-reflection proof required')
def source_spell(dbc, raw, offsets, *, family_namespace, semantics,
category_context, proc_proof):
charged = bool(raw.get('procFlags'))
src = checked_constant_source(dbc, raw, offsets,
family_namespace=family_namespace, category_context=category_context,
reflection_context=semantics,
proc_namespace_proof=proc_proof if charged else None,
incoming_harmful_proc=charged)
validate_source(src, proc_proof)
return src
def validate_source(src, proc_proof):
integer(src.get('entry'), 1, 0x7fffffff, 'reflection spell ID')
validate_namespace(src.get('reflection_context'))
validate_spell_category_namespace(src.get('spell_category_context'))
if validate_family(src.get('class_family')) != 0:
raise ValueError('Generic school-reflection family required')
for key, count in (('attributes', 5), ('power', 6), ('equippedItem', 3), ('visuals', 2)):
if not isinstance(src.get(key), list) or len(src[key]) != count or any(type(v) is not int for v in src[key]):
raise ValueError('Typed reflection scalar groups required')
if (src['attributes'] != [0]*5 or src['power'] != [0]*6 or
src['equippedItem'] != [-1, 0, 0]):
raise ValueError('Unreviewed reflection attributes, resources or equipment')
school = integer(src.get('school'), 0, 6, 'reflection school index')
if school not in (2, 3, 6):
raise ValueError('Reviewed Fire, Nature or Arcane school required')
if (src.get('castingTimeIndex'), src.get('rangeIndex')) != (1, 1):
raise ValueError('Instant self-range reflection required')
if type(src.get('speed')) not in (int, float) or not math.isfinite(src['speed']) or src['speed']:
raise ValueError('Neutral reflection projectile speed required')
integer(src.get('durationIndex'), 1, 0x7fffffff, 'finite reflection duration')
if src['visuals'][1] or any(v < 0 for v in src['visuals']):
raise ValueError('Unreviewed secondary reflection visual')
for group, keys in (('timing', ('recoveryTime', 'categoryRecoveryTime', 'startRecoveryCategory', 'startRecoveryTime')),
('levels', ('spellLevel', 'baseLevel', 'maxLevel'))):
if not isinstance(src.get(group), dict) or set(src[group]) != set(keys):
raise ValueError('Complete reflection '+group+' required')
for value in src[group].values():
integer(value, 0, 0, 'neutral reflection '+group)
conditions = src.get('conditions')
if not isinstance(conditions, dict) or set(conditions) != set(CONDITIONS):
raise ValueError('Complete reflection conditions required')
for key, value in conditions.items():
integer(value, 0, 0xffffffff if key == 'procFlags' else
101 if key == 'procChance' else 1 if key == 'procCharges' else 0,
'reflection '+key)
context = None
mode = (conditions['procFlags'], conditions['procChance'], conditions['procCharges'])
if mode[0]:
if mode[1:] != (100, 1):
raise ValueError('Charged reflection requires exactly one guaranteed charge')
disk = [0]*173; disk[0] = src['entry']; disk[1:4] = list(mode)
context = review_proc_conditions(dict(entry=src['entry'], **conditions), disk,
dict(ProcFlags=1, ProcChance=2, ProcCharges=3), proc_proof, incoming_harmful=True)
if src.get('proc_context') != context:
raise ValueError('Reflection proc namespace differs')
categories = (1, 1, 0)
else:
if mode != (0, 101, 0) or src.get('proc_context') is not None:
raise ValueError('Neutral timed reflector sentinel and zero charges required')
categories = (0, 0, 0)
if tuple(src.get(k) for k in ('dispel_type', 'defense_type', 'prevention_type')) != categories or any(
type(src.get(k)) is not int for k in ('dispel_type', 'defense_type', 'prevention_type')):
raise ValueError('Explicit reflection dispel/defense categories differ')
effects = src.get('effects'); active = []
multipliers=src.get('effect_value_multipliers')
if not isinstance(multipliers,list)or len(multipliers)!=3 or any(type(v)not in(int,float)or v not in(0,1) for v in multipliers):
raise ValueError('Explicit reflection value multipliers required')
if not isinstance(effects, list) or len(effects) != 3:
raise ValueError('Three reflection effect slots required')
for index, effect in enumerate(effects):
review_effect_shape(effect)
if not effect[0]:
if effect != [0]*11+[-1] or multipliers[index]:
raise ValueError('Nonneutral empty reflection effect')
continue
if (effect[:7] != [6, 74, 99, 1, 1, 0, 0] or
effect[7:11] != [1 << school, 1, 0, 0] or effect[11] != -1):
raise ValueError('Constant 100% self school-reflection effect required')
active.append(index)
if len(active) != 1:
raise ValueError('Exactly one school-reflection effect required')
integer(src.get('spellIconId'), 1, 0x7fffffff, 'source reflection icon')
for key in ('name', 'nameSubtext', 'description', 'auraDescription'):
text = src.get(key)
if not isinstance(text, str) or '\0' in text or len(text.encode()) > 4096:
raise ValueError('Reflection text bound')
if any(token != '$d' for token in re.findall(r'\$[^\s.,%;:!?()]*', text)):
raise ValueError('Unreviewed reflection tooltip expression')
if not src['name']:
raise ValueError('Named reflection source required')
return active, context
def review_visual(src, candidate, schema):
"""Require a rebuildable complete source-stage witness, not packet delivery."""
from aura_visual_profile import review_lifecycle_link
if not isinstance(candidate, dict) or candidate.get('kind') != 'source-owned-visual-link-candidate':
raise ValueError('Verified source-owned reflection visual required')
rebuilt = review_lifecycle_link(candidate, schema)
if rebuilt != candidate:
raise ValueError('Reflection visual lifecycle differs')
if (candidate.get('profile_definition', {}).get('spell') != src['entry'] or
candidate.get('visual_reference', {}).get('source_visual_id') != src['visuals'][0] or
candidate['record']['record'].get('SpellID') != src['entry']):
raise ValueError('Reflection visual source identity differs')
return candidate
def new_component(sources, native, schemas, maxima, registry, *, source_tables,
target_icon_names, new_icon_ids, icon_assets, read_icon,
proc_proof, proc_overrides, visual_links):
if not isinstance(sources, list) or not 1 <= len(sources) <= 4096 or len({s['entry'] for s in sources}) != len(sources):
raise ValueError('Bounded unique reflection sources required')
required = (*REQUIRED_REFERENCE_TABLES, 'SpellCastTimes', 'SpellRange', 'SpellDuration')
if any(t not in native for t in required):
raise ValueError('Complete native reflection reference tables required')
if set(new_icon_ids) != {str(s['entry']) for s in sources}:
raise ValueError('Explicit reflection icon identities required')
expected_visuals = {s['entry'] for s in sources if s['visuals'][0]}
if not isinstance(visual_links, dict) or set(visual_links) != expected_visuals:
raise ValueError('Complete exact reflection visual dependencies required')
tables = NEW_DEFINITION_CHILD_TABLES+('SpellCategories', 'SpellAuraOptions')
for table in {'Spell', 'SpellName', *tables, 'SpellXSpellVisual'}:
if table not in schemas or canonical_sha256(schemas[table]) != (TABLES | SUPPLEMENTAL_TABLES)[table][2]:
raise ValueError('Reviewed reflection schema required')
overrides = review_proc_override_snapshot(proc_overrides, [s['entry'] for s in sources])
if not overrides['overrides_absent']:
raise ValueError('Reflection proc override requires separate filter conversion')
review_new_timing(source_tables, native, 0)
available = available_index(icon_assets); registry = deepcopy(registry)
occupied = {t: {r['ID'] for r in native[t]} for t in tables}
new_registry_values(registry, maxima, occupied, tables=tables)
options = registry.pop('SpellAuraOptions', {}); records = []; spells = []; visual_ids = set()
for src in sorted(sources, key=lambda s: s['entry']):
indices, context = validate_source(src, proc_proof); ident = src['entry']
duration = review_duration_reference(source_tables['SpellDuration'], native['SpellDuration'], src['durationIndex'])
if duration['duration_ms'] <= 0 or duration['duration_ms'] != duration['max_duration_ms']:
raise ValueError('Fixed positive reflection duration required')
for table in REQUIRED_REFERENCE_TABLES:
if any((r.get('ID') if table in ('Spell', 'SpellName') else r.get('SpellID')) == ident for r in native[table]):
raise ValueError('Reflection has positive native reference')
fid, asset = verified_spell_icon(src, new_icon_ids, source_tables['SpellIcon'], target_icon_names, available, read_icon)
effect_rows = {i: dict(deepcopy(NEW_EFFECT_NEUTRAL), EffectAura=74,
EffectBasePointsF=100, EffectAmplitude=src['effect_value_multipliers'][i],
EffectMiscValue=[src['effects'][i][7], 0]) for i in indices}
created = new_definition_records(src, effect_rows, fid, schemas, maxima, registry,
occupied, allocation_prefix='new-source-school-reflection-definition')
for row in created:
if row['table_name'] == 'SpellCategories':
row['record']['DispelType'] = src['dispel_type']
wire = encode(row['record'], schemas['SpellCategories'])
row.update(wire_hex=wire.hex(), sha256=hashlib.sha256(wire).hexdigest())
records.extend(created)
key = str(ident)
if key not in options:
options[key] = max([maxima['SpellAuraOptions'], *options.values()])+1
aura = dict(CHILD_NEUTRAL['SpellAuraOptions'], ID=options[key], SpellID=ident,
ProcTypeMask=context['target_proc_type_mask'] if context else [0, 0],
ProcChance=src['conditions']['procChance'], ProcCharges=src['conditions']['procCharges'])
wire = encode(aura, schemas['SpellAuraOptions'])
records.append(dict(table_name='SpellAuraOptions', table_hash=hex(SUPPLEMENTAL_TABLES['SpellAuraOptions'][0]),
id=aura['ID'], record=aura, wire_hex=wire.hex(), sha256=hashlib.sha256(wire).hexdigest(),
source_spell_id=ident, baseline_record_sha256=None, allocation_policy='new-source-school-reflection-definition-child'))
visual = visual_links.get(ident)
if visual is not None:
review_visual(src, visual, schemas['SpellXSpellVisual'])
row = visual['record']; vid = row['id']
if vid in visual_ids or vid in {r['ID'] for r in native['SpellXSpellVisual']} or vid <= maxima['SpellXSpellVisual']:
raise ValueError('Reflection visual allocation collision')
visual_ids.add(vid); records.append(deepcopy(row))
spells.append(dict(spell_id=ident, source_definition=deepcopy(src),
source_record_sha256=canonical_sha256(src), class_family=deepcopy(src['class_family']),
levels=deepcopy(src['levels']), effect_indices=indices,
source_semantics=deepcopy(src['reflection_context']), proc_context=deepcopy(context),
duration_reference=duration, visual_link=deepcopy(visual),
icon_asset=dict(file_data_id=fid, **asset), known_spells_modified=False,
engine_accepted=False, gameplay_verified=False))
registry['SpellAuraOptions'] = options
new_registry_values(registry, maxima, occupied, tables=tables)
return dict(kind='source-school-reflection-definition-candidates', definition_policy=POLICY,
build=BUILD, schema=SCHEMA, records=records, spells=spells,
child_id_registry=registry, proc_namespace=deepcopy(proc_proof),
proc_override_snapshot=deepcopy(proc_overrides),
source_proc_override_review=overrides, id_remapping=False, installable=False,
installed=False, dependency_complete=False, engine_accepted=False,
gameplay_verified=False, limits=[
'School reflection definitions only; source server executes damage, reflection and charge consumption.',
'No inferred parent Fire-only filter; actual source event flags and override evidence are retained.',
'Visual reference equivalence does not establish actual engine rendering or asset-byte parity.'])
def review_record(src, spell_metadata, row):
"""Check one encoded definition against its fully reviewed source semantics.
The composer separately validates wire encoding, source capture, allocations,
original API absence, and complete required table sets. This rejects altered
values even when an attacker recomputes a record's wire/hash consistently.
"""
ident = src['entry']; table = row.get('table_name'); record = row.get('record')
if not isinstance(record, dict) or row.get('source_spell_id') != ident or record.get('ID') != row.get('id'):
raise ValueError('Reflection record identity differs')
rid = row['id']
if table == 'SpellName':
expected = dict(ID=ident, Name_lang=src['name'])
elif table == 'Spell':
expected = dict(ID=ident, NameSubtext_lang=src['nameSubtext'],
Description_lang=src['description'], AuraDescription_lang=src['auraDescription'])
elif table == 'SpellMisc':
from spell_passive_compat import NEW_MISC_NEUTRAL
expected = dict(deepcopy(NEW_MISC_NEUTRAL), ID=rid, SpellID=ident,
Attributes=src['attributes']+[0]*12,
SpellIconFileDataID=spell_metadata['icon_asset']['file_data_id'],
DurationIndex=src['durationIndex'], SchoolMask=1 << src['school'])
elif table == 'SpellEquippedItems':
expected = dict(ID=rid, SpellID=ident, EquippedItemClass=src['equippedItem'][0],
EquippedItemSubclass=src['equippedItem'][1], EquippedItemInvTypes=src['equippedItem'][2])
elif table == 'SpellCategories':
expected = dict(CHILD_NEUTRAL['SpellCategories'], ID=rid, SpellID=ident,
DefenseType=src['defense_type'], PreventionType=src['prevention_type'], DispelType=src['dispel_type'])
elif table == 'SpellAuraOptions':
context = src.get('proc_context')
expected = dict(CHILD_NEUTRAL['SpellAuraOptions'], ID=rid, SpellID=ident,
ProcTypeMask=context['target_proc_type_mask'] if context else [0, 0],
ProcChance=src['conditions']['procChance'], ProcCharges=src['conditions']['procCharges'])
elif table == 'SpellEffect':
index = record.get('EffectIndex')
if type(index) is not int or index not in spell_metadata['effect_indices']:
raise ValueError('Reflection effect index differs')
expected = dict(deepcopy(NEW_EFFECT_NEUTRAL), ID=rid, SpellID=ident,
EffectIndex=index, EffectAura=74, EffectBasePointsF=100,
EffectAmplitude=src['effect_value_multipliers'][index],
EffectMiscValue=[src['effects'][index][7], 0])
elif table == 'SpellXSpellVisual':
visual = spell_metadata.get('visual_link')
if not isinstance(visual, dict):
raise ValueError('Reflection visual metadata missing')
expected = visual['record']['record']
else:
raise ValueError('Unreviewed reflection child table: '+str(table))
if record != expected:
raise ValueError('Reflection source record semantics differ: '+table)
return True