"""Package full raw runtime artifacts, with paths and pairing credentials redacted.
No domain events or trace spans are selected out, added, or summarised in the raw files.
"""
import pathlib,sqlite3,json,shutil,re,hashlib,sys,urllib.parse
root=pathlib.Path(__file__).parent
pub=root/'published';pub.mkdir(exist_ok=True)
for side in ['base','head']:
 run=root/('capture-20261130T154000-'+side);out=pub/side;out.mkdir(exist_ok=True)
 source=sqlite3.connect(run/'server/userdata/statev2.sqlite');dest=sqlite3.connect(out/'statev2.sqlite');source.backup(dest)
 credentials=[r[0] for r in source.execute('select credential from auth_pairing_links')];source.close()
 def clean(s):
  for old,new in [(str(run),'/proof'),(sys.argv[1],'/workspace/base'),(sys.argv[2],'/workspace/head'),(str(pathlib.Path.home()),'/home/proof')]:
   s=s.replace(urllib.parse.quote(old,safe=''),urllib.parse.quote(new,safe='')).replace(old,new)
  for c in credentials:
   if c:s=s.replace(c,'<redacted-pairing-credential>')
  s=re.sub(r'([?&]wsTicket=)[^&\s"\\]+',r'\1<redacted-ticket>',s)
  return s
 for (table,) in dest.execute("select name from sqlite_master where type='table'").fetchall():
  cols=[x[1] for x in dest.execute('pragma table_info("'+table+'")')]
  for col in cols:
   q=lambda a:'"'+a.replace('"','""')+'"'
   for (value,) in dest.execute(f'SELECT DISTINCT {q(col)} FROM {q(table)} WHERE typeof({q(col)})=\'text\'').fetchall():
    value2=clean(value)
    if col=='credential' and table=='auth_pairing_links':value2='redacted-'+hashlib.sha256(value.encode()).hexdigest()
    if value2!=value:dest.execute(f'UPDATE {q(table)} SET {q(col)}=? WHERE {q(col)}=?',(value2,value))
 dest.commit();dest.execute('vacuum');dest.close()
 trace=clean((run/'server/userdata/logs/server.trace.ndjson').read_text());(out/'server.trace.ndjson').write_text(trace)
 for name in ['terminal.cast','terminal.txt','rpc.ndjson','unborn-cli.json','multi-cli.json','remote-cli.json']:
  (out/name).write_text(clean((run/name).read_text()))
 for name in ['terminal.mp4','non-git-terminal.png','unborn-terminal.png']:
  if (run/name).exists():shutil.copy(run/name,out/name)
 for name in ['statev2.sqlite','server.trace.ndjson']:
  data=(out/name).read_bytes()
  assert str(pathlib.Path.home()).encode() not in data and str(root).encode() not in data
  assert all(c.encode() not in data for c in credentials if c)
 (out/'REDACTIONS.txt').write_text('Full runtime SQLite database and full server trace. Only filesystem path prefixes and pairing credentials are privacy-redacted. All domain events, sequence numbers, timestamps, span IDs, parent-child relationships, failures, tables, and rows are retained. SQLite VACUUM removed stale credential/path bytes. Terminal MP4 replays actual captured stdout, with JSON reflowed and pauses added for reading; terminal.cast retains original stdout timing.\n')
for name in ['proof-driver.py','proof-rpc.ts','render-recording.py','package-evidence.py']:
 shutil.copy(root/name,pub/name)
print(pub)
