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

605 lines
58 KiB
Python

"""Reviewed constant equipment/set aura corrections using the shared spell codec.
This is definition conversion, independent of learned spells, racial abilities
and talent purchases. Source IDs remain intact. Positive same-spell native
contexts are required; no missing parent or asset is fabricated.
"""
from copy import deepcopy
from pathlib import Path
import hashlib,math,re
from octo_client_data import canonical_sha256
from spell_passive_compat import (BUILD,SCHEMA,TABLES,SUPPLEMENTAL_TABLES,CONDITIONS,CHILD_NEUTRAL,
NEW_EFFECT_NEUTRAL,NEW_MISC_NEUTRAL,integer,one,encode,allocate,registry_values,
new_registry_values,verified_spell_icon)
from item_batch_stage import available_index
from spell_family_compat import validate_family
from spell_definition_common import (REQUIRED_REFERENCE_TABLES,
checked_constant_source,review_neutral_children,review_new_timing,new_definition_records,
NEW_DEFINITION_CHILD_TABLES)
POLICY='positive-constant-item-stat-aura-v1'
PERCENT_CRIT_POLICY='positive-constant-item-percent-crit-aura-v1'
PERCENT_HIT_POLICY='positive-constant-item-percent-hit-aura-v1'
PERCENT_PARRY_POLICY='positive-constant-item-percent-parry-aura-v1'
PERCENT_DODGE_POLICY='positive-constant-item-percent-dodge-aura-v1'
PERCENT_SWIM_POLICY='positive-constant-item-percent-swim-speed-aura-v1'
POSITIVE_SKILL_POLICY='positive-constant-item-skill-aura-v1'
SCHOOL_DAMAGE_POLICY='positive-constant-item-school-damage-aura-v1'
PERCENT_SPELL_CRIT_POLICY='positive-constant-item-spell-crit-aura-v1'
PERCENT_SPELL_HIT_POLICY='positive-constant-item-spell-hit-aura-v1'
PERCENT_ALL_CRIT_POLICY='positive-constant-item-all-crit-aura-v1'
SPELL_BONUS_POLICY='positive-constant-item-damage-healing-aura-v1'
MANA_REGEN_POLICY='positive-constant-item-mana-regeneration-v1'
CASTING_MANA_REGEN_POLICY='positive-constant-casting-mana-regeneration-v1'
PERCENT_AURAS={'weapon-crit':52,'weapon-hit':54,'parry':47,'dodge':49,'swim-speed':58,'spell-crit':57,'spell-hit':55,'all-crit':52,'casting-mana-regen':134}
# Source-backed named semantics, not numeric equivalence across versions.
# Tortoise Aura::HandleShieldBlockValue158 -> SHIELD_BLOCK_VALUE/FLAT_MOD.
# Forever Player::GetClassicShieldBlockValue consumes MOD_BLOCK_VALUE_FLAT274;
# native158 instead means ALLOW_TALENT_SWAPPING and must never be copied.
AURA_MAPPING={22:22,51:51,99:99,124:124,158:274}
# Named caster modifiers retain source/target55 spell hit,57 global spell crit,
# and135 flat healing. Source71 school crit is NOT native71 (teleport
# return point) and remains rejected. SpellAuras.cpp and AuraEffects.cpp
# use flat healing bonuses and percentage points for these matching names.
# Healing/damage and school crit keep school MASKS; they are never ratings.
# Opt-in school_damage: both pinned SpellAuraDefines.h name13
# SPELL_AURA_MOD_DAMAGE_DONE. Tortoise Aura::HandleModDamageDone and target
# AuraEffect::HandleModDamageDone consume EffectMiscValue as a school MASK,
# not a school index or combat rating. Keep the spell's own school separate.
# Only positive, permanent, unconditional same-ID native contexts are admitted;
# no new definitions or client-side damage application are synthesized.
def validate_source(src,*,skill_bonus=False,percent_stat=None,school_damage=False,flat_modifier=False,spell_bonus=False,mana_regen=False):
if type(mana_regen)is not bool or mana_regen and(skill_bonus or percent_stat or school_damage or flat_modifier or spell_bonus):raise ValueError('Separate named mana regeneration policy required')
if type(spell_bonus)is not bool or spell_bonus and(skill_bonus or percent_stat or school_damage or flat_modifier):raise ValueError('Separate named damage/healing bonus policy required')
if type(flat_modifier)is not bool or flat_modifier and(skill_bonus or percent_stat or school_damage):raise ValueError('Separate flat spell-modifier policy required')
if type(school_damage)is not bool or school_damage and(skill_bonus or percent_stat):raise ValueError('Separate school-damage policy required')
if percent_stat not in(None,*PERCENT_AURAS)or percent_stat and skill_bonus:raise ValueError('Separate named item-percent/skill policy required')
swim=percent_stat=='swim-speed'
integer(src['entry'],1,0x7fffffff,'item-stat source spell')
if skill_bonus and src.get('skill_category_reference') is None and any(k in src for k in('category_id','spell_category_context')):
raise ValueError('Orphan categorized skill metadata requires explicit reference')
if src.get('skill_category_reference') is not None:
if not skill_bonus:raise ValueError('Categorized reference is specific to item skill bonuses')
validate_skill_category_reference(src['skill_category_reference'])
if src.get('category_id')!=src['skill_category_reference']['source_category'][0]or type(src.get('category_id'))is not int or any(type(src.get(k))is not int or src[k]!=0 for k in('defense_type','prevention_type')):
raise ValueError('Categorized skill identity/defense context differs')
validate_family(src.get('class_family'),warrior=skill_bonus or flat_modifier)
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('Item-stat source shape: '+key)
# Source DONT_AFFECT_SHEATH_STATE and native DO_NOT_SHEATH both name0x40000;
# source/native MOD_INCREASE_SWIM_SPEED is58. Preserve this explicit passive
# context, rather than treating swimming as melee haste or a combat rating.
allowed_attributes=([448,0,0,0,0],[464,0,0,0,0])if percent_stat=='casting-mana-regen'else([448,0,0,0,0],)if mana_regen else([262208,0,0,0,0],)if swim else([128,0,0,0,0],[192,0,0,0,0])if skill_bonus else([192,0,0,0,0],)
for key in('school','castingTimeIndex','durationIndex','rangeIndex'):integer(src[key],0,0x7fffffff,'item-stat '+key)
if type(src['speed'])not in(int,float)or not math.isfinite(src['speed']):raise ValueError('Item-stat speed type differs')
if swim or school_damage or spell_bonus or mana_regen:integer(src['school'],0,6,'source spell school index')
if src['attributes']not in allowed_attributes or(src['school'],src['castingTimeIndex'],src['durationIndex'],src['rangeIndex'],src['speed'])!=(src['school']if swim or school_damage or spell_bonus or mana_regen else 0,1,21,1,0):raise ValueError('Unreviewed passive equipment metadata')
if src['power']!=[0]*6 or src['equippedItem'][0]!=-1 or src['equippedItem'][1]not in(-1,0)or src['equippedItem'][2]or src['visuals']!=[0,0]:raise ValueError('Unreviewed item-stat cost/equipment/visual conditions')
integer(src['spellIconId'],1,0x7fffffff,'source icon')
if set(src.get('conditions',{}))!=set(CONDITIONS):raise ValueError('Complete item-stat conditions required')
for key,value in src['conditions'].items():integer(value,0,255 if key=='procChance'else 0,'item-stat '+key)
if set(src.get('timing',{}))!={'recoveryTime','categoryRecoveryTime','startRecoveryCategory','startRecoveryTime'}or any(type(v)is not int or v for v in src['timing'].values()):raise ValueError('Item-stat timing must be unconditional')
if set(src.get('levels',{}))!={'spellLevel','baseLevel','maxLevel'}:raise ValueError('Complete item-stat levels required')
for key,value in src['levels'].items():integer(value,0,65535,'item-stat '+key)
for key in('name','nameSubtext','description','auraDescription'):
if not isinstance(src.get(key),str)or '\0'in src[key]or len(src[key].encode())>4096:raise ValueError('Item-stat text bound')
if not src['name']or not isinstance(src.get('effects'),list)or len(src['effects'])!=3:raise ValueError('Complete item-stat identity/effects required')
active=[]
for index,e in enumerate(src['effects']):
if not isinstance(e,list)or len(e)!=12 or any(type(v)not in(int,float)or not math.isfinite(v)for v in e)or any(type(e[i])is not int for i in(0,1,2,3,4,7,8,9,10)):raise ValueError('Item-stat effect type/shape differs')
if not e[0]:
if e!=[0]*11+[-1]:raise ValueError('Unreviewed empty item-stat effect')
continue
if e[0]!=6 or e[1]not in({107}if flat_modifier else {30,98}if skill_bonus else {57}if percent_stat=='spell-crit' else {52,57}if percent_stat=='all-crit' else {PERCENT_AURAS[percent_stat]}if percent_stat else {85}if mana_regen else {13,135}if spell_bonus else {13}if school_damage else AURA_MAPPING) or e[3:7]!=[1,1,0,0]or e[8:11]!=[1,0,0]or (e[11]not in(-1,0)and not(spell_bonus and e[1]==135 and type(e[11])in(int,float)and e[11]==1)):raise ValueError('Unreviewed constant item-stat mechanic')
if mana_regen:integer(e[7],0,0,'source mana regeneration power')
integer(e[2]+1,1 if percent_stat else 0,32767 if skill_bonus else 100 if percent_stat or e[1]==51 else 0xffffff,'constant item-stat amount')
if flat_modifier:integer(e[7],17,17,'reviewed source jump-target operation')
elif skill_bonus:integer(e[7],1,65535,'source skill identity')
elif e[1]==22 or school_damage or spell_bonus:integer(e[7],1,127,'source effect school mask')
elif e[7]!=0:raise ValueError('Unreviewed item-stat misc parameter')
active.append(index)
if not active:raise ValueError('No constant item-stat effect')
if spell_bonus and not any(src['effects'][i][1]==135 for i in active):raise ValueError('Damage/healing policy requires a healing modifier')
for key in('description','auraDescription'):
for token in re.findall(r'\$[^\s.,%;:!?()]*',src[key]):
if not re.fullmatch(r'\$s[123](?![0-9])',token)or int(token[2])-1 not in active:raise ValueError('Unreviewed item-stat tooltip token')
return active
def source_spell(dbc,raw,offsets,*,skill_bonus=False,family_namespace=None,percent_stat=None,school_damage=False,spell_bonus=False,mana_regen=False,skill_category_reference=None):
if skill_category_reference is not None:
if not skill_bonus:raise ValueError('Separate categorized skill source policy required')
validate_skill_category_reference(skill_category_reference)
src=checked_constant_source(dbc,raw,offsets,family_namespace=family_namespace,
category_context=skill_category_reference['spell_category_namespace']if skill_category_reference is not None else None,
skill_category_reference=skill_category_reference);validate_source(src,skill_bonus=skill_bonus,percent_stat=percent_stat,school_damage=school_damage,spell_bonus=spell_bonus,mana_regen=mana_regen);return src
def classify_sources(dbc,sources,offsets,*,family_namespace=None):
"""Batch existing static policies; unsupported mechanics stay explicit.
This source/capture review does not validate native contexts, install
definitions, grant known spells or establish equipped gameplay effects.
"""
if not isinstance(sources,list)or not 1<=len(sources)<=4096:raise ValueError('Static source classification count bound')
ids=[integer(r.get('entry'),1,0x7fffffff,'source classification spell')for r in sources]
if len(set(ids))!=len(ids):raise ValueError('Duplicate source classification spell')
policies=[('flat-item-stat',{}),*[(name,dict(percent_stat=name))for name in PERCENT_AURAS],('skill-bonus',dict(skill_bonus=True)),('school-damage',dict(school_damage=True)),('spell-bonus',dict(spell_bonus=True)),('mana-regeneration',dict(mana_regen=True))]
rows=[]
for raw in sorted(sources,key=lambda r:r['entry']):
row=dict(spell_id=raw['entry'],source_name=raw['name'],engine_loaded=False,gameplay_verified=False);failures=[]
for name,kwargs in policies:
try:src=source_spell(dbc,raw,offsets,family_namespace=family_namespace,**kwargs)
except ValueError as error:failures.append(dict(policy=name,reason=str(error)));continue
row.update(source_policy=name,validated_source=src);break
else:row['blocked_policies']=failures
rows.append(row)
return dict(kind='source-item-static-policy-classification',spells=rows,source_spell_count=len(rows),
source_policies_validated=sum('validated_source'in r for r in rows),native_context_reviewed=False,
installed=False,known_spells_modified=False,gameplay_verified=False)
def component(sources,native,schemas,maxima,registry,*,percent_stat=None,skill_bonus=False,skill_rows=None,duration_reference=None,school_damage=False,spell_bonus=False,mana_regen=False):
if not isinstance(sources,list)or not 1<=len(sources)<=4096 or len({s['entry']for s in sources})!=len(sources):raise ValueError('Item-stat source count/identity differs')
if any(t not in native for t in REQUIRED_REFERENCE_TABLES):raise ValueError('Complete explicit native item-stat references required')
registry=deepcopy(registry);occupied={r['ID']for r in native['SpellEffect']};registry_values(registry,maxima['SpellEffect'],occupied)
records=[];verified=[]
for src in sorted(sources,key=lambda s:s['entry']):
indices=set(validate_source(src,percent_stat=percent_stat,skill_bonus=skill_bonus,school_damage=school_damage,spell_bonus=spell_bonus,mana_regen=mana_regen));ident=src['entry']
name=one(native['SpellName'],lambda r:r['ID']==ident,'positive item-stat name');text=one(native['Spell'],lambda r:r['ID']==ident,'positive item-stat text');misc=one(native['SpellMisc'],lambda r:r['SpellID']==ident,'positive item-stat misc')
# The explicit percentage policies may correct a source name only
# after the complete same-ID effect/context checks below. No name
# matching, alias search or source-ID remapping chooses the spell.
if name['Name_lang']!=src['name']and not percent_stat:raise ValueError('Same-ID item-stat name collision')
attrs=misc['Attributes']
reviewed_attrs=list(attrs);reviewed_misc=deepcopy(misc)
if percent_stat:
# Tortoise Aura::HandleAuraModCritPercent (52) and Forever
# AuraEffect::HandleAuraModWeaponCritPercent (52) affect weapon
# crit percentage, not ITEM_MOD_CRIT_RATING. Source unrestricted
# equipment applies melee/ranged; retain that exact restriction.
# Hit54, parry47 and dodge49 retain the exact named source/native
# percent aura types. They are distinct from rating effects.
# SharedDefines.h names native Attr1 bit0x400 NO_THREAT. Remove
# only this additional, named native flag; preserve unknown Attr15.
if len(attrs)!=17 or attrs[1]not in(0,0x400):raise ValueError('Native percent-crit attributes differ')
reviewed_attrs[1]=src['attributes'][1]
reviewed_misc.update(Attributes=reviewed_attrs)
if percent_stat or duration_reference is not None:
# An explicit source/native timing review can also reconcile a
# permanent flat/skill aura. Do not relax any effect, cost, proc,
# family, attribute or neutral-child validation for that review.
expected=dict(source_duration_id=21,target_duration_id=21,duration_ms=-1,max_duration_ms=-1,
source_duration_per_level=0,target_duration_per_resource=0,permanent=True)
if (not isinstance(duration_reference,dict)or duration_reference!=expected
or any(type(duration_reference[k])is not type(v)for k,v in expected.items())
or misc['DurationIndex']not in(0,21)):
raise ValueError('Reviewed source/native permanent static duration required')
reviewed_misc.update(DurationIndex=21)
if len(attrs)!=17 or reviewed_attrs[:5]!=src['attributes']or any(v for i,v in enumerate(attrs[5:],5)if i!=15)or attrs[15]&~0x2000:raise ValueError('Native item-stat attributes differ')
misc_context=dict(NEW_MISC_NEUTRAL)
if percent_stat=='swim-speed' or school_damage or spell_bonus or mana_regen:misc_context['SchoolMask']=1<<src['school'] # Source index→native school mask, not a copied index.
for key,value in misc_context.items():
if key=='Attributes':continue
if reviewed_misc[key]!=value:raise ValueError('Native item-stat context differs: '+key)
integer(misc['SpellIconFileDataID'],1,0x7fffffff,'retained native icon')
review=review_neutral_children(native,src)
levels=[r for r in native['SpellLevels']if r['SpellID']==ident]
if len(levels)>1 or any(r['DifficultyID']or r['MaxPassiveAuraLevel']for r in levels):raise ValueError('Native item-stat level context differs')
if not levels and any(src['levels'].values()):raise ValueError('Missing level record cannot discard source level conditions')
effects=[r for r in native['SpellEffect']if r['SpellID']==ident]
if not effects or len({r['EffectIndex']for r in effects})!=len(effects)or any(r['EffectIndex']not in indices for r in effects):raise ValueError('Missing/extra/duplicate native item-stat effects')
presented=static_description_fields(src,percent_stat=percent_stat,school_damage=school_damage)if school_damage or percent_stat in('swim-speed','casting-mana-regen')else {key:src[key]for key in('description','auraDescription')}
changes=[('Spell',text,dict(text,NameSubtext_lang=src['nameSubtext'],Description_lang=presented['description'],AuraDescription_lang=presented['auraDescription']))]
if percent_stat and name['Name_lang']!=src['name']:
changes.append(('SpellName',name,dict(name,Name_lang=src['name'])))
if percent_stat or reviewed_misc!=misc:changes.append(('SpellMisc',misc,reviewed_misc))
if levels:
old=levels[0];changes.append(('SpellLevels',old,dict(old,SpellLevel=src['levels']['spellLevel'],BaseLevel=src['levels']['baseLevel'],MaxLevel=src['levels']['maxLevel'])))
for index in sorted(indices):
e=src['effects'][index];old=next((r for r in effects if r['EffectIndex']==index),None);aura=e[1]if percent_stat or skill_bonus or school_damage or spell_bonus or mana_regen else AURA_MAPPING[e[1]]
effect_neutral=dict(NEW_EFFECT_NEUTRAL)
if spell_bonus and e[1]==135 and e[11]==1:
# Legacy constant healing rows retain their actual same-ID native coefficient.
# Source coefficient1 is not permission to synthesize a missing native effect.
if old is None or type(old.get('EffectBonusCoefficient'))not in(int,float)or old.get('EffectBonusCoefficient')!=1:raise ValueError('Healing coefficient requires exact positive source/native parity')
effect_neutral['EffectBonusCoefficient']=1
if skill_bonus:
if not isinstance(skill_rows,list):raise ValueError('Positive native skill reference required')
skill=one(skill_rows,lambda r:r['ID']==e[7],'positive item skill reference')
if not isinstance(skill.get('DisplayName_lang'),str)or not skill['DisplayName_lang']:raise ValueError('Named native skill reference required')
if old is None:
new=dict(NEW_EFFECT_NEUTRAL,ID=allocate(registry,ident,index,maxima['SpellEffect'],occupied),SpellID=ident,EffectIndex=index,EffectAura=aura,EffectMiscValue=[e[7],0])
else:
if old['EffectAura']!=aura or old['EffectMiscValue']!=[e[7],0]or any(old[k]!=v for k,v in effect_neutral.items()):raise ValueError('Native item-stat effect semantics differ')
new=deepcopy(old)
new['EffectBasePointsF']=e[2]+1;changes.append(('SpellEffect',old,new))
for table,old,new in changes:
wire=encode(new,schemas[table])
if old is not None:encode(old,schemas[table]);integer(old['ID'],1,maxima[table],'native item-stat baseline ID')
if old==new:continue
records.append(dict(table_name=table,table_hash=hex((TABLES|SUPPLEMENTAL_TABLES)[table][0]),id=new['ID'],record=new,wire_hex=wire.hex(),sha256=hashlib.sha256(wire).hexdigest(),source_spell_id=ident,source_effect_index=new.get('EffectIndex'),baseline_record_sha256=canonical_sha256(old)if old else None,changed_fields=sorted(k for k in new if old is None or old[k]!=new[k]),allocation_policy='source-derived-constant-item-stat-slot'if old is None else'same-ID-source-item-stat-correction'))
if table=='Spell'and(school_damage or percent_stat in('swim-speed','casting-mana-regen')):
records[-1]['constant_description_policy']=NEW_STATIC_POLICIES[percent_stat or 'school-damage']
verified.append(dict(spell_id=ident,source_record_sha256=canonical_sha256(src),effects=[dict(index=i,source_aura=src['effects'][i][1],target_aura=src['effects'][i][1]if percent_stat or skill_bonus or school_damage or spell_bonus or mana_regen else AURA_MAPPING[src['effects'][i][1]],amount=src['effects'][i][2]+1)for i in sorted(indices)],native_child_review=review,retained_icon_file_id=misc['SpellIconFileDataID'],known_spells_modified=False,engine_accepted=False,gameplay_verified=False))
policy={'weapon-crit':PERCENT_CRIT_POLICY,'weapon-hit':PERCENT_HIT_POLICY,
'parry':PERCENT_PARRY_POLICY,'dodge':PERCENT_DODGE_POLICY,'swim-speed':PERCENT_SWIM_POLICY,'spell-crit':PERCENT_SPELL_CRIT_POLICY,'spell-hit':PERCENT_SPELL_HIT_POLICY,'all-crit':PERCENT_ALL_CRIT_POLICY,'casting-mana-regen':CASTING_MANA_REGEN_POLICY}.get(percent_stat,POSITIVE_SKILL_POLICY if skill_bonus else MANA_REGEN_POLICY if mana_regen else SPELL_BONUS_POLICY if spell_bonus else SCHOOL_DAMAGE_POLICY if school_damage else POLICY)
return dict(kind='source-item-stat-spell-components',build=BUILD,schema=SCHEMA,definition_policy=policy,records=records,spells=verified,child_id_registry=registry,dependency_complete=False,installable=False,installed=False,engine_accepted=False,gameplay_verified=False,limitations=['Positive existing same-spell contexts only; no new spell parent, learned spell or effect application synthesized.','Armor/resistance/AP/block/explicit percentage/skill values preserve reviewed source semantics; active gameplay remains server-authoritative.','Retained icon and reference data are not proof of asset parity, client cache acceptance or gameplay.'])
NEW_SKILL_POLICY='new-item-skill-bonus-definition-candidate-v2'
NEW_CATEGORIZED_SKILL_POLICY='new-item-categorized-skill-bonus-definition-candidate-v1'
SKILL_CATEGORY_REFERENCE_POLICY='source-native-zero-charge-aura-category-v1'
SKILL_CATEGORY_HEADERS=dict(source='635d63c4f0e969cb7029e2989f9861e4b90e9fc444580220025d657c5e1dd8b2',target='9b0e2ad90eea77c961b00f1fc482e9d9e521aa85c58b63863a35d3a338a31799')
def skill_category_namespace(source,target):
from spell_result_profile import enum
mappings=[]
for name,value in (('SKILL_CATEGORY_WEAPON',6),('SKILL_CATEGORY_SECONDARY',9)):
for role,path in (('source',source),('target',target)):
actual,digest=enum(Path(path),'SkillCategory')
if digest!=SKILL_CATEGORY_HEADERS[role]or actual.get(name)!=value:raise ValueError('Named item skill category namespace differs')
mappings.append(dict(source_name=name,target_name=name,source_value=value,target_value=value))
return dict(policy='named-weapon-and-secondary-skill-categories-v1',header_sha256=dict(SKILL_CATEGORY_HEADERS),mappings=mappings)
def validate_skill_category_reference(proof):
from spell_definition_common import validate_spell_category_namespace
if not isinstance(proof,dict)or set(proof)!={'policy','source_category','native_category','skill_category_namespace','spell_category_namespace'}or proof['policy']!=SKILL_CATEGORY_REFERENCE_POLICY:
raise ValueError('Explicit categorized skill reference required')
src=proof['source_category'];native=proof['native_category']
if not isinstance(src,list)or len(src)!=2 or any(type(v)is not int for v in src)or not 0<src[0]<=65535 or src[1]!=0:
raise ValueError('Source zero-flag spell category reference required')
if not isinstance(native,dict)or set(native)!={'ID','Name_lang','Flags','UsesPerWeek','MaxCharges','ChargeRecoveryTime','TypeMask'}:
raise ValueError('Complete native spell category reference required')
if native['ID']!=src[0]or native['Name_lang']!='Aura'or any(type(native[k])is not int or native[k]!=0 for k in native if k not in('ID','Name_lang'))or type(native['ID'])is not int:
raise ValueError('Native neutral Aura category identity differs')
expected=dict(policy='named-weapon-and-secondary-skill-categories-v1',header_sha256=dict(SKILL_CATEGORY_HEADERS),mappings=[dict(source_name=n,target_name=n,source_value=v,target_value=v)for n,v in(('SKILL_CATEGORY_WEAPON',6),('SKILL_CATEGORY_SECONDARY',9))])
if proof['skill_category_namespace']!=expected or any(type(r.get(k))is not int for r in proof['skill_category_namespace'].get('mappings',[])for k in('source_value','target_value')):
raise ValueError('Named weapon/secondary skill categories required')
validate_spell_category_namespace(proof['spell_category_namespace'])
return src[0]
def skill_category_reference(source_row,native_row,*,skill_namespace,spell_namespace):
proof=dict(policy=SKILL_CATEGORY_REFERENCE_POLICY,source_category=list(source_row),native_category=deepcopy(native_row),skill_category_namespace=deepcopy(skill_namespace),spell_category_namespace=deepcopy(spell_namespace))
validate_skill_category_reference(proof);return proof
NEW_STATIC_POLICIES={name:'new-item-'+name+'-literal-definition-candidate-v2'for name in('swim-speed','school-damage','aoe-damage-avoidance','damage-shield','casting-mana-regen')}
SKILL_CHILD_TABLES=('SpellMisc','SpellEffect','SpellEquippedItems','SpellClassOptions')
def new_skill_component(sources,native,schemas,maxima,registry,*,source_tables,
target_icon_names,new_icon_ids,icon_assets,read_icon):
"""Uninstalled missing-parent candidates; never creates learned/SLA entries.
Filtered absence and neutral higher attributes are explicitly unverified.
Installation requires original client API checks and real cache acceptance.
"""
if not isinstance(sources,list)or not 1<=len(sources)<=4096 or len({s['entry']for s in sources})!=len(sources):raise ValueError('New skill source count/identity differs')
if any(t not in native for t in(*REQUIRED_REFERENCE_TABLES,'SkillLine','SpellCastTimes','SpellDuration','SpellRange')):raise ValueError('Complete explicit new-skill native references required')
categorized=any(s.get('skill_category_reference')is not None for s in sources)
if categorized and any(s.get('skill_category_reference')is None for s in sources):raise ValueError('Mixed categorized and neutral skill definitions require separate components')
expected_tables={'SkillLine','SpellIcon','SpellCastTimes','SpellDuration','SpellRange'}|({'SpellCategory'}if categorized else set())
if categorized and 'SpellCategory'not in native:raise ValueError('Explicit native spell category reference required')
if set(source_tables)!=expected_tables or set(new_icon_ids)!={str(s['entry'])for s in sources}or not callable(read_icon):raise ValueError('Explicit source dependencies and icon identities required')
review_new_timing(source_tables,native,21)
available=available_index(icon_assets);registry=deepcopy(registry)
if registry.get('SkillLineAbility'):raise ValueError('Item skill definition must not allocate learned-spell links')
child_tables=SKILL_CHILD_TABLES+(('SpellCategories',)if categorized else())
occupied={t:{r['ID']for r in native[t]}for t in child_tables};new_registry_values(registry,maxima,occupied,tables=child_tables)
records=[];verification=[]
for src in sorted(sources,key=lambda s:s['entry']):
if not isinstance(src.get('class_family'),dict):raise ValueError('Explicit source spell-family metadata required for a new skill definition')
indices=validate_source(src,skill_bonus=True);ident=src['entry']
if any(src['levels'].values())or src['conditions']['procChance']not in(0,101):raise ValueError('New skill candidate has unreviewed source level/chance context')
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('New skill has a positive native reference: '+table)
category_ref=src.get('skill_category_reference')
if category_ref is not None:
category_id=validate_skill_category_reference(category_ref)
source_category=source_tables['SpellCategory'].by_id.get(category_id)
native_category=one(native['SpellCategory'],lambda r:r['ID']==category_id,'native Aura spell category')
if source_category is None or skill_category_reference(source_category,native_category,skill_namespace=category_ref['skill_category_namespace'],spell_namespace=category_ref['spell_category_namespace'])!=category_ref:
raise ValueError('Source/native categorized skill reference changed')
skills=[]
for index in indices:
e=src['effects'][index];raw=source_tables['SkillLine'].by_id.get(e[7]);row=one(native['SkillLine'],lambda r:r['ID']==e[7],'positive source skill identity')
if raw is None or len(raw)!=22 or raw[1]not in((6,9)if category_ref is not None else(6,))or row['CategoryID']!=raw[1]or row['DisplayName_lang']!=source_tables['SkillLine'].string(raw[3]):raise ValueError('Source/native weapon skill identity differs')
skills.append(dict(effect_index=index,skill_id=e[7],source_skill_name=row['DisplayName_lang'],source_aura=e[1],target_aura=e[1]))
fid,asset=verified_spell_icon(src,new_icon_ids,source_tables['SpellIcon'],target_icon_names,available,read_icon)
effects={i:dict(deepcopy(NEW_EFFECT_NEUTRAL),EffectAura=src['effects'][i][1],EffectBasePointsF=src['effects'][i][2]+1,EffectMiscValue=[src['effects'][i][7],0])for i in indices}
created=new_definition_records(src,effects,fid,schemas,maxima,registry,occupied,allocation_prefix='new-item-skill-definition')
if category_ref is not None:
for record in created:
if record['table_name']=='SpellCategories':
record['record']['Category']=src['category_id'];wire=encode(record['record'],schemas['SpellCategories']);record.update(wire_hex=wire.hex(),sha256=hashlib.sha256(wire).hexdigest())
records.extend(created)
verification.append(dict(spell_id=ident,source_record_sha256=canonical_sha256(src),skill_references=skills,icon_asset=dict(file_data_id=fid,**asset),class_family=deepcopy(src.get('class_family')),levels=deepcopy(src['levels']),source_proc_chance_without_proc_flags=src['conditions']['procChance'],filtered_reference_absence_only=True,installed_definition_absence_verified=False,known_spells_modified=False,engine_accepted=False,gameplay_verified=False))
if category_ref is not None:verification[-1].update(source_definition=deepcopy(src),skill_category_reference=deepcopy(category_ref),category_id=src['category_id'])
return dict(kind='source-item-skill-definition-candidates',build=BUILD,schema=SCHEMA,definition_policy=NEW_CATEGORIZED_SKILL_POLICY if categorized else NEW_SKILL_POLICY,records=records,spells=verification,child_id_registry=registry,id_remapping=False,dependency_complete=False,installable=False,installed=False,engine_accepted=False,gameplay_verified=False,limitations=['Supplied reference absence does not prove original client API unavailability or complete installed absence.','Native attributes5..16 use explicit neutral candidate values; no unknown client bit is synthesized.','No SkillLineAbility, learned-spell, racial or talent state records are created. Source skill identity is never widened based on a spell name.','No-trigger chance0/101 does not create a proc; actual aura activation remains server-driven.','Definitions, timing references and icon bytes do not prove engine cache acceptance, item-set activation or gameplay.'])
def new_static_component(sources,native,schemas,maxima,registry,*,source_tables,
target_icon_names,new_icon_ids,icon_assets,read_icon,
percent_stat=None,school_damage=False):
"""Missing permanent equipment aura definitions using existing semantics.
Only separately reviewed swim-speed, school-damage and casting mana regeneration policies apply.
Source level requirements, spell school and effect school masks stay distinct.
Reference absence is a candidate check, not original-engine acceptance.
"""
if type(school_damage)is not bool or (percent_stat,school_damage)not in(('swim-speed',False),('casting-mana-regen',False),(None,True)):
raise ValueError('Explicit separate new swim-speed, school-damage or casting mana regeneration policy required')
if not isinstance(sources,list)or not 1<=len(sources)<=4096 or len({s['entry']for s in sources})!=len(sources):raise ValueError('New static source count/identity differs')
if any(t not in native for t in(*REQUIRED_REFERENCE_TABLES,'SpellCastTimes','SpellDuration','SpellRange')):raise ValueError('Complete explicit new-static native references required')
if any(t not in schemas or t not in maxima for t in('Spell','SpellName',*NEW_DEFINITION_CHILD_TABLES)):raise ValueError('Complete new-static schema/allocation context required')
if set(source_tables)!={'SpellIcon','SpellCastTimes','SpellDuration','SpellRange'}or set(new_icon_ids)!={str(s['entry'])for s in sources}or not callable(read_icon):raise ValueError('Explicit source dependencies and icon identities required')
review_new_timing(source_tables,native,21)
available=available_index(icon_assets);registry=deepcopy(registry)
if registry.get('SkillLineAbility'):raise ValueError('Item definition must not allocate learned-spell links')
occupied={t:{r['ID']for r in native[t]}for t in NEW_DEFINITION_CHILD_TABLES}
new_registry_values(registry,maxima,occupied,tables=NEW_DEFINITION_CHILD_TABLES)
records=[];verification=[]
for src in sorted(sources,key=lambda s:s['entry']):
if not isinstance(src.get('class_family'),dict):raise ValueError('Explicit source spell-family metadata required for a new static definition')
indices=validate_source(src,percent_stat=percent_stat,school_damage=school_damage);ident=src['entry']
if src['conditions']['procChance']not in(0,101):raise ValueError('New static candidate has unreviewed source chance context')
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('New static has a positive native reference: '+table)
fid,asset=verified_spell_icon(src,new_icon_ids,source_tables['SpellIcon'],target_icon_names,available,read_icon)
effects={i:dict(deepcopy(NEW_EFFECT_NEUTRAL),EffectAura=src['effects'][i][1],EffectBasePointsF=src['effects'][i][2]+1,EffectMiscValue=[src['effects'][i][7],0])for i in indices}
presented=deepcopy(src);presented.update(static_description_fields(src,percent_stat=percent_stat,school_damage=school_damage))
records.extend(new_definition_records(presented,effects,fid,schemas,maxima,registry,occupied,allocation_prefix='new-item-static-definition'))
for row in records:
if row['table_name']=='Spell'and row['source_spell_id']==ident:row['constant_description_policy']=NEW_STATIC_POLICIES[percent_stat or 'school-damage']
verification.append(dict(spell_id=ident,source_definition=deepcopy(src),source_record_sha256=canonical_sha256(src),effect_indices=indices,effects=[dict(index=i,source_aura=src['effects'][i][1],target_aura=src['effects'][i][1],amount=src['effects'][i][2]+1,misc=src['effects'][i][7])for i in indices],icon_asset=dict(file_data_id=fid,**asset),class_family=deepcopy(src['class_family']),levels=deepcopy(src['levels']),source_school_index=src['school'],target_school_mask=1<<src['school'],filtered_reference_absence_only=True,installed_definition_absence_verified=False,known_spells_modified=False,engine_accepted=False,gameplay_verified=False))
return dict(kind='source-item-static-definition-candidates',build=BUILD,schema=SCHEMA,definition_policy=NEW_STATIC_POLICIES[percent_stat or 'school-damage'],records=records,spells=verification,child_id_registry=registry,id_remapping=False,dependency_complete=False,installable=False,installed=False,engine_accepted=False,gameplay_verified=False,limitations=['Supplied reference absence does not prove original client API unavailability.','Native attributes5..16 use explicit neutral candidate values.','No learned-spell, talent or racial links are created; the server owns aura application.','Definition loading and descriptions do not prove gameplay effects.'])
def static_description_fields(src,*,percent_stat=None,school_damage=False):
"""Literal source amounts for proven constant equipment aura descriptions.
Original70334 API56529 rendered69 as1796 with a generic $s1 token. Keep
effect69 intact; avoid destination expected-stat presentation for these
unconditional, non-scaling source amounts. No dynamic spell text applies.
"""
if type(school_damage)is not bool or(percent_stat,school_damage)not in(('swim-speed',False),('casting-mana-regen',False),(None,True)):raise ValueError('Explicit constant equipment text policy required')
indices=validate_source(src,percent_stat=percent_stat,school_damage=school_damage)
def literal(match):
index=int(match[1])-1
if index not in indices:raise ValueError('Constant description references inactive effect')
return str(src['effects'][index][2]+1)
return {key:re.sub(r'\$s([123])(?![0-9])',literal,src[key])for key in('description','auraDescription')}
TEXT_POLICY='source-item-linked-text-with-verified-effect-token-indices-v6'
TEXT_NAMESPACE_POLICY='named-source-native-item-tooltip-effect-enums-v1'
def item_text_namespace(paths):
"""Compare symbolic enum names from the pinned source and target headers."""
from pathlib import Path
from aura_definition_profile import scalar_namespace
proof=scalar_namespace(paths)
def names(path,prefix):
text=re.sub(r'/\*.*?\*/|//[^\n]*','',Path(path).read_text(),flags=re.S)
return {m[1]:int(m[2],0)for m in re.finditer(r'\b('+prefix+r'[A-Z0-9_]+)\s*=\s*(0x[0-9A-Fa-f]+|[0-9]+)\s*[,}]',text)}
groups={}
for label,prefix,suffix in [('effects','SPELL_EFFECT_','defines'),('auras','SPELL_AURA_','auras')]:
source=names(paths['source_'+suffix],prefix);target=names(paths['target_'+suffix],prefix);shared={}
for name,value in source.items():
if target.get(name)==value:shared.setdefault(str(value),[]).append(name)
groups[label]={k:sorted(v)for k,v in sorted(shared.items(),key=lambda kv:int(kv[0]))}
return dict(policy=TEXT_NAMESPACE_POLICY,header_sha256=proof['header_sha256'],**groups)
def item_text_rows(source_dbc,item_rows,native_text,native_effects,published_rows,text_schema,namespace,*,effect_schema=None,duration_context=None,name_context=None):
"""Batch source text and equivalent local/cross-spell $sN/$tN references.
This is presentation only. Duration tokens require matching source/native
bindings and signed duration semantics. Tick intervals require the actual
same-effect period. Periodic totals, arithmetic, conditional and enchantment
tokens remain explicit blockers.
"""
from turtle_data import spell_layout
import struct
if source_dbc.fields!=173 or canonical_sha256(text_schema)!=TABLES['Spell'][2]:raise ValueError('Reviewed source/target spell text schemas required')
from aura_definition_profile import SCALAR_POLICY,SCALAR_HEADER_PINS
token_enums=None
if namespace!=dict(policy=SCALAR_POLICY,header_sha256=SCALAR_HEADER_PINS):
if namespace.get('policy')!=TEXT_NAMESPACE_POLICY or namespace.get('header_sha256')!=SCALAR_HEADER_PINS:raise ValueError('Reviewed source/target enum namespace required')
for key,prefix in [('effects','SPELL_EFFECT_'),('auras','SPELL_AURA_')]:
values=namespace.get(key)
if not isinstance(values,dict)or not values or any(not isinstance(k,str)or not k.isdecimal()or not 0<=int(k)<=65535 or not isinstance(v,list)or not v or any(not isinstance(n,str)or not re.fullmatch(prefix+'[A-Z0-9_]+',n)for n in v)for k,v in values.items()):raise ValueError('Named tooltip effect enum proof required')
token_enums=namespace
native={r['ID']:deepcopy(r)for r in native_text}
constant_descriptions={}
effects={r['ID']:deepcopy(r)for r in native_effects}
misc={}
if len(native)!=len(native_text)or len(effects)!=len(native_effects):raise ValueError('Duplicate native text/effect identity')
if duration_context is not None:
if not isinstance(duration_context,dict)or set(duration_context)!={'source','native','misc','misc_schema'}or duration_context['source'].fields!=4:raise ValueError('Complete source/native tooltip duration context required')
misc={r['ID']:deepcopy(r)for r in duration_context['misc']}
if len(misc)!=len(duration_context['misc']):raise ValueError('Duplicate native tooltip timing identity')
names={}
if name_context is not None:
if not isinstance(name_context,dict)or set(name_context)!={'native','schema'}or canonical_sha256(name_context['schema'])!=TABLES['SpellName'][2]:raise ValueError('Reviewed source spell-name context required')
names={r['ID']:deepcopy(r)for r in name_context['native']}
if len(names)!=len(name_context['native']):raise ValueError('Duplicate native spell-name identity')
targets={'Spell':(native,text_schema),'SpellEffect':(effects,effect_schema)}
if duration_context is not None:targets['SpellMisc']=(misc,duration_context['misc_schema'])
if name_context is not None:targets['SpellName']=(names,name_context['schema'])
# The effective package may ADD source spells/effects absent from a filtered
# native extract. These records are just as relevant as replacements. Check
# both schemas and payloads before merging; presence is not engine acceptance.
for row in published_rows:
table=row.get('table_name')
if table in targets:
target,schema=targets[table]
if row.get('record_status','valid')!='valid':raise ValueError('Published spell/effect removal is not a text policy')
contract=(TABLES|SUPPLEMENTAL_TABLES)[table]
if schema is None or canonical_sha256(schema)!=contract[2]:raise ValueError('Reviewed published text/effect schema required')
r=row.get('record')
if not isinstance(r,dict)or type(row.get('id'))is not int or not 0<row['id']<=0x7fffffff or r.get('ID')!=row['id']or row.get('table_hash')!=hex(contract[0]):raise ValueError('Published item text/effect identity differs')
raw=encode(r,schema)
if row.get('wire_hex')!=raw.hex()or row.get('sha256')!=hashlib.sha256(raw).hexdigest():raise ValueError('Published item text/effect bytes differ')
target[row['id']]=deepcopy(r)
if table=='Spell'and(row.get('constant_description_policy')in NEW_STATIC_POLICIES.values()or row.get('allocation_policy')=='new-item-static-definition-parent'):
constant_descriptions[row['id']]=row.get('constant_description_policy','previous-reviewed-static-definition')
ids=sorted({integer(item['spellid_'+str(i)],0,0x7fffffff,'source item spell')for item in item_rows for i in range(1,6)}-{0})
if len(ids)>100000:raise ValueError('Source text batch bound')
layout=spell_layout();records=[];blocked=[];unchanged=[];name_blocked=[]
by_spell={}
for e in effects.values():
if e['DifficultyID']==0:by_spell.setdefault(e['SpellID'],[]).append(e)
def signed(value):return struct.unpack('<i',struct.pack('<I',value))[0]
def real(value):return struct.unpack('<f',struct.pack('<I',value))[0]
# Named enums already reviewed in the pinned four-header contract. Other
# numeric effect/aura pairs are not assumed equivalent by this text policy.
named={(6,99),(19,0),(6,75),(53,0)}
amount_token=re.compile(r'\$(?:([1-9][0-9]{0,9}))?s([123])(?![0-9])')
# Actual original70334 API51898/51899 resolves the source /10 syntax.
# Only exact positive integer constants are reviewed below; other legacy
# arithmetic and rounding remain separate unsupported expressions.
division_token=re.compile(r'\$/10;(?:([1-9][0-9]{0,9}))?s([123])(?![0-9])')
period_token=re.compile(r'\$(?:([1-9][0-9]{0,9}))?t([123])(?![0-9])')
duration_token=re.compile(r'\$(?:([1-9][0-9]{0,9}))?d(?![A-Za-z0-9])')
by_misc={}
for row in misc.values():
if row['DifficultyID']==0:by_misc.setdefault(row['SpellID'],[]).append(row)
for ident in ids:
s=source_dbc.by_id.get(ident);old=native.get(ident)
if ident in constant_descriptions:
# This narrower converter has actual native evidence that generic
# $sN formatting scales fixed source values. Keep its literals and
# require that policy to revalidate them when the source changes.
blocked.append(dict(spell=ident,reason='published constant item text requires its static policy revalidation'))
continue
if s is None or old is None:blocked.append(dict(spell=ident,reason='source or accessible native text missing'));continue
new=deepcopy(old);mapping={};references={};amount_relations=set();duration_reviews={};range_reviews={};period_reviews={};division_reviews={};reason=None
for field in ('NameSubtext_lang','Description_lang','AuraDescription_lang'):
text=source_dbc.string(s[layout[field]])
if len(text.encode())>4096:reason='source text bound';break
divided=list(division_token.finditer(text));tokens=list(amount_token.finditer(text))+divided
if '$'in amount_token.sub('',division_token.sub('',period_token.sub('',duration_token.sub('',text)))):reason='complex source tooltip tokens require their own verified relation';break
for token in duration_token.finditer(text):
reference=int(token[1])if token[1]else ident
if reference in duration_reviews:continue
if duration_context is None:reason='source tooltip duration context missing';break
source=source_dbc.by_id.get(reference);timing=by_misc.get(reference,[])
if reference>0x7fffffff or source is None or reference not in native or len(timing)!=1:reason='source tooltip referenced timing definition missing or ambiguous';break
duration=source[layout['DurationIndex']]
if timing[0].get('PvPDurationIndex',0)or timing[0].get('MinDuration',0):reason='source/native tooltip duration binding differs';break
try:
from spell_definition_common import review_duration_reference
# Duration IDs are table-local references, not spell IDs.
# Follow the actual native binding and prove its signed
# timing fields match; never rewrite either spell identity.
duration_reviews[reference]=review_duration_reference(duration_context['source'],duration_context['native'],duration,native_id=timing[0]['DurationIndex'])
except ValueError as error:reason='source tooltip duration: '+str(error);break
if reason:break
for token in tokens:
reference=int(token[1])if token[1]else ident;index=int(token[2])-1
relation=(reference,index)
if relation in amount_relations and token.re is not division_token:continue
source=source_dbc.by_id.get(reference)
if reference>0x7fffffff or source is None or reference not in native:reason='source tooltip referenced spell definition missing';break
shape=(source[layout['Effect']+index],source[layout['EffectAura']+index])
if not ((str(shape[0])in token_enums['effects']and (shape[1]==0 or str(shape[1])in token_enums['auras']))if token_enums else shape in named):reason='effect token semantic family not reviewed';break
die=signed(source[layout['EffectDieSides']+index]);per=real(source[layout['EffectRealPointsPerLevel']+index])
if not math.isfinite(per)or int(per)!=per:reason='fractional source tooltip level rounding unresolved';break
variable=die not in(0,1)
if real(source[layout['EffectDicePerLevel']+index])!=0 or variable and (die<2 or per!=0):reason='random source tooltip amount';break
value=signed(source[layout['EffectBasePoints']+index])+(die if die else 0)
if token.re is division_token:
if variable or per or value<=0 or value%10:reason='division tooltip requires an exact positive constant quotient';break
division_reviews[f'{reference}:{index}']=dict(divisor=10,source_operand=value,source_quotient=value//10)
candidates=[e for e in by_spell.get(reference,[])if(e['Effect'],e['EffectAura'])==shape and e['EffectMiscValue'][0]==signed(source[layout['EffectMiscValue']+index])and e['EffectTriggerSpell']==source[layout['EffectTriggerSpell']+index]and e['EffectRealPointsPerLevel']==per and not any(e[k]for k in ('Coefficient','ResourceCoefficient','EffectPointsPerResource','EffectBonusCoefficient','BonusCoefficientFromAP','ScalingClass','EffectAttributes'))and e['GroupSizeBasePointsCoefficient']==1 and e['PvpMultiplier']==1]
if variable:
from spell_definition_common import review_existing_effect_range
matched=[]
for effect in candidates:
try:review_existing_effect_range(signed(source[layout['EffectBasePoints']+index]),die,effect)
except ValueError:continue
matched.append(effect)
candidates=matched
else:candidates=[e for e in candidates if e['EffectBasePointsF']==value and not e['Variance']]
if relation in references:candidates=[e for e in candidates if e['EffectIndex']==references[relation]]
if len(candidates)!=1:reason='source token has no unique amount-compatible native effect';break
if variable:range_reviews[f'{reference}:{index}']=dict(review_existing_effect_range(signed(source[layout['EffectBasePoints']+index]),die,candidates[0]),native_effect_id=candidates[0]['ID'])
references[relation]=candidates[0]['EffectIndex']
amount_relations.add(relation)
if not token[1]:mapping[index]=candidates[0]['EffectIndex']
if reason:break
for token in period_token.finditer(text):
reference=int(token[1])if token[1]else ident;index=int(token[2])-1
relation=(reference,index);review_key=f'{reference}:{index}'
if review_key in period_reviews:continue
source=source_dbc.by_id.get(reference)
if reference>0x7fffffff or source is None or reference not in native:reason='source tooltip referenced spell definition missing';break
shape=(source[layout['Effect']+index],source[layout['EffectAura']+index])
if not ((str(shape[0])in token_enums['effects']and str(shape[1])in token_enums['auras'])if token_enums else shape in named)or not shape[1]:reason='periodic token semantic family not reviewed';break
# The source disk DBD calls this EffectAuraPeriod. The SQL-
# expanded server SpellEntry calls it EffectAmplitude; its
# formatter divides milliseconds by1000. Only whole seconds
# are admitted, avoiding unverified fractional rounding.
period=source[layout['EffectAuraPeriod']+index]
if type(period)is not int or not 0<period<=0x7fffffff or period%1000:reason='source tooltip period is not reviewed whole seconds';break
candidates=[e for e in by_spell.get(reference,[])if(e['Effect'],e['EffectAura'])==shape and e['EffectMiscValue'][0]==signed(source[layout['EffectMiscValue']+index])and e['EffectTriggerSpell']==source[layout['EffectTriggerSpell']+index]and e['EffectAuraPeriod']==period and not e['EffectAttributes']and (relation not in references or e['EffectIndex']==references[relation])]
if len(candidates)!=1:reason='source token has no unique period-compatible native effect';break
effect=candidates[0];references[relation]=effect['EffectIndex']
if not token[1]:mapping[index]=effect['EffectIndex']
period_reviews[review_key]=dict(source_period_ms=period,native_period_ms=effect['EffectAuraPeriod'],native_effect_id=effect['ID'],source_effect_index=index,native_effect_index=effect['EffectIndex'])
if reason:break
def rewrite(token,kind):return '$'+(token[1]or'')+kind+str(references[(int(token[1])if token[1]else ident,int(token[2])-1)]+1)
new[field]=division_token.sub(lambda m:'$/10;'+(m[1]or'')+'s'+str(references[(int(m[1])if m[1]else ident,int(m[2])-1)]+1),period_token.sub(lambda m:rewrite(m,'t'),amount_token.sub(lambda m:rewrite(m,'s'),text)))
if reason:blocked.append(dict(spell=ident,reason=reason));continue
if name_context is not None:
source_name=source_dbc.string(s[layout['Name_lang']]);old_name=names.get(ident)
if old_name is None or not source_name or len(source_name.encode())>4096:
name_blocked.append(dict(spell=ident,reason='source or accessible native name missing/invalid'))
elif old_name['Name_lang']!=source_name:
new_name=dict(old_name,Name_lang=source_name);raw_name=encode(new_name,name_context['schema'])
records.append(dict(table_name='SpellName',table_hash=hex(TABLES['SpellName'][0]),id=ident,record=new_name,wire_hex=raw_name.hex(),sha256=hashlib.sha256(raw_name).hexdigest(),policy=TEXT_POLICY,source_spell_id=ident,baseline_record_sha256=canonical_sha256(old_name),source_record_sha256=canonical_sha256(list(s))))
if new==old:unchanged.append(ident);continue
raw=encode(new,text_schema)
records.append(dict(table_name='Spell',table_hash=hex(TABLES['Spell'][0]),id=ident,record=new,wire_hex=raw.hex(),sha256=hashlib.sha256(raw).hexdigest(),policy=TEXT_POLICY,source_spell_id=ident,baseline_record_sha256=canonical_sha256(old),source_record_sha256=canonical_sha256(list(s)),source_to_native_effect_indices={str(k):v for k,v in sorted(mapping.items())}))
cross={f'{spell}:{index}':value for(spell,index),value in sorted(references.items())if spell!=ident}
if cross:
records[-1]['referenced_source_to_native_effect_indices']=cross
records[-1]['referenced_source_record_sha256']={str(spell):canonical_sha256(list(source_dbc.by_id[spell]))for spell,index in sorted(references)if spell!=ident}
if duration_reviews:
records[-1]['duration_reference_reviews']={str(k):v for k,v in sorted(duration_reviews.items())}
records[-1]['source_duration_dbc_sha256']=duration_context['source'].digest()
if range_reviews:records[-1]['existing_variable_range_reviews']=range_reviews
if period_reviews:records[-1]['periodic_interval_reviews']=period_reviews
if division_reviews:records[-1]['constant_division_reviews']=division_reviews
return dict(kind='source-item-linked-text-batch',policy=TEXT_POLICY,rows=records,blocked=blocked,unchanged=unchanged,name_blocked=name_blocked,source_linked_spells=len(ids),source_dbc_sha256=source_dbc.digest(),installed=False,engine_accepted=False,gameplay_verified=False)
def review_categorized_skill_record(src,spell_metadata,row):
"""Exact new categorized-skill rows for the shared package reviewer.
Callers independently review raw source/DBC capture, icon bytes, original API
absence, reference inputs, schema/encoding, allocations and complete tables.
"""
if src.get('skill_category_reference') is None:
raise ValueError('Categorized skill source reference missing')
indices=validate_source(src,skill_bonus=True);ident=src['entry']
if spell_metadata.get('source_record_sha256')!=canonical_sha256(src)or spell_metadata.get('source_definition')!=src or spell_metadata.get('skill_category_reference')!=src['skill_category_reference']or spell_metadata.get('category_id')!=src['category_id']:
raise ValueError('Categorized skill metadata/source identity differs')
rid=row.get('id');table=row.get('table_name');record=row.get('record')
if row.get('source_spell_id')!=ident or not isinstance(record,dict)or record.get('ID')!=rid:raise ValueError('Categorized skill row identity differs')
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':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[table],ID=rid,SpellID=ident,Category=src['category_id'],DefenseType=src['defense_type'],PreventionType=src['prevention_type'])
elif table=='SpellEffect':
index=record.get('EffectIndex')
if type(index)is not int or index not in indices:raise ValueError('Categorized skill effect index differs')
effect=src['effects'][index];expected=dict(deepcopy(NEW_EFFECT_NEUTRAL),ID=rid,SpellID=ident,EffectIndex=index,EffectAura=effect[1],EffectBasePointsF=effect[2]+1,EffectMiscValue=[effect[7],0])
elif table=='SpellClassOptions':
family=validate_family(src['class_family'],warrior=True)
if not family:raise ValueError('Unreviewed neutral skill family row')
expected=dict(ID=rid,SpellID=ident,ModalNextSpell=0,SpellClassSet=family,SpellClassMask=[0]*4)
else:raise ValueError('Unreviewed categorized skill row table')
if record!=expected:raise ValueError('Categorized skill row semantics differ: '+table)
return True