#!/usr/bin/env python3
"""Shape a synthetic Antigravity child's transcript for the 256 KiB tail boundary.
Usage: shape-transcript.py <transcript.jsonl> <two|one|partial|undelimited>
Keeps a backup beside the source; uses an ignored JSON field as ASCII byte padding.
"""
import json, sys
from pathlib import Path
p=Path(sys.argv[1]); mode=sys.argv[2]; cap=262144
backup=p.with_suffix('.original.jsonl')
if not backup.exists(): backup.write_bytes(p.read_bytes())
rows=[json.loads(s) for s in backup.read_text().splitlines()]
assert len(rows)>=6
# Keep the original opening records; make the two boundary records clear and identical on both sides.
a={'step_index':4,'type':'GENERIC','status':'DONE', 'content':'Step 4: Searcher sent the marker number (4242) to the caller.'}
b={'step_index':5,'type':'PLANNER_RESPONSE','status':'DONE', 'content':'Step 5: Reported the marker number (4242) to the caller.'}
def line(r): return (json.dumps(r,separators=(',',':'),ensure_ascii=True)+'\n').encode()
def padded(r,n,newline=True):
 r={**r,'padding':''}; r['padding']='x'*(n-len(line(r))+(0 if newline else 1))
 result=line(r) if newline else line(r)[:-1]
 assert len(result)==n
 return result
prefix=b''.join(line(r) for r in rows[:4])
if mode=='two': data=prefix+padded(a,cap-len(line(b)))+line(b)
elif mode=='one': data=prefix+line(a)+padded(b,cap)
elif mode=='partial': data=prefix+padded(a,cap)+line(b)
elif mode=='undelimited': data=prefix+padded(b,cap+100,newline=False)
else: raise ValueError(mode)
p.write_bytes(data)
start=max(0,len(data)-cap)
print(json.dumps({'case':mode,'bytes':len(data),'retainedBytes':len(data[start:]),'precedingByte':data[start-1:start].decode(),'retainedLineCount':len(data[start:].splitlines()),'retainedStartsWith':data[start:start+40].decode(),'retainedContainsNewline':b'\n' in data[start:]}))
