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

802 lines
66 KiB
Python

#!/usr/bin/env python3
"""Build reviewed passive item-effect/link records, retaining genuine spell IDs.
Destination-only row IDs are allocated beyond the full native table bounds and
persist in an explicit registry. Shared effects are preserved; explicit timing
refresh clones records while retaining parent identities. New proc/use/charged/
conditional effects require separate review.
"""
import argparse,copy,hashlib,json,struct,math
from pathlib import Path
from item_sparse_compat import ROOT,fields,encode,check_db2
NATIVE=Path.home()/'Projects/WoW-Hybrid/servers/trinity-forever/install/bin/dbc/enUS'
DBD=Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions'
TABLES={'ItemEffect':(0x4002a5b1,0x4ca77678,9),'ItemXItemEffect':(0x00cb674f,0x96f083ad,2)}
ON_HIT_HEADERS=dict(source='243c0244d03e1af290a1c6fbd4f9cfaecc0a7f5298de67530f77ebddcd96f26e',target='5cc1a60184e3f38745ed0bb7217f9e30d7962dc26f7d38798a8735687eac966f')
def _on_hit_contract():
return dict(policy='named-item-on-hit-trigger-v1',header_sha256=dict(ON_HIT_HEADERS),
source_name='ITEM_SPELLTRIGGER_CHANCE_ON_HIT',target_name='ITEM_SPELLTRIGGER_ON_PROC',source_trigger=2,target_trigger=2)
def on_hit_namespace(source,target):
from spell_result_profile import enum
for role,path,name in(('source',source,'ITEM_SPELLTRIGGER_CHANCE_ON_HIT'),('target',target,'ITEM_SPELLTRIGGER_ON_PROC')):
values,digest=enum(Path(path),'ItemSpelltriggerType')
if digest!=ON_HIT_HEADERS[role]or values.get(name)!=2:raise ValueError('Pinned item on-hit trigger namespace differs')
return _on_hit_contract()
def review_on_hit(source,context,snapshot):
if context is None:
if snapshot is not None:raise ValueError('Proc snapshot requires explicit item trigger namespace')
return None
if not isinstance(context,dict)or context!=_on_hit_contract()or any(type(context.get(k))is not int for k in('source_trigger','target_trigger')):
raise ValueError('Verified named item on-hit namespace required')
ids={p['spellid_'+str(i)]for p in source for i in range(1,6)if p['spellid_'+str(i)]and p['spelltrigger_'+str(i)]==2}
if not ids:return dict(source_spell_ids=[],overrides_absent=True,server_authoritative=True)
from spell_definition_common import review_proc_override_snapshot
review=review_proc_override_snapshot(snapshot,ids)
if not review['overrides_absent']:raise ValueError('Source on-hit proc overrides need separate review')
return review
def _on_use_contract():
return dict(policy='named-equipped-item-on-use-trigger-v1',header_sha256=dict(ON_HIT_HEADERS),
source_name='ITEM_SPELLTRIGGER_ON_USE',target_name='ITEM_SPELLTRIGGER_ON_USE',source_trigger=0,target_trigger=0)
def on_use_namespace(source,target):
from spell_result_profile import enum
for role,path in(('source',source),('target',target)):
values,digest=enum(Path(path),'ItemSpelltriggerType')
if digest!=ON_HIT_HEADERS[role]or values.get('ITEM_SPELLTRIGGER_ON_USE')!=0 or values.get('ITEM_SPELLTRIGGER_ON_EQUIP')!=1:
raise ValueError('Pinned item use/equip trigger namespace differs')
return _on_use_contract()
def review_on_use(source,context):
"""Uncharged equipment only; consumed items and categories stay separate."""
if context is None:return None
if not isinstance(context,dict)or context!=_on_use_contract()or any(type(context.get(k))is not int for k in('source_trigger','target_trigger')):
raise ValueError('Verified named equipped-item use namespace required')
ids=set()
for proto in source:
for i in range(1,6):
if not proto['spellid_'+str(i)]or proto['spelltrigger_'+str(i)]!=0:continue
if (type(proto['spellid_'+str(i)])is not int or not 0<proto['spellid_'+str(i)]<2**31
or type(proto['spelltrigger_'+str(i)])is not int
or type(proto.get('class'))is not int or proto['class']not in(2,4)
or type(proto.get('inventory_type'))is not int or proto['inventory_type']not in(*range(1,18),19,20,21,22,23,26,28)
or any(proto.get(k)for k in('script_name','extra_flags','duration'))):raise ValueError('Unreviewed equipped-item use execution context')
for field in('spellcharges_','spellppmrate_','spellcategory_'):
value=proto[field+str(i)]
if type(value)not in(int,float)or value!=0:raise ValueError('Charged, PPM or category use requires separate review')
for field in('spellcooldown_','spellcategorycooldown_'):
value=proto[field+str(i)]
if type(value)is not int or not -1<=value<=86400000:raise ValueError('Equipped-item use cooldown bound')
ids.add(proto['spellid_'+str(i)])
return dict(source_spell_ids=sorted(ids),policy=context['policy'],server_authoritative=True,gameplay_verified=False)
def review_passive_category_references(references):
"""Source-checked skill definitions with explicit neutral Aura categories.
This does not admit category cooldowns, charged uses, PPM or other aura
mechanics. The caller still owns definition publication and source capture.
"""
if references is None:return {}
if not isinstance(references,dict)or not 1<=len(references)<=4096:raise ValueError('Bounded passive category source definitions required')
from spell_item_static_compat import validate_source,validate_skill_category_reference
reviewed={}
for key,source in references.items():
if not isinstance(source,dict)or str(key)!=str(source.get('entry'))or type(source.get('entry'))is not int or source['entry']in reviewed:
raise ValueError('Passive category source identity differs')
validate_source(source,skill_bonus=True)
category=validate_skill_category_reference(source.get('skill_category_reference'))
if source.get('category_id')!=category:raise ValueError('Passive category source/reference differs')
reviewed[source['entry']]=source
return reviewed
def _passive_category_allowed(proto,index,trigger,references):
category=proto['spellcategory_'+str(index)]
if type(category)is not int:return False
if not category:return True
source=references.get(proto['spellid_'+str(index)])
return (source is not None and category==source['category_id']and trigger==1
and type(proto.get('class'))is int and proto['class']in(2,4)
and all(type(proto[k+str(index)])in(int,float)and proto[k+str(index)]==0 for k in('spellcharges_','spellppmrate_'))
and all(type(proto[k+str(index)])is int and proto[k+str(index)]==0 for k in('spellcooldown_','spellcategorycooldown_'))
and not any(proto.get(k)for k in('script_name','extra_flags','duration')))
def _allowed_triggers(on_hit_review,on_use_review):
return(1,)+((2,)if on_hit_review is not None else())+((0,)if on_use_review is not None else())
def _cooldown_allowed(proto,index,trigger,on_use_review):
if trigger==0 and on_use_review is not None:
return all(type(proto[k+str(index)])is int and -1<=proto[k+str(index)]<=86400000 for k in('spellcooldown_','spellcategorycooldown_'))
return proto['spellcooldown_'+str(index)]in(-1,0)and proto['spellcategorycooldown_'+str(index)]in(-1,0)
def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()
def effective_item_links(native_links,package_rows):
"""Actual link ownership after reviewed replacements and tombstones."""
result={r['ID']:dict(r)for r in native_links}
if len(result)!=len(native_links):raise ValueError('Duplicate native item link identity')
for row in package_rows:
if row['table_name']!='ItemXItemEffect':continue
if row.get('record_status','valid')=='removed':result.pop(row['id'],None)
else:result[row['id']]=dict(ID=row['id'],**row['record'])
return [result[key]for key in sorted(result)]
def _source_ppm_allowed(value,trigger,reviewed):
# Native ItemEffect has no PPM column. Positive rates remain explicit
# source/server metadata; never encode a made-up client proc probability.
return type(value)in(int,float)and math.isfinite(value)and(value==0 or(reviewed and trigger==2 and value>0))
def review_obtainability_reference(reference, *, missing_slots_only):
"""Admit only the saved source-query/equipped-slot flag-4 contract."""
if reference is None:return False
expected={'policy':'source-query-equipped-slot-obtainability-v1','source_flag_name':'ITEM_EXTRA_NOT_OBTAINABLE',
'source_flag_value':4,'scope':'additive-reviewed-equipment-slots','source_extra_flags_on_wire':False}
if (not missing_slots_only or not isinstance(reference,dict)
or any(reference.get(k)!=v for k,v in expected.items())
or not isinstance(reference.get('reference_source_receipt'),str)
or not reference['reference_source_receipt']):
raise ValueError('Reviewed source obtainability metadata context required')
return True
def compose_passive_link_completion(package,items,reviewed_spell_ids,effects,links,schemas,maxima,*,on_hit_context=None,proc_override_snapshot=None,on_use_context=None,allow_on_hit_replacement=False,missing_slots_only=False,passive_category_references=None,native_item_reuse=None,obtainability_reference=None,effective_parent_authority=None):
"""Complete source-reviewed per-item passives after metadata publication.
Set membership is independent of per-piece effects. Default completion
requires every source spell to pass the caller's definition review.
Exact existing slots remain; conflicting slots stay explicitly held.
Only original native links can receive the existing reviewed tombstones.
No metadata, shared effect row, learned spell or character state is changed.
Explicit missing-slots mode adds only independently reviewed equipment
passives, retaining every existing link and reporting unresolved source slots.
Explicit native Item reuse permits only the source-entry-bound, already
reviewed stat-only Sparse family and records source effect-slot authority.
Explicit effective-parent authority admits separately pinned, complete
compatible parents without claiming unrelated source-template equality.
Its unsupported or occupied source slots remain deferred independently.
"""
from item_basic_compat import encode as basic_encode
from item_sparse_compat import package_payloads,package_pages
if (package.get('build')!='1.60.1.70334'or package.get('schema')!='wowstatic_camelot_1_60_1'
or package.get('push_id')!=package_payloads(package['rows'])[0]):raise ValueError('Passive-link preserved package differs')
if (not isinstance(reviewed_spell_ids,set)or len(reviewed_spell_ids)>4096
or any(type(i)is not int or not 0<i<0x80000000 for i in reviewed_spell_ids)):raise ValueError('Explicit reviewed spell IDs required')
if not isinstance(items,list)or not 1<=len(items)<=4096 or len({r['entry']for r in items})!=len(items):raise ValueError('Passive-link item selection differs')
if type(allow_on_hit_replacement)is not bool:raise ValueError('Explicit on-hit replacement review required')
if type(missing_slots_only)is not bool:raise ValueError('Typed missing-slot completion policy required')
if missing_slots_only and any((on_hit_context is not None,on_use_context is not None,allow_on_hit_replacement)):
raise ValueError('Missing-slot completion is additive equipment passives only')
on_hit_review=review_on_hit([r['source']for r in items],on_hit_context,proc_override_snapshot)
on_use_review=review_on_use([r['source']for r in items],on_use_context)
category_sources=review_passive_category_references(passive_category_references)
# Local/reference ItemQuery and equipped-passive consumers do not
# transmit or branch on NOT_OBTAINABLE4. This permits only descriptive
# source slots; every other item execution dependency remains strict.
review_obtainability_reference(obtainability_reference,missing_slots_only=missing_slots_only)
# A source-published Item is a producer authority gate, not a DB2 link
# admission rule. Explicit additive reuse retains the complete original
# Item and an already reviewed stat-only Sparse override; authority extends
# only to source effect slots, never to the preserved template fields.
native_slot_items={};native_slot_receipt=None
if native_item_reuse is not None:
if (not missing_slots_only or not isinstance(native_item_reuse,dict)
or native_item_reuse.get('kind')!='source-entry-native-item-effect-slot-authority-v1'
or native_item_reuse.get('source_entry_field')!='Turtle::OBJECT_FIELD_ENTRY'
or native_item_reuse.get('native_entry_field')!='WorldPackets::Item::ItemBonusKey.ItemID'
or not isinstance(native_item_reuse.get('entry_binding_receipt'),str)
or not native_item_reuse['entry_binding_receipt']
or not isinstance(native_item_reuse.get('native_items'),list)
or not 1<=len(native_item_reuse['native_items'])<=4096):
raise ValueError('Explicit additive native Item slot authority required')
native_slot_items={r['ID']:r for r in native_item_reuse['native_items']}
if len(native_slot_items)!=len(native_item_reuse['native_items']):raise ValueError('Duplicate native Item slot authority')
native_slot_receipt=native_item_reuse['entry_binding_receipt']
# Independent field authority for complete effective parents. Unrelated
# source/native name/stat/price differences are not an ItemXItemEffect key
# requirement. Exact parent type, bytes and typed source-entry binding stay
# mandatory; no original/published parent metadata is rewritten.
effective_parents={}
if effective_parent_authority is not None:
expected={'kind':'source-entry-effective-item-effect-slot-authority-v1',
'source_entry_field':'Turtle::OBJECT_FIELD_ENTRY',
'native_entry_field':'WorldPackets::Item::ItemBonusKey.ItemID',
'scope':'additive-reviewed-equipment-slots-only',
'entry_binding_receipt':'docs/evidence/content-data/source-native-item-entry-authority-20261023/assessment.json',
'relationship_receipt':'docs/evidence/content-data/item-passive-native-original-reassessment-20261023/assessment.json'}
if (not missing_slots_only or native_item_reuse is not None
or not isinstance(effective_parent_authority,dict)
or any(effective_parent_authority.get(k)!=v for k,v in expected.items())
or not isinstance(effective_parent_authority.get('parents'),list)
or not 1<=len(effective_parent_authority['parents'])<=4096):
raise ValueError('Explicit effective-parent effect-slot authority required')
if any(not isinstance(r,dict) or type(r.get('ID'))is not int or not 0<r['ID']<0x80000000
or not isinstance(r.get('basic_record'),dict) or not isinstance(r.get('sparse_record'),dict)
or not isinstance(r.get('wire_sha256'),dict) or set(r['wire_sha256'])!={'Item','ItemSparse'}
for r in effective_parent_authority['parents']):
raise ValueError('Complete typed effective-parent records required')
effective_parents={r['ID']:r for r in effective_parent_authority['parents']}
if len(effective_parents)!=len(effective_parent_authority['parents']):
raise ValueError('Duplicate effective-parent effect-slot authority')
published={(r['table_name'],r['id']):r for r in package['rows']}
if len(published)!=len(package['rows']):raise ValueError('Duplicate preserved passive-link identity')
by_effect={r['ID']:dict(r)for r in effects}
if len(by_effect)!=len(effects):raise ValueError('Duplicate passive effect baseline')
for row in package['rows']:
if row['table_name']=='ItemEffect':
if row.get('record_status','valid')!='valid':raise ValueError('Shared effect removals are unreviewed')
by_effect[row['id']]=dict(row['record'],ID=row['id'])
effective=effective_item_links(links,package['rows']);by_item={}
for link in effective:by_item.setdefault(link['ItemID'],[]).append(link)
selected=[];preserved=[];blocked=[];deferred_slots=[];native_slot_selected={}
effect_fields=[field[0]for field in schemas['ItemEffect']]
for item in sorted(items,key=lambda r:r['entry']):
proto=item['source'];ident=item['entry'];pin=hashlib.sha256(json.dumps(proto,sort_keys=True,separators=(',',':'),ensure_ascii=False,allow_nan=False).encode()).hexdigest()
try:
if proto['entry']!=ident or item['source_record_sha256']!=pin:raise ValueError('Source item identity/hash differs')
drafts={r['table_name']:r for r in item['components']}
reuse_effect_parent=ident in effective_parents
if reuse_effect_parent:
parent=effective_parents[ident]
basic=parent['basic_record'];sparse=parent['sparse_record']
if (parent.get('source_record_sha256')!=pin or basic.get('ID')!=ident
or sparse.get('ID',ident)!=ident
or any(basic.get(dest)!=proto.get(source)for dest,source in
(('ClassID','class'),('SubclassID','subclass'),('InventoryType','inventory_type')))
or not basic.get('InventoryType') or sparse.get('InventoryType')!=basic.get('InventoryType')):
raise ValueError('Effective parent source entry/type slot authority differs')
pins={}
for table,record,encoder in (('Item',basic,basic_encode),('ItemSparse',sparse,lambda r:encode(r,schemas['ItemSparse']))):
wire=encoder(record);digest=hashlib.sha256(wire).hexdigest();pins[table]=digest
if parent.get('wire_sha256',{}).get(table)!=digest:
raise ValueError('Effective parent expected bytes differ')
current=published.get((table,ident))
if current is not None:
if (current.get('record_status','valid')!='valid' or encoder(current['record'])!=wire
or current.get('wire_hex')!=wire.hex() or current.get('sha256')!=digest):
raise ValueError('Effective parent published bytes differ')
elif parent.get('original_baseline',{}).get(table)!=(
'runtime/item-correction-catalogue-20261022/native-effective-cache.json'if table=='Item'else
'runtime/catalog-items-20261018/ItemSparse-full-verification.json'):
raise ValueError('Effective parent original baseline required')
native_slot_selected[ident]=dict(kind='source-entry-effective-item-effect-slots-v1',source_entry=ident,
source_record_sha256=pin,entry_binding_receipt=effective_parent_authority['entry_binding_receipt'],
relationship_receipt=effective_parent_authority['relationship_receipt'],effective_parent_wire_sha256=pins,
authority='source-effect-slots-only',full_source_metadata_authority=False)
reuse_native_item=ident in native_slot_items and ('Item',ident)not in published
if reuse_native_item:
native=native_slot_items[ident];basic_encode(native)
if (native.get('ID')!=ident or any(native.get(dest)!=proto.get(source)
for dest,source in(('ClassID','class'),('SubclassID','subclass'),('InventoryType','inventory_type')))):
raise ValueError('Native Item source entry/type slot authority differs')
sparse=published.get(('ItemSparse',ident));authority=(sparse or{}).get('source_intrinsic_field_authority',{})
partial_policies={'source-authoritative-original-native-intrinsic-fields-v1':'source-entry-native-item-stat-fields-v1',
'source-authoritative-original-native-intrinsic-fields-v2':'source-entry-native-item-stat-fields-v2'}
if (not sparse or sparse.get('record_status','valid')!='valid'
or sparse.get('policy')not in partial_policies
or sparse.get('source_record_sha256')is not None
or authority.get('kind')!=partial_policies.get(sparse.get('policy'))
or authority.get('source_entry')!=ident or authority.get('source_record_sha256')!=pin
or authority.get('entry_binding_receipt')!=native_slot_receipt
or authority.get('original_native_nonstat_fields_preserved')is not True
or set(authority.get('fields',[]))!={'StatModifier_bonusStat','StatPercentEditor'}
or set(sparse.get('changed_fields',[]))-{'StatModifier_bonusStat','StatPercentEditor'}):
raise ValueError('Native Item reuse requires reviewed partial Sparse authority')
if authority['kind']=='source-entry-native-item-stat-fields-v2':
basic={k:v for k,v in native.items()if k!='ID'};record=sparse['record']
target=dict(entry=ident,**{k:basic[v]for k,v in [('class','ClassID'),('subclass','SubclassID'),('inventory_type','InventoryType')]},
item_level=record['ItemLevel'],quality=record['OverallQualityID'])
basic_pin=hashlib.sha256(json.dumps(basic,sort_keys=True,separators=(',',':'),ensure_ascii=False,allow_nan=False).encode()).hexdigest()
if (authority.get('target_budget_identity')!=target or authority.get('native_basic_record_sha256')!=basic_pin
or record['InventoryType']!=native['InventoryType']):
raise ValueError('Native Item reuse scoped Sparse target identity differs')
wire=encode(sparse['record'],schemas['ItemSparse'])
if wire.hex()!=sparse['wire_hex']or hashlib.sha256(wire).hexdigest()!=sparse['sha256']:
raise ValueError('Native Item reuse Sparse bytes differ')
native_slot_selected[ident]=dict(kind='source-entry-native-item-effect-slots-v1',source_entry=ident,
source_record_sha256=pin,entry_binding_receipt=native_slot_receipt,
original_native_item_wire_sha256=hashlib.sha256(basic_encode(native)).hexdigest(),
authority='source-effect-slots-only',full_source_metadata_authority=False)
if authority['kind']=='source-entry-native-item-stat-fields-v2':
native_slot_selected[ident].update(partial_sparse_authority_kind=authority['kind'],partial_sparse_wire_sha256=sparse['sha256'])
for table,encoder in(()if reuse_native_item or reuse_effect_parent else(('Item',basic_encode),('ItemSparse',lambda r:encode(r,schemas['ItemSparse'])))):
draft=drafts.get(table);current=published.get((table,ident))
if not current or current.get('record_status','valid')!='valid':raise ValueError('Published source metadata missing')
wire=encoder(current['record'])
if wire.hex()!=current['wire_hex']or hashlib.sha256(wire).hexdigest()!=current['sha256']:raise ValueError('Published source metadata bytes differ')
if draft is None:
# A catalogue can predate a completed weapon conversion.
# Reuse only a published row pinned to this exact source
# snapshot; never rebuild or overwrite its damage mapping.
if current.get('source_record_sha256')!=pin:raise ValueError('Published metadata lacks exact source snapshot pin')
elif (draft['source_record_sha256']!=pin or draft['id']!=ident
or encoder(draft['record']).hex()!=draft['wire_hex']
or wire.hex()!=draft['wire_hex']):raise ValueError('Published metadata differs from reviewed source conversion')
extra=proto.get('extra_flags',0)
if proto.get('script_name')or proto.get('duration')or(extra and not(extra==4 and obtainability_reference is not None)):raise ValueError('Unreviewed source execution dependency')
wanted=[]
for i in range(1,6):
spell=proto['spellid_'+str(i)]
if not spell:
if proto['spellcharges_'+str(i)]:raise ValueError('Orphan source charges')
continue
if missing_slots_only and spell not in reviewed_spell_ids:
deferred_slots.append(dict(entry=ident,slot=i-1,spell_id=spell,reason='Source spell definition review missing'))
continue
if spell not in reviewed_spell_ids:raise ValueError('Source spell definition review missing')
trigger=proto['spelltrigger_'+str(i)]
if (trigger not in _allowed_triggers(on_hit_review,on_use_review) or proto['spellcharges_'+str(i)]or not _source_ppm_allowed(proto['spellppmrate_'+str(i)],trigger,allow_on_hit_replacement)
or not _passive_category_allowed(proto,i,trigger,category_sources)or not _cooldown_allowed(proto,i,trigger,on_use_review)):
if reuse_effect_parent:
# ItemXItemEffect binds each LegacySlotIndex separately.
# Keep an unsupported slot untouched while completing a
# different independently reviewed equipment slot.
deferred_slots.append(dict(entry=ident,slot=i-1,spell_id=spell,reason='Unreviewed source use/proc/charge/cooldown'))
continue
raise ValueError('Unreviewed source use/proc/charge/cooldown')
wanted.append(dict(LegacySlotIndex=i-1,TriggerType=trigger,Charges=0,CoolDownMSec=proto['spellcooldown_'+str(i)],
CategoryCoolDownMSec=proto['spellcategorycooldown_'+str(i)],SpellCategoryID=proto['spellcategory_'+str(i)],SpellID=spell,ChrSpecializationID=0,PlayerConditionID=0))
actual=[];existing=by_item.get(ident,[])
for link in existing:
effect=by_effect.get(link['ItemEffectID'])
if effect is None:raise ValueError('Missing existing passive effect baseline')
actual.append({field:effect[field]for field in effect_fields})
if len({r['LegacySlotIndex']for r in actual})!=len(actual):raise ValueError('Ambiguous native item effect slots')
if missing_slots_only:
by_slot={r['LegacySlotIndex']:r for r in actual};missing=[]
for row in wanted:
old=by_slot.get(row['LegacySlotIndex'])
if old is None:missing.append(row['LegacySlotIndex'])
elif old!=row:
if reuse_effect_parent:
deferred_slots.append(dict(entry=ident,slot=row['LegacySlotIndex'],spell_id=row['SpellID'],reason='Existing slot differs; additive completion cannot replace it'))
continue
raise ValueError('Existing slot differs; additive completion cannot replace it')
if not missing:preserved.append(ident);continue
# Parent entry/type/bytes and source slots were reviewed above.
# This view selects only independently reviewed missing slots;
# it is never published as a replacement source snapshot.
proto=copy.deepcopy(proto)
for i in range(1,6):
if i-1 not in missing:proto['spellid_'+str(i)]=0
selected.append(proto);continue
if sorted(actual,key=lambda r:r['LegacySlotIndex'])==wanted:
preserved.append(ident);continue
if any(('ItemXItemEffect',r['ID'])in published for r in existing):raise ValueError('Existing overlay needs explicit replacement review')
selected.append(proto)
except ValueError as error:blocked.append(dict(entry=ident,reason=str(error)))
bounds={t:max([maxima[t]]+[r['id']for r in package['rows']if r['table_name']==t])for t in TABLES}
reg=dict(slots={});selected_ids={p['entry']for p in selected}
component=generate(selected,list(by_effect.values()),[]if missing_slots_only else[r for r in effective if r['ItemID']in selected_ids],[dict(ID=i)for i in sorted(reviewed_spell_ids)],
reg,schemas,bounds,source_authoritative_links=not missing_slots_only,on_hit_context=on_hit_context,proc_override_snapshot=proc_override_snapshot,on_use_context=on_use_context,allow_on_hit_replacement=allow_on_hit_replacement,passive_category_references=passive_category_references)
for row in component['records']:
if row.get('source_item')in native_slot_selected:
row['source_effect_slot_authority']=dict(native_slot_selected[row['source_item']],source_slot=row['source_slot'])
source_by_entry={item['entry']:item for item in items}
for row in component['records']:
item=source_by_entry[row['source_item']]
if item['source'].get('extra_flags')==4:
row['source_reference_obtainability']=dict(obtainability_reference,source_item=item['entry'],source_record_sha256=item['source_record_sha256'])
added=component['records'];result=copy.deepcopy(package);result['rows']+=added
if len({(r['table_name'],r['id'])for r in result['rows']})!=len(result['rows']):raise ValueError('Passive link publication collision')
result['push_id']=package_payloads(result['rows'])[0];result['pushes']=package_pages(result['rows'])
return dict(package=result,added=added,preserved_item_ids=preserved,selected_item_ids=[p['entry']for p in selected],blocked=blocked,
registry=reg,installed=False,engine_loaded=False,gameplay_verified=False,
**(dict(completion_policy='additive-reviewed-missing-equipment-slots',deferred_source_slots=deferred_slots,
existing_links_preserved=True,full_item_definition_completion_claimed=False)if missing_slots_only else{}),
server_authoritative_item_ppm=component.get('server_authoritative_item_ppm',[]),
**(dict(passive_category_review=component['passive_category_review'])if category_sources else{}),
**(dict(on_hit_review=on_hit_review)if on_hit_review is not None else{}),
**(dict(on_use_review=on_use_review)if on_use_review is not None else{}),
limits=['Per-piece uncharged equipment use/passive links; source use execution remains entirely server-authoritative.'if on_use_review is not None else'Per-piece uncharged passive/on-hit links; source on-hit execution remains entirely server-authoritative.'if on_hit_review is not None else'Per-piece uncharged unconditional passives only; item-set bonuses and proc/use rules are separate.','Caller must review source/native spell definitions; serialization does not prove actual equipment mechanics.'])
def rebase_qualified_passive_rows(package,reviewed_parent,writer_rows,native_maxima,schemas):
"""Rebase an already-reviewed additive passive batch onto a newer package.
This does not review spell definitions or server behavior. It retains the
owning writer rows verbatim except for destination-only ID collisions and
the corresponding link field; all current metadata remains intact.
"""
if (not isinstance(writer_rows,list) or not writer_rows or len(writer_rows)>4096 or
set(native_maxima)!=set(TABLES) or set(schemas)!=set(TABLES) or
any(type(v)is not int or v<0 for v in native_maxima.values())):
raise ValueError('Bounded reviewed passive rows, schemas and native maxima required')
for name in ('build','schema','layout_hash','dbd_sha256','destination_db2_sha256','basic_sha256'):
if package.get(name)!=reviewed_parent.get(name):raise ValueError('Native metadata lineage differs: '+name)
def indexed(rows):
result={(r['table_name'],r['id']):r for r in rows}
if len(result)!=len(rows):raise ValueError('Duplicate metadata row identity')
return result
current=indexed(package['rows']);prior=indexed(reviewed_parent['rows']);saved=indexed(writer_rows)
if any(t not in TABLES for t,_ in saved) or any(prior.get(k)!=v for k,v in saved.items()):
raise ValueError('Writer rows differ from their reviewed parent')
for key,row in prior.items():
if key[0] in TABLES and key not in saved and current.get(key)!=row:
raise ValueError('Previously reviewed native effect baseline changed')
pairs={}
for row in writer_rows:
table=row['table_name'];ident=row.get('source_item');slot=row.get('source_slot')
if (type(ident)is not int or ident<=0 or type(slot)is not int or not 0<=slot<5 or
type(row['id'])is not int or not native_maxima[table]<row['id']<=0x7fffffff or
not isinstance(row.get('record'),dict)):
raise ValueError('Invalid reviewed passive row identity')
wire=encode(row['record'],schemas[table])
if wire.hex()!=row.get('wire_hex') or hashlib.sha256(wire).hexdigest()!=row.get('sha256'):
raise ValueError('Reviewed passive row bytes changed')
group=pairs.setdefault((ident,slot),{})
if table in group:raise ValueError('Duplicate reviewed passive slot')
group[table]=row
if len(pairs)*2!=len(writer_rows):raise ValueError('Reviewed effect/link pairs incomplete')
for (ident,slot),pair in pairs.items():
if set(pair)!=set(TABLES):raise ValueError('Reviewed effect/link pairs incomplete')
effect=pair['ItemEffect'];link=pair['ItemXItemEffect']
if (effect['record']['LegacySlotIndex']!=slot or link['record']['ItemID']!=ident or
link['record']['ItemEffectID']!=effect['id']):raise ValueError('Reviewed passive slot relationship differs')
for table in ('Item','ItemSparse'):
old=prior.get((table,ident));new=current.get((table,ident))
if not old or not new or not isinstance(old.get('record'),dict) or not isinstance(new.get('record'),dict):
raise ValueError('Reviewed passive item parent missing')
left=dict(old['record']);right=dict(new['record'])
if table=='Item':left.pop('IconFileDataID',None);right.pop('IconFileDataID',None)
pin=old.get('source_record_sha256')
if (not isinstance(pin,str) or len(pin)!=64 or any(c not in '0123456789abcdef' for c in pin) or
left!=right or pin!=new.get('source_record_sha256')):
raise ValueError('Reviewed passive item source identity changed')
effects={r['id']:r for r in package['rows'] if r['table_name']=='ItemEffect' and isinstance(r.get('record'),dict)}
for row in package['rows']:
if row['table_name']!='ItemXItemEffect' or not isinstance(row.get('record'),dict):continue
effect=effects.get(row['record']['ItemEffectID'])
if effect and (row['record']['ItemID'],effect['record']['LegacySlotIndex']) in pairs:
raise ValueError('Current overlay already contains a reviewed passive slot')
bounds={t:max([native_maxima[t]]+[r['id'] for r in package['rows']+writer_rows if r['table_name']==t]) for t in TABLES}
remap={}
for table in TABLES:
for row in sorted((r for r in writer_rows if r['table_name']==table),key=lambda r:r['id']):
if (table,row['id']) in current:
bounds[table]+=1
if bounds[table]>0x7fffffff:raise ValueError('Passive destination IDs exhausted')
remap[(table,row['id'])]=bounds[table]
additions=[]
for saved_row in writer_rows:
row=copy.deepcopy(saved_row);table=row['table_name'];row['id']=remap.get((table,row['id']),row['id'])
if table=='ItemXItemEffect':
old_effect=row['record']['ItemEffectID'];new_effect=remap.get(('ItemEffect',old_effect),old_effect)
if new_effect!=old_effect:
row['record']['ItemEffectID']=new_effect;wire=encode(row['record'],schemas[table]);row['wire_hex']=wire.hex();row['sha256']=hashlib.sha256(wire).hexdigest()
additions.append(row)
result=copy.deepcopy(package);result['rows'].extend(additions)
from item_sparse_compat import _package_data
push,header,pages=_package_data(result['rows']);result['push_id']=push;result['pushes']=pages
result['private_passive_rebase']=dict(kind='reviewed-passive-effect-rebase-v1',pairs=len(pairs),rows=len(additions),
remapped_ids=len(remap),installed=False,native_accepted=False,server_parity=False)
return result,header,dict(kind='reviewed-passive-effect-rebase-v1',pairs=len(pairs),rows=len(additions),
remapped_ids=[{'table':table,'old_id':old,'new_id':new} for (table,old),new in sorted(remap.items())],
preserved_rows=len(package['rows']),installed=False,native_accepted=False,gameplay_verified=False)
def compile_relationship_catalogue(source,links,names,registry,schemas,maxima,preserved_rows,*,allow_unavailable_ppm=False):
"""Batch ALL effect slots into typed components, not approved gameplay.
Source ON_USE0/ON_EQUIP1/CHANCE_ON_HIT2 correspond to the destination's
ON_USE0/ON_EQUIP1/ON_PROC2. Source4/5 are deliberately NOT copied to the
destination's unrelated death/pickup triggers. Charges and millisecond
cooldowns retain their signs. PPM remains server execution metadata:
neither source0x58 nor native ItemEffect has a per-item PPM column.
Missing spell definitions and existing links remain installation gates.
A typed slot inventory may explicitly omit server-only PPM metadata; opt in
to preserving that absence as an unresolved annotation, never a zero rate.
"""
if not isinstance(source,list)or not 1<=len(source)<=100000:raise ValueError('Source relationship catalogue bound')
if type(allow_unavailable_ppm)is not bool:raise ValueError('Explicit unavailable-PPM policy required')
known={r['ID']for r in names}|{r['id']for r in preserved_rows if r['table_name']=='SpellName'and r.get('record_status','valid')=='valid'}
slots=registry.setdefault('slots',{});allocated={};seen=set();records=[];items=[]
for kind,key in(('ItemEffect','effect'),('ItemXItemEffect','link')):
values=[v[key]for v in slots.values()]
if len(set(values))!=len(values)or any(type(i)is not int or not maxima[kind]<i<=0x7fffffff for i in values):raise ValueError('Effect catalogue registry collision')
allocated[kind]=max([maxima[kind],*values,*[r['id']for r in preserved_rows if r['table_name']==kind]])
native_links={}
for row in effective_item_links(links,preserved_rows):native_links.setdefault(row['ItemID'],[]).append(row['ID'])
for proto in sorted(source,key=lambda r:r['entry']):
ident=proto['entry']
if type(ident)is not int or not 0<=ident<=0x7fffffff or ident in seen:raise ValueError('Source effect catalogue identity bound/duplicate')
seen.add(ident)
if not ident:continue
item=dict(entry=ident,components=[],errors=[],spell_dependencies=[],native_links_to_reconcile=sorted(native_links.get(ident,[])),
server_execution=[],installable=False,engine_verified=False,gameplay_verified=False)
for index in range(1,6):
spell=proto['spellid_'+str(index)]
if not spell:continue
slot=index-1;trigger=proto['spelltrigger_'+str(index)]
try:
if type(spell)is not int or not 0<spell<=0x7fffffff or type(trigger)is not int or trigger not in(0,1,2):raise ValueError('Unreviewed source spell identity/trigger semantics')
effect=dict(LegacySlotIndex=slot,TriggerType=trigger,Charges=proto['spellcharges_'+str(index)],
CoolDownMSec=proto['spellcooldown_'+str(index)],CategoryCoolDownMSec=proto['spellcategorycooldown_'+str(index)],
SpellCategoryID=proto['spellcategory_'+str(index)],SpellID=spell,ChrSpecializationID=0,PlayerConditionID=0)
raw_effect=encode(effect,schemas['ItemEffect']) # Existing exact70334 serializer and signed-width checks.
ppm=proto.get('spellppmrate_'+str(index))
ppm_unavailable=ppm is None and allow_unavailable_ppm
if not ppm_unavailable and(type(ppm)not in(int,float)or not math.isfinite(ppm)):raise ValueError('Invalid source per-item PPM')
key=f'{ident}:{slot}'
if key not in slots:
allocated['ItemEffect']+=1;allocated['ItemXItemEffect']+=1
slots[key]={'effect':allocated['ItemEffect'],'link':allocated['ItemXItemEffect']}
ids=slots[key]
if max(ids.values())>0x7fffffff:raise ValueError('Effect catalogue target row allocation exhausted')
link=dict(ItemEffectID=ids['effect'],ItemID=ident);raw_link=encode(link,schemas['ItemXItemEffect'])
for name,record,raw,row_id in(('ItemEffect',effect,raw_effect,ids['effect']),('ItemXItemEffect',link,raw_link,ids['link'])):
component=dict(table_name=name,table_hash=hex(TABLES[name][0]),id=row_id,record=record,wire_hex=raw.hex(),
sha256=hashlib.sha256(raw).hexdigest(),source_item=ident,source_slot=slot,installable_alone=False)
item['components'].append(component);records.append(component)
item['spell_dependencies'].append(dict(spell_id=spell,native_name_present=spell in known,definition_semantics_verified=False))
if ppm_unavailable:item['server_execution'].append(dict(slot=slot,ppm=None,wire_field_available=False,authority='Source metadata unavailable in typed slot inventory',source_negative_value_unreviewed=False,metadata_unavailable=True))
elif ppm:item['server_execution'].append(dict(slot=slot,ppm=ppm,wire_field_available=False,authority='Tortoise per-item proc roll',source_negative_value_unreviewed=ppm<0))
except (ValueError,OverflowError)as error:item['errors'].append(dict(slot=slot,error=str(error)))
items.append(item)
return dict(kind='source-item-effect-relationship-catalogue',schema_version=1,build='1.60.1.70334',items=items,records=records,
counts=dict(source_items=len(items),effect_slots=sum(len(i['spell_dependencies'])for i in items),component_rows=len(records),
items_with_errors=sum(bool(i['errors'])for i in items),source_semantics_review_required=sum(any(e['source_negative_value_unreviewed']for e in i['server_execution'])for i in items),
missing_native_spell_names=len({d['spell_id']for i in items for d in i['spell_dependencies']if not d['native_name_present']}),
unavailable_ppm_metadata=sum(bool(e.get('metadata_unavailable'))for i in items for e in i['server_execution'])),
installed=False,engine_verified=False,gameplay_verified=False,
limits=['Typed relationship components, not complete spell/proc support.','Source spell definitions and native link reconciliation are mandatory installation gates.','Existing registry identities reserved, never silently discarded.'])
def compose_matching_link_timings(package,items,effects,links,schemas,maxima):
"""Correct timing fields only when every source/native link identity matches.
Applies across item classes and all five slots. No missing link, spell,
category, charge, condition or trigger is introduced. Clone changed effects
and retain parent IDs so unrelated users of a shared effect stay intact.
"""
from item_sparse_compat import package_payloads,package_pages
from item_batch_stage import source_hash
if (package.get('build')!='1.60.1.70334'or package.get('schema')!='wowstatic_camelot_1_60_1'
or package.get('push_id')!=package_payloads(package['rows'])[0]):raise ValueError('Item timing package identity differs')
if not isinstance(items,list)or not 1<=len(items)<=100000 or len({i['entry']for i in items})!=len(items):raise ValueError('Distinct bounded timing source items required')
published={(r['table_name'],r['id']):r for r in package['rows']}
if len(published)!=len(package['rows']):raise ValueError('Duplicate published timing identity')
by_effect={r['ID']:dict(r)for r in effects};by_item={}
for r in package['rows']:
if r['table_name']=='ItemEffect':
if r.get('record_status','valid')!='valid':by_effect.pop(r['id'],None)
else:by_effect[r['id']]=r['record']
for r in effective_item_links(links,package['rows']):by_item.setdefault(r['ItemID'],[]).append(r)
selected=[];preserved=[];blocked=[];replacements={};hashes={};changed_slots=[]
timing=('CoolDownMSec','CategoryCoolDownMSec')
for item in sorted(items,key=lambda i:i['entry']):
ident=item['entry'];p=item['source']
if not any(p['spellid_'+str(i)]for i in range(1,6)):continue
try:
if p['entry']!=ident or source_hash(p)!=item['source_record_sha256']:raise ValueError('Source item timing hash differs')
for table in ('Item','ItemSparse'):
r=published.get((table,ident))
if not r or r.get('record_status','valid')!='valid'or r.get('source_record_sha256')!=item['source_record_sha256']:raise ValueError('Published source metadata missing or stale')
wanted={i-1:dict(LegacySlotIndex=i-1,TriggerType=p['spelltrigger_'+str(i)],Charges=p['spellcharges_'+str(i)],
CoolDownMSec=p['spellcooldown_'+str(i)],CategoryCoolDownMSec=p['spellcategorycooldown_'+str(i)],SpellCategoryID=p['spellcategory_'+str(i)],SpellID=p['spellid_'+str(i)],ChrSpecializationID=0,PlayerConditionID=0)
for i in range(1,6)if p['spellid_'+str(i)]}
actual={}
for link in by_item.get(ident,[]):
effect=by_effect.get(link['ItemEffectID'])
if not effect or effect['LegacySlotIndex']in actual:raise ValueError('Missing or duplicate native effect slot')
actual[effect['LegacySlotIndex']]=(link,effect)
if set(actual)!=set(wanted):raise ValueError('Source/native effect slot set differs')
changed=[]
for slot,record in wanted.items():
if any(type(v)is not int for v in record.values()):raise ValueError('Integer source item effect fields required')
if record['TriggerType']not in(0,1,2):raise ValueError('Unreviewed item trigger namespace')
if any(type(record[k])is not int or not -1<=record[k]<=86400000 for k in timing):raise ValueError('Source item cooldown bound')
link,old=actual[slot]
if any(old.get(k)!=v for k,v in record.items()if k not in timing):raise ValueError('Spell/trigger/charge/category/condition identity differs')
if any(old[k]!=record[k]for k in timing):changed.append(slot)
if not changed:preserved.append(ident);continue
subset=copy.deepcopy(p)
for i in range(1,6):
if i-1 not in changed:subset['spellid_'+str(i)]=0
selected.append(subset);hashes[ident]=item['source_record_sha256']
for slot in changed:
replacements[ident,slot]=actual[slot][0]['ID']
changed_slots.append(dict(item=ident,slot=slot,changes={k:[actual[slot][1][k],wanted[slot][k]]for k in timing if actual[slot][1][k]!=wanted[slot][k]}))
except ValueError as error:blocked.append(dict(entry=ident,reason=str(error)))
catalogue=compile_relationship_catalogue(selected,links,[],{'slots':{}},schemas,maxima,package['rows'])if selected else dict(records=[],items=[])
if any(i['errors']for i in catalogue['items']):raise ValueError('Matched timing serialization failed')
rows=catalogue['records']
for row in rows:
row['source_record_sha256']=hashes[row['source_item']];row['policy']='source-matching-link-timings-only'
if row['table_name']=='ItemXItemEffect':row['id']=replacements[row['source_item'],row['source_slot']]
keys={(r['table_name'],r['id'])for r in rows};result=copy.deepcopy(package)
result['rows']=[r for r in result['rows']if(r['table_name'],r['id'])not in keys]+rows
if len({(r['table_name'],r['id'])for r in result['rows']})!=len(result['rows']):raise ValueError('Item timing publication collision')
result['push_id']=package_payloads(result['rows'])[0];result['pushes']=package_pages(result['rows'])
return dict(package=result,selected=[p['entry']for p in selected],preserved=preserved,blocked=blocked,added=rows,changed_slots=changed_slots,
policy='source-matching-link-timings-only',installed=False,engine_verified=False,gameplay_verified=False)
def compose_consumable_links(package,items,reviewed_spell_ids,effects,links,schemas,maxima,registry,*,refresh_cooldowns=False):
"""Publish missing source consumable links, leaving existing definitions intact.
Caller explicitly reviews spell definitions. This is not spell conversion.
Both engines use negative charges for consumed items, milliseconds for item
cooldowns and seconds for item lifetime. Only single-slot, one-use consumables
are covered here; scripts, PPM, equipment and additional effects remain gated.
Existing links are never replaced on the strength of a spell-name match.
Explicit refresh_cooldowns clones timing-only conflicts with identical
spell/slot/trigger/charges, retaining the existing parent link identity.
"""
from item_sparse_compat import package_payloads,package_pages
from item_batch_stage import source_hash
if (package.get('build')!='1.60.1.70334' or package.get('schema')!='wowstatic_camelot_1_60_1'
or package.get('push_id')!=package_payloads(package['rows'])[0]):raise ValueError('Consumable package identity differs')
if not isinstance(reviewed_spell_ids,set) or not reviewed_spell_ids or any(type(i)is not int or not 0<i<2**31 for i in reviewed_spell_ids):raise ValueError('Explicit reviewed consumable spell IDs required')
if not isinstance(items,list) or not 1<=len(items)<=4096 or len({i['entry']for i in items})!=len(items):raise ValueError('Consumable selection bound/duplicate')
published={(r['table_name'],r['id']):r for r in package['rows']}
if len(published)!=len(package['rows']):raise ValueError('Duplicate package identity')
effective=effective_item_links(links,package['rows']);by_effect={r['ID']:r for r in effects}
for r in package['rows']:
if r['table_name']=='ItemEffect' and r.get('record_status','valid')=='valid':by_effect[r['id']]=dict(r['record'],ID=r['id'])
if type(refresh_cooldowns)is not bool:raise ValueError('Explicit cooldown refresh policy required')
replacements={}
selected=[];preserved=[];blocked=[]
for item in sorted(items,key=lambda i:i['entry']):
p=item['source'];ident=item['entry']
try:
if p['entry']!=ident or item['source_record_sha256']!=source_hash(p):raise ValueError('Source consumable hash differs')
if type(p['class'])is not int or p['class']!=0 or p['inventory_type']!=0 or p.get('script_name') or p.get('extra_flags'):raise ValueError('Unreviewed consumable execution context')
if [i for i in range(1,6)if p['spellid_'+str(i)]]!=[1]:raise ValueError('Single source use slot required')
if p['spellid_1']not in reviewed_spell_ids or p['spelltrigger_1']!=0 or p['spellcharges_1']!=-1 or p['spellppmrate_1']!=0:raise ValueError('Unreviewed consumable spell/trigger/charges')
if any(p['spellcharges_'+str(i)]for i in range(2,6)):raise ValueError('Orphan source charges')
for key in ('spellcooldown_1','spellcategorycooldown_1'):
if type(p[key])is not int or not -1<=p[key]<=86400000:raise ValueError('Consumable cooldown bounds')
if type(p['spellcategory_1'])is not int or not 0<=p['spellcategory_1']<=65535:raise ValueError('Consumable category bounds')
for table in ('Item','ItemSparse'):
r=published.get((table,ident))
if not r or r.get('record_status','valid')!='valid' or r.get('source_record_sha256')!=item['source_record_sha256']:raise ValueError('Published source metadata missing or stale')
wanted=dict(LegacySlotIndex=0,TriggerType=0,Charges=-1,CoolDownMSec=p['spellcooldown_1'],CategoryCoolDownMSec=p['spellcategorycooldown_1'],SpellCategoryID=p['spellcategory_1'],SpellID=p['spellid_1'],ChrSpecializationID=0,PlayerConditionID=0)
existing=[l for l in effective if l['ItemID']==ident]
if existing:
if len(existing)==1 and all(by_effect.get(existing[0]['ItemEffectID'],{}).get(k)==v for k,v in wanted.items()):preserved.append(ident);continue
timing={'CoolDownMSec','CategoryCoolDownMSec','SpellCategoryID'}
if (not refresh_cooldowns or len(existing)!=1 or
not all(by_effect.get(existing[0]['ItemEffectID'],{}).get(k)==v for k,v in wanted.items() if k not in timing)):
raise ValueError('Existing consumable link needs explicit replacement review')
# Clone the effect instead of mutating a record shared by other items.
replacements[ident]=existing[0]['ID']
selected.append(p)
except ValueError as error:blocked.append(dict(entry=ident,reason=str(error)))
reg=copy.deepcopy(registry)
for ident in replacements:reg.setdefault('slots',{}).pop(f'{ident}:0',None)
catalogue=compile_relationship_catalogue(selected,links,[dict(ID=i)for i in sorted(reviewed_spell_ids)],reg,schemas,maxima,package['rows']) if selected else dict(records=[],items=[])
if any(i['errors']for i in catalogue['items']):raise ValueError('Consumed effect serialization failed')
rows=catalogue['records']
for r in rows:
r['source_record_sha256']=next(i['source_record_sha256']for i in items if i['entry']==r['source_item'])
for r in rows:
if r['table_name']=='ItemXItemEffect' and r['source_item']in replacements:r['id']=replacements[r['source_item']]
keys={(r['table_name'],r['id'])for r in rows}
result=copy.deepcopy(package);result['rows']=[r for r in result['rows']if (r['table_name'],r['id'])not in keys]+rows
if len({(r['table_name'],r['id'])for r in result['rows']})!=len(result['rows']):raise ValueError('Consumable publication collision')
result['push_id']=package_payloads(result['rows'])[0];result['pushes']=package_pages(result['rows'])
return dict(package=result,registry=reg,selected=[p['entry']for p in selected],preserved=preserved,blocked=blocked,added=rows,
policy='source-single-use-consumable-cooldowns-v1'if refresh_cooldowns else'missing-single-use-consumable-links-v1',cooldown_replacements=sorted(replacements),installed=False,engine_verified=False,gameplay_verified=False)
def generate(source,effects,links,names,registry,schemas,maxima,*,source_authoritative_links=False,on_hit_context=None,proc_override_snapshot=None,on_use_context=None,allow_on_hit_replacement=False,passive_category_references=None):
if type(allow_on_hit_replacement)is not bool:raise ValueError('Explicit on-hit replacement policy required')
if type(source_authoritative_links)is not bool:raise ValueError('Explicit source-authoritative link policy required')
on_hit_review=review_on_hit(source,on_hit_context,proc_override_snapshot)
on_use_review=review_on_use(source,on_use_context)
category_sources=review_passive_category_references(passive_category_references)
if allow_on_hit_replacement and(not source_authoritative_links or on_hit_review is None):raise ValueError('On-hit replacement requires source-owned links and reviewed trigger/proc metadata')
by_effect={r['ID']:r for r in effects};known_spells={r['ID'] for r in names}
if len(by_effect)!=len(effects):raise ValueError('Duplicate native effect identity')
if len({r['ID']for r in links})!=len(links):raise ValueError('Duplicate native item-effect link identity')
if any(r['ItemEffectID']not in by_effect for r in links):raise ValueError('Native item-effect link baseline is incomplete')
if any(r['ID']>maxima['ItemEffect'] for r in effects) or any(r['ID']>maxima['ItemXItemEffect'] for r in links):raise ValueError('Native header/export ID bounds differ; review copy records')
if len({r['entry'] for r in source})!=len(source):raise ValueError('Duplicate source item identity')
slots=registry.setdefault('slots',{});allocated={};preserved=[];effect_rows=[];link_rows=[];removed=[];used=set()
for kind,field in (('ItemEffect','effect'),('ItemXItemEffect','link')):
ids=[r[field] for r in slots.values()]
if len(set(ids))!=len(ids) or any(not maxima[kind]<i<=0x7fffffff for i in ids):raise ValueError('Registry collides with native table or itself; reviewed migration required')
allocated[kind]=max([maxima[kind],*ids])
for proto in sorted(source,key=lambda r:r['entry']):
entry=proto['entry'];wanted={}
for i in range(1,6):
spell=int(proto['spellid_'+str(i)])
if spell:wanted[i-1]=(spell,int(proto['spelltrigger_'+str(i)]))
existing={}
for link in links:
if link['ItemID']!=entry:continue
effect=by_effect[link['ItemEffectID']];slot=effect['LegacySlotIndex']
if slot in existing:raise ValueError('Ambiguous native item effect slot')
existing[slot]=(effect['SpellID'],effect['TriggerType'])
if existing and not source_authoritative_links:
if existing!=wanted:raise ValueError('Existing native effects differ; no unreviewed removal/remap')
preserved.append({'item':entry,'slots':existing,'scope':'Existing spell/slot/trigger identities retained; other effect parameters not claimed converted.'});continue
if source_authoritative_links:
if on_use_review is not None and any(t==0 for _,t in wanted.values())and existing:
raise ValueError('Existing on-use link replacement requires separate review')
if on_hit_review is not None and any(t==2 for _,t in wanted.values())and existing and not allow_on_hit_replacement:
raise ValueError('Existing on-hit link replacement requires separate review')
# Replace this item's links only. The effect rows can be shared by
# unrelated items and must never be rewritten or removed here.
for slot,(spell,trigger) in wanted.items():
i=slot+1
if (spell not in known_spells or trigger not in _allowed_triggers(on_hit_review,on_use_review) or proto['spellcharges_'+str(i)]!=0
or not _passive_category_allowed(proto,i,trigger,category_sources)or not _source_ppm_allowed(proto['spellppmrate_'+str(i)],trigger,allow_on_hit_replacement)
or not _cooldown_allowed(proto,i,trigger,on_use_review)):
raise ValueError('Source-authoritative replacement requires reviewed uncharged passive definitions')
for link in sorted((r for r in links if r['ItemID']==entry),key=lambda r:r['ID']):
raw=encode(link,schemas['ItemXItemEffect'])
removed.append(dict(table_name='ItemXItemEffect',table_hash=hex(TABLES['ItemXItemEffect'][0]),
id=link['ID'],record_status='removed',record=None,wire_hex='',
sha256=hashlib.sha256(b'').hexdigest(),source_item=entry,
baseline_record=dict(link),baseline_record_sha256=hashlib.sha256(raw).hexdigest(),
policy='source-authoritative-per-item-passive-link-replacement'))
for slot,(spell,trigger) in sorted(wanted.items()):
i=slot+1
if spell not in known_spells:raise ValueError('Native spell definition name absent; do not substitute another spell')
if trigger not in _allowed_triggers(on_hit_review,on_use_review) or proto['spellcharges_'+str(i)]!=0 or not _passive_category_allowed(proto,i,trigger,category_sources)or not _cooldown_allowed(proto,i,trigger,on_use_review):
raise ValueError('New effect is not a reviewed uncharged unconditional passive')
if trigger==2 and (not _source_ppm_allowed(proto['spellppmrate_'+str(i)],trigger,allow_on_hit_replacement)or any(proto.get(k,0)for k in('script_name','extra_flags','duration'))):
raise ValueError('Unreviewed on-hit item execution metadata')
key=f'{entry}:{slot}'
used.add(key)
if key not in slots:
allocated['ItemEffect']+=1;allocated['ItemXItemEffect']+=1
slots[key]={'effect':allocated['ItemEffect'],'link':allocated['ItemXItemEffect']}
ids=slots[key]
if max(ids.values())>0x7fffffff:raise ValueError('Internal effect/link identity outside native bounds')
effect={'LegacySlotIndex':slot,'TriggerType':trigger,'Charges':0,'CoolDownMSec':proto['spellcooldown_'+str(i)],
'CategoryCoolDownMSec':proto['spellcategorycooldown_'+str(i)],'SpellCategoryID':proto['spellcategory_'+str(i)],'SpellID':spell,'ChrSpecializationID':0,'PlayerConditionID':0}
link={'ItemEffectID':ids['effect'],'ItemID':entry}
for name,row,ident,dest in [('ItemEffect',effect,ids['effect'],effect_rows),('ItemXItemEffect',link,ids['link'],link_rows)]:
raw=encode(row,schemas[name]);dest.append({'table_name':name,'table_hash':hex(TABLES[name][0]),'id':ident,'record':row,'wire_hex':raw.hex(),'sha256':hashlib.sha256(raw).hexdigest(),'source_item':entry,'source_slot':slot})
if set(slots)-used:raise ValueError('Previously owned effect/link rows removed; reviewed migration required')
result={'build':'1.60.1.70334','records':removed+effect_rows+link_rows,'native_preserved':preserved,
'source_authoritative_links':source_authoritative_links,
'limits':['New rows cover reviewed passive relationships only; same spell ID/name does not prove full spell-effect equivalence.',
'Internal effect/link row IDs are target representation, not new item/spell/talent IDs.',
'Existing effects are retained only when spell/slot/trigger identities match; no complete proc/cooldown conversion claim.',
'Registry collisions on a future native data revision require explicit migration/removal planning.']}
if category_sources:
from octo_client_data import canonical_sha256
result['passive_category_review']=dict(policy='source-checked-zero-cooldown-equipped-skill-categories-v1',source_spell_ids=sorted(category_sources),source_definition_sha256={str(i):canonical_sha256(v)for i,v in category_sources.items()},source_category_ids={str(i):v['category_id']for i,v in category_sources.items()},category_ids_preserved=True,server_authoritative=True,gameplay_verified=False)
if allow_on_hit_replacement:
result['server_authoritative_item_ppm']=[dict(item=p['entry'],slot=i-1,ppm=p['spellppmrate_'+str(i)],native_ppm_field_available=False)for p in source for i in range(1,6)if p['spellid_'+str(i)]and p['spelltrigger_'+str(i)]==2]
if on_hit_review is not None:
result['on_hit_review']=on_hit_review
result['limits'][0]='Reviewed uncharged on-equip and on-hit relationships; no proc roll or successful gameplay is synthesized.'
if on_use_review is not None:
result['on_use_review']=on_use_review
result['limits'][0]='Reviewed uncharged equipped-item relationships retain distinct source use/equip/proc triggers; no successful server action is synthesized.'
result['limits'].append('Explicit uncharged equipped on-use slots retain signed cooldowns; no consumed-item, category or successful cast claim.')
return result
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
for name in ('source','effects','links','names','registry','output'):p.add_argument('--'+name,type=Path,required=True)
p.add_argument('--source-authoritative-links',action='store_true',help='Explicit per-item passive-link replacement; never alter shared native spell/effect rows')
p.add_argument('--component-catalogue',action='store_true',help='Batch all source use/equip/proc slots as uninstalled typed components')
p.add_argument('--preserved-package',type=Path,help='Reserve every currently owned internal effect/link row ID')
a=p.parse_args()
if not all(x.resolve().is_relative_to(ROOT) for x in (a.registry,a.output)):p.error('Generated profile/registry must stay inside gateway')
schemas={};maxima={};provenance={}
for name,(table,layout,count) in TABLES.items():
path=NATIVE/(name+'.db2');check_db2(path,table,layout);schemas[name]=fields(DBD/(name+'.dbd'),layout,count)
with path.open('rb') as f:header=f.read(168)
maxima[name]=struct.unpack_from('<I',header,164)[0]
provenance[name]={'table_hash':hex(table),'layout_hash':hex(layout),'native_max_id':maxima[name],'db2_sha256':sha(path),'dbd_sha256':sha(DBD/(name+'.dbd'))}
registry_input_sha256=sha(a.registry)if a.registry.exists()else None
registry=json.loads(a.registry.read_text()) if a.registry.exists() else {'version':1,'slots':{}}
if registry.get('version')!=1:raise ValueError('Unknown internal row registry version')
if a.component_catalogue:
if not a.preserved_package:raise ValueError('Existing package required for catalogue allocation')
report=compile_relationship_catalogue(json.loads(a.source.read_text()),json.loads(a.links.read_text()),json.loads(a.names.read_text()),registry,schemas,maxima,json.loads(a.preserved_package.read_text())['rows'])
else:report=generate(json.loads(a.source.read_text()),json.loads(a.effects.read_text()),json.loads(a.links.read_text()),json.loads(a.names.read_text()),registry,schemas,maxima,source_authoritative_links=a.source_authoritative_links)
report['native_tables']=provenance;report['input_sha256']={k:sha(getattr(a,k)) for k in ('source','effects','links','names')}
report['input_sha256']['registry']=registry_input_sha256
if a.component_catalogue:report['input_sha256']['preserved_package']=sha(a.preserved_package)
for path,value in ((a.registry,registry),(a.output,report)):
path.parent.mkdir(parents=True,exist_ok=True);path.write_text(json.dumps(value,indent=2)+'\n')
if a.component_catalogue:print('Batch relationship components:',report['counts'],'; NOT installed; spell/link dependencies retained.')
else:print('Generated',len(report['records']),'passive effect/link records; preserved',len(report['native_preserved']),'existing item effect sets; no client/server changes.')