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

254 lines
15 KiB
Python

#!/usr/bin/env python3
"""Fail-closed current-metadata validation of generated Warrior cooldown routes.
This is an offline build prerequisite, never a packet sender. PushID is reported
as provenance; only full current identity-set comparison authorizes each route.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import sys
import warrior_cooldown_modifier as policy
ROOT = Path(__file__).resolve().parents[1]
MAX_PACKAGE = 160 * 1024 * 1024 # Current 74642-row pinned candidate is 140,262,230 bytes.
DATA = ROOT / "docs/evidence/data/warrior-cooldown-class-identities-20261022"
DEFAULT_SOURCE = DATA / "source-class4.json"
DEFAULT_NATIVE = DATA / "native-base-class4.json"
DEFAULT_PROVENANCE = DATA / "provenance.json"
DEFAULT_HEADER = ROOT / "include/gateway/warrior_cooldown_modifiers.hpp"
DEFAULT_PINS = {'source': 'd50a565da3ee55e39881eac2e10253b16f47dd4e58c913f466e7e8d483a110cc', 'native': '317a021989bbcf0e5e61744df79df2223d1036b38348bd43af5cf1f12d9b5fc2', 'provenance': '24f27204b8ad6cffcc5a2b916beeee74210bb48d293b63d56c61ac5b48305440', 'header': 'a26f602ea52ea465bb078d6376feaceb24ff4667f2a67066b9ff9c83223fd5c7'}
def _pairs(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError('duplicate JSON key')
result[key] = value
return result
def read_pinned(path, expected, limit):
if type(expected) is not str or not re.fullmatch(r'[0-9a-f]{64}', expected):
raise ValueError('exact SHA256 input pin required')
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
try:
info = os.fstat(fd)
if not stat.S_ISREG(info.st_mode) or not 0 < info.st_size <= limit:
raise ValueError('bounded regular input required')
with os.fdopen(fd, 'rb', closefd=False) as stream:
raw = stream.read(limit + 1)
if len(raw) != info.st_size or hashlib.sha256(raw).hexdigest() != expected:
raise ValueError('input size or digest changed')
return raw
finally:
os.close(fd)
def header_contract(text):
"""Read only literal generated declarations; never evaluate C++ expressions."""
def unique(pattern):
found = re.findall(pattern, text, re.S)
if len(found) != 1:
raise ValueError('one exact generated header declaration required')
return found[0]
source_sha = unique(r'inline constexpr char SourceInventorySha256\[\]="([0-9a-f]{64})";')
native_sha = unique(r'inline constexpr char NativeInventorySha256\[\]="([0-9a-f]{64})";')
count, body = unique(r'inline constexpr std::array<BitRoute,([0-9]+)> Routes\{\{(.*?)\}\};')
entries = re.findall(r'\{\s*([0-9]+)\s*,\s*([0-9]+)\s*\}\s*,?', body)
rest = re.sub(r'\{\s*[0-9]+\s*,\s*[0-9]+\s*\}\s*,?', '', body)
if rest.strip() or not 1 <= int(count) <= 64 or len(entries) != int(count):
raise ValueError('literal bounded route array required')
routes = [(int(a), int(b)) for a, b in entries]
if any(not 0 <= a < 64 or not 0 <= b < 128 for a, b in routes):
raise ValueError('route bit bounds')
if routes != sorted(routes) or len({a for a, _ in routes}) != len(routes) or len({b for _, b in routes}) != len(routes):
raise ValueError('sorted unique route identities required')
return source_sha, native_sha, routes
def current_inventory(native, package):
if type(native) is not list or not 1 <= len(native) <= 100000:
raise ValueError('complete bounded native class export required')
seen, spells = set(), set()
for row in native:
if type(row) is not dict or set(row) != {'ID', 'SpellID', 'ModalNextSpell', 'SpellClassSet', 'SpellClassMask'}:
raise ValueError('complete typed native row required')
rid = policy._integer(row['ID'], 1, 0x7fffffff, 'native identity')
sid = policy._integer(row['SpellID'], 1, 0x7fffffff, 'native spell')
policy._integer(row['ModalNextSpell'], 0, 0x7fffffff, 'native modal')
policy._integer(row['SpellClassSet'], 0, 255, 'native family')
words = row['SpellClassMask']
if type(words) is not list or len(words) != 4:
raise ValueError('four native class words required')
for word in words:
policy._integer(word, -0x80000000, 0xffffffff, 'native class word')
if rid in seen or sid in spells:
raise ValueError('duplicate complete native identity')
seen.add(rid)
spells.add(sid)
if type(package) is not dict or type(package.get('rows')) is not list:
raise ValueError('complete metadata package rows required')
policy._integer(package.get('push_id'), 1, 0x7fffffff, 'package PushID')
return policy.effective_native_class4([row for row in native if row['SpellClassSet'] == 4], package['rows'])
def review_named_families(header, package):
"""Same flat11 policy; all named-class routes use current exact sets."""
marker=re.findall(r'CooldownFamilyProfileSha256\[\]="([0-9a-f]{64})";',header)
if not marker:return None
if len(marker)!=1:raise ValueError('one cooldown family profile required')
route_pin=re.findall(r'CooldownFamilyRoutesSha256\[\]="([0-9a-f]{64})";',header)
if len(route_pin)!=1:raise ValueError('one cooldown family route header required')
folder=ROOT/'docs/evidence/data/cooldown-class-identities-20261024'
source=json.loads(read_pinned(folder/'source-memberships.json','ff45b347b8b63eb2798431db0c2bb877963afc222af8dbb6fc09b82fcb5d6675',16*1024*1024))
native=json.loads(read_pinned(folder/'native-base.json','3afe055808095e686c9624111f4f53a538b2e670c9275291357abc1f09613045',16*1024*1024))
profile=json.loads(read_pinned(folder/'profile.json',marker[0],1024*1024))
route_text=read_pinned(ROOT/'include/gateway/spell_cooldown_family_routes.hpp',route_pin[0],65536).decode()
count,body=re.findall(r'std::array<ClassBitRoute,([0-9]+)> ClassRoutes\{\{(.*?)\}\};',route_text,re.S)[0]
entries=[tuple(map(int,x))for x in re.findall(r'\{([0-9]+),([0-9]+),([0-9]+)\},',body)]
expected=[(x['character_class'],x['source_bit'],x['native_bit'])for x in profile['routes']]
if entries!=expected or len(entries)!=int(count):raise ValueError('compiled cooldown routes differ from exact profile')
if profile['class_families']!={'1':4,'2':10,'3':9,'4':8,'5':6,'7':11,'8':3,'9':5,'11':7}:raise ValueError('named class family namespace changed')
current_inventory(native,package) # Existing complete-row uniqueness/schema gate.
overlays=[x for x in package['rows']if x.get('table_name')=='SpellClassOptions']
checks=[];effective_ids=set()
for cls,family in profile['class_families'].items():
if cls=='1':continue # Existing class4 review already validates the unchanged17.
grouped=[x for x in profile['routes']if x['character_class']==int(cls)]
if len({x['source_bit']for x in grouped})!=len(grouped)or len({x['native_bit']for x in grouped})!=len(grouped):raise ValueError('replacement aggregate route is not injective')
current=policy.effective_native_class([x for x in native if x['SpellClassSet']==family],overlays,family=family)
for row in current:
if row['SpellID']in effective_ids:raise ValueError('duplicate effective native spell class identity')
effective_ids.add(row['SpellID'])
derived=policy.derive(source,current,[x['source_bit']for x in grouped],family=family)
admitted={x['source_bit']:x['native_bit']for x in derived['admitted']}
for x in grouped:checks.append(dict(character_class=int(cls),family=family,source_bit=x['source_bit'],native_bit=x['native_bit'],admissible=admitted.get(x['source_bit'])==x['native_bit']))
return dict(admissible=all(x['admissible']for x in checks),routes_checked=len(checks),named_classes=9,old_warrior_routes_reused=17,new_routes=105,routes=checks,profile_sha256=marker[0],route_header_sha256=route_pin[0],original_receive_consumer_observed=False)
def review(header, source, native, package):
source_pin, baseline_native_pin, routes = header_contract(header)
current = current_inventory(native, package)
if policy._sha(source) != source_pin:
raise ValueError('header source inventory no longer matches pinned complete source')
profile = policy.derive(source, current, [a for a, _ in routes])
admitted = {row['source_bit']: row for row in profile['admitted']}
old, new = policy._inventories(source, current)
checks = []
for source_bit, native_bit in routes:
wanted = {sid for sid, (family, mask) in old.items() if family == 4 and mask & (1 << source_bit)}
actual = {sid for sid, mask in new.items() if mask & (1 << native_bit)}
exact = admitted.get(source_bit)
okay = bool(exact and exact['native_bit'] == native_bit and wanted == actual)
checks.append({'source_bit': source_bit, 'native_bit': native_bit, 'admissible': okay,
'source_spell_ids': sorted(wanted), 'current_native_spell_ids': sorted(actual),
'missing_native_spell_ids': sorted(wanted - actual),
'collateral_native_spell_ids': sorted(actual - wanted),
'current_unique_native_bit': exact['native_bit'] if exact else None})
return {'schema_version': 1, 'scope': 'Every generated route against complete current effective class4 inventory',
'admissible': all(row['admissible'] for row in checks), 'routes_checked': len(checks), 'routes': checks,
'package_push_id': package['push_id'], 'push_id_is_content_identity': False,
'source_inventory_sha256': profile['source_inventory_sha256'],
'header_original_native_inventory_sha256': baseline_native_pin,
'current_native_inventory_sha256': profile['native_inventory_sha256'],
'native_inventory_changed_since_header': baseline_native_pin != profile['native_inventory_sha256'],
'source_rows': len(source), 'current_native_class4_rows': len(current),
'live_acceptance': False, 'raw_same_bit_fallback': False}
def validate_files(args, *, return_package=False):
inputs = [('header', args.header, args.header_sha256, 65536),
('source', args.source, args.source_sha256, 16 * 1024 * 1024),
('native', args.native, args.native_sha256, 16 * 1024 * 1024),
('package', args.package, args.package_sha256, MAX_PACKAGE)]
raw = {name: read_pinned(path, expected, limit) for name, path, expected, limit in inputs}
decoded = {n: json.loads(raw[n], object_pairs_hook=_pairs) for n in ('source', 'native', 'package')}
if return_package:
# The codec builder also requires the strict finite-number policy of
# read_compatibility_package; inspect this already decoded object only.
import math
def finite(value):
if isinstance(value, float) and not math.isfinite(value):
raise ValueError('Nonfinite public JSON number')
if isinstance(value, dict):
for child in value.values(): finite(child)
elif isinstance(value, list):
for child in value: finite(child)
finite(decoded['package'])
result = review(raw['header'].decode('utf-8'), decoded['source'], decoded['native'], decoded['package'])
families=review_named_families(raw['header'].decode('utf-8'),decoded['package'])
if families is not None:
result['named_class_families']=families
result['admissible']=result['admissible'] and families['admissible']
result['input_sha256'] = {str(path): expected for _, path, expected, _ in inputs}
provenance_path = getattr(args, 'provenance', None)
if provenance_path is not None:
provenance_pin = args.provenance_sha256
provenance = json.loads(read_pinned(provenance_path, provenance_pin, 65536), object_pairs_hook=_pairs)
if type(provenance.get('schema_version')) is not int or provenance['schema_version'] != 1:
raise ValueError('typed portable provenance required')
pins = provenance.get('portable_inventory_sha256')
if type(pins) is not dict or pins.get('source-class4.json') != args.source_sha256 or pins.get('native-base-class4.json') != args.native_sha256:
raise ValueError('portable provenance inventory pins differ')
if (len(decoded['source']) != provenance['source']['family4_rows'] or
len(decoded['native']) != provenance['native']['family4_rows']):
raise ValueError('complete family4 provenance row counts differ')
if (any(row['family'] != 4 for row in decoded['source']) or
any(row['SpellClassSet'] != 4 for row in decoded['native'])):
raise ValueError('portable complete family4 arrays may not include other families')
result['input_sha256'][str(provenance_path)] = provenance_pin
result['portable_provenance_verified'] = True
result['guard_sha256'] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
result['policy_sha256'] = hashlib.sha256(Path(policy.__file__).read_bytes()).hexdigest()
return (result, decoded['package']) if return_package else result
def validate_current_package(package, package_sha256, *, header=DEFAULT_HEADER,
header_sha256=DEFAULT_PINS['header'], return_package=False):
"""Portable precompile API; no runtime-directory or original export dependency.
The caller must refuse admissible=False and record the returned exact input
pins in matching protocol/core/schema build provenance. This never builds,
installs, rewrites metadata, or rebinds a changed route automatically.
"""
from types import SimpleNamespace
return validate_files(SimpleNamespace(
header=Path(header), header_sha256=header_sha256,
source=DEFAULT_SOURCE, source_sha256=DEFAULT_PINS['source'],
native=DEFAULT_NATIVE, native_sha256=DEFAULT_PINS['native'],
provenance=DEFAULT_PROVENANCE, provenance_sha256=DEFAULT_PINS['provenance'],
package=Path(package), package_sha256=package_sha256), return_package=return_package)
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name, default in [('header', DEFAULT_HEADER), ('source', DEFAULT_SOURCE),
('native', DEFAULT_NATIVE), ('provenance', DEFAULT_PROVENANCE)]:
parser.add_argument('--' + name, type=Path, default=default)
parser.add_argument('--' + name + '-sha256', default=DEFAULT_PINS[name])
parser.add_argument('--package', type=Path, required=True)
parser.add_argument('--package-sha256', required=True)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
try:
result = validate_files(args)
except (ValueError, OSError, UnicodeError, KeyError, TypeError) as exc:
print('Warrior cooldown build guard refused: ' + str(exc), file=sys.stderr)
return 2
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result, indent=2) + '\n')
print('Warrior cooldown routes: ' + ('PASS' if result['admissible'] else 'REFUSED') + ' (' + str(result['routes_checked']) + ' checked)')
return 0 if result['admissible'] else 1
if __name__ == '__main__':
raise SystemExit(main())