Files

798 lines
60 KiB
Python

#!/usr/bin/env python3
"""Bounded, read-only Turtle DBC ingestion and reproducible talent UI data.
Raw rows retain their source schema; modern tables are never decoded as DBC.
"""
import argparse
import hashlib
import json
import os
import re
from pathlib import Path
import struct
import copy
import math
from collections import Counter,deque
ROOT=Path(__file__).resolve().parents[1]
CLIENT=Path('/mnt/Games/Games/TurtleWoW/dbc')
SERVER=Path.home()/'Servers/tortoise-docker/data/dbc'
TABLES=('Spell','Talent','TalentTab','SkillLine','SkillLineAbility','SpellIcon','SpellVisual','SpellVisualKit','SpellVisualEffectName','SpellCastTimes','SpellDuration','SpellRange','SpellRadius','SpellItemEnchantment','ChrRaces','ChrClasses')
def spell_layout(path=None):
"""Resolve disk columns, not the server's SQL-expanded SpellEntry struct.
Vanilla locstrings contain eight locales plus their flags word. SQL adds
bonus-coefficient fields absent from this 173-column disk representation.
Fail closed if the reviewed DBD layout changes.
"""
if path is None:
path=Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions/Spell.dbd'
source=path.read_text()
declarations=source.split('\n\n',1)[0].splitlines()[1:]
localized={line.split()[1] for line in declarations if line.startswith('locstring ')}
block=source.split('BUILD 1.12.0.5595-1.12.3.6141\n',1)[1].split('\n\n',1)[0]
offsets={};column=0
for line in block.splitlines():
match=re.fullmatch(r'(?:\$[^$]+\$)?(\w+)(?:<\d+>)?(?:\[(\d+)\])?',line)
if not match:raise ValueError('Unreviewed Spell DBD field: '+line)
name,count=match.groups();offsets[name]=column
column+=(9 if name in localized else 1)*int(count or 1)
if column!=173:raise ValueError('Reviewed Spell DBD width changed')
return offsets
class DBC:
def __init__(self,path,fields=None):
self.path=path;self.bytes=path.read_bytes()
if len(self.bytes)<20 or len(self.bytes)>67108864:raise ValueError('DBC size bound')
magic,n,f,size,strings=struct.unpack_from('<4s4I',self.bytes)
if magic!=b'WDBC' or size!=f*4 or n>100000 or f>512 or len(self.bytes)!=20+n*size+strings or (fields and fields!=f):raise ValueError('DBC schema/bounds mismatch: '+path.name)
self.fields=f;self.count=n;self.strings=self.bytes[20+n*size:]
self.rows=[struct.unpack_from('<'+str(f)+'I',self.bytes,20+i*size) for i in range(n)]
self.by_id={r[0]:r for r in self.rows}
if len(self.by_id)!=n:raise ValueError('Ambiguous DBC row IDs')
def string(self,offset):
if not 0<=offset<len(self.strings):raise ValueError('DBC string offset bound')
end=self.strings.find(b'\0',offset)
if end<0:raise ValueError('Unterminated DBC string')
return self.strings[offset:end].decode('utf-8')
def digest(self):return hashlib.sha256(self.bytes).hexdigest()
# Reviewed 1.12 disk shapes, not the server's SQL-expanded structures. Child
# tables below are retained opaquely unless a relationship is explicitly named.
INVENTORY_SCHEMAS={'Spell':173,'Talent':21,'TalentTab':15,'SpellItemEnchantment':24,
'SkillLineAbility':15,'ItemSet':45,'SpellIcon':2,'SpellCastTimes':4,
'SpellDuration':4,'SpellRange':22,'SpellRadius':4,'SpellVisual':16,
'SpellVisualKit':35,'SpellVisualEffectName':5,'ItemDisplayInfo':23}
# Reviewed ItemDisplayInfo.dbd BUILD 1.0.0.3980-1.12.3.6141 disk columns.
# Names are contextual source tokens, not resolved asset paths. The independent
# source-client-derived reader is benilla-formats/src/items.rs; provenance and
# exact field map are pinned in evidence/data/item-display-dependencies.json.
ITEM_DISPLAY_FIELDS={'ModelName':(1,2),'ModelTexture':(3,4),'InventoryIcon':(5,),
'GeosetGroup':(6,7,8),'Flags':(9,),'GroupSoundIndex':(11,),
'HelmetGeosetVisID':(12,13),'Texture':tuple(range(14,22)),
'SpellVisualID':(10,),'ItemVisual':(22,)}
ITEM_DISPLAY_TEXTURE_REGIONS=('ArmUpper','ArmLower','Hand','TorsoUpper','TorsoLower','LegUpper','LegLower','Foot')
PROVENANCE_STATUSES=('candidate-unverified','agreement-unverified','selected-by-pinned-evidence','local-template-snapshot')
MAX_INVENTORY_RECORDS=100000
MAX_INVENTORY_LINKS=2000000
def _canonical(value):
return json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=False,allow_nan=False).encode()
def _source_identity(value):
if not isinstance(value,dict) or not isinstance(value.get('dataset'),str) or not 0<len(value['dataset'])<=256 or value.get('provenance') not in PROVENANCE_STATUSES:
raise ValueError('Require explicit bounded dataset identity and provenance status')
if len(_canonical(value))>4096:raise ValueError('Source provenance size bound')
return json.loads(_canonical(value))
def _typed(table,ident):
if not isinstance(table,str) or not re.fullmatch('[A-Za-z][A-Za-z0-9]{0,63}',table) or type(ident) is not int or not 0<ident<=0xffffffff:
raise ValueError('Require distinct table name and positive uint32 source ID')
return [table,ident]
def item_display_composition(dbc,raw):
"""Retain reviewed source composition without assigning modern semantics.
Source model/texture tokens are contextual names, not resolved paths or
verified shared geometry. In particular a worn armor display may have no
standalone mesh: its body texture layers and geosets still matter.
"""
if dbc.fields!=23 or len(raw)!=23:raise ValueError('Unreviewed source item appearance layout')
value={name:[dbc.string(raw[i]) if raw[i] else '' for i in ITEM_DISPLAY_FIELDS[name]]
for name in ('ModelName','ModelTexture','Texture')}
value.update({name:[raw[i] for i in ITEM_DISPLAY_FIELDS[name]]
for name in ('GeosetGroup','Flags','HelmetGeosetVisID','GroupSoundIndex')})
return value
def inventory_table(table_name,dbc,source_identity):
"""Describe one candidate only; unsupported shapes retain raw rows, no links.
Offsets match the reviewed DBD disk blocks and Tortoise DBCStructure.h.
A caller-supplied dataset labels an analysis set, never proves patch order.
No content is converted, installed, granted or declared engine-compatible.
"""
source=_source_identity(source_identity)
if not re.fullmatch('[A-Za-z][A-Za-z0-9]{0,63}',table_name):raise ValueError('Invalid table name')
if len(dbc.rows)>MAX_INVENTORY_RECORDS:raise ValueError('Inventory record bound')
expected=INVENTORY_SCHEMAS.get(table_name);reviewed=expected==dbc.fields
records=[];links=[];assets=[];notes=[];seen=set()
def link(owner,table,ident,field,slot=None,**semantics):
if not ident:return
row=dict(source=owner,target=_typed(table,ident),field=field,semantics=semantics)
if slot is not None:row['slot']=slot
links.append(row)
if len(links)>MAX_INVENTORY_LINKS:raise ValueError('Inventory link bound')
def asset(owner,offset,field,skip_empty=False,**context):
if offset:
value=dbc.string(offset)
if not skip_empty or value:assets.append(dict(source=owner,field=field,path=value,availability='unverified',destination_usable=False,**context))
for raw in sorted(dbc.rows,key=lambda r:r[0]):
if len(raw)!=dbc.fields or any(type(v) is not int or not 0<=v<=0xffffffff for v in raw):raise ValueError('Invalid raw DBC row')
ident=raw[0]
if ident in seen:raise ValueError('Duplicate candidate row ID')
seen.add(ident);owner=[table_name,ident]
records.append(dict(identity=owner,raw_fields=list(raw),raw_sha256=hashlib.sha256(struct.pack('<'+str(len(raw))+'I',*raw)).hexdigest(),
status='reviewed-shape' if reviewed and ident else 'blocked-non-wire-identity' if not ident else 'blocked-unreviewed-schema'))
if not reviewed or not ident:continue
if table_name=='Spell':
for field,index,target,count in [('CastingTimeIndex',18,'SpellCastTimes',1),('DurationIndex',30,'SpellDuration',1),('RangeIndex',36,'SpellRange',1),
('Totem',40,'Item',2),('EffectRadiusIndex',88,'SpellRadius',3),('EffectTriggerSpell',109,'Spell',3),
('SpellVisualID',115,'SpellVisual',2),('SpellIconID',117,'SpellIcon',1),('ActiveIconID',118,'SpellIcon',1)]:
for slot in range(count):link(owner,target,raw[index+slot],field,slot if count>1 else None)
for slot in range(8):
reagent=struct.unpack('<i',struct.pack('<I',raw[42+slot]))[0]
if reagent>0:link(owner,'Item',reagent,'Reagent',slot,count=raw[50+slot])
elif reagent<0:notes.append(dict(source=owner,field='Reagent',slot=slot,value=reagent,status='signed-nonpositive-sentinel/no-item-link'))
for slot in range(3):
effect=raw[61+slot];misc=raw[106+slot];item=raw[103+slot]
if effect in (53,54):link(owner,'SpellItemEnchantment',misc,'EffectMiscValue',slot,effect=effect)
elif misc:notes.append(dict(source=owner,field='EffectMiscValue',slot=slot,value=misc,effect=effect,status='opaque-effect-dependent-value'))
if effect in (24,34):link(owner,'Item',item,'EffectItemType',slot,effect=effect)
elif item:notes.append(dict(source=owner,field='EffectItemType',slot=slot,value=item,effect=effect,status='unreviewed-effect-dependent-reference'))
elif table_name=='Talent':
link(owner,'TalentTab',raw[1],'TabID')
for slot in range(9):link(owner,'Spell',raw[4+slot],'SpellRank',slot,server_consumes_slot=slot<5)
for slot in range(3):link(owner,'Talent',raw[13+slot],'PrereqTalent',slot,required_rank_index=raw[16+slot],server_consumes_slot=slot==0)
link(owner,'Spell',raw[20],'RequiredSpellID')
elif table_name=='TalentTab':
link(owner,'SpellIcon',raw[10],'SpellIconID');asset(owner,raw[14],'BackgroundFile')
elif table_name=='SpellItemEnchantment':
for slot in range(3):
effect,arg=raw[1+slot],raw[10+slot]
if effect in (1,3):link(owner,'Spell',arg,'EffectArg',slot,enchantment_type=effect)
elif effect not in range(7):notes.append(dict(source=owner,field='EffectArg',slot=slot,value=arg,enchantment_type=effect,status='unreviewed-enchantment-type'))
link(owner,'ItemVisuals',raw[22],'ItemVisual')
elif table_name=='SkillLineAbility':
for field,index,target in [('SkillLine',1,'SkillLine'),('Spell',2,'Spell'),('ForwardSpell',8,'Spell')]:link(owner,target,raw[index],field)
elif table_name=='ItemSet':
for slot in range(17):link(owner,'Item',raw[10+slot],'ItemID',slot)
for slot in range(8):link(owner,'Spell',raw[27+slot],'SetSpellID',slot,threshold=raw[35+slot])
link(owner,'SkillLine',raw[43],'RequiredSkill',required_rank=raw[44])
elif table_name=='ItemDisplayInfo':
records[-1]['appearance_composition']=item_display_composition(dbc,raw)
for field in ('ModelName','ModelTexture'):
for slot,index in enumerate(ITEM_DISPLAY_FIELDS[field]):
asset(owner,raw[index],field,skip_empty=True,slot=slot,name_kind='source-component-name',
resolution_context='inventory-type-dependent-item-object-component',resolved_path=None)
asset(owner,raw[5],'InventoryIcon',skip_empty=True,name_kind='source-icon-name',resolution_context='Interface\\Icons',resolved_path=None)
for slot,index in enumerate(ITEM_DISPLAY_FIELDS['Texture']):
asset(owner,raw[index],'Texture',skip_empty=True,slot=slot,region=ITEM_DISPLAY_TEXTURE_REGIONS[slot],
name_kind='source-component-name',resolution_context='character-equipment-body-region',resolved_path=None)
link(owner,'SpellVisual',raw[10],'SpellVisualID')
visual=struct.unpack('<i',struct.pack('<I',raw[22]))[0]
if visual>0:link(owner,'ItemVisuals',visual,'ItemVisual',source_signed=True)
elif visual<0:notes.append(dict(source=owner,field='ItemVisual',value=visual,status='signed-nonpositive-sentinel/no-visual-link'))
notes.append(dict(source=owner,field='appearance-resolution',status='unresolved-asset-and-composition-context',
retained_source_fields=['GeosetGroup','Flags','GroupSoundIndex','HelmetGeosetVisID'],
destination_field_semantics_verified=False))
elif table_name=='SpellIcon':asset(owner,raw[1],'TextureFilename')
return dict(schema_version=1,kind='source-candidate-dependency-inventory',table=table_name,source_identity=source,
candidate_sha256=dbc.digest(),schema=dict(format='WDBC',fields=dbc.fields,expected_reviewed_fields=expected,
status='reviewed-disk-shape' if reviewed else 'blocked-unreviewed-schema'),
records=records,references=links,assets=assets,semantic_notes=notes,
runtime_effective_verified=False,converted=False,engine_loaded=False,
limits=['Explicit relationships only; opaque fields and child records do not establish dependency completeness.',
'Candidate provenance is retained, not independently verified. Assets are named, not verified present or usable.',
'No destination schema, data conversion, installation or gameplay acceptance claim.'])
def item_references(templates,source_identity):
"""Index existing full public item snapshots without querying the database."""
source=_source_identity(source_identity)
if not isinstance(templates,list) or len(templates)>MAX_INVENTORY_RECORDS:raise ValueError('Item inventory record bound')
records=[];links=[];seen=set()
fields={'display_id':'ItemDisplayInfo','set_id':'ItemSet','required_spell':'Spell','required_skill':'SkillLine'}
for row in sorted(templates,key=lambda r:r['entry']):
if not isinstance(row,dict):raise ValueError('Public item row must be an object')
ident=row['entry']
if type(ident) is not int or not 0<=ident<=0xffffffff:raise ValueError('Invalid stored public item identity')
owner=['Item',ident]
if row['entry'] in seen:raise ValueError('Duplicate public item identity')
seen.add(row['entry']);encoded=_canonical(row)
if len(encoded)>1048576:raise ValueError('Item row size bound')
records.append(dict(identity=owner,raw_fields=json.loads(encoded),raw_sha256=hashlib.sha256(encoded).hexdigest(),status='public-template-retained' if ident else 'blocked-non-wire-identity'))
if not ident:continue
for field,target in fields.items():
ident=row[field]
if ident:links.append(dict(source=owner,target=_typed(target,ident),field=field,semantics={}))
for slot in range(1,6):
ident=row['spellid_'+str(slot)]
if ident:
semantics={key:row[key+'_'+str(slot)] for key in ('spelltrigger','spellcharges','spellcooldown','spellcategory','spellcategorycooldown')}
links.append(dict(source=owner,target=_typed('Spell',ident),field='spellid',slot=slot-1,semantics=semantics))
return dict(schema_version=1,kind='source-item-dependency-inventory',table='Item',source_identity=source,records=records,references=links,assets=[],semantic_notes=[],
runtime_effective_verified=False,converted=False,engine_loaded=False,
limits=['Full template rows retained; server item-query fallback cooldowns and missing-spell filtering are separate behavior.',
'Explicit links only, not a complete item dependency or conversion claim.'])
def inventory_item_snapshot(directory,dataset=None):
"""Bridge a completed public bulk export into the existing typed Item graph.
Read/revalidate files only. Snapshot consistency and server provenance are
retained claims of the exporter, not independently repeated database checks.
Joining an explicit analysis dataset never selects an effective DBC winner.
"""
directory=Path(directory)
if directory.is_symlink() or not directory.is_dir():raise ValueError('Require a regular completed item snapshot directory')
def raw_file(name,bound):
path=directory/name
if path.is_symlink() or not path.is_file() or not 0<path.stat().st_size<=bound:raise ValueError('Missing/oversized/linked item snapshot file')
raw=path.read_bytes()
if not 0<len(raw)<=bound:raise ValueError('Item snapshot file size changed')
return raw
def decode(raw):
def unique(pairs):
value={}
for key,item in pairs:
if key in value:raise ValueError('Duplicate item snapshot JSON field')
value[key]=item
return value
return json.loads(raw,object_pairs_hook=unique,parse_constant=lambda _:(_ for _ in ()).throw(ValueError('Nonfinite snapshot value')))
def encoded(value):return (json.dumps(value,ensure_ascii=False,sort_keys=True,indent=2,allow_nan=False)+'\n').encode()
def sha(raw):return hashlib.sha256(raw).hexdigest()
original=raw_file('manifest.json',4194304);manifest=decode(original)
if (not isinstance(manifest,dict) or type(manifest.get('schema_version')) is not int or manifest['schema_version']!=1 or
manifest.get('kind')!='public-local-tortoise-item-inventory' or
manifest.get('source')!='authorized local Tortoise tw_world.item_template'):
raise ValueError('Unreviewed public item snapshot identity')
metadata=manifest.get('database_provenance',{})
if not isinstance(metadata,dict) or metadata.get('database')!='tw_world' or metadata.get('table')!='item_template':raise ValueError('Item snapshot belongs to another source table')
revision=manifest.get('server_source_git_revision')
if not isinstance(revision,str) or not re.fullmatch(r'[0-9a-f]{40}(?:[0-9a-f]{24})?',revision):raise ValueError('Missing pinned item snapshot source revision')
count,chunk_size,total=(manifest.get(key) for key in ('item_count','chunk_size','total_chunk_bytes'))
if (type(count) is not int or not 1<=count<=MAX_INVENTORY_RECORDS or type(chunk_size) is not int or
not 1<=chunk_size<=4096 or type(total) is not int or not 1<=total<=268435456):raise ValueError('Item snapshot analysis size bound')
schema=manifest.get('schema',{});columns=schema.get('column_names') if isinstance(schema,dict) else None
if (not isinstance(columns,list) or not 1<=len(columns)<=512 or
any(not isinstance(key,str) or not re.fullmatch('[A-Za-z_][A-Za-z_0-9]*',key) for key in columns) or len(set(columns))!=len(columns) or
'entry' not in columns or sha(encoded(schema))!=manifest.get('schema_sha256')):raise ValueError('Item snapshot schema/hash mismatch')
required={'entry','display_id','set_id','required_spell','required_skill'}|{f'{key}_{slot}' for slot in range(1,6) for key in ('spellid','spelltrigger','spellcharges','spellcooldown','spellcategory','spellcategorycooldown')}
if not required<=set(columns):raise ValueError('Item snapshot lacks reviewed dependency columns')
chunks=manifest.get('chunks')
if not isinstance(chunks,list) or len(chunks)!=(count+chunk_size-1)//chunk_size or len(chunks)>4096:raise ValueError('Incomplete item chunk inventory')
rows=[];ids=[];content=hashlib.sha256();actual_total=0;files=[]
for index,chunk in enumerate(chunks):
name=f'items-{index:06d}.json'
expected=min(chunk_size,count-len(rows))
if not isinstance(chunk,dict) or chunk.get('path')!=name or type(chunk.get('count')) is not int or chunk['count']!=expected:raise ValueError('Unsafe/unordered/incomplete item chunk identity')
remaining=total-actual_total
if remaining<=0:raise ValueError('Item chunks exceed declared snapshot bound')
raw=raw_file(name,min(134217728,remaining))
if len(raw)!=chunk.get('bytes') or sha(raw)!=chunk.get('sha256'):raise ValueError('Item snapshot chunk hash/size mismatch')
if actual_total+len(raw)>total:raise ValueError('Item chunks exceed declared snapshot bound')
values=decode(raw)
if not isinstance(values,list) or len(values)!=expected:raise ValueError('Item snapshot chunk row count mismatch')
for row in values:
if not isinstance(row,dict) or set(row)!=set(columns) or type(row.get('entry')) is not int or not 0<=row['entry']<=0xffffffff or (ids and row['entry']<=ids[-1]):raise ValueError('Item snapshot row schema/identity/order mismatch')
if any(type(row[key]) is not int for key in required):raise ValueError('Item dependency columns require source integers')
ids.append(row['entry']);rows.append(row);content.update(_canonical(row)+b'\n')
if chunk.get('first_id')!=values[0]['entry'] or chunk.get('last_id')!=values[-1]['entry']:raise ValueError('Item chunk range mismatch')
actual_total+=len(raw);files.append((name,len(raw),sha(raw)))
if (len(rows)!=count or actual_total!=total or manifest.get('first_id')!=ids[0] or manifest.get('last_id')!=ids[-1] or
sha(''.join(str(i)+'\n' for i in ids).encode())!=manifest.get('ids_sha256') or content.hexdigest()!=manifest.get('content_sha256')):
raise ValueError('Complete item snapshot content/inventory hash mismatch')
classification=manifest.get('source_identity_classification',{})
if (not isinstance(classification,dict) or classification.get('all_stored_rows_preserved') is not True or
type(classification.get('positive_uint32_rows')) is not int or classification['positive_uint32_rows']!=sum(i>0 for i in ids) or
not isinstance(classification.get('blocked'),list) or len(classification['blocked'])>1 or any(not isinstance(row,dict) for row in classification['blocked']) or
[row.get('entry') for row in classification.get('blocked',[])]!=([0] if ids[0]==0 else [])):
raise ValueError('Stored item sentinel classification differs')
source=dict(dataset=dataset or 'item-snapshot-sha256:'+sha(original),provenance='local-template-snapshot',
manifest_sha256=sha(original),schema_sha256=manifest['schema_sha256'],
content_sha256=manifest['content_sha256'],ids_sha256=manifest['ids_sha256'],server_source_git_revision=revision)
result=item_references(rows,source)
# Check observed file drift after constructing the full inventory. This is
# not a filesystem snapshot or proof of exporter/runtime server consistency.
if raw_file('manifest.json',4194304)!=original:raise ValueError('Item snapshot manifest changed during analysis')
for name,size,digest in files:
raw=raw_file(name,134217728)
if len(raw)!=size or sha(raw)!=digest:raise ValueError('Item snapshot chunk changed during analysis')
result['snapshot_provenance']={key:value for key,value in manifest.items() if key!='chunks'}
result['snapshot_verification']=dict(manifest_and_chunks_rehashed=True,content_and_schema_and_ids_verified=True,
second_file_pass_matching=True,live_database_requeried=False,effective_client_tables_selected=False)
return result
def dependency_closure(inventories,roots):
"""Iterative graph traversal; retain cycles without recursion or ID remaps.
Exactly one candidate per table and one explicitly labelled dataset may be
joined. This is always an analysis graph, never an effective-source verdict.
"""
if not isinstance(inventories,list) or not inventories or len(inventories)>128:raise ValueError('Inventory graph bound')
datasets=set();tables=set();records={};edges={};assets={};notes={};edge_count=0
for inventory in inventories:
source=_source_identity(inventory['source_identity']);datasets.add(source['dataset'])
table=inventory['table']
if table in tables:raise ValueError('Multiple candidate inventories for one table; resolve or inspect separately')
tables.add(table)
for row in inventory['records']:
key=tuple(row['identity'])
if key in records:raise ValueError('Duplicate typed record identity')
if key[1]==0:continue
_typed(*key);records[key]=row
if len(records)>MAX_INVENTORY_RECORDS:raise ValueError('Graph record bound')
for edge in inventory['references']:
owner=tuple(_typed(*edge['source']));_typed(*edge['target'])
edges.setdefault(owner,[]).append(edge);edge_count+=1
if edge_count>MAX_INVENTORY_LINKS:raise ValueError('Graph edge bound')
for row in inventory.get('assets',[]):assets.setdefault(tuple(row['source']),[]).append(row)
for row in inventory.get('semantic_notes',[]):notes.setdefault(tuple(row['source']),[]).append(row)
if len(datasets)!=1:raise ValueError('Do not mix different source candidate datasets')
if not isinstance(roots,list) or len(roots)>MAX_INVENTORY_RECORDS:raise ValueError('Graph root bound')
root_keys=sorted(set(tuple(_typed(*key)) for key in roots));queue=deque(root_keys);visited=set();missing=set();references=[];unverified_assets=[];semantic_notes=[]
while queue:
owner=queue.popleft()
if owner in visited:continue
visited.add(owner)
if owner not in records:missing.add(owner);continue
unverified_assets+=assets.get(owner,[]);semantic_notes+=notes.get(owner,[])
for edge in sorted(edges.get(owner,[]),key=lambda e:_canonical(e)):
references.append(edge);queue.append(tuple(edge['target']))
selected=sorted(visited-set(missing));adj={owner:[] for owner in selected};reverse={owner:[] for owner in selected}
for edge in references:
a,b=tuple(edge['source']),tuple(edge['target'])
if a in adj and b in adj:adj[a].append(b);reverse[b].append(a)
# Iterative Kosaraju: cycle components are useful batch boundaries, and a
# real long trigger chain cannot overflow Python's call stack.
seen=set();order=[]
for owner in selected:
if owner in seen:continue
stack=[(owner,False)]
while stack:
node,finished=stack.pop()
if finished:order.append(node);continue
if node in seen:continue
seen.add(node);stack.append((node,True));stack.extend((n,False) for n in sorted(adj[node],reverse=True) if n not in seen)
seen=set();cycles=[]
for owner in reversed(order):
if owner in seen:continue
component=[];stack=[owner];seen.add(owner)
while stack:
node=stack.pop();component.append(node)
for other in reverse[node]:
if other not in seen:seen.add(other);stack.append(other)
if len(component)>1 or owner in adj[owner]:cycles.append([list(k) for k in sorted(component)])
return dict(schema_version=1,kind='offline-declared-reference-closure',dataset=next(iter(datasets)),roots=[list(k) for k in root_keys],
records=[records[k] for k in selected],references=references,missing=[list(k) for k in sorted(missing)],cycles=sorted(cycles),
unverified_assets=unverified_assets,semantic_notes=semantic_notes,declared_references_resolved=not missing,
blocked_records=[list(k) for k in selected if records[k]['status'].startswith('blocked-')],
dependency_complete=False,runtime_effective_verified=False,converted=False,engine_loaded=False,
limits=['Closure covers explicitly reviewed links only; opaque fields, asset dependencies and source selection remain separate validation.',
'Cycles are retained as typed strongly connected components; no gameplay semantics or destination definitions are invented.'])
def lua(value):
if value is None:return 'nil'
if isinstance(value,str):
# Lua5.1 decimal escapes, not JSON's unsupported Unicode/\u escapes.
return '"'+''.join('\\%03d'%ord(c) if ord(c)<32 else '\\'+c if c in ('"','\\') else c for c in value)+'"'
if isinstance(value,(int,float)):return str(value)
if isinstance(value,list):return '{'+','.join(lua(v) for v in value)+'}'
if isinstance(value,dict):return '{'+','.join('['+lua(k)+']='+lua(v) for k,v in value.items())+'}'
raise ValueError('Unsupported Lua data type')
def read_spell_chain(path,*,include_previous=False):
"""Server spell_chain rows (spell_id, prev_spell, first_spell, rank) as TSV.
Vanilla SkillLineAbility forward edges are incomplete (11 talent chains on
Octo patch-5); vanilla cores carry the rest in spell_chain (33 chains).
"""
rows=[]
for line in Path(path).read_text().splitlines():
if not line.strip():continue
spell,previous,first,rank=map(int,line.split()[:4])
rows.append((spell,previous,first,rank) if include_previous else (spell,first,rank))
if not 0<len(rows)<=100000:raise ValueError('spell_chain row bound')
return rows
def talent_rank_successors(talents,abilities,spells,chain_rows=()):
"""Use authentic SkillLineAbility forward edges, as SpellMgr::LoadSpellChains.
Higher trained ability ranks prove the talent base is learned without adding
invented spell IDs to the received server-known set or changing its count.
Optional server spell_chain rows add the chains the DBC lacks; both sources
are unioned (a successor only ever proves the base talent is learned).
"""
if talents.fields!=21 or abilities.fields!=15:raise ValueError('Reviewed talent/rank ability schema required')
present={r[2]for r in abilities.rows};forward={}
for row in abilities.rows:
source,target=row[2],row[8]
if not target or source not in spells.by_id or target not in spells.by_id or target not in present:continue
if source in forward and forward[source]!=target:raise ValueError('Ambiguous ability rank successor')
forward[source]=target
result={}
for row in talents.rows:
for source in row[4:9]:
if not source:continue
seen={source};chain=[];current=source
while current in forward:
current=forward[current]
if current in seen:raise ValueError('Cyclic talent ability rank chain')
seen.add(current);chain.append(current)
if len(chain)>128:raise ValueError('Talent ability rank chain bound')
if chain:result[source]=chain
if chain_rows:
ranks={};members={}
for spell,first,rank in chain_rows:ranks[spell]=(first,rank);members.setdefault(first,[]).append((rank,spell))
for row in talents.rows:
for source in row[4:9]:
if not source or source not in ranks:continue
first,rank=ranks[source]
higher=[spell for r,spell in sorted(members[first])if r>rank]
if higher:result[source]=result.get(source,[])+[s for s in higher if s not in result.get(source,[])]
return dict(sorted(result.items()))
def validated_talent_rank_successors(talents,abilities,spells,chain_rows=(),*,talent_tabs=None):
"""Resolve trained actions to actual talent point spells, with explicit holds.
Reuses the Source SkillLineAbility forward and spell_chain authorities used
above. This stricter profile boundary additionally requires same-line/class
classification and unambiguous talent ownership. The received known-spell
set is never expanded. A trained action rank does not become a point count.
"""
if talents.fields!=21 or abilities.fields!=15:raise ValueError('Reviewed talent/rank ability schema required')
if talent_tabs is not None and talent_tabs.fields!=15:raise ValueError('Reviewed TalentTab schema required')
held=[];rows={};owners={};candidates={}
for row in abilities.rows:rows.setdefault(row[2],[]).append(row)
tabs={r[0]:r[12] for r in talent_tabs.rows} if talent_tabs is not None else {}
for row in talents.rows:
for point,spell in enumerate(row[4:9],1):
if spell:owners.setdefault(spell,[]).append((row[0],point,tabs.get(row[1],0)))
def hold(root,kind,**detail):held.append(dict(rank_spell=root,kind=kind,**detail))
def classified(root,spell,lines,mask):
if spell not in spells.by_id:hold(root,'missing-source-spell',spell=spell);return False
same=[r for r in rows.get(spell,[]) if r[1] in lines]
if not same:hold(root,'foreign-or-missing-skill-line',spell=spell,expected_lines=sorted(lines));return False
if mask and not any(not r[4] or r[4]&mask for r in same):
hold(root,'foreign-class',spell=spell,class_mask=mask);return False
return True
# Accept both the existing (spell,first,rank) reader shape and complete
# (spell,previous,first,rank) rows. Complete rows also validate predecessor
# identity/order rather than discarding the saved server relationship.
ranks={};groups={};bad_groups=set()
for row in chain_rows:
if len(row)==3:spell,first,rank=row;previous=None
elif len(row)==4:spell,previous,first,rank=row
else:raise ValueError('spell_chain row shape')
value=(first,rank,previous)
if spell in ranks and ranks[spell]!=value:bad_groups.update((first,ranks[spell][0]))
ranks[spell]=value;groups.setdefault(first,set()).add(spell)
for first,members in groups.items():
seen={}
for spell in members:
_,rank,previous=ranks[spell]
if rank<1 or rank in seen and seen[rank]!=spell:bad_groups.add(first)
seen[rank]=spell
if previous is not None:
if previous and (previous not in members or ranks[previous][0]!=first or ranks[previous][1]>=rank):bad_groups.add(first)
if not previous and (spell!=first or rank!=1):bad_groups.add(first)
if first not in members or ranks[first][1]!=1:bad_groups.add(first)
for root,owner in sorted(owners.items()):
if len(owner)!=1:hold(root,'ambiguous-talent-point-owner',owners=owner);continue
mask=owner[0][2];lines={r[1] for r in rows.get(root,[]) if not mask or not r[4] or r[4]&mask}
has_chain=root in ranks and any(ranks[s][1]>ranks[root][1] for s in groups[ranks[root][0]])
has_forward=any(r[8] for r in rows.get(root,[]))
if not has_chain and not has_forward:continue
if talent_tabs is not None and not mask:hold(root,'missing-talent-class');continue
if not lines or not classified(root,root,lines,mask):
if not lines:hold(root,'missing-root-skill-line')
continue
chain=[];current=root;seen={root};valid=True
while True:
targets={r[8] for r in rows.get(current,[]) if r[1] in lines and r[8]}
if not targets:break
if len(targets)!=1:hold(root,'ambiguous-ability-successor',spell=current,targets=sorted(targets));valid=False;break
current=next(iter(targets))
if current in seen:hold(root,'cyclic-ability-successor',spell=current);valid=False;break
if len(chain)>=128:hold(root,'ability-successor-bound');valid=False;break
seen.add(current)
if not classified(root,current,lines,mask):valid=False;break
chain.append(current)
if valid:candidates[root]=set(chain)
# An invalid forward graph is not repaired by an independent union.
if not valid:continue
if root in ranks:
first,rank,_=ranks[root]
if first in bad_groups:
hold(root,'ambiguous-or-cyclic-server-chain',first=first);candidates.pop(root,None);continue
for spell in sorted(groups[first],key=lambda s:(ranks[s][1],s)):
if ranks[spell][1]>rank and classified(root,spell,lines,mask):candidates[root].add(spell)
# A direct point spell already has its exact Source point rank. For a
# trained action shared by multiple point roots, only same-talent ordered
# point roots can resolve to the highest actual point rank. Foreign talent
# ownership remains held, never selected by numeric spell/rank order.
claims={}
for root,targets in candidates.items():
for spell in targets:
if spell not in owners:claims.setdefault(spell,[]).append(root)
result={}
for spell,roots in sorted(claims.items()):
root=max(roots,key=lambda r:owners[r][0][1])
if (len({owners[r][0][0] for r in roots})!=1 or
any(r!=root and root not in candidates[r] for r in roots)):
for claimed_root in roots:hold(claimed_root,'ambiguous-trained-action-owner',spell=spell,roots=sorted(roots))
continue
result.setdefault(root,[]).append(spell)
return dict(sorted(result.items())),held
def spell_tooltip_graph(spells,roots,*,duration_candidates=(),icon_candidates=(),radius_candidates=(),server_templates=None):
"""Batch static presentation dependencies; never grant or execute spells.
Ambiguous auxiliary records remain unresolved. Capture/selection provenance
is checked by the staging caller, rather than inferred from archive names.
"""
if spells.fields!=173:raise ValueError('Reviewed173-column Spell source required')
if len(roots)>20000 or any(type(i)is not int or not 0<i<=0x7fffffff for i in roots):raise ValueError('Tooltip root identity/count bound')
if any(t.fields!=4 for t in (*duration_candidates,*radius_candidates))or any(t.fields!=2 for t in icon_candidates):raise ValueError('Tooltip auxiliary schema differs')
offsets=spell_layout();queue=deque(sorted(set(roots)));records={};missing=set();issues=[]
signed=lambda n:struct.unpack('<i',struct.pack('<I',n))[0]
def floating(n):
value=struct.unpack('<f',struct.pack('<I',n))[0]
if not math.isfinite(value):raise ValueError('Nonfinite source tooltip coefficient')
return value
while queue:
ident=queue.popleft()
if ident in records or ident in missing:continue
if len(records)+len(missing)>=100000:raise ValueError('Tooltip dependency graph bound')
raw=spells.by_id.get(ident)
if raw is None:missing.add(ident);continue
server=server_templates.get(ident)if server_templates is not None else None
if server is not None and server.get('entry')!=ident:raise ValueError('Tooltip SQL identity differs')
def numeric(column,fallback):
value=fallback if server is None else server[column]
if not isinstance(value,(int,float))or isinstance(value,bool)or not math.isfinite(value):raise ValueError('Nonfinite Source tooltip SQL field: '+column)
return value
def source_int(column,fallback):
value=numeric(column,fallback)
if value!=int(value)or not -0x80000000<=value<=0xffffffff:raise ValueError('Source tooltip signed field bound: '+column)
return signed(int(value)&0xffffffff)
record=dict(id=ident,name=spells.string(raw[offsets['Name_lang']]),rank=spells.string(raw[offsets['NameSubtext_lang']]),
description=spells.string(raw[offsets['Description_lang']]),auraDescription=spells.string(raw[offsets['AuraDescription_lang']]),
procChance=numeric('procChance',raw[offsets['ProcChance']]),procCharges=numeric('procCharges',raw[offsets['ProcCharges']]),
stackAmount=numeric('stackAmount',raw[offsets['CumulativeAura']]),maxTargets=numeric('maxAffectedTargets',raw[offsets['MaxTargets']]),
maxTargetLevel=numeric('maxTargetLevel',raw[offsets['MaxTargetLevel']]),
maxLevel=numeric('maxLevel',raw[offsets['MaxLevel']]),baseLevel=numeric('baseLevel',raw[offsets['BaseLevel']]),
spellLevel=numeric('spellLevel',raw[offsets['SpellLevel']]),effects=[])
if any(len(record[k])>8192 for k in('description','auraDescription')):raise ValueError('Tooltip text bound')
for index in range(3):
suffix=str(index+1)
record['effects'].append(dict(effect=numeric('effect'+suffix,raw[offsets['Effect']+index]),
basePoints=source_int('effectBasePoints'+suffix,signed(raw[offsets['EffectBasePoints']+index])),
baseDice=source_int('effectBaseDice'+suffix,signed(raw[offsets['EffectBaseDice']+index])),
dieSides=source_int('effectDieSides'+suffix,signed(raw[offsets['EffectDieSides']+index])),
aura=numeric('effectApplyAuraName'+suffix,raw[offsets['EffectAura']+index]),misc=source_int('effectMiscValue'+suffix,signed(raw[offsets['EffectMiscValue']+index])),
trigger=numeric('effectTriggerSpell'+suffix,raw[offsets['EffectTriggerSpell']+index]),
amplitudeMs=numeric('effectAmplitude'+suffix,raw[offsets['EffectAuraPeriod']+index]),
dicePerLevel=numeric('effectDicePerLevel'+suffix,floating(raw[offsets['EffectDicePerLevel']+index])),
pointsPerLevel=numeric('effectRealPointsPerLevel'+suffix,floating(raw[offsets['EffectRealPointsPerLevel']+index])),
pointsPerComboPoint=numeric('effectPointsPerComboPoint'+suffix,floating(raw[offsets['EffectPointsPerCombo']+index]))))
radius_id=numeric('effectRadiusIndex'+suffix,raw[offsets['EffectRadiusIndex']+index])
if radius_id:
alternatives={tuple(floating(n)for n in t.by_id[radius_id][1:])for t in radius_candidates if radius_id in t.by_id}
if len(alternatives)==1:
base,per_level,maximum=next(iter(alternatives))
if 0<=base<=0x7fffffff and per_level==0 and maximum in(0,base):record['effects'][-1]['radius']=base
else:issues.append(dict(spell=ident,kind='nonconstant-radius',reference=radius_id,effect=index+1))
else:issues.append(dict(spell=ident,kind='conflicting-radius'if alternatives else'missing-radius',reference=radius_id,effect=index+1))
duration_id=numeric('durationIndex',raw[offsets['DurationIndex']])
if duration_id:
alternatives={tuple(signed(n)for n in t.by_id[duration_id][1:])for t in duration_candidates if duration_id in t.by_id}
if len(alternatives)==1:
base,per_level,maximum=next(iter(alternatives))
# Source SpellEntry::GetDuration reads abs(Duration[0]);
# CalculateDuration never consumes Duration[1]. Combo points,
# scripts and spellmods act later and are not tooltip guesses.
if base not in(-1,0,-0x80000000):
record['durationMs']=abs(base)
record['sourceDurationFields']=[base,per_level,maximum]
else:issues.append(dict(spell=ident,kind='zero-or-permanent-duration',reference=duration_id))
else:issues.append(dict(spell=ident,kind='conflicting-duration'if alternatives else'missing-duration',reference=duration_id))
icon_id=raw[offsets['SpellIconID']]
paths={t.string(t.by_id[icon_id][1])for t in icon_candidates if icon_id in t.by_id}-{''}
normalized={p.replace('/','\\').lower()for p in paths}
if len(normalized)==1:record['icon']=sorted(paths)[0]
else:issues.append(dict(spell=ident,kind='conflicting-icon'if paths else'missing-icon',reference=icon_id))
records[ident]=record
for effect in record['effects']:
if effect['trigger']>0x7fffffff:raise ValueError('Trigger dependency identity bound')
if effect['trigger']:queue.append(effect['trigger'])
for text in(record['description'],record['auraDescription']):
for value in re.findall(r'(?<!\$)\$(?:[*/][0-9]+;)?([1-9][0-9]*)[A-Za-z]',text):
reference=int(value)
if reference>0x7fffffff:raise ValueError('Tooltip dependency identity bound')
queue.append(reference)
return dict(records=dict(sorted(records.items())),missing=sorted(missing),issues=issues)
def refresh_talent_data(data,spells,*,duration_candidates=(),icon_candidates=(),radius_candidates=(),server_templates=None):
"""Update all rank presentation records, preserving tree and learned-state IDs."""
if not isinstance(data,dict)or not isinstance(data.get('talents'),list)or not 1<=len(data['talents'])<=4096:raise ValueError('Bounded existing talent data required')
roots=[rank['id']for t in data['talents']for rank in t['ranks']]
if len(set(roots))!=len(roots):raise ValueError('Ambiguous repeated talent rank spell identity')
retained_chains=data.get('rankSuccessors',{})
extra=[ident for values in retained_chains.values()for ident in values]
graph=spell_tooltip_graph(spells,roots+extra,duration_candidates=duration_candidates,icon_candidates=icon_candidates,radius_candidates=radius_candidates,server_templates=server_templates)
if any(i in graph['missing']for i in roots):raise ValueError('Source is missing a genuine talent rank')
result=copy.deepcopy(data);changes=[];root_ids=set(roots)
if 'rankSuccessors'in result:
checked={}
for key,value in result['rankSuccessors'].items():
ident=int(key)
if str(ident)!=str(key)or ident<=0 or ident not in spells.by_id or ident in checked or not isinstance(value,list)or len(value)>128:raise ValueError('Rank successor identity/chain bound')
if any(type(i)is not int or i not in spells.by_id for i in value)or len(set(value))!=len(value)or ident in value:raise ValueError('Invalid retained rank successor chain')
checked[ident]=value
result['rankSuccessors']=dict(sorted(checked.items()))
for talent in result['talents']:
for rank in talent['ranks']:
replacement=copy.deepcopy(graph['records'][rank['id']])
# Unknown/conflicting icon candidates do not replace a previously
# installed source icon with an arbitrary archive or question mark.
if 'icon'not in replacement:replacement['icon']=rank.get('icon')
differences=sorted(k for k in set(rank)|set(replacement)if rank.get(k)!=replacement.get(k))
if differences:changes.append(dict(talent=talent['id'],spell=rank['id'],fields=differences))
rank.clear();rank.update(replacement)
result['tooltipSpells']={i:r for i,r in graph['records'].items()if i not in root_ids}
relationship=lambda value:dict(tabs=value['tabs'],talents=[dict({k:v for k,v in t.items()if k!='ranks'},ranks=[r['id']for r in t['ranks']])for t in value['talents']])
before=hashlib.sha256(_canonical(relationship(data))).hexdigest();after=hashlib.sha256(_canonical(relationship(result))).hexdigest()
if before!=after:raise ValueError('Presentation refresh changed talent relationships')
return result,dict(talents=len(result['talents']),rank_records=len(roots),dependency_records=len(result['tooltipSpells']),changes=changes,
changed_fields=dict(sorted(Counter(k for c in changes for k in c['fields']).items())),relationship_sha256=after,
missing_references=graph['missing'],unresolved_auxiliary_records=graph['issues'],
current_SQL_definition_records=sum(i in server_templates for i in graph['records'])if server_templates is not None else 0,
engine_loaded=False,gameplay_verified=False,relationships_or_server_state_changed=False,
duration_policy='Source SpellEntry::GetDuration nominal absolute base after full candidate-row agreement. Duration[1] is unused; combo/script/spellmod/diminishing effects are not predicted; zero/permanent/ambiguous rows remain held.')
def stage_talent_refresh(baseline,spell_path,inventory_path,output,*,duration_paths=(),icon_paths=(),radius_paths=(),talent_path=None,skill_line_ability_path=None,spell_chain_path=None):
"""Stage presentation only, reusing the existing observed-content validator.
No installation, database access, spell grants, tree mutation or server code.
The baseline owns retained tree relationships; auxiliary agreement is not
misrepresented as an observed effective archive selection.
"""
from spell_content_compare import _observed_context
baseline=Path(baseline);output=Path(output)
if not 0<baseline.stat().st_size<=2097152:raise ValueError('Talent baseline size bound')
if output.exists()or output.is_symlink()or not output.parent.is_dir()or not output.resolve().is_relative_to(ROOT/'runtime'):
raise ValueError('Require a NEW private runtime output directory with existing parent')
source=DBC(Path(spell_path),173)
context=_observed_context(source,json.loads(Path(inventory_path).read_text()),'enUS')
def candidates(paths,fields):return [DBC(Path(p),fields)for p in sorted(set(map(str,paths)))]
durations=candidates(duration_paths,4);icons=candidates(icon_paths,2);radii=candidates(radius_paths,4)
baseline_data=json.loads(baseline.read_text())
# Rank successors must come from the SAME Octo data being staged. A baseline
# without them made trained higher ranks (e.g. Bloodthirst 23881->23894)
# count as unlearned talents (2026-11-10 regression).
if (talent_path is None)!=(skill_line_ability_path is None):raise ValueError('Talent and SkillLineAbility DBCs are required together')
if talent_path is not None:
baseline_data=dict(baseline_data,rankSuccessors=talent_rank_successors(DBC(Path(talent_path),21),DBC(Path(skill_line_ability_path),15),source,
read_spell_chain(spell_chain_path)if spell_chain_path else()))
elif not baseline_data.get('rankSuccessors'):
raise ValueError('Baseline has no rankSuccessors; pass talent_path and skill_line_ability_path')
data,report=refresh_talent_data(baseline_data,source,duration_candidates=durations,icon_candidates=icons,radius_candidates=radii)
payload=('-- Generated from pinned observed Octo Spell data; provenance and limits in report.json.\nGatewayTurtleData='+lua(data)+'\n').encode()
if len(payload)>2097152:raise ValueError('Generated talent data size bound')
report.update(kind='octo-talent-presentation-refresh',schema_version=1,source=context,
baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),converter_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
auxiliary_candidates={key:[dict(path=str(t.path),sha256=t.digest(),rows=t.count,fields=t.fields)for t in tables]
for key,tables in [('SpellDuration',durations),('SpellIcon',icons),('SpellRadius',radii)]},
limits=['Tree relationships are retained from the pinned baseline, not inferred from Spell names.',
'Auxiliary row agreement is not proof of effective archive precedence or installed asset availability.',
'Static tooltip definitions do not establish runtime damage, spell execution or all-class compatibility.'])
files={'TurtleData.lua':payload,'talent-data.json':(json.dumps(data,sort_keys=True,ensure_ascii=False,indent=2,allow_nan=False)+'\n').encode(),
'report.json':(json.dumps(report,sort_keys=True,ensure_ascii=False,indent=2,allow_nan=False)+'\n').encode()}
manifest=dict(kind='staged-talent-presentation',schema_version=1,files={name:hashlib.sha256(raw).hexdigest()for name,raw in files.items()},
installed=False,engine_loaded=False,server_changed=False)
files['manifest.json']=(json.dumps(manifest,sort_keys=True,indent=2)+'\n').encode()
output.mkdir(mode=0o700)
for name,raw in files.items():
with (output/name).open('xb')as stream:stream.write(raw)
return report,manifest
def generate(output):
output.mkdir(parents=True,exist_ok=True);manifest={};tables={}
for name in TABLES:
table=DBC(CLIENT/(name+'.dbc'));tables[name]=table
server=SERVER/(name+'.dbc')
manifest[name]={'source':str(table.path),'sha256':table.digest(),'rows':table.count,'fields':table.fields,'record_bytes':table.fields*4,'server_identical':server.exists() and hashlib.sha256(server.read_bytes()).hexdigest()==table.digest()}
# Machine-readable raw records are explicit arrays, not falsely named modern fields.
(output/(name+'.raw.json')).write_text(json.dumps({'schema':manifest[name],'rows':table.rows,'string_block_hex':table.strings.hex()},separators=(',',':')))
if tables['Spell'].fields!=173 or tables['Talent'].fields!=21 or tables['TalentTab'].fields!=15 or tables['SpellIcon'].fields!=2:raise ValueError('Reviewed Turtle semantic schema changed')
spells,talents,tabs,icons=(tables[k] for k in ('Spell','Talent','TalentTab','SpellIcon'))
layout=spell_layout();definitions=[];tab_rows=[]
for row in tabs.rows:
icon=icons.by_id.get(row[10])
tab_rows.append({'id':row[0],'name':tabs.string(row[1]),'icon':icons.string(icon[1]) if icon else None,'classMask':row[12],'order':row[13]})
for r in talents.rows:
ranks=[s for s in r[4:9] if s]
if not ranks or list(r[4:4+len(ranks)])!=ranks or any(r[4+len(ranks):9]):raise ValueError('Talent rank definition')
rank_rows=[]
for spell_id in ranks:
s=spells.by_id[spell_id];icon=icons.by_id.get(s[layout['SpellIconID']]);effects=[]
for i in range(3):
effects.append({'effect':s[layout['Effect']+i],'basePoints':struct.unpack('<i',struct.pack('<I',s[layout['EffectBasePoints']+i]))[0],'aura':s[layout['EffectAura']+i],'misc':s[layout['EffectMiscValue']+i],'trigger':s[layout['EffectTriggerSpell']+i]})
rank_rows.append({'id':spell_id,'name':spells.string(s[layout['Name_lang']]),'rank':spells.string(s[layout['NameSubtext_lang']]),'description':spells.string(s[layout['Description_lang']]),'icon':icons.string(icon[1]) if icon else None,'procChance':s[layout['ProcChance']],'procCharges':s[layout['ProcCharges']],'effects':effects})
definitions.append({'id':r[0],'tab':r[1],'row':r[2],'column':r[3],'prerequisite':r[13],'prerequisiteRank':r[16],'requiredSpell':r[20],'ranks':rank_rows})
report={'schema_version':1,'tables':manifest,'talent_tabs':tab_rows,'talents':definitions,'limits':['Extracted installed-client DBCs match server copies; effective MPQ patch-order provenance still requires verification.','Shared spell IDs do not establish equal effects or tooltips.','No all-class real-client integration claim.']}
successors=talent_rank_successors(talents,tables['SkillLineAbility'],spells)
report['rank_successors']=successors
addon={'tabs':tab_rows,'talents':definitions,'rankSuccessors':successors}
# The renderer resolves cross-spell tokens through tooltipSpells. Keep
# default generation on the same complete Source graph as refresh staging;
# rank-only records omit referenced effects, durations and trained ranks.
addon,tooltip_report=refresh_talent_data(addon,spells,
duration_candidates=[tables['SpellDuration']],icon_candidates=[icons],radius_candidates=[tables['SpellRadius']])
report['talents']=addon['talents'];report['tooltip_presentation']=tooltip_report
(output/'talents.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
(output/'TurtleData.lua').write_text('-- Generated from the installed Turtle client; source hashes in talents.json.\nGatewayTurtleData='+lua(addon)+'\n')
modern_file=ROOT/'runtime/forever-SpellName.json'
if modern_file.exists():
modern={r['ID'] for r in json.loads(modern_file.read_text())}
(output/'spell-identity-availability.json').write_text(json.dumps({'turtle_count':len(spells.rows),'forever_name_count':len(modern),'missing_forever_spell_name':sorted(set(spells.by_id)-modern),'warning':'Name-record presence does not establish complete spell/effect compatibility.'},indent=2)+'\n')
coverage={str(c):{'talent_trees':sum(bool(t['classMask']&(1<<(c-1))) for t in tab_rows),'talent_rows':sum(bool(tabs.by_id[t['tab']][12]&(1<<(c-1))) for t in definitions),'real_client':'partial Human Warrior only' if c==1 else 'unverified'} for c in tables['ChrClasses'].by_id}
(output/'coverage.json').write_text(json.dumps({'classes':coverage,'races':{str(r):'partial Human Warrior only' if r==1 else 'unverified' for r in tables['ChrRaces'].by_id}},indent=2)+'\n')
print('Read',len(tables),'actual Turtle tables;',len(definitions),'talents and',len(tab_rows),'class trees; generated server-data UI inputs, not proof of gameplay compatibility.')
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--output',type=Path,default=ROOT/'build/turtle-data')
mode=p.add_mutually_exclusive_group()
mode.add_argument('--inventory-candidate',type=Path)
mode.add_argument('--inventory-items',type=Path,help='Read/revalidate a completed bulk item snapshot into the existing typed dependency inventory; no database access')
mode.add_argument('--refresh-talent-data',type=Path,help='Stage existing talent JSON with pinned observed Octo spell presentation; does not install or change gameplay')
p.add_argument('--observed-spell',type=Path)
p.add_argument('--observed-spell-inventory',type=Path)
p.add_argument('--duration-candidate',type=Path,action='append',default=[])
p.add_argument('--icon-candidate',type=Path,action='append',default=[])
p.add_argument('--radius-candidate',type=Path,action='append',default=[])
p.add_argument('--talent-dbc',type=Path,help='Octo Talent.dbc; with --skill-line-ability-dbc recomputes rankSuccessors')
p.add_argument('--skill-line-ability-dbc',type=Path)
p.add_argument('--spell-chain-tsv',type=Path,help='server spell_chain export (spell_id prev first rank); completes rankSuccessors')
p.add_argument('--table')
p.add_argument('--provenance',choices=PROVENANCE_STATUSES,default='candidate-unverified')
p.add_argument('--dataset',help='Explicit analysis-set identity; default isolates this file hash')
args=p.parse_args()
if not args.output.resolve().is_relative_to(ROOT):p.error('Output must stay in gateway')
if args.refresh_talent_data:
if not args.observed_spell or not args.observed_spell_inventory or args.table or args.dataset or args.provenance!='candidate-unverified':p.error('Refresh requires observed Spell and validated inventory; no candidate-selection overrides')
report,manifest=stage_talent_refresh(args.refresh_talent_data,args.observed_spell,args.observed_spell_inventory,args.output,
duration_paths=args.duration_candidate,icon_paths=args.icon_candidate,radius_paths=args.radius_candidate,talent_path=args.talent_dbc,skill_line_ability_path=args.skill_line_ability_dbc,spell_chain_path=args.spell_chain_tsv)
print(json.dumps({k:report[k]for k in ('talents','rank_records','dependency_records','engine_loaded','gameplay_verified')}|dict(changed_records=len(report['changes']),missing_references=len(report['missing_references']),unresolved_auxiliary_records=len(report['unresolved_auxiliary_records']),manifest=manifest['kind'])))
elif args.observed_spell or args.observed_spell_inventory or args.duration_candidate or args.icon_candidate or args.radius_candidate:p.error('Observed/auxiliary options require --refresh-talent-data')
elif args.inventory_items:
if args.table or args.provenance!='candidate-unverified':p.error('Item snapshots retain their source provenance, not a caller-supplied DBC table/provenance')
if not args.output.resolve().is_relative_to(ROOT/'runtime') or args.output.exists() or args.output.is_symlink() or not args.output.parent.is_dir():p.error('Item inventory requires a NEW runtime JSON output with an existing parent')
result=inventory_item_snapshot(args.inventory_items,args.dataset)
fd=os.open(args.output,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'w') as stream:json.dump(result,stream,ensure_ascii=False,sort_keys=True,indent=2);stream.write('\n')
print('Inventoried',len(result['records']),'stored source item records;',len(result['references']),'declared links; no effective DBC selection, conversion, installation or engine acceptance claim.')
elif args.inventory_candidate:
if not args.table:p.error('--inventory-candidate requires --table')
if not args.output.resolve().is_relative_to(ROOT/'runtime') or args.output.exists():p.error('Candidate inventory requires a new runtime JSON output')
table=DBC(args.inventory_candidate)
source=dict(dataset=args.dataset or 'candidate-sha256:'+table.digest(),provenance=args.provenance,path=str(args.inventory_candidate.resolve()))
result=inventory_table(args.table,table,source)
args.output.write_text(json.dumps(result,ensure_ascii=False,sort_keys=True,indent=2)+'\n')
print('Inventoried',len(result['records']),'candidate records;',len(result['references']),'declared links;',result['schema']['status'],'; no conversion or engine acceptance claim.')
else:
if args.table or args.dataset or args.provenance!='candidate-unverified':p.error('Inventory options require --inventory-candidate')
generate(args.output)