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

173 lines
15 KiB
Python

#!/usr/bin/env python3
"""Compose reviewed source item/spell corrections through the existing registry.
Offline only: no install, server access, learning, authentication or UI input.
Inputs are explicitly pinned and output directories are never overwritten.
"""
import argparse,hashlib,json
from pathlib import Path
from aura_definition_profile import scalar_namespace,attack_power_scalar_rows
from item_enchantment_visual_profile import defense_scalar_rows
from spell_item_static_compat import item_text_rows,item_text_namespace
from spell_passive_compat import fields
from item_sparse_compat import package_payloads,package_pages
from turtle_data import DBC,ROOT
def generate(config):
paths={}
for key,entry in config['inputs'].items():
path=Path(entry['path']);path=path if path.is_absolute()else ROOT/path
if hashlib.sha256(path.read_bytes()).hexdigest()!=entry['sha256']:raise ValueError('Input changed: '+key)
paths[key]=path
load=lambda name:json.loads(paths[name].read_text())
package=load('package');package_payloads(package['rows']);metadata=None
if config.get('scalar_enchant_only'):
if config['scalar_enchant_only'] is not True:raise ValueError('Typed scalar-enchant-only scope required')
from item_enchantment_visual_profile import scalar_namespace,constant_enchantment_rows
proof=scalar_namespace(*[paths[k]for k in ('source_items_enum','target_items_enum','source_aura_enum','target_aura_enum','source_shared_enum','target_shared_enum','source_enchant_enum','target_enchant_enum')])
schema=fields(ROOT.parent/'tools/WoWDBDefs/definitions/SpellItemEnchantment.dbd','SpellItemEnchantment')
result=constant_enchantment_rows(DBC(paths['source_enchants'],24),DBC(paths['source_spells'],173),load('native_enchants'),schema,proof)
merged={(r['table_name'],r['id']):r for r in package['rows']};changes=[]
for row in result['rows']:
key=(row['table_name'],row['id']);old=merged.get(key)
if old is None or old.get('wire_hex')!=row['wire_hex']:
changes.append(dict(group='scalar-enchantment',table=key[0],id=key[1],new=old is None));merged[key]=row
staged=dict(package,rows=list(merged.values()))
staged['push_id']=package_payloads(staged['rows'])[0];staged['pushes']=package_pages(staged['rows'])
for key,path in paths.items():
if hashlib.sha256(path.read_bytes()).hexdigest()!=config['inputs'][key]['sha256']:raise ValueError('Input changed during enchant conversion: '+key)
return staged,dict(kind='source-item-correction-batch',scope='scalar-enchantment-only',inputs=config['inputs'],enchantments=result,changed=changes,installed=False,engine_accepted=False,gameplay_verified=False)
if config.get('item_text_only'):
if config['item_text_only'] is not True:raise ValueError('Typed item-text-only scope required')
# Reuse the full source inventory and current effective package. A text
# rerun must not also replay old metadata, enchantment or set snapshots.
dbd=ROOT.parent/'tools/WoWDBDefs/definitions'
proof=item_text_namespace({k:paths[k]for k in ('source_defines','source_auras','target_defines','target_auras')})
timing=None
if config.get('item_text_duration_context'):
if config['item_text_duration_context'] is not True:raise ValueError('Typed item-text duration scope required')
timing=dict(source=DBC(paths['source_durations'],4),native=load('native_durations'),misc=load('native_misc'),misc_schema=fields(dbd/'SpellMisc.dbd','SpellMisc'))
names=None
if config.get('item_text_name_context'):
if config['item_text_name_context'] is not True:raise ValueError('Typed item-text name scope required')
names=dict(native=load('native_names'),schema=fields(dbd/'SpellName.dbd','SpellName'))
result=item_text_rows(DBC(paths['source_spells'],173),load('items'),load('native_text'),load('native_effects'),package['rows'],fields(dbd/'Spell.dbd','Spell'),proof,effect_schema=fields(dbd/'SpellEffect.dbd','SpellEffect'),duration_context=timing,name_context=names)
merged={(r['table_name'],r['id']):r for r in package['rows']};changes=[]
for row in result['rows']:
key=(row['table_name'],row['id']);old=merged.get(key)
if old is None or old.get('wire_hex')!=row['wire_hex']:
changes.append(dict(group='item-text',table=key[0],id=key[1],new=old is None))
merged[key]=row
staged=dict(package,rows=list(merged.values()))
staged['push_id']=package_payloads(staged['rows'])[0];staged['pushes']=package_pages(staged['rows'])
for key,path in paths.items():
if hashlib.sha256(path.read_bytes()).hexdigest()!=config['inputs'][key]['sha256']:raise ValueError('Input changed during conversion: '+key)
return staged,dict(kind='source-item-correction-batch',scope='item-text-only',inputs=config['inputs'],text_namespace=proof,item_text=result,changed=changes,installed=False,engine_accepted=False,gameplay_verified=False)
if config.get('all_ready_metadata'):
from item_catalog_stage import compose_metadata_batch,source_artwork_icon_bindings,refresh_failed_basic_components
from item_sparse_compat import fields as item_fields
manifest=load('catalogue_manifest');catalogue=paths['catalogue_manifest'].parent
if manifest.get('kind')!='source-item-catalogue-conversion'or manifest.get('build')!='1.60.1.70334':raise ValueError('Pinned complete source catalogue required')
items=[]
for file in manifest['files']:
if not file['path'].startswith('items-'):continue
if Path(file['path']).name!=file['path']:raise ValueError('Unsafe catalogue chunk path')
p=catalogue/file['path'];raw=p.read_bytes()
if len(raw)!=file['bytes']or hashlib.sha256(raw).hexdigest()!=file['sha256']:raise ValueError('Source catalogue changed')
items.extend(json.loads(raw))
art=load('artwork_manifest');mapping=load('icon_mapping')
if art.get('kind')!='source-icon-artwork-batch':raise ValueError('Reviewed complete source artwork required')
refreshed=None;artwork_bindings=None
if config.get('refresh_source_artwork_metadata'):
from item_package_preflight import target_index
eligible=[r for r in items if r['entry']and 'icon'in r]
icons,artwork_bindings=source_artwork_icon_bindings([r['source']for r in eligible],
{r['entry']:r['icon']for r in eligible},paths['artwork_manifest'].parent)
for item in eligible:item['icon']=icons[item['entry']]
updated,refreshed=refresh_failed_basic_components(eligible,target_index(load('native_basic'),'Item'))
by_id={r['entry']:r for r in updated};items=[by_id.get(r['entry'],r)for r in items]
target=ROOT/'runtime/native-client/_classic_beta_/Interface'
provider=target/'AddOns/WoWHybridContent/SourceItemIconData.lua'
expected=next(r for r in art['files']if r['path']=='SourceItemIconData.lua')['sha256']
if hashlib.sha256(provider.read_bytes()).hexdigest()!=expected:raise ValueError('Installed source artwork provider differs')
# Hash each shared icon once, not once per referencing item.
bad_icons=set()
for asset in art['assets']:
p=target/'Icons'/Path(asset['path']).name
try:matches=hashlib.sha256(p.read_bytes()).hexdigest()==asset['sha256']
except OSError:matches=False
if not matches:bad_icons.add(asset['path'])
selected=[dict(entry=r['entry'])for r in items if r['entry']and str(r['entry'])in mapping['items']and mapping['items'][str(r['entry'])]not in bad_icons]
result=compose_metadata_batch(package,items,selected,item_fields(ROOT.parent/'tools/WoWDBDefs/definitions/ItemSparse.dbd'),complete_partial_pairs=True,all_source=True)
package=result.pop('package');result.pop('header');metadata=result;metadata['unavailable_icon_assets']=sorted(bad_icons)
if refreshed is not None:
metadata['basic_refresh']=refreshed;metadata['source_artwork_bindings']=artwork_bindings
published=package['rows']
dbd=ROOT.parent/'tools/WoWDBDefs/definitions'
enum_paths={k:paths[k]for k in ('source_defines','source_auras','target_defines','target_auras')}
proof=scalar_namespace(enum_paths);text_proof=item_text_namespace(enum_paths)
source=DBC(paths['source_spells'],173)
scalar=attack_power_scalar_rows(load('source_attack_power'),load('native_effects'),load('native_levels'),published,fields(dbd/'SpellEffect.dbd','SpellEffect'),proof,fields(dbd/'SpellLevels.dbd','SpellLevels'))
text=item_text_rows(source,load('items'),load('native_text'),load('native_effects'),published+scalar['rows'],fields(dbd/'Spell.dbd','Spell'),text_proof,effect_schema=fields(dbd/'SpellEffect.dbd','SpellEffect'))
enchant=defense_scalar_rows(DBC(paths['source_enchants'],24),source,load('native_enchants'),fields(dbd/'SpellItemEnchantment.dbd','SpellItemEnchantment'))
sets=load('sets');known={r['ID']for r in load('native_text')}|{r['id']for r in published if r['table_name']=='Spell'and r.get('record_status','valid')=='valid'}
eligible={d['set_id']for d in sets['dependencies']if set(d['spell_ids'])<=known}
deferred=[dict(set_id=d['set_id'],unresolved_spell_parents=sorted(set(d['spell_ids'])-known))for d in sets['dependencies']if d['set_id']not in eligible]
set_rows=[r for r in sets['records']if r['source_set']in eligible]
# Validate relation removals, inline IDs and all encoded digests at the
# existing publication boundary, before composing any staged package.
package_payloads(set_rows)
merged={(r['table_name'],r['id']):r for r in published};changes=[dict(group='all-ready-source-metadata',table=r['table_name'],id=r['id'],new=True)for r in(metadata['added']if metadata else[])]
for group,rows in [('attack-power',scalar['rows']),('item-text',text['rows']),('enchantment',enchant['rows']),('set-relations',set_rows)]:
for row in rows:
key=(row['table_name'],row['id']);old=merged.get(key)
if old==row:continue
if old is None or old.get('wire_hex')!=row['wire_hex']or old.get('record_status','valid')!=row.get('record_status','valid'):changes.append(dict(group=group,table=key[0],id=key[1],new=old is None))
merged[key]=row
staged=dict(package,rows=list(merged.values()))
staged['push_id']=package_payloads(staged['rows'])[0];staged['pushes']=package_pages(staged['rows'])
professions=None
if config.get('profession_skill_lines'):
from spell_passive_compat import source_profession_link_removals
professions=source_profession_link_removals(DBC(paths['source_abilities'],15),source,load('native_abilities'),staged['rows'],config['profession_skill_lines'],fields(dbd/'SkillLineAbility.dbd','SkillLineAbility'))
for row in professions['rows']:
staged['rows'].append(row);changes.append(dict(group='profession-associations',table=row['table_name'],id=row['id'],new=True))
staged['push_id']=package_payloads(staged['rows'])[0];staged['pushes']=package_pages(staged['rows'])
proc_links=None
if 'proc_links'in config:
from item_effect_compat import compose_passive_link_completion,on_hit_namespace,TABLES as LINK_TABLES
from item_sparse_compat import fields as item_fields
schemas={n:item_fields(dbd/(n+'.dbd'),v[1],v[2])for n,v in LINK_TABLES.items()}
schemas['ItemSparse']=item_fields(dbd/'ItemSparse.dbd')
bounds={k:v['native_max_id']for k,v in load('effect_catalogue')['native_tables'].items()}
result=compose_passive_link_completion(staged,load('catalogue_items'),set(config['proc_links']['reviewed_spell_ids']),load('native_item_effects'),load('native_item_links'),schemas,bounds,
on_hit_context=on_hit_namespace(paths['item_source_enums'],paths['item_target_enums']),proc_override_snapshot=load('proc_overrides'),allow_on_hit_replacement=True)
staged=result.pop('package');proc_links=result
changes.extend(dict(group='source-proc-links',table=r['table_name'],id=r['id'],new=True)for r in result['added'])
report=dict(kind='source-item-correction-batch',inputs=config['inputs'],namespace=proof,text_namespace=text_proof,changed=changes,
attack_power=scalar,item_text=text,enchantments=enchant,proc_links=proc_links,metadata=metadata,professions=professions,
sets=dict(metadata_selected=len(eligible),total=len(sets['dependencies']),rows=len(set_rows),deferred=deferred,linked_effect_semantics_verified=False),
installed=False,engine_accepted=False,gameplay_verified=False,
limits=['Selected source snapshots are pinned; full Octo patch precedence/live equivalence remains unverified.',
'Set parents/bonus thresholds and links only. Positive native spell parents are required, but presence does not prove effect parity.',
'Complex source tooltip tokens, fractional scaling and unresolved set parents remain explicit blockers.',
'The installed server remains authoritative. This tool does not install content or change character/server state.'])
# Re-read hashes to reject concurrently changed snapshots.
for key,path in paths.items():
if hashlib.sha256(path.read_bytes()).hexdigest()!=config['inputs'][key]['sha256']:raise ValueError('Input changed during conversion: '+key)
return staged,report
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--config',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
if not a.output.resolve().is_relative_to(ROOT/'runtime')or a.output.exists():p.error('New workspace runtime output directory required')
staged,report=generate(json.loads(a.config.read_text()));a.output.mkdir(parents=True)
for name,value in [('package.json',staged),('report.json',report)]:
text=json.dumps(value,ensure_ascii=False,sort_keys=True,allow_nan=False,**(dict(separators=(',',':'))if name=='package.json'else dict(indent=2)))
(a.output/name).write_text(text+'\n')
print('Staged',len(staged['rows']),'rows;',len(report['changed']),'wire changes. No installation or engine/gameplay claim.')
if report.get('scope')=='scalar-enchantment-only':print('Scalar enchantments',len(report['enchantments']['rows']),'corrections;',len(report['enchantments']['blocked']),'deferred;',len(report['changed']),'changed package rows')
elif report.get('scope')=='item-text-only':
print('Full item-linked text pass:',report['item_text']['source_linked_spells'],'linked spells;',len(report['item_text']['blocked']),'blocked. Other definition groups preserved.')
else:print('Static attack-power',len(report['attack_power']['rows']),'item text',len(report['item_text']['rows']),'enchants',len(report['enchantments']['rows']),'sets',report['sets']['metadata_selected'],'/',report['sets']['total'])
if __name__=='__main__':main()