Files
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

119 lines
8.7 KiB
Python

#!/usr/bin/env python3
"""Parse our diagnostic SavedVariables as data, without executing Lua or reading auth logs."""
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import re
ROOT=Path(__file__).resolve().parents[1]
SECRET_REDACTION='--[[ secret value ]]'
TOKEN=re.compile(r'\s+|"(?:\\.|[^"\\])*"|--\[\[ secret value \]\]|[-+]?[0-9]+(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?|[A-Za-z_][A-Za-z_0-9]*|[{}\[\]=,;]',re.S)
def quoted(token):
data=bytearray();i=1
escapes={'n':10,'r':13,'t':9,'b':8,'f':12,'v':11,'a':7,'\\':92,'"':34,"'":39}
while i<len(token)-1:
c=token[i];i+=1
if c!='\\':data.extend(c.encode());continue
c=token[i];i+=1
if c.isdecimal():
digits=c
while i<len(token)-1 and len(digits)<3 and token[i].isdecimal():digits+=token[i];i+=1
value=int(digits)
if value>255:raise ValueError('Lua string escape bound')
data.append(value)
elif c in escapes:data.append(escapes[c])
else:raise ValueError('Unsupported Lua string escape')
return data.decode('utf-8')
def parse(text,variable='GatewayDiagnosticsSaved',*,max_tokens=200_000):
# Explicit larger data inventories share this non-executing parser. Keep
# diagnostic defaults and a hard ceiling; this does not evaluate Lua.
if type(max_tokens)is not int or not 1<=max_tokens<=500_000:raise ValueError('Lua data token bound must be1..500000')
if len(text)>2_000_000:raise ValueError('Diagnostic export size bound')
tokens=[];pos=0
while pos<len(text):
match=TOKEN.match(text,pos)
if not match:raise ValueError('Non-data Lua syntax rejected')
token=match.group();pos=match.end()
# The client's own SavedVariables writer emits nil followed by this
# exact marker for a protected value. Keep the nil, never recover the
# secret or accept general Lua comments/expressions.
if token==SECRET_REDACTION:
if not tokens or tokens[-1]!='nil':raise ValueError('Secret marker without redacted nil')
elif not token.isspace():tokens.append(token)
if len(tokens)>max_tokens:raise ValueError('Diagnostic token bound')
at=0
def take(expected=None):
nonlocal at
if at>=len(tokens):raise ValueError('Truncated diagnostic table')
t=tokens[at];at+=1
if expected is not None and t!=expected:raise ValueError('Unexpected diagnostic data syntax')
return t
def value(depth=0):
if depth>12:raise ValueError('Diagnostic nesting bound')
t=take()
if t=='{':
out={};index=1
while at<len(tokens) and tokens[at]!='}':
if tokens[at]=='[':
take('[');key=value(depth+1);take(']');take('=')
else:key=index;index+=1
if key in out:raise ValueError('Duplicate diagnostic table key')
out[key]=value(depth+1)
if at<len(tokens) and tokens[at] in (',',';'):take()
elif at>=len(tokens) or tokens[at]!='}':raise ValueError('Missing table separator')
take('}')
return [out[i] for i in range(1,len(out)+1)] if out and set(out)==set(range(1,len(out)+1)) else out
if t.startswith('"'):return quoted(t)
if t in ('true','false','nil'):return {'true':True,'false':False,'nil':None}[t]
if re.fullmatch(r'[-+]?[0-9]+(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?',t):return float(t) if any(c in t for c in '.eE') else int(t)
raise ValueError('Executable Lua expressions rejected')
take(variable);take('=');out=value()
if at!=len(tokens) or not isinstance(out,dict):raise ValueError('Trailing Lua rejected')
return out
def native_error_summary(history):
"""Count known diagnostic errors without exporting arbitrary Lua/history text."""
if not isinstance(history,list):raise ValueError('Native console history schema changed')
messages=[v for row in history if isinstance(row,list) for v in row if isinstance(v,str)]
return {
'lua_error_rows':sum(v.startswith('Lua Error:') for v in messages),
'protected_power_observer_rows':sum('GWPowerPeak' in v and 'attempt to compare' in v and 'secret number' in v for v in messages),
'truncated_cooldown_probe_rows':sum('GW spell cooldown' in v and "expected near '<eof>'" in v for v in messages),
'note':'Counts from persisted history only; unknown error bodies/commands are not exported. A live session may have unsaved errors.'}
def main():
p=argparse.ArgumentParser();p.add_argument('--input',type=Path);p.add_argument('--output',type=Path,default=ROOT/'runtime/console-report.json');p.add_argument('--native',action='store_true');args=p.parse_args()
if not args.output.resolve().is_relative_to(ROOT):raise ValueError('Report output must stay in gateway')
if args.input is None:
files=list(Path('/mnt/Games/Games/WoW-Forever/_classic_beta_/WTF').rglob('Blizzard_Console.lua' if args.native else 'GatewayDiagnostics.lua'))
if len(files)!=1:raise ValueError('Expected one local diagnostic export; choose --input explicitly')
args.input=files[0]
raw=args.input.read_text();saved=parse(raw,'Blizzard_Console_SavedVars' if args.native else 'GatewayDiagnosticsSaved')
if args.native:
history=saved.get('messageHistory',[]);commands=saved.get('commandHistory',[])
if not isinstance(history,list) or not isinstance(commands,list):raise ValueError('Native history schema changed')
allowed_commands={'help','help console','help combat','help debug','help net','help developerLogWriteToFile','help testOutput','cvarlist developerLog','developerLog 0','developerLog 1'}
messages=[]
for row in history:
if not isinstance(row,list):continue
for value in row:
if isinstance(value,str) and (value.startswith('Commands registered for the category ') or value=='Console help categories:' or value.startswith('> ') and value[2:] in allowed_commands or re.fullmatch(r'"developerLog[A-Za-z]*" is "[01]"',value)):
messages.append({'message':value,'numeric_metadata':{str(i):v for i,v in enumerate(row) if type(v) in (int,float)}})
report={'source':'Blizzard_Console.lua / Blizzard_Console_SavedVars','history_count':len(history),'command_count':len(commands),'allowed_command_history':[c for c in commands if c in allowed_commands],'lua_diagnostics':native_error_summary(history),'messages':messages,'font_height':saved.get('fontHeight'),'is_shown_at_save':saved.get('isShown'),'note':'Only public diagnostic help/CVar rows exported; arbitrary native history omitted. Numeric array fields are not assigned unverified timestamp semantics.'}
args.output.parent.mkdir(parents=True,exist_ok=True);args.output.write_text(json.dumps(report,indent=2)+'\n')
print('Read native console SavedVariables; history rows',len(history),'; exported public diagnostic rows',len(messages));print('Report:',args.output);return
commands=saved.get('commands',[])
if not isinstance(commands,list) or len(commands)>4096:raise ValueError('Invalid command catalog')
selected={name: next((c for c in commands if c.get('command')==name),None) for name in ('help','ConsoleKey','closeconsole','cvarlist','cmdlist','testOutput','developerLog','developerLogWriteToFile','developerLogFilterDebug','developerLogFilterNormal','consoleShowDebugMessages','logWowConnections','ClientCastDebug','enableQuestCacheLogging')}
report={'build':saved.get('build'),'version':saved.get('version'),'interface':saved.get('interface'),'saved_sha256':hashlib.sha256(raw.encode()).hexdigest(),'command_count':len(commands),'command_types':dict(Counter(str(c.get('commandType')) for c in commands)),'categories':dict(Counter(str(c.get('category')) for c in commands)),'selected_commands':selected,'console_event_registered':saved.get('consoleEventRegistered'),'console_event_count':saved.get('eventCount'),'console_messages':saved.get('consoleMessages'),'safe_cvars':saved.get('cvars'),'apis':saved.get('apis'),'namespaces':saved.get('namespaces'),'commands':sorted(commands,key=lambda c:c.get('command',''))}
# Do not publish an export containing any stored local credential, even accidentally.
encoded=json.dumps(report,indent=2)
for secret in (ROOT/'secrets').rglob('password.txt'):
value=secret.read_text().strip()
if value and value in encoded:raise ValueError('Credential-containing export rejected; value omitted')
args.output.parent.mkdir(parents=True,exist_ok=True);args.output.write_text(encoded+'\n')
print('Actual client build',report['build'],'; catalog',len(commands),'; captured console headers',len(saved.get('consoleMessages',[])))
print('Report:',args.output)
if __name__=='__main__':main()