367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
206 lines
14 KiB
Python
206 lines
14 KiB
Python
"""Explicit same-item Material field retention, never a legacy sentinel map.
|
|
|
|
Only an already exported, agreeing Item/ItemSparse pair is eligible. The raw
|
|
source remains unchanged, and every other converter/dependency guard still runs.
|
|
"""
|
|
import copy
|
|
import base64
|
|
import binascii
|
|
import hashlib
|
|
import json
|
|
|
|
POLICY='retain-exact-native-item-material-v1'
|
|
FLAG_POLICY='retain-native-material-with-reviewed-source-flags-v1'
|
|
FLAG_HEADERS=dict(source='243c0244d03e1af290a1c6fbd4f9cfaecc0a7f5298de67530f77ebddcd96f26e',target='5cc1a60184e3f38745ed0bb7217f9e30d7962dc26f7d38798a8735687eac966f')
|
|
FLAG_MAPPINGS=(
|
|
('ITEM_FLAG_CONJURED','ITEM_FLAG_CONJURED',0x2),
|
|
('ITEM_FLAG_LOOTABLE','ITEM_FLAG_HAS_LOOT',0x4),
|
|
('ITEM_FLAG_INDESTRUCTIBLE','ITEM_FLAG_NO_USER_DESTROY',0x20),
|
|
('ITEM_FLAG_NO_EQUIP_COOLDOWN','ITEM_FLAG_NO_EQUIP_COOLDOWN',0x80),
|
|
('ITEM_FLAG_WRAPPER','ITEM_FLAG_IS_WRAPPER',0x200),
|
|
('ITEM_FLAG_PARTY_LOOT','ITEM_FLAG_MULTI_DROP',0x800),
|
|
('ITEM_FLAG_CHARTER','ITEM_FLAG_PETITION',0x2000),
|
|
('ITEM_FLAG_HAS_TEXT','ITEM_FLAG_HAS_TEXT',0x4000),
|
|
('ITEM_FLAG_NO_DISENCHANT','ITEM_FLAG_NO_DISENCHANT',0x8000),
|
|
('ITEM_FLAG_REAL_DURATION','ITEM_FLAG_REAL_DURATION',0x10000),
|
|
('ITEM_FLAG_NO_CREATOR','ITEM_FLAG_NO_CREATOR',0x20000),
|
|
('ITEM_FLAG_UNIQUE_EQUIPPED','ITEM_FLAG_UNIQUE_EQUIPPABLE',0x80000))
|
|
|
|
def _flag_contract():
|
|
return dict(policy=FLAG_POLICY,header_sha256=dict(FLAG_HEADERS),mappings=[dict(source_name=a,target_name=b,source_value=v,target_value=v)for a,b,v in FLAG_MAPPINGS],omitted_or_deferred_bits_allowed=False)
|
|
|
|
def flag_namespace(source,target):
|
|
from pathlib import Path
|
|
from spell_result_profile import enum
|
|
for role,path,name in (('source',source,'ItemPrototypeFlags'),('target',target,'ItemFlags')):
|
|
values,pin=enum(Path(path),name)
|
|
if pin!=FLAG_HEADERS[role]:raise ValueError('Pinned item flag header changed')
|
|
for old,new,value in FLAG_MAPPINGS:
|
|
if values.get(old if role=='source'else new)!=value:raise ValueError('Named existing item flag mapping changed')
|
|
return _flag_contract()
|
|
|
|
def validate_flag_namespace(proof):
|
|
if not isinstance(proof,dict)or proof!=_flag_contract()or any(type(r.get(k))is not int for r in proof.get('mappings',[])for k in('source_value','target_value')):
|
|
raise ValueError('Explicit named lossless item flag proof required')
|
|
|
|
def reviewed_source_flags(source,proof):
|
|
from item_sparse_compat import legacy_item_flags
|
|
validate_flag_namespace(proof)
|
|
flags=source.get('flags');converted=legacy_item_flags(flags)
|
|
if converted!=flags or flags&~sum(row[2]for row in FLAG_MAPPINGS):
|
|
raise ValueError('Material flag policy cannot omit or defer source bits')
|
|
return converted
|
|
|
|
|
|
def native_sparse_record(row,schema):
|
|
"""Decode only schema-declared C# byte[] export representations."""
|
|
row=copy.deepcopy(row)
|
|
for name,kind,bits,unsigned,count in schema:
|
|
if kind=='int' and bits==8 and unsigned and count>1 and isinstance(row.get(name),str):
|
|
try:raw=base64.b64decode(row[name],validate=True)
|
|
except (ValueError,binascii.Error) as error:raise ValueError('Invalid native byte array: '+name) from error
|
|
if len(raw)!=count or base64.b64encode(raw).decode()!=row[name]:
|
|
raise ValueError('Native byte array count/encoding differs: '+name)
|
|
row[name]=list(raw)
|
|
return row
|
|
|
|
def digest(value):
|
|
return hashlib.sha256(json.dumps(value,sort_keys=True,ensure_ascii=False,separators=(',',':'),allow_nan=False).encode()).hexdigest()
|
|
|
|
def evidence(source,basic,sparse,schema):
|
|
from item_basic_compat import encode as basic_encode
|
|
from item_sparse_compat import encode
|
|
if not all(isinstance(row,dict) for row in (source,basic,sparse)):
|
|
raise ValueError('Material retention requires both exact native records')
|
|
ident=source.get('entry')
|
|
if type(ident)is not int or not 0<ident<=0x7fffffff or type(source.get('material'))is not int or source['material']!=-1:
|
|
raise ValueError('Material retention applies only to an exact negative source field')
|
|
for key in ('class','subclass','inventory_type'):
|
|
if type(source.get(key))is not int:raise ValueError('Material retention source identity type')
|
|
if not isinstance(source.get('name'),str) or not source['name']:
|
|
raise ValueError('Material retention requires exact named identity')
|
|
if (type(basic.get('ID'))is not int or type(sparse.get('ID'))is not int
|
|
or basic['ID']!=ident or sparse['ID']!=ident
|
|
or any(type(basic.get(k))is not int or basic[k]!=source[v] for k,v in
|
|
[('ClassID','class'),('SubclassID','subclass'),('InventoryType','inventory_type')])
|
|
or type(sparse.get('InventoryType'))is not int or sparse['InventoryType']!=source['inventory_type']
|
|
or sparse.get('Display_lang')!=source['name']):
|
|
raise ValueError('Material retention exact native item identity differs')
|
|
material=basic.get('Material')
|
|
if type(material)is not int or not 0<=material<=8 or type(sparse.get('Material'))is not int or sparse['Material']!=material:
|
|
raise ValueError('Material retention native field pair differs or is unreviewed')
|
|
if set(sparse)!={'ID',*(field[0] for field in schema)}:
|
|
raise ValueError('Material retention requires a complete native sparse baseline')
|
|
sparse=native_sparse_record(sparse,schema)
|
|
return dict(policy=POLICY,source_item=ident,source_record_sha256=digest(source),
|
|
identity=dict(name=source['name'],class_id=source['class'],subclass_id=source['subclass'],inventory_type=source['inventory_type']),
|
|
source_material=-1,native_material=material,source_field_conversion='deferred',
|
|
native_basic_record_sha256=hashlib.sha256(basic_encode(basic)).hexdigest(),
|
|
native_sparse_record_sha256=hashlib.sha256(encode(sparse,schema)).hexdigest())
|
|
|
|
def verify(source,basic,sparse,schema,proof):
|
|
actual=evidence(source,basic,sparse,schema)
|
|
if not isinstance(proof,dict) or proof!=actual or digest(proof)!=digest(actual):
|
|
raise ValueError('Material retention provenance or baseline changed')
|
|
return actual['native_material']
|
|
|
|
def scalar_reasons(source,basic,sparse,schema,proof,revision,*,container=False,flag_namespace=None,reference_retention=None,effect_retention=None,effect_context=None):
|
|
"""Remove precisely the verified field blocker; retain all other reasons."""
|
|
from item_package_preflight import scalar_exclusions,container_exclusions
|
|
verify(source,basic,sparse,schema,proof)
|
|
reasons=(container_exclusions if container else scalar_exclusions)(source,basic,set(),revision)
|
|
reasons=[reason for reason in reasons if reason!='unreviewed source material']
|
|
if flag_namespace is not None:
|
|
validate_flag_namespace(flag_namespace)
|
|
try:reviewed_source_flags(source,flag_namespace)
|
|
except ValueError:pass # Keep every original blocker; never clear unknown bits.
|
|
else:reasons=[r for r in reasons if r!='nonzero/unreviewed source field: flags']
|
|
if reference_retention is not None:
|
|
from item_reference_retention import verify as verify_references,FIELDS
|
|
verify_references(source,basic,sparse,schema,reference_retention)
|
|
retained={'nonzero/unreviewed source field: '+old for old,_ in FIELDS}
|
|
reasons=[r for r in reasons if r not in retained]
|
|
if effect_retention is not None:
|
|
from item_effect_reference_retention import verify as verify_effects,SOURCE_FIELDS
|
|
verify_effects(source,basic,sparse,schema,effect_context,effect_retention)
|
|
reasons=[r for r in reasons if r not in {'nonempty/unreviewed source spell field: '+field for field in SOURCE_FIELDS}]
|
|
return reasons
|
|
|
|
def compose(package,source,basics,natives,schema,*,revision,flag_namespace=None,retain_native_references=False,effect_context=None):
|
|
"""Evaluate a recorded candidate scope; append safe scalar metadata only.
|
|
|
|
Existing Item/Sparse package records are never replaced. A package Item
|
|
override must equal the selected baseline before any sparse row is added.
|
|
"""
|
|
from item_basic_compat import TABLE as BASIC_TABLE,SCALAR_CLASSES,encode as basic_encode,convert as basic_convert
|
|
from item_sparse_compat import TABLE,convert,encode,package_payloads,package_pages
|
|
from item_package_preflight import package_budget
|
|
if flag_namespace is not None:validate_flag_namespace(flag_namespace)
|
|
if type(retain_native_references)is not bool:raise ValueError('Explicit reference retention boolean required')
|
|
if effect_context is not None and effect_context.get('package_push_id')!=package.get('push_id'):raise ValueError('Existing effect context package differs')
|
|
covered,_=package_budget(package)
|
|
if package.get('build')!='1.60.1.70334' or package_payloads(package['rows'])[0]!=package.get('push_id'):
|
|
raise ValueError('Material batch preserved package identity differs')
|
|
if 'pushes' in package and package['pushes']!=package_pages(package['rows']):
|
|
raise ValueError('Material batch preserved package page identities differ')
|
|
if not isinstance(source,list) or not 1<=len(source)<=4096 or len({s['entry'] for s in source})!=len(source):
|
|
raise ValueError('Material batch requires bounded unique recorded scope')
|
|
overrides={(int(row['table_hash'],16),row['id']):row for row in package['rows']}
|
|
added=[];accepted=[];held=[];already_exact=[]
|
|
for item in source:
|
|
ident=item['entry'];basic=basics.get(ident);native=natives.get(ident)
|
|
proof=evidence(item,basic,native,schema)
|
|
native=native_sparse_record(native,schema)
|
|
prior=overrides.get((BASIC_TABLE,ident))
|
|
if prior is not None and (prior.get('record_status','valid')!='valid'
|
|
or prior.get('wire_hex')!=basic_encode(basic).hex() or prior.get('record')!=basic):
|
|
raise ValueError('Material batch package Item baseline differs: '+str(ident))
|
|
if ident in covered:
|
|
held.append(dict(entry=ident,reasons=['existing-package-metadata-preserved']));continue
|
|
container=(item['class'],item['subclass'],item['inventory_type'])==(1,0,18)
|
|
reference_proof=None;reference_error=None
|
|
if retain_native_references:
|
|
from item_reference_retention import evidence as reference_evidence
|
|
try:reference_proof=reference_evidence(item,basic,native,schema)
|
|
except ValueError as error:reference_error=str(error) # Never clear an existing reference.
|
|
effect_proof=None;effect_error=None
|
|
if effect_context is not None:
|
|
from item_effect_reference_retention import evidence as effect_evidence
|
|
try:effect_proof=effect_evidence(item,basic,native,schema,effect_context)
|
|
except ValueError as error:effect_error=str(error)
|
|
reasons=scalar_reasons(item,basic,native,schema,proof,revision,container=container,flag_namespace=flag_namespace,reference_retention=reference_proof,effect_retention=effect_proof,effect_context=effect_context)
|
|
if effect_error is not None:reasons.append('existing-native-effect-reference: '+effect_error)
|
|
if reference_error is not None:reasons.append('existing-native-quest-page-reference: '+reference_error)
|
|
if not container and item['class'] not in SCALAR_CLASSES:
|
|
reasons.append('outside-reviewed-scalar-classes')
|
|
if reasons:
|
|
held.append(dict(entry=ident,reasons=reasons));continue
|
|
# Preserve the complete native basic row including its icon. This
|
|
# batch makes no new appearance or icon-resource equivalence claim.
|
|
retained=basic_convert(item,basic)
|
|
try:
|
|
row=convert(item,retained,None,schema,native,material_retention=proof)
|
|
if flag_namespace is not None and row['Flags'][0]!=reviewed_source_flags(item,flag_namespace):raise ValueError('Reviewed source flags were not preserved')
|
|
if reference_proof is not None:
|
|
from item_reference_retention import FIELDS
|
|
if any(row[new]!=native[new] for _,new in FIELDS):raise ValueError('Existing quest/page reference changed')
|
|
raw=encode(row,schema)
|
|
except (ValueError,KeyError,OverflowError,ZeroDivisionError) as error:
|
|
held.append(dict(entry=ident,reasons=['existing-converter: '+str(error)]));continue
|
|
if raw==encode(native,schema):
|
|
already_exact.append(dict(entry=ident,material=proof['native_material'],material_retention=proof));continue
|
|
record=dict(table_name='ItemSparse',table_hash=hex(TABLE),id=ident,record=row,wire_hex=raw.hex(),
|
|
sha256=hashlib.sha256(raw).hexdigest(),source_record_sha256=digest(item),
|
|
policy=POLICY,material_retention=proof,preserved_native_fields=['Material'])
|
|
if flag_namespace is not None:record.update(source_flag_namespace=copy.deepcopy(flag_namespace),source_flags_preserved=True)
|
|
if reference_proof is not None:record['reference_retention']=copy.deepcopy(reference_proof)
|
|
if effect_proof is not None:record['effect_reference_retention']=copy.deepcopy(effect_proof)
|
|
added.append(record);accepted.append(dict(entry=ident,material=proof['native_material'],
|
|
source_record_sha256=proof['source_record_sha256'],**(dict(source_flags=item['flags'],native_flags=row['Flags'][0],flag_policy=FLAG_POLICY)if flag_namespace is not None else{}),changed_fields=[key for key in row if row[key]!=native[key]]))
|
|
rows=copy.deepcopy(package['rows'])+added;push,header=package_payloads(rows)
|
|
pages=package_pages(rows)
|
|
complete=dict(package,rows=rows,push_id=push,pushes=pages)
|
|
return dict(package=complete,rows=rows,push_id=push,pushes=pages,header=header,added=added,accepted=accepted,held=held,already_exact=already_exact,
|
|
preserved_records=len(package['rows']),scope=len(source),retain_native_references=retain_native_references,**(dict(source_flag_namespace=copy.deepcopy(flag_namespace),flag_policy=FLAG_POLICY)if flag_namespace is not None else{}),installed=False,native_acceptance_verified=False,
|
|
material_sentinel_conversion=False,material_audio_parity_verified=False)
|