367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
135 lines
7.2 KiB
Python
135 lines
7.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Background planning over existing validated conversions and public traces.
|
|
|
|
Reuses item_catalog_stage's pinned catalogue, not another converter. Never
|
|
opens a game/server socket, installs content, or guesses opcode/data semantics.
|
|
"""
|
|
import argparse
|
|
from collections import Counter
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
|
|
from item_catalog_stage import catalogue_plan
|
|
from item_package_preflight import read_public_json
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
MAX_JSON = 536870912
|
|
|
|
|
|
def metadata_comparison(plan, package):
|
|
if (package.get('build'), package.get('schema')) != (plan['build'], plan['schema']):
|
|
raise ValueError('Destination build/schema differs from catalogue')
|
|
installed = {}
|
|
for row in package['rows']:
|
|
if row['table_name'] not in ('Item', 'ItemSparse'):
|
|
continue
|
|
key = (row['table_name'], row['id'])
|
|
if key in installed:
|
|
raise ValueError('Duplicate destination component')
|
|
raw = bytes.fromhex(row['wire_hex'])
|
|
if hashlib.sha256(raw).hexdigest() != row['sha256']:
|
|
raise ValueError('Destination component hash differs')
|
|
installed[key] = row['sha256']
|
|
items = {}
|
|
for ident, source in plan['items'].items():
|
|
entry = int(ident)
|
|
components = source['components']
|
|
missing = [table for table in ('Item', 'ItemSparse') if (table, entry) not in installed]
|
|
differs = [table for table, digest in components.items()
|
|
if (table, entry) in installed and installed[table, entry] != digest]
|
|
if source['errors']:
|
|
status = 'blocked-conversion'
|
|
elif not all(table in components for table in ('Item', 'ItemSparse')):
|
|
status = 'blocked-incomplete-metadata'
|
|
elif missing:
|
|
status = 'converted-draft-missing-destination-components'
|
|
elif differs:
|
|
status = 'present-different-review-required'
|
|
else:
|
|
status = 'metadata-byte-identical'
|
|
items[ident] = dict(status=status, missing=missing, differing=differs)
|
|
return dict(counts=dict(sorted(Counter(row['status'] for row in items.values()).items())), items=items,
|
|
limitations=['Metadata equality is not effect/asset or gameplay compatibility.',
|
|
'Differences can be intentional newer corrections; never overwrite automatically.',
|
|
'Converted drafts retain unresolved dependencies in the existing catalogue.'])
|
|
|
|
|
|
def trace_summary(document):
|
|
# Only export a whitelist of public numeric metadata; never copy packets,
|
|
# credentials, chat text or arbitrary fields from a diagnostic document.
|
|
trace = document.get('trace', document)
|
|
if not isinstance(trace, dict) or not isinstance(trace.get('trace'), list):
|
|
raise ValueError('Public WorldTrace report required')
|
|
rows = trace['trace']
|
|
if len(rows) > 2000000:
|
|
raise ValueError('Trace row bound')
|
|
counts = Counter()
|
|
for row in rows:
|
|
direction, opcode, size = (row.get(key) for key in ('direction', 'opcode', 'bytes'))
|
|
# wine_pipe_host: 1 source receive, 2 engine send, 3 engine delivery,
|
|
# 4 translated source send. Do not conflate 2 and 4.
|
|
if type(direction) is not int or direction not in (1, 2, 3, 4) or type(opcode) is not int or not 0 <= opcode <= 0xffffffff or type(size) is not int or not 0 <= size <= 1048576:
|
|
raise ValueError('Invalid public opcode metadata')
|
|
counts[direction, opcode] += 1
|
|
lost = trace.get('lost_metadata_rows')
|
|
if type(lost) is not int or lost < 0:
|
|
raise ValueError('Trace gap accounting required')
|
|
return dict(opcodes=[dict(direction=d, opcode=o, samples=n) for (d, o), n in sorted(counts.items())],
|
|
lost_metadata_rows=lost, observer_error_present=bool(trace.get('observer_error')),
|
|
absence_proven=False, packet_semantics_verified=False)
|
|
|
|
|
|
def source_opcode_names(text):
|
|
return {int(value, 16): name for name, value in
|
|
re.findall(r'^\s*((?:SMSG|MSG|CMSG)_[A-Z0-9_]+)\s*=\s*(0x[0-9a-fA-F]+)', text, re.M)}
|
|
|
|
|
|
def run(args):
|
|
output = args.output.resolve()
|
|
if not output.is_relative_to(ROOT / 'runtime') or output.exists():
|
|
raise ValueError('New runtime output directory required')
|
|
output.mkdir(parents=True)
|
|
plan = catalogue_plan(args.catalogue)
|
|
package, package_hash = read_public_json(args.package, MAX_JSON)
|
|
metadata = metadata_comparison(plan, package)
|
|
names = source_opcode_names(args.source_opcodes.read_text())
|
|
observed = []
|
|
for path in args.trace:
|
|
document, digest = read_public_json(path, MAX_JSON)
|
|
summary = trace_summary(document)
|
|
for row in summary['opcodes']:
|
|
if row['direction'] in (1, 4):
|
|
row['source_name'] = names.get(row['opcode'])
|
|
observed.append(dict(input_sha256=digest, **summary))
|
|
matrix_bytes = (ROOT / 'docs/NATIVE_PROTOCOL_MATRIX.md').read_bytes()
|
|
result = dict(kind='existing-server-mapping-audit', schema_version=1,
|
|
catalogue_manifest_sha256=plan['catalogue_manifest_sha256'],
|
|
destination_package_sha256=package_hash,
|
|
source_opcode_header_sha256=hashlib.sha256(args.source_opcodes.read_bytes()).hexdigest(),
|
|
protocol_matrix_sha256=hashlib.sha256(matrix_bytes).hexdigest(),
|
|
item_summary=metadata['counts'], dependency_kinds=len(plan['dependency_targets']),
|
|
observed_traces=observed, installed=False, engine_loaded=False, gameplay_verified=False,
|
|
next_action='Resolve shared dependency/error groups through existing converters; validate staged packages before installation.',
|
|
limitations=metadata['limitations'] + ['Trace recognition does not prove dispatch or gameplay support.',
|
|
'Only supplied captures are observed; this is not all server traffic or live Octo verification.'])
|
|
for name, value in [('catalogue-plan.json', plan), ('metadata-comparison.json', metadata), ('report.json', result)]:
|
|
(output / name).write_text(json.dumps(value, sort_keys=True, separators=(',', ':')) + '\n')
|
|
# Publish this marker last; a partial output is never a successful audit.
|
|
files = [dict(path=path.name, sha256=hashlib.sha256(path.read_bytes()).hexdigest())
|
|
for path in sorted(output.glob('*.json'))]
|
|
(output / 'manifest.json').write_text(json.dumps(dict(kind=result['kind'], complete=True, files=files), indent=2) + '\n')
|
|
print(json.dumps(dict(output=str(output), counts=metadata['counts'], dependency_kinds=result['dependency_kinds'],
|
|
observed_traces=len(observed), installed=False), sort_keys=True))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--catalogue', type=Path, required=True)
|
|
parser.add_argument('--package', type=Path, default=ROOT / 'docs/evidence/data/item-sparse-compat/package.json')
|
|
parser.add_argument('--source-opcodes', type=Path, default=Path.home() / 'Servers/tortoise-wow/src/game/Protocol/Opcodes_1_12_1.h')
|
|
parser.add_argument('--trace', type=Path, nargs='*', default=[])
|
|
parser.add_argument('--output', type=Path, required=True)
|
|
run(parser.parse_args())
|