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

131 lines
8.9 KiB
Python

#!/usr/bin/env python3
"""Project the frozen full packet sources onto the writer-only codec contract.
The C codec entry accepts serialized adapter inputs and invokes packet Write;
original CMSG Read and live-world initialization bodies are not entry points.
All retained writer bytes remain unchanged. No undefined symbols are stubbed.
"""
import argparse,hashlib,json,re,shutil
from pathlib import Path
def sha_bytes(value):return hashlib.sha256(value).hexdigest()
def mask(text):
out=list(text);i=0
while i<len(text):
end=None
if text.startswith('//',i):end=text.find('\n',i+2);end=len(text) if end<0 else end
elif text.startswith('/*',i):
end=text.find('*/',i+2)
if end<0:raise ValueError('Unclosed source comment')
end+=2
elif text[i] in ('"',"'"):
quote=text[i];j=i+1
while j<len(text):
if text[j]=='\\':j+=2;continue
if text[j]==quote:break
j+=1
if j>=len(text):raise ValueError('Unclosed source literal')
end=j+1
if end is not None:
for j in range(i,end):
if out[j]!='\n':out[j]=' '
i=end
else:i+=1
return ''.join(out)
def body_end(code,opening):
if code[opening]!='{':raise ValueError('Function body required')
depth=0
for n in range(opening,len(code)):
if code[n]=='{':depth+=1
elif code[n]=='}':
depth-=1
if depth==0:return n+1
raise ValueError('Unclosed function body')
def selected_function(text,needle):
code=mask(text);matches=list(re.finditer(re.escape(needle),code))
if len(matches)!=1:raise ValueError('Source helper identity must be unique: '+needle)
start=code.rfind('\n',0,matches[0].start())+1;opening=code.find('{',matches[0].end());end=body_end(code,opening)
return text[start:end]
def writer_projection(text):
code=mask(text);spans=[]
pattern=re.compile(r'(?m)^[ \t]*(?:[\w:*&<>]+[ \t]+)*(?:[\w:<>]+::)?(?:Read\w*|Initialize|GenerateDataForUnits)(?:<[^\n()]*>)?[ \t]*\(|^[ \t]*[^\n;{}]*operator[ \t]*>>[ \t]*\(')
for match in pattern.finditer(code):
opening=code.find('{',match.end());semi=code.find(';',match.end())
if opening<0 or (semi>=0 and semi<opening):continue
start=match.start();previous=code.rfind('\n',0,max(0,start-1))+1
if code[previous:start].lstrip().startswith('template'):start=previous
end=body_end(code,opening);spans.append((start,end,text[match.start():opening].strip()))
# Explicit instantiations of the removed live-world template are not writers.
for m in re.finditer(r'(?m)^template\s+bool\s+ContentTuningParams::GenerateDataForUnits[^;]*;',code):spans.append((m.start(),m.end(),m.group(0).strip()))
spans.sort();previous=0;out=[];removed=[]
for start,end,name in spans:
if start<previous:raise ValueError('Overlapping source function projection')
out += [text[previous:start],'\n'*text[start:end].count('\n')];previous=end;removed.append(name)
out.append(text[previous:]);return ''.join(out),removed
def curate(closure,forever,reuse_closure=None):
closure=closure.resolve();manifest_path=closure/'windows-codec-closure.json';m=json.loads(manifest_path.read_text())
if m.get('writer_projection'):raise ValueError('Already projected; reuse its receipt')
adapter=(closure/'gateway/src/forever_create.cpp').read_text()
if re.search(r'\.\s*(Read\w*|Initialize|GenerateDataForUnits)\s*\(',mask(adapter)):raise ValueError('Codec adapter unexpectedly calls a reader/world initializer')
changes=[]
for name in m['sources']:
if not name.startswith('forever/') or '/Server/Packets/' not in name:continue
path=closure/name;before=path.read_bytes()
if sha_bytes(before)!=m['files'][name]:raise ValueError('Frozen source changed before projection')
after,removed=writer_projection(before.decode())
if not removed:continue
path.write_text(after);m['files'][name]=sha_bytes(path.read_bytes());changes.append({'path':name,'source_sha256':sha_bytes(before),'writer_sha256':m['files'][name],'omitted_nonwriter_functions':removed})
# Exact original write-stream overloads. The existing generated source owns
# XYZ; add only XY/XYZO referenced by the retained native update writers.
position=forever/'src/server/game/Entities/Object/Position.cpp';position_text=position.read_text()
retained=(closure/'generated/packed_position.cpp').read_text()
methods=[]
for kind in ['XY','XYZO']:
signature='ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer<Position::'+kind+'> const& streamer)'
original=selected_function(position_text,signature)
if signature in retained:
if selected_function(retained,signature)!=original:raise ValueError('Retained Position writer differs from original')
else:methods.append(original)
bytebuffer=forever/'src/server/shared/Packets/ByteBuffer.cpp'
if not bytebuffer.exists():bytebuffer=forever/'src/common/Packets/ByteBuffer.cpp'
byte_text=bytebuffer.read_text()
methods += [selected_function(byte_text,'void ByteBuffer::OnInvalidPosition(')]
extra_sources=[]
for source,needle,namespace in [(forever/'dep/g3dlite/source/Vector3.cpp','const Vector3& Vector3::zero()','G3D'),(forever/'src/server/game/Server/Packets/CharacterPackets.cpp','ByteBuffer& operator<<(ByteBuffer& data, ChrCustomizationChoice const& customizationChoice)','UF')]:
methods.append('namespace '+namespace+' {\n'+selected_function(source.read_text(),needle)+'\n}')
extra_sources.append({'path':str(source),'sha256':sha_bytes(source.read_bytes()),'function':needle})
helper='generated/windows_writer_helpers.cpp';text='// Exact source writer/error helpers; no reader or live-world initialization.\n#include "Position.h"\n#include "ByteBuffer.h"\n#include "UpdateFields.h"\n#include "G3D/Vector3.h"\n#include <sstream>\n'+ '\n\n'.join(methods)+'\n'
(closure/helper).write_text(text);m['files'][helper]=sha_bytes(text.encode());m['sources'].append(helper)
# Reuse the union of already pinned helper/header dependencies. The added
# source is small; no reference database or full source tree is copied.
deps=set()
for name in m['sources']:
if Path(name).name in ['packed_position.cpp','forever_create.cpp']:deps.update(m['unit_dependencies'][name])
deps.add(helper);m['unit_dependencies'][helper]=sorted(deps)
m.setdefault('unit_flags',{})[helper]=['-D_USE_MATH_DEFINES=1']
# Reuse the already frozen Windows formatting closure which the original
# ByteBuffer error helper requires. No fresh original header export.
if reuse_closure is not None:
baseline=Path(reuse_closure).resolve();old=json.loads((baseline/'windows-codec-closure.json').read_text())
formatting=[name for name in old['files'] if name in ('forever/src/common/Utilities/StringFormat.cpp','forever/src/common/Utilities/StringFormat.h') or name.startswith('forever/dep/fmt/include/fmt/')]
for name in formatting:
target=closure/name
if name in m['files']:
if m['files'][name]!=old['files'][name]:raise ValueError('Changed original formatting dependency requires new authority')
continue
source=baseline/name
if sha_bytes(source.read_bytes())!=old['files'][name]:raise ValueError('Frozen formatting dependency changed')
target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source,target);m['files'][name]=old['files'][name]
formatter='forever/src/common/Utilities/StringFormat.cpp'
if formatter not in m['files']:raise ValueError('Pinned original formatting source is unavailable')
if formatter not in m['sources']:m['sources'].append(formatter)
m['unit_dependencies'][formatter]=sorted(set(m['unit_dependencies'][helper])|set(formatting))
m['unit_dependencies'][helper]=sorted(set(m['unit_dependencies'][helper])|set(formatting))
m['formatting_dependency_reuse']={'baseline':str(baseline),'files':formatting,'original_source_changed':False}
m['writer_projection']={'policy':'exact-source-write-only-codec-v1','changes':changes,'helper_sources':{str(position):sha_bytes(position.read_bytes()),str(bytebuffer):sha_bytes(bytebuffer.read_bytes())},'additional_exact_helpers':extra_sources,'original_native_behavior_changed':False,'actual_native_link_acceptance':'PENDING'}
manifest_path.write_text(json.dumps(m,indent=2)+'\n');return m['writer_projection']
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--closure',required=True,type=Path);p.add_argument('--forever-source',required=True,type=Path);p.add_argument('--reuse-closure',type=Path);a=p.parse_args();x=curate(a.closure,a.forever_source,a.reuse_closure);print('Projected',len(x['changes']),'packet units; exact native writer bytes retained.')
if __name__=='__main__':main()