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

970 lines
63 KiB
Python

#!/usr/bin/env python3
"""Plan or convert a pinned map/asset batch using the established converters.
Outputs are private candidates: this module never allocates IDs, installs files,
opens clients, or turns structural conversion into runtime acceptance. Each job
uses named payloads and immutable REA receipts. ADT routing prefers identical
native data, then an admitted native profile, then Source conversion when no
native base exists. Other asset adapters use the same existing public APIs.
Non-reuse contracts must pin a receipt and a nonempty ``provenance`` list of
original REA consumer references (path, sha256 and optional bytes). The dispatcher
checks those immutable references; the existing backend still enforces its exact
supported format/profile. A receipt descriptor alone does not admit new behavior.
"""
from pathlib import Path
import argparse
import hashlib
import inspect
import json
import re
import struct
import map_asset_preflight as terrain
import m2_equipment_convert as model
SHA = re.compile(r'[0-9a-f]{64}')
MAX_PAYLOAD = 64 * 1024 * 1024
MAX_BATCH_BYTES = 512 * 1024 * 1024
OPERATIONS = {'native-patch', 'source-adt-split', 'm2-convert', 'wmo-group', 'wmo-root', 'wdl-native-profile', 'wdt-original529-links'}
APIS = {
'native-patch': {'adt_near_terrain_candidate', 'adt_near_terrain_profile_candidate'},
'source-adt-split': {'adt_split_candidate'},
'm2-convert': {'convert_equipment'},
'wmo-group': {'classic_wmo_group_candidate'},
'wmo-root': {'classic_wmo_numeric_candidate'},
'wdl-native-profile': {'wdl_source_height_native_profile_candidate'},
'wdt-original529-links': {'wdt_native_component_links_candidate'},
}
def reuse_saved_source_worldmap_art(area, base_inventory, overlay, overlay_inventory,
selection, primary_stage, retry_stage, source_contract):
"""Compose proven Source tile layouts without selecting native UiMap IDs.
The staged BLP artifacts remain source-only. Their original successful
decodes are reused, while the isolated short-DXT3 retry closes only the
previously held files; no source texture payload is read here.
"""
require(area.get('count') == 175 and len(area.get('rows', [])) == 175,
'saved Source WorldMapArea catalogue differs')
require(base_inventory.get('status') == 'PRIVATE_CANDIDATE_NAMES_ONLY' and
base_inventory.get('worldmaparea_current_selection', {}).get('unchanged') is True and
base_inventory.get('found_tile_members') == 1584 and
base_inventory.get('complete_12_tile_candidate_directories') == 132,
'saved current Source base-art inventory differs')
require(overlay.get('status') == 'PASS_SOURCE_STATIC_DBC_AND_UI_FIELDS_NATIVE_HELD' and
overlay.get('record_count') == 707 and overlay.get('named_area_records') == 707 and
overlay_inventory.get('status') == 'PRIVATE_CANDIDATE_NAMES_ONLY' and
overlay_inventory.get('found_members') == overlay_inventory.get('unique_members') == 1019 and
not overlay_inventory.get('missing_members'), 'saved Source overlay inventory differs')
require(source_contract.get('status') == 'PASS_STATIC_SPECIAL_MODE_RECORD_IDENTITY_RUNTIME_MODE_HELD' and
source_contract.get('source_client_runtime_path_verified') is False and
source_contract.get('native_C_Map_binding_proved') is False,
'original Source GetMapInfo special-mode contract required')
require(selection.get('status') == 'SOURCE_ONLY_CKEY_ABSENT_FROM_SELECTED_PRIVATE_NATIVE_MAP' and
selection.get('content_count') == 2599 and selection.get('named_references') == 2603 and
selection.get('native_fdi_allocated') is False and selection.get('native_selector_qualified') is False,
'qualified source-only texture selection required')
first, retry = primary_stage.get('jobs', []), retry_stage.get('jobs', [])
require(len(first) == len(retry) == 1 and
first[0].get('status') == 'PARTIAL_SOURCE_TEXTURES_PRIVATE' and
retry[0].get('status') == 'CONVERTED_PRIVATE' and
all(s.get('installed') is False and s.get('native_accepted') is False for s in (primary_stage, retry_stage)) and
all(j.get('source_only_staging') is True and j.get('runtime_candidate') is False for j in (first[0], retry[0])),
'saved source-only BLP stages are not qualified')
outputs = first[0].get('outputs', []) + retry[0].get('outputs', [])
artifacts = {r.get('source_input'): r for r in outputs}
aliases = selection.get('aliases', {})
require(len(outputs) == len(artifacts) == len(aliases) == 2599 and set(artifacts) == set(aliases) and
{r.get('source_input') for r in first[0].get('held_sources', [])} ==
{r.get('source_input') for r in retry[0].get('outputs', [])}, 'source art retry closure differs')
runtime = Path(__file__).resolve().parents[1] / 'runtime'
names = {}
for key, row in aliases.items():
artifact = artifacts[key]
require(artifact.get('role') == 'source-texture' and artifact.get('decode', {}).get('decoded') is True and
artifact.get('sha256') == row.get('sha256') and artifact.get('bytes') == row.get('bytes') and
isinstance(artifact.get('path'), str), 'staged Source texture binding differs')
path = Path(artifact['path'])
require(not path.is_symlink() and path.is_file() and path.resolve().is_relative_to(runtime.resolve()),
'staged Source texture must remain private')
st = path.stat(); expected = {'device': st.st_dev, 'inode': st.st_ino, 'bytes': st.st_size, 'mtime_ns': st.st_mtime_ns}
require(artifact.get('artifact_token') == expected, 'staged Source texture changed since decode')
for name in row.get('source_names', []):
require(isinstance(name, str) and name not in names, 'ambiguous Source map-art name')
names[name] = {'source_content': key, 'path': str(path), 'sha256': row['sha256'],
'bytes': row['bytes'], 'artifact_token': expected}
require(len(names) == 2603 and set(names) == set(base_inventory.get('members', {})) |
set(overlay_inventory.get('members', {})), 'Source map-art name closure differs')
base_by_area = {}
for name, row in base_inventory['members'].items():
base_by_area.setdefault(row['area_record_id'], {})[row['tile_index']] = name
overlay_by_id = {}
for name, row in overlay_inventory['members'].items():
for ref in row['references']:
group = overlay_by_id.setdefault(ref['overlay_id'], {})
require(ref['tile_index'] not in group, 'duplicate Source overlay tile')
group[ref['tile_index']] = name
areas, held_areas = [], []
for row in area['rows']:
if not row.get('AreaName'):
held_areas.append(row['ID']); continue
tiles = base_by_area.get(row['ID'], {})
require(set(tiles) == set(range(1, 13)), 'Source base-map tile grid is incomplete')
areas.append({'source_world_map_area_id': row['ID'], 'source_map_id': row['MapID'],
'source_area_id': row['AreaID'], 'source_directory': row['AreaName'],
'source_bounds': [row['LocLeft'], row['LocRight'], row['LocTop'], row['LocBottom']],
'source_special_map_selection': [-1, row['ID'] + 1],
'width': 1024, 'height': 768, 'tile_width': 256, 'tile_height': 256,
'tiles': [names[tiles[i]] for i in range(1, 13)]})
overlays = []
for row in overlay['rows']:
width, height = row['texture_width'], row['texture_height']
require(type(width) is int and type(height) is int and 0 < width <= 8192 and 0 < height <= 8192,
'Source overlay dimensions are not qualified')
count = ((width + 255) // 256) * ((height + 255) // 256)
tiles = overlay_by_id.get(row['id'], {})
require(set(tiles) == set(range(1, count + 1)), 'Source overlay tile grid is incomplete')
overlays.append({'source_overlay_id': row['id'], 'source_world_map_area_id': row['source_map_area_id'],
'source_area_ids': row['area_ids'], 'texture_name': row['texture_name'],
'width': width, 'height': height, 'offset': row['offset'],
'map_point': row['map_point'], 'hit_rect': row['hit_rect'],
'tiles': [names[tiles[i]] for i in range(1, count + 1)]})
require(len(areas) == 132 and len(held_areas) == 43 and len(overlays) == 707,
'Source map-art profile extent differs')
return {'kind': 'source-worldmap-art-layout-profile-v1', 'status': 'PRIVATE_SOURCE_ART_PROFILE_ONLY',
'source_area_selection': 'original special-map mode only; normal-mode and live state remain unverified',
'source_archive_selection': 'saved original builtin order; launcher hooks and server fork unverified',
'base_area_count': len(areas), 'unnamed_area_ids_held': held_areas, 'overlay_count': len(overlays),
'distinct_texture_contents': len(artifacts), 'named_texture_references': len(names),
'areas': areas, 'overlays': overlays, 'native_map_ids_assigned': False,
'native_texture_file_data_ids_assigned': False, 'native_ui_or_rendering_verified': False,
'source_payloads_reread': 0, 'installed': False, 'native_accepted': False}
def reuse_saved_emerald_wdt(handoff, role_audit, active_registry, outdoor_coverage):
"""Reconcile the pinned Map169 WDT, without converting or reading asset bodies.
This is a static relationship assessment. It does not establish which WDT
the running client loads, complete scene dependencies, or native rendering.
"""
require(handoff.get('status') == 'PASS_FINAL_ALL_APPLICABLE_ORIGINAL_TERRAIN_WDT_ROLE_MERGE',
'qualified original-profile WDT handoff required')
rows = [r for r in handoff.get('rows', []) if r.get('MapID') == 169]
require(len(rows) == 1, 'one saved Emerald Dream WDT required')
row = rows[0]
require(row.get('status') == 'PASS_FINAL_ORIGINAL_PROFILE_SOURCE_ROLE_WDT' and
row.get('source_reference') == 'world/maps/emeralddream/emeralddream.wdt' and
row.get('reserved_final_WDT_FDI') == 8551267 and SHA.fullmatch(row.get('sha256', '')) and
row.get('bytes') == 163908 and row.get('runtime_scene_verified') is False and
all(row.get('fields_preserved', {}).get(k) is True for k in
('MPHD', 'MAIN', 'MAI2', 'other_unlisted_MAID_roles', 'all_other_bytes')),
'saved Map169 WDT identity or original profile differs')
require((row.get('source_MAIN'), row.get('native_active_MAIN'), row.get('active_source_ROOT'),
row.get('active_source_TEX0'), row.get('active_source_pairs'), row.get('active_source_triplets')) ==
(256, 256, 247, 256, 247, 222), 'saved Map169 role counts differ')
require(role_audit.get('status') == 'PRIVATE_STRUCTURAL_SOURCE_COMPONENT_ASSOCIATION' and
role_audit.get('original_WDT_file_data_id') == 8551267 and
role_audit.get('original_WDT_sha256') == row.get('baseline', {}).get('sha256') and
all(role_audit.get(k) is True for k in ('original_MPHD_MAIN_preserved',
'opaque_MAI2_bytes_preserved', 'all_other_MAID_roles_preserved', 'native_profile_flags_preserved')) and
role_audit.get('runtime_activation_verified') is False and role_audit.get('publishable') is False,
'saved Map169 original-consumer audit differs')
changes = role_audit.get('changes')
require(isinstance(changes, list) and len(changes) == 222 and
len({tuple(x['tile']) for x in changes}) == 222, 'saved Map169 tile audit extent differs')
flattened = {(tuple(x['tile']), role, value['old_file_data_id'], value['new_file_data_id'], value['offset'])
for x in changes for role, value in x['roles'].items()}
handoff_changes = {(tuple(x['tile']), x['role'], x['old_file_data_id'], x['new_file_data_id'], x['offset'])
for x in row.get('changes', [])}
require(len(flattened) == len(handoff_changes) == 438 and flattened == handoff_changes and
all('OBJ0' in x['roles'] and set(x['roles']) <= {'OBJ0', 'OBJ1'} for x in changes),
'Map169 WDT role change ownership differs')
assets = active_registry.get('assets')
require(isinstance(assets, list) and len(assets) == 32337, 'active 32337 registry required')
assets = [x for x in assets if x.get('file_data_id') == 8551267]
require(len(assets) == 1 and assets[0].get('kind') == 'terrain-wdt' and
assets[0].get('source_path') == row['source_reference'] and assets[0].get('sha256') == row['sha256'] and
assets[0].get('bytes') == row['bytes'] and assets[0].get('native_group_control') == 780817,
'active registered Map169 WDT binding differs')
maps = [x for x in outdoor_coverage.get('maps', []) if x.get('MapID') == 169]
require(outdoor_coverage.get('summary', {}).get('status') == 'PASS_CACHED_ALL_OUTDOOR_AREA_CURRENT_NEXT_RESOURCE_COVERAGE_JOIN' and
len(maps) == 1 and maps[0].get('Map_definition_present') is True and
maps[0].get('current_WDT_FDI') == 8551267 and maps[0].get('Source_MAIN_tiles') == 256 and
maps[0].get('current', {}).get('Source_ROOT_TEX_pair_linked') == 247 and
maps[0].get('current', {}).get('Source_near_triplet_linked') == 222,
'saved Map169 metadata coverage differs')
return {'kind': 'saved-emerald-dream-wdt-reuse-v1', 'registered_wdt_fdi': 8551267,
'registered_wdt_sha256': row['sha256'], 'source_main_cells': 256,
'saved_active_main_cells': 256, 'saved_root_tex_pairs': 247, 'saved_near_triplets': 222,
'new_assets': 0, 'asset_bodies_read': False, 'installed': False,
'current_source_archive_selection_verified': False, 'native_wdt_selection_verified': False,
'complete_scene_dependencies_verified': False, 'native_runtime_verified': False}
def encoded(value):
return (json.dumps(value, sort_keys=True, indent=2, allow_nan=False) + '\n').encode()
def digest(raw):
return hashlib.sha256(raw).hexdigest()
def require(condition, reason):
if not condition:
raise ValueError(reason)
def token(path):
st = path.stat()
return st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns
class Inputs:
"""One immutable-file cache shared by payloads and contract references."""
def __init__(self, base):
self.base = base
self.cache = {}
self.tokens = {}
self.bytes_read = 0
def read(self, ref, maximum=MAX_PAYLOAD):
require(isinstance(ref, dict), 'pinned file reference required')
require(isinstance(ref.get('sha256'), str) and SHA.fullmatch(ref['sha256']),
'lowercase SHA256 required')
require(isinstance(ref.get('path'), str), 'file path required')
path = Path(ref['path'])
path = path if path.is_absolute() else self.base / path
require(not path.is_symlink() and path.is_file(), 'regular immutable input required')
path = path.resolve()
identity = token(path)
require(0 < identity[2] <= maximum, 'input byte bound exceeded')
if 'bytes' in ref:
require(type(ref['bytes']) is int and ref['bytes'] == identity[2],
'declared input extent differs')
key = identity
if key not in self.cache:
require(self.bytes_read + identity[2] <= MAX_BATCH_BYTES, 'batch byte bound exceeded')
raw = path.read_bytes()
require(token(path) == identity, 'input changed while reading')
self.cache[key] = (raw, digest(raw))
self.bytes_read += len(raw)
self.tokens[path] = identity
require(self.cache[key][1] == ref['sha256'], 'input SHA256 differs')
return self.cache[key][0]
def stable(self):
require(all(token(p) == t for p, t in self.tokens.items()), 'batch input changed')
def load_current_source_selection(saved, inputs):
"""Bind optional saved map qualification to the exact current archive lifetime."""
refs = saved.get('current_source_receipts')
if refs is None:
return None
require(isinstance(refs, dict) and set(refs) == {'selection', 'inventory', 'archive_order'},
'paired current Source selection, inventory and archive order required')
root = Path(__file__).resolve().parents[1]
expected = {'selection': root/'runtime/continuation-20261029/octo-update-freshness/current-openworld-142-selection.private.json',
'inventory': root/'runtime/continuation-20261029/octo-update-freshness/current-inventory.private.json',
'archive_order': root/'runtime/continuation-20261028/current-source20-requalification/input-manifest.private.json'}
docs = {}
for name, path in expected.items():
pin = refs[name]
require(isinstance(pin, dict) and isinstance(pin.get('path'), str), 'pinned current Source reference required')
actual = Path(pin['path']); actual = actual if actual.is_absolute() else inputs.base/actual
require(actual.resolve() == path.resolve(), 'exact current Source owning receipt required')
docs[name] = json.loads(inputs.read(pin, 16 * 1024 * 1024))
selection, inventory, order = docs['selection'], docs['inventory'], docs['archive_order']
require(selection.get('kind') == 'current-source-openworld-142-selection-v1' and
selection.get('status') == 'COMPLETE_CONDITIONAL_ORIGINAL_ORDER' and
selection.get('archive_stats_stable') is True and
selection.get('launcher_hook_equivalence_verified') is False and
selection.get('server_fork_equivalence_verified') is False and
selection.get('world_entry_or_rendering_verified') is False and
selection.get('counts') == {'source62': {'unchanged': 62},
'source78': {'unchanged': 77, 'unchanged-reused-current20-receipt': 1},
'wdt': {'unchanged': 2}} and
isinstance(selection.get('records'), dict) and len(selection['records']) == 142 and
inventory.get('kind') == 'source-archive-current-stat-comparison-v1' and
isinstance(inventory.get('current'), dict) and isinstance(order.get('explicit_archive_order'), list),
'current Source selection qualification differs')
by_name = {Path(p).name.casefold(): row for p, row in inventory['current'].items()}
require(len(by_name) == len(inventory['current']), 'unique current archive basenames required')
names = [r['archive'].casefold() for r in order['explicit_archive_order']]
require(len(names) == 17 and len(set(names)) == 17, 'complete reviewed original archive order required')
for name in names + ['wow.exe']:
entry = by_name.get(name)
require(isinstance(entry, dict) and isinstance(entry.get('path'), str), 'current Source archive inventory incomplete')
path = Path(entry['path'])
require(not path.is_symlink() and path.is_file(), 'current Source archive unavailable')
identity = token(path)
require(identity == (entry.get('device'), entry.get('inode'), entry.get('bytes'), entry.get('mtime_ns')),
'current Source archive lifetime changed')
inputs.tokens[path.resolve()] = identity
return selection
def check_current_source_selection(selection, operation, job, source_sha256, family_kind=None):
if selection is None:
return None
if operation == 'wdt-original529-links':
name = {0:'world/maps/azeroth/azeroth.wdt', 1:'world/maps/kalimdor/kalimdor.wdt'}.get(job.get('map_id'))
family = 'wdt'
else:
require(operation == 'source-adt-split', 'current Source receipt outside supported saved map scope')
name = job.get('source_reference')
require(isinstance(name, str), 'exact Source member identity required')
name = name.replace('\\', '/').lower()
family = 'source78' if family_kind == 'source-only78' else 'source62'
row = selection['records'].get(name)
require(isinstance(row, dict) and row.get('family') == family and
row.get('state') in ('unchanged', 'unchanged-reused-current20-receipt') and
row.get('current_sha256') == row.get('prior_sha256') == source_sha256,
'current Source member identity or content differs from saved candidate')
return {'member': name, 'family': family, 'archive': row['archive'],
'selection': 'reviewed-original-order-conditional', 'archive_lifetime_checked': True,
'launcher_hook_equivalence_verified': False, 'server_fork_equivalence_verified': False,
'runtime_verified': False}
def load_contract(ref, inputs, operation):
require(isinstance(ref, dict) and ref.get('operation') == operation,
'operation-specific contract required')
require(ref.get('admission') == 'private-candidate', 'explicit private-candidate admission required')
provenance = ref.get('provenance')
require(isinstance(provenance, list) and 1 <= len(provenance) <= 64,
'pinned original REA consumer provenance required')
for proof in provenance:
inputs.read(proof, 16 * 1024 * 1024)
document = json.loads(inputs.read(ref.get('receipt'), 16 * 1024 * 1024))
require(isinstance(document, dict), 'contract receipt object required')
if (operation == 'source-adt-split' and 'reuse_saved' in ref and
ref['reuse_saved'].get('family_kind') != 'source-only78'):
root = Path(__file__).resolve().parents[1]
assessment = root / 'docs/evidence/content-data/continental-Source-only62-20261025/assessment.json'
path = Path(ref['receipt']['path'])
path = path if path.is_absolute() else inputs.base / path
require(path.resolve() == assessment and
document.get('status') == 'PASS_ALL62_NEW_SOURCE_ONLY_TERRAIN_COMPONENTS_PRIVATE',
'exact Source-only62 owning assessment required')
expected_witness = root / document['validation']['new62_receipt']
require(any((Path(p['path']) if Path(p['path']).is_absolute() else inputs.base / p['path']).resolve()
== expected_witness.resolve() for p in provenance),
'owning Source-only62 focused check must be pinned in provenance')
saved = ref['reuse_saved']
require(isinstance(saved, dict) and saved.get('partial_components') is True,
'explicit partial saved-component policy required')
family_ref = saved.get('family_receipt')
require(isinstance(family_ref, dict) and
(Path(family_ref['path']) if Path(family_ref['path']).is_absolute() else inputs.base / family_ref['path']).resolve()
== (root / document['candidate_manifest']).resolve(), 'exact saved Source-only62 manifest required')
family = json.loads(inputs.read(family_ref, 16 * 1024 * 1024))
require(family.get('status') == 'PRIVATE_SOURCE_ONLY62_COMPONENTS_ALL_HELD' and
len(family.get('results', [])) == 62 and not family.get('held'),
'saved Source-only62 family differs')
base = root / 'runtime/rea-system-jobs-20261022/custom-map-resource-closure-20261024'
expected = {'textures': base / 'Source208-selector-safe-stage-inputs/canonical-Source1028-world-texture-bindings.json',
'wmos': base / 'WMO-root26-stage-handoff.json',
'swamp': base / 'combined8991-to9079-new-resource-bindings.json'}
refs = saved.get('binding_receipts')
require(isinstance(refs, dict) and set(refs) == set(expected), 'three exact saved binding receipts required')
loaded = {}
for name, expected_path in expected.items():
proof = refs[name]; p = Path(proof['path']); p = p if p.is_absolute() else inputs.base / p
require(p.resolve() == expected_path.resolve(), 'saved component binding receipt differs')
loaded[name] = json.loads(inputs.read(proof, 16 * 1024 * 1024))
bindings = {r['source_path']: r['file_data_id'] for r in loaded['textures']['aliases']}
bindings.update({r['source_member']: r['file_data_id'] for r in loaded['wmos']['all26_source_paths_to_root_FDIDs']})
bindings.update({r['source_path']: r['file_data_id'] for r in loaded['swamp']['SourceSwamp_bindings']})
document['_source62_saved'] = {'family': family, 'bindings': bindings}
if (operation == 'source-adt-split' and 'reuse_saved' in ref and
ref['reuse_saved'].get('family_kind') == 'source-only78'):
root = Path(__file__).resolve().parents[1]
base = root / 'runtime/rea-system-jobs-20261022'
expected_receipt = base / 'continent-native-split-ADT-20261025/completed-split-family-focused-check.json'
receipt_path = Path(ref['receipt']['path']); receipt_path = receipt_path if receipt_path.is_absolute() else inputs.base / receipt_path
require(receipt_path.resolve() == expected_receipt.resolve() and
document.get('status') == 'PASS_SOURCE462_NEW_SPLIT_CONSTRUCTOR_BOUNDARY',
'exact Source462 owning focused check required')
original = root / 'docs/evidence/content-data/Source-v18-native-split-ADT-20261025/assessment.json'
require(any((Path(p['path']) if Path(p['path']).is_absolute() else inputs.base / p['path']).resolve() == original.resolve()
for p in provenance), 'original Source split consumer proof required')
saved = ref['reuse_saved']; require(saved.get('partial_components') is True,
'explicit partial saved-component policy required')
refs = {'family_receipt': base/'continent-native-split-ADT-20261025/source462-split-candidate-manifest.json',
'scope_receipt': base/'continent-Source-only62-20261025/exact-new-Source-only62-worklist.json',
'preflight_receipt': base/'continent-terrain-Source463-20261025/qualified-source463/preflight-checkpoint.json'}
loaded = {}
for key, expected in refs.items():
pin = saved.get(key); require(isinstance(pin, dict), 'saved Source78 family references required')
p = Path(pin['path']); p = p if p.is_absolute() else inputs.base/p
require(p.resolve() == expected.resolve(), 'saved Source78 family reference differs')
loaded[key] = json.loads(inputs.read(pin, 64 * 1024 * 1024))
family = loaded['family_receipt']; scope = loaded['scope_receipt']; preflight = loaded['preflight_receipt']
require(family.get('status') == 'PRIVATE_PARTIAL_ROLE_CANDIDATES_ALL_HELD' and len(family.get('results', [])) == 462 and
scope.get('status') == 'COMPLETE_EXACT_SOURCE_ONLY62_CAPTURE_SCOPE_AFTER_RETAINED_DEDUP' and
len(scope.get('retained_rows', [])) == 78 and isinstance(preflight, list),
'saved Source78 family/scope differs')
binding = saved.get('binding_receipts')
supplement = saved.get('supplemental_receipt')
expected_binding_names = {'textures', 'canonical', 'wmos', 'swamp'} if supplement else {'textures'}
require(isinstance(binding, dict) and set(binding) == expected_binding_names,
'exact saved Source binding receipts required')
expected = base/'custom-map-resource-closure-20261024/complete-source796-texture-bindings.json'
pin = binding['textures']; p = Path(pin['path']); p = p if p.is_absolute() else inputs.base/p
require(p.resolve() == expected.resolve(), 'saved Source796 binding path differs')
data = json.loads(inputs.read(pin, 16 * 1024 * 1024))
document['_source78_saved'] = {'family':family, 'scope':{r['source_ADT_path']:r for r in scope['retained_rows']},
'preflight':{r['source_reference']:r for r in preflight},
'bindings':{r['source_path']:r['file_data_id'] for r in data['aliases']}}
if supplement:
expected = root/'runtime/continuation-20261029/converter-worldmap-reuse/source78-new-tex-private/handoff.private.json'
p = Path(supplement['path']); p = p if p.is_absolute() else inputs.base/p
require(p.resolve() == expected.resolve(), 'exact supplemental Source78 TEX receipt required')
extra = json.loads(inputs.read(supplement, 16 * 1024 * 1024))
require(extra.get('kind') == 'source78-new-tex-role-batch-v1' and extra.get('status') == 'PASS' and
extra.get('staged') == 37 and len(extra.get('rows', [])) == 37 and not extra.get('held') and
extra.get('previous_saved_root_or_obj_touched') is False and extra.get('scene_dependency_closure') is False and
extra.get('native_accepted') is False, 'supplemental Source78 TEX qualification differs')
expected_more = {'canonical': base/'custom-map-resource-closure-20261024/Source208-selector-safe-stage-inputs/canonical-Source1028-world-texture-bindings.json',
'wmos': base/'custom-map-resource-closure-20261024/WMO-root26-stage-handoff.json',
'swamp': base/'custom-map-resource-closure-20261024/combined8991-to9079-new-resource-bindings.json'}
docs = {}
for name, path in expected_more.items():
pin = binding[name]; p = Path(pin['path']); p = p if p.is_absolute() else inputs.base/p
require(p.resolve() == path.resolve(), 'supplemental Source78 binding path differs')
docs[name] = json.loads(inputs.read(pin, 16 * 1024 * 1024))
ids = {r['source_path']:r['file_data_id'] for r in docs['canonical']['aliases']}
ids.update({r['source_member']:r['file_data_id'] for r in docs['wmos']['all26_source_paths_to_root_FDIDs']})
ids.update({r['source_path']:r['file_data_id'] for r in docs['swamp']['SourceSwamp_bindings']})
rows = {r['source_reference']:r for r in extra['rows']}
require(len(rows) == 37, 'distinct supplemental Source78 TEX identities required')
document['_source78_saved'].update(supplemental=rows, supplemental_bindings=ids)
if operation == 'wdl-native-profile':
require(document.get('status') == 'PASS_CHANGED_WDL_NATIVE_PROFILE_FAMILY' and
document.get('policy') == 'original70334-source-heights-no-extra-MAOE' and
document.get('native_policy_not_Source_behavior_equivalence') is True,
'qualified original-native WDL presentation assessment required')
witness = document.get('original_REA_witness')
require(isinstance(witness, str), 'original WDL consumer witness required')
expected = (Path(__file__).resolve().parents[1] / witness).resolve()
require(any((Path(p['path']) if Path(p['path']).is_absolute() else inputs.base / p['path']).resolve() == expected
for p in provenance), 'original WDL witness must be pinned in provenance')
if 'reuse_saved' in ref:
saved = ref['reuse_saved']; family_ref = saved.get('family_receipt') if isinstance(saved, dict) else None
require(isinstance(family_ref, dict) and
(Path(family_ref['path']) if Path(family_ref['path']).is_absolute() else inputs.base / family_ref['path']).resolve()
== (Path(__file__).resolve().parents[1] / document['full_output_and_binding_receipt']).resolve(),
'exact owning WDL output family required')
family = json.loads(inputs.read(family_ref, 16 * 1024 * 1024))
require(family.get('status') == 'PASS_CHANGED_WDL_NATIVE_PROFILE_FAMILY' and
family.get('runtime_verified') is False and family.get('whole_map_graph_closed') is False,
'qualified private WDL output family required')
document['_wdl_saved_family'] = family
if operation == 'wdt-original529-links':
root = Path(__file__).resolve().parents[1]
original = root / 'docs/evidence/content-data/openworld-original529-presentation-20261026/assessment.json'
require(document.get('status') == 'PASS_FINAL_ORIGINAL529_OUTDOOR_WDT2_COMPONENT_FAMILY' and
document.get('all_original0_1_global6_and_MAI2_preserved') is True and
document.get('native_acceptance') is False, 'qualified private WDT component family required')
proof_paths = {(Path(p['path']) if Path(p['path']).is_absolute() else inputs.base / p['path']).resolve()
for p in provenance}
require(original.resolve() in proof_paths, 'original529 assessment must be pinned in provenance')
assessment_ref = next(p for p in provenance
if (Path(p['path']) if Path(p['path']).is_absolute() else inputs.base / p['path']).resolve() == original.resolve())
assessment = json.loads(inputs.read(assessment_ref, 16 * 1024 * 1024))
require(assessment.get('status') == 'PASS_PRIVATE_OPENWORLD_WDT_PRODUCER_AND_ACTUAL_COMPONENT_BOUNDARIES' and
Path(assessment['REA']['exact_529_seed']).resolve() in proof_paths,
'original529 profile seed must be pinned in provenance')
scope_ref = ref.get('source_scope')
require(isinstance(scope_ref, dict) and
(Path(scope_ref['path']) if Path(scope_ref['path']).is_absolute() else inputs.base / scope_ref['path']).resolve()
== (root / document['input_scope']).resolve(), 'exact saved Source outdoor scope required')
scope = json.loads(inputs.read(scope_ref))
maps = {x['MapID']: x for x in scope['maps'] if x.get('MapID') in (0, 1)}
active = {mid: set() for mid in (0, 1)}
for x in scope['tiles']:
if x.get('MapID') in active and x.get('Source_WDT_MAIN') is True:
xy = x.get('tile')
require(isinstance(xy, list) and len(xy) == 2 and all(type(v) is int and 0 <= v < 64 for v in xy),
'invalid saved Source MAIN coordinate')
active[x['MapID']].add(tuple(xy))
audits = ref.get('map_audits')
require(isinstance(audits, dict), 'pinned WDT composition audits required')
loaded_audits = {}
for row in document['rows']:
mid = row.get('MapID')
if mid not in (0, 1): continue
audit_ref = audits.get(str(mid))
require(isinstance(audit_ref, dict) and
(Path(audit_ref['path']) if Path(audit_ref['path']).is_absolute() else inputs.base / audit_ref['path']).resolve()
== Path(row['audit']).resolve(), 'exact saved WDT composition audit required')
audit = json.loads(inputs.read(audit_ref, 16 * 1024 * 1024))
require(audit.get('kind') == 'native-wdt-original529-five-role-MAI2-presentation-v1' and
audit.get('status') == 'PRIVATE_STRUCTURAL_SOURCE_COMPONENT_ASSOCIATION' and
audit.get('original_WDT_file_data_id') == row['control'] and
audit.get('original_WDT_sha256') == row['baseline_sha256'] and
audit.get('runtime_activation_verified') is False and audit.get('publishable') is False,
'WDT audit identity differs')
loaded_audits[mid] = audit
require(set(maps) == set(active) == set(loaded_audits) == {0, 1}, 'complete Map0/1 saved WDT family required')
document['_wdt_scope'] = {'maps': maps, 'active': active, 'audits': loaded_audits}
if operation in ('source-adt-split', 'wdt-original529-links') and 'reuse_saved' in ref:
document['_current_source_selection'] = load_current_source_selection(ref['reuse_saved'], inputs)
require('accepted_status' in ref or 'accepted_kind' in ref,
'exact receipt status or descriptor kind required')
if 'accepted_status' in ref:
status = document.get('status')
require(isinstance(status, str) and status == ref['accepted_status'],
'contract receipt status differs')
require(status.startswith(('PASS_', 'QUALIFIED_', 'COMPLETE_')),
'successful owning contract required')
if 'accepted_kind' in ref:
require(isinstance(ref['accepted_kind'], str) and
document.get('kind') == ref['accepted_kind'], 'contract descriptor kind differs')
if 'operation' in document:
require(document['operation'] == operation, 'receipt operation differs')
api = ref.get('api')
require(api in APIS[operation], 'unsupported converter API')
return document, api
def domain(job):
map_id = job.get('map_id')
tile = job.get('tile')
require(type(map_id) is int and map_id >= 0, 'map_id integer domain')
require(isinstance(tile, list) and len(tile) == 2 and
all(type(v) is int and 0 <= v < 64 for v in tile), 'tile coordinate domain')
return map_id, tuple(tile)
def check_scope(job, contract, source_sha256, native_sha256):
scope = contract.get('scope', {})
require(isinstance(scope, dict), 'contract scope object required')
if 'map_ids' in scope:
require(job.get('map_id') in scope['map_ids'], 'map outside contract scope')
if 'tiles' in scope:
require(job.get('tile') in scope['tiles'], 'tile outside contract scope')
for field, actual in [('source_sha256', source_sha256), ('native_sha256', native_sha256)]:
if field in scope:
require(actual is not None and actual == scope[field], 'payload outside contract scope')
def supported_options(function, options, reserved):
require(isinstance(options, dict), 'backend options object required')
allowed = {k for k, p in inspect.signature(function).parameters.items()
if p.kind == inspect.Parameter.KEYWORD_ONLY} - set(reserved)
require(set(options) <= allowed, 'unsupported or reserved backend option')
result = dict(options)
if 'roles' in result:
require(isinstance(result['roles'], list), 'roles must be a JSON list')
result['roles'] = tuple(result['roles'])
return result
def prepare(operation, api, document, contract, job, source, native, source_sha256=None, native_sha256=None):
function = getattr(model if operation == 'm2-convert' else terrain, api, None)
require(callable(function), 'supported backend API not available in this revision')
reserved = {'map_id', 'native_file_data_id', 'native_profile'}
if operation == 'wdl-native-profile':
reserved.remove('native_profile')
options = supported_options(function, job.get('options', {}), reserved)
if operation == 'native-patch':
map_id, tile = domain(job)
ident = job.get('native_file_data_id')
require(type(ident) is int and 0 < ident <= 0xFFFFFFFF, 'native FileDataID required')
kwargs = dict(map_id=map_id, native_file_data_id=ident, **options)
if api == 'adt_near_terrain_profile_candidate':
key = contract.get('native_profile_key')
require(key is None or isinstance(key, str), 'native profile receipt key required')
kwargs['native_profile'] = document if key is None else document[key]
return function, (native, source, tile), kwargs, operation
if operation == 'source-adt-split':
_, tile = domain(job)
saved_family = document.get('_source62_saved') or document.get('_source78_saved')
require(contract.get('dependencies_complete') is True or
(saved_family and contract.get('dependencies_complete') is False),
'Source dependency-closure admission or exact partial saved family required')
if (saved_family and contract['reuse_saved'].get('use_saved_bindings') is True
and 'file_data_ids' not in options):
options['file_data_ids'] = saved_family['bindings']
require('file_data_ids' in options and isinstance(options['file_data_ids'], dict),
'explicit Source dependency bindings required')
return function, (source, tile), options, operation
if operation in ('m2-convert', 'wmo-group'):
return function, (source,), options, operation
if operation == 'wdt-original529-links':
mid = job.get('map_id')
require(type(mid) is int and mid in (0, 1) and native is not None, 'Map0/1 pinned native WDT required')
require(options == {}, 'WDT linkage is derived only from saved qualified bindings')
info = document['_wdt_scope']; audit = info['audits'][mid]
rows = [r for r in document['rows'] if r.get('MapID') == mid]
require(len(rows) == 1, 'one saved WDT output per map required')
row = rows[0]; source_info = info['maps'][mid]['Source_WDT']
require(source_sha256 == source_info['sha256'] and native_sha256 == row['baseline_sha256'] and
job.get('source_reference') == row['source_reference'] == source_info['path'] and
job.get('native_file_data_id') == row['control'], 'WDT Source/native identity differs from saved cohort')
bindings = {}
for change in audit['changes']:
xy = tuple(change['tile'])
raw_roles = change['roles']; explicit = {'ROOT', 'TEX0', 'OBJ0', 'OBJ1', 'MINIMAP'}
require(set(raw_roles) <= explicit | {'LOD', 'MAPTEXTURE', 'MAPTEXTUREN'} and
all(raw_roles[k]['new_file_data_id'] == 0 for k in set(raw_roles) - explicit),
'unqualified WDT presentation role')
roles = {name: value['new_file_data_id'] for name, value in raw_roles.items() if name in explicit}
if not roles: continue # The original529 profile itself clears three auxiliary roles.
require(len(xy) == 2 and xy not in bindings and xy in info['active'][mid], 'WDT changed tile outside saved Source MAIN')
bindings[xy] = roles
for activated in (x for x in document['activated_rows'] if x.get('MapID') == mid):
xy = tuple(activated['tile'])
require(xy in info['active'][mid] and xy in bindings and
all(bindings[xy].get(role) == fdi for role, fdi in activated['bindings'].items()),
'activated WDT tile differs from saved five-role cohort')
kwargs = dict(tile_file_data_ids=bindings, native_file_data_id=row['control'], native_sha256=native_sha256,
allow_source_obj0=True, source_empty_obj1_tiles={tuple(x) for x in audit['Source_empty_OBJ1_tiles']},
presentation_profile='original529-five-role-MAI2', source_active_tiles=info['active'][mid])
return function, (native,), kwargs, operation
if operation == 'wdl-native-profile':
require(options == {'native_profile': document['policy']},
'explicit qualified original-native WDL presentation profile required')
return function, (source,), options, operation
if operation == 'wmo-root':
require(contract.get('dependencies_complete') is True,
'WMO dependency-closure admission required')
require(isinstance(job.get('source_reference'), str), 'WMO source reference required')
return function, (source, job['source_reference']), options, operation
raise ValueError('unsupported operation')
def invoke(prepared):
function, args, options, operation = prepared
result = function(*args, **options)
if operation == 'source-adt-split':
return result
if operation == 'm2-convert':
body, skins, audit = result
return dict(model=body, **{'skin' + str(i): b for i, b in enumerate(skins)}), audit
body, audit = result
return {{'native-patch': 'root', 'wmo-group': 'group', 'wmo-root': 'wmo',
'wdl-native-profile': 'wdl', 'wdt-original529-links': 'wdt'}[operation]: body}, audit
def saved_candidate(operation, job, contract, document, inputs, source_sha256):
"""Consume only an exact prior owning candidate; no silent reconversion."""
saved = contract['reuse_saved']
require(isinstance(saved, dict) and isinstance(saved.get('candidates'), dict), 'pinned saved candidates required')
root = Path(__file__).resolve().parents[1]
if operation == 'wdl-native-profile':
rows = [r for r in document['_wdl_saved_family']['outputs'] if r.get('Source_sha256') == source_sha256]
require(len(rows) == 1, 'one qualified saved WDL output per Source identity required')
row = rows[0]; ref = saved['candidates'].get(source_sha256); audit = row['receipt']
expected = (root / row['output']).resolve()
require(audit.get('native_profile') == document['policy'] and audit.get('runtime_verified') is False and
audit.get('publishable') is False, 'saved WDL qualification differs')
role = 'wdl'
elif operation == 'wdt-original529-links':
mid = job['map_id']; rows = [r for r in document['rows'] if r.get('MapID') == mid]
require(len(rows) == 1, 'one qualified saved WDT output per map required')
row = rows[0]; ref = saved['candidates'].get(str(mid)); audit = document['_wdt_scope']['audits'][mid]
expected = Path(row['file']).resolve(); role = 'wdt'
else:
raise ValueError('saved candidate reuse is unsupported for this operation')
require(isinstance(ref, dict) and
(Path(ref['path']) if Path(ref['path']).is_absolute() else inputs.base / ref['path']).resolve() == expected,
'saved candidate path differs from owning receipt')
body = inputs.read(ref)
if operation == 'wdl-native-profile':
require(len(body) == audit['bytes'] and hashlib.md5(body).hexdigest() == audit['content_key'],
'saved WDL extent or owning CASC content key differs')
else:
require(len(body) == row['bytes'] and ref['sha256'] == row['sha256'],
'saved WDT extent or owning SHA256 differs')
return {role: body}, audit
def saved_source62_candidate(job, contract, document, inputs, source_sha256):
saved = contract['reuse_saved']; proof = document['_source62_saved']
options = job.get('options', {}); roles = options.get('roles', ['root', 'tex0', 'obj0'])
require(isinstance(roles, list) and roles and len(set(roles)) == len(roles) and
set(roles) <= {'root', 'tex0', 'obj0'}, 'bounded saved split roles required')
map_id, tile = domain(job); reference = job.get('source_reference')
matches = [r for r in proof['family']['results'] if r.get('source_reference') == reference and
r.get('source_sha256_pin_reused') == source_sha256]
require(len(matches) == 1, 'one exact saved Source ADT identity required')
row = matches[0]
require(row.get('tile') == list(tile) and {'azeroth': 0, 'kalimdor': 1}.get(row.get('directory')) == map_id and
row.get('publishable') is False, 'saved Source tile/map identity differs')
ids = options.get('file_data_ids')
if ids is None and saved.get('use_saved_bindings') is True:
ids = proof['bindings']
require(isinstance(ids, dict), 'explicit Source dependency bindings required')
candidates = saved.get('candidates'); require(isinstance(candidates, dict), 'saved component pins required')
root = Path(__file__).resolve().parents[1]; outputs = {}
for role in roles:
for name in row['required_bindings'][role]:
require(name in proof['bindings'] and ids.get(name) == proof['bindings'][name],
'saved Source component dependency binding differs')
expected = row['files'].get(role); reference_pin = candidates.get(reference + ':' + role)
require(isinstance(expected, dict) and isinstance(reference_pin, dict), 'saved component is missing')
p = Path(reference_pin['path']); p = p if p.is_absolute() else inputs.base / p
require(p.resolve() == (root / expected['file']).resolve() and reference_pin['sha256'] == expected['sha256'],
'saved component path or owning SHA256 differs')
body = inputs.read(reference_pin)
require(len(body) == expected['bytes'], 'saved component extent differs')
outputs[role] = body
return outputs, {'saved_source_only62': True, 'source_reference': reference, 'roles': roles,
'dependencies_complete': False, 'publishable': False, 'runtime_verified': False,
'holds': row['holds']}
def saved_source78_candidate(job, contract, document, inputs, source_sha256):
saved = contract['reuse_saved']; proof = document['_source78_saved']; options = job.get('options', {})
roles = options.get('roles', ['root', 'tex0', 'obj0'])
require(isinstance(roles, list) and roles and len(set(roles)) == len(roles) and
set(roles) <= {'root', 'tex0', 'obj0'}, 'bounded saved split roles required')
map_id, tile = domain(job); reference = job.get('source_reference'); scope = proof['scope'].get(reference)
require(isinstance(scope, dict) and scope.get('category') == 'source_only' and
scope.get('map_id') == map_id and scope.get('tile') == list(tile), 'saved Source78 tile/map scope differs')
matches = [r for r in proof['family']['results'] if r.get('source_reference') == reference and
r.get('source_sha256_pin_reused') == source_sha256]
require(len(matches) == 1 and matches[0].get('category') == 'source_only' and
matches[0].get('publishable') is False, 'one exact saved Source78 ADT identity required')
row = matches[0]; item = proof['preflight'].get(reference); deps = item.get('dependencies') if isinstance(item, dict) else None
require(isinstance(deps, dict) and deps.get('sha256') == source_sha256, 'saved Source78 preflight identity differs')
required = {'root': [], 'tex0': deps['textures'],
'obj0': deps['model_placements']['referenced_assets'] + deps['wmo_placements']['referenced_assets']}
ids = options.get('file_data_ids')
if ids is None and saved.get('use_saved_bindings') is True: ids = proof['bindings']
require(isinstance(ids, dict), 'explicit Source dependency bindings required')
candidates = saved.get('candidates'); require(isinstance(candidates, dict), 'saved component pins required')
root = Path(__file__).resolve().parents[1]; outputs = {}
for role in roles:
expected = row['files'].get(role); active_bindings = proof['bindings']
extra = proof.get('supplemental', {}).get(reference) if role == 'tex0' and expected is None else None
if extra:
require(extra.get('map_id') == map_id and extra.get('tile') == list(tile) and
extra.get('source_sha256_reused') == source_sha256 and extra.get('source_layer_validation') is True and
extra.get('runtime_verified') is False and extra.get('publishable') is False,
'supplemental Source78 TEX identity differs')
expected = extra['output']; active_bindings = proof['supplemental_bindings']
pin = candidates.get(reference + ':' + role)
require(isinstance(expected, dict) and isinstance(pin, dict), 'saved component is missing')
for name in required[role]:
desired = active_bindings.get(name)
supplied = desired if options.get('file_data_ids') is None and saved.get('use_saved_bindings') is True else ids.get(name)
require(desired is not None and supplied == desired,
'saved Source component dependency binding differs')
p = Path(pin['path']); p = p if p.is_absolute() else inputs.base/p
require(p.resolve() == (root/expected['file']).resolve() and pin['sha256'] == expected['sha256'],
'saved component path or owning SHA256 differs')
body = inputs.read(pin); require(len(body) == expected['bytes'], 'saved component extent differs')
outputs[role] = body
return outputs, {'saved_source_only78':True, 'source_reference':reference, 'roles':roles,
'dependencies_complete':False, 'publishable':False, 'runtime_verified':False, 'holds':row['held']}
def route(job, source, native):
kind = job.get('kind')
if kind == 'adt':
domain(job)
require(len(source) >= 12 and source[:4] in (b'MVER', b'REVM') and
struct.unpack_from('<I', source, 8)[0] == 18, 'unsupported Source ADT version')
if native is not None:
return 'reuse' if source == native else 'native-patch'
return 'source-adt-split'
if kind == 'wdt':
require(native is not None and job.get('requires_native_patch') is True,
'WDT requires its qualified explicit native component-link patch')
return 'wdt-original529-links'
require(kind in ('m2', 'wmo-group', 'wmo-root', 'wdl'), 'unsupported asset kind')
if native is not None:
require(job.get('requires_native_patch', False) is False,
'requested native asset patch has no qualified adapter')
return 'reuse'
return {'m2': 'm2-convert', 'wmo-group': 'wmo-group', 'wmo-root': 'wmo-root',
'wdl': 'wdl-native-profile'}[kind]
def run_batch(manifest_path, *, action='plan', output=None, base_directory=None):
require(action in ('plan', 'convert'), 'plan or convert action required')
path = None
if isinstance(manifest_path, dict):
raw_manifest = encoded(manifest_path)
require(len(raw_manifest) <= 8 * 1024 * 1024, 'bounded manifest required')
base = Path(base_directory or Path.cwd()).resolve()
else:
path = Path(manifest_path)
require(not path.is_symlink() and path.is_file() and path.stat().st_size <= 8 * 1024 * 1024,
'bounded manifest file required')
raw_manifest = path.read_bytes()
base = path.resolve().parent
manifest = json.loads(raw_manifest)
require(manifest.get('kind') == 'map-conversion-batch-v1', 'map-conversion-batch-v1 required')
jobs = manifest.get('jobs')
require(isinstance(jobs, list) and 1 <= len(jobs) <= 4096, 'bounded job list required')
require(all(isinstance(j, dict) and isinstance(j.get('id'), str) for j in jobs) and
len({j['id'] for j in jobs}) == len(jobs), 'distinct job IDs required')
payloads = manifest.get('payloads', {})
contracts = manifest.get('contracts', {})
require(isinstance(payloads, dict) and isinstance(contracts, dict), 'payload/contract dictionaries required')
target = Path(output) if output is not None else None
require(action != 'convert' or target is not None, 'convert output directory required')
if target is not None:
require(not target.exists() and not target.is_symlink(), 'new immutable output directory required')
target.mkdir(mode=0o700, parents=True)
(target / 'input-manifest.json').write_bytes(raw_manifest)
inputs = Inputs(base)
results = []
operations = {}
operation_errors = {}
loaded = {}
errors = {}
contract_cache = {}
def payload(ref):
require(isinstance(ref, str) and ref in payloads, 'declared payload reference required')
if ref not in loaded and ref not in errors:
try:
loaded[ref] = inputs.read(payloads[ref])
except (ValueError, OSError) as error:
errors[ref] = str(error)
require(ref not in errors, errors.get(ref, 'input unavailable'))
return loaded[ref]
for job in jobs:
row = {'id': job['id'], 'kind': job.get('kind'), 'map_id': job.get('map_id'),
'tile': job.get('tile'), 'installed': False, 'runtime_verified': False}
try:
source = payload(job.get('source'))
native = payload(job['native']) if job.get('native') is not None else None
source_sha256 = payloads[job['source']]['sha256']
native_sha256 = payloads[job['native']]['sha256'] if native is not None else None
operation = route(job, source, native)
row['operation'] = operation
contract = document = api = prepared = None
if operation != 'reuse':
ref = job.get('contracts', {}).get(operation)
require(isinstance(ref, str) and ref in contracts,
'qualified contract unavailable; no automatic Source fallback')
contract = contracts[ref]
key = (ref, operation)
if key not in contract_cache:
contract_cache[key] = load_contract(contract, inputs, operation)
document, api = contract_cache[key]
check_scope(job, contract, source_sha256, native_sha256)
if document.get('_current_source_selection') is not None:
row['current_source_qualification'] = check_current_source_selection(
document['_current_source_selection'], operation, job, source_sha256,
contract['reuse_saved'].get('family_kind'))
row['contract'] = {'id': ref, 'sha256': contract['receipt']['sha256'], 'api': api,
'provenance': contract['provenance']}
if operation == 'wdt-original529-links':
row['contract'].update(source_scope=contract['source_scope'], map_audits=contract['map_audits'])
if operation in ('wdl-native-profile', 'wdt-original529-links', 'source-adt-split') and 'reuse_saved' in contract:
row['contract']['reuse_saved'] = contract['reuse_saved']
prepared = prepare(operation, api, document, contract, job, source, native, source_sha256, native_sha256)
if action == 'plan':
row['status'] = 'PLANNED'
row['scope'] = 'supported API route; backend qualification remains to be run'
else:
signature = digest(encoded({'operation': operation, 'api': api, 'job':
{k: job[k] for k in ('kind', 'map_id', 'tile', 'native_file_data_id', 'options', 'source_reference') if k in job},
'source': source_sha256, 'native': native_sha256,
'contract': {k: v for k, v in row.get('contract', {}).items() if k != 'id'}}))
if signature in operation_errors:
row['conversion_reused'] = True
raise ValueError(operation_errors[signature])
if signature not in operations:
if operation == 'reuse':
parts, audit = {'native': native}, {'identity_reuse': source == native, 'native_first_preserved': True}
else:
try:
if operation == 'source-adt-split' and 'reuse_saved' in contract:
parts, audit = (saved_source78_candidate if '_source78_saved' in document else
saved_source62_candidate)(job, contract, document, inputs, source_sha256)
elif operation in ('wdl-native-profile', 'wdt-original529-links') and 'reuse_saved' in contract:
parts, audit = saved_candidate(operation, job, contract, document, inputs, source_sha256)
else:
parts, audit = invoke(prepared)
if operation == 'wdt-original529-links':
expected = next(r['sha256'] for r in document['rows'] if r['MapID'] == job['map_id'])
require(digest(parts['wdt']) == expected, 'WDT candidate differs from saved qualified composition')
except (ValueError, TypeError, KeyError, OSError, NotImplementedError) as error:
operation_errors[signature] = str(error)
raise
require(isinstance(parts, dict) and parts and
all(isinstance(k, str) and isinstance(v, bytes) for k, v in parts.items()),
'backend byte outputs required')
audit_raw = encoded(audit)
outputs = []
for role, body in sorted(parts.items()):
require(re.fullmatch(r'[a-z0-9_]+', role), 'bounded backend output role required')
body_sha256 = digest(body)
name = body_sha256 + '.' + role + '.bin'
dest = target / name
if not dest.exists():
dest.write_bytes(body)
outputs.append({'role': role, 'file': name, 'bytes': len(body), 'sha256': body_sha256})
audit_sha256 = digest(audit_raw)
audit_name = audit_sha256 + '.audit.json'
if not (target / audit_name).exists():
(target / audit_name).write_bytes(audit_raw)
operations[signature] = (outputs, {'file': audit_name, 'sha256': audit_sha256})
else:
row['conversion_reused'] = True
row['outputs'], row['audit'] = operations[signature]
qualified_reuse = operation in ('wdl-native-profile', 'wdt-original529-links', 'source-adt-split') and 'reuse_saved' in contract
row['status'] = 'REUSED' if operation == 'reuse' or qualified_reuse else 'CONVERTED'
if qualified_reuse:
row['reused_qualified_output'] = True
row['scope'] = 'private candidate for the requested operation; not map/runtime acceptance'
except (ValueError, TypeError, KeyError, OSError, NotImplementedError) as error:
row['status'] = 'HELD'
row['reason'] = str(error)
row['error_type'] = type(error).__name__
results.append(row)
inputs.stable()
if path is not None:
require(path.read_bytes() == raw_manifest, 'manifest changed during batch')
counts = {key: sum(r['status'] == key for r in results)
for key in ('PLANNED', 'CONVERTED', 'REUSED', 'HELD')}
report = {'kind': 'map-conversion-batch-report-v1', 'action': action,
'manifest_sha256': digest(raw_manifest), 'requested': len(jobs),
'resolved': counts['CONVERTED'] + counts['REUSED'], 'held': counts['HELD'],
'counts': counts, 'unique_input_files_read': len(inputs.cache),
'input_bytes_read': inputs.bytes_read, 'unique_operations_executed': len(operations) + len(operation_errors),
'rows': results, 'candidate_content_complete': False,
'remaining_acceptance': ['backend audit scope and holds', 'definition and asset closure',
'publication and native rendering/gameplay acceptance'],
'installed': False, 'runtime_verified': False}
if target is not None:
(target / 'report.json').write_bytes(encoded(report))
return report
def plan_batch(request, *, base_directory=None):
return run_batch(request, action='plan', base_directory=base_directory)
def convert_batch(request, output, *, base_directory=None):
return run_batch(request, action='convert', output=output, base_directory=base_directory)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--manifest', type=Path, required=True)
parser.add_argument('--action', choices=('plan', 'convert'), default='plan')
parser.add_argument('--output', type=Path)
args = parser.parse_args()
if args.action == 'convert' and args.output is None:
parser.error('convert requires --output')
result = run_batch(args.manifest, action=args.action, output=args.output)
print(json.dumps({key: result[key] for key in ('requested', 'resolved', 'held', 'counts')}))
return 0
if __name__ == '__main__':
raise SystemExit(main())