import subprocess,os,time,json,sys,hashlib,select
from pathlib import Path
ROOT=Path(os.environ['PROOF_ROOT'])
side=sys.argv[1]; home=sys.argv[2]
out=ROOT/(side+'-'+time.strftime('%Y%m%dT%H%M%S')); out.mkdir()
uid=subprocess.check_output(['id','-u',os.environ['PROOF_USER']],text=True).strip()
prefix=['sudo','-n','-u',os.environ['PROOF_USER'],'env','HOME='+str(ROOT/'account'),'XDG_RUNTIME_DIR=/run/user/'+uid]
wt=os.environ['CHECKOUT']
cli=prefix+['SQLITE_TMPDIR='+str(ROOT/'small-tmp'),os.environ['NODE_BIN'],wt+'/apps/server/src/bin.ts']
db=home+'/userdata/statev2.sqlite'
def run(cmd): return subprocess.run(cmd,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT).stdout
start=time.time(); events=[]; transcript=''
def clean(s):
 s=s.replace(str(ROOT/'small-tmp'),'<small-tmp>').replace(home,'<data-home>').replace(str(ROOT),'<proof-dir>').replace(wt,'<checkout>')
 s=s.replace(os.environ['NODE_BIN'],'node')
 return s
def emit(s):
 global transcript
 s=clean(s); transcript+=s; events.append([time.time()-start,'o',s]); print(s,end='',flush=True)
def status():
 return run(prefix+['systemctl','--user','show','t3code.service','-p','ActiveState','-p','MainPID','-p','ExecMainStartTimestampMonotonic'])
def snap():
 return run(prefix+['sqlite3',db,'pragma auto_vacuum; pragma page_count; pragma freelist_count; select count(*) from orchestration_events;'])
emit('Linux CLI | real systemd user service | pinned t3@0.1.14\n'+side+' commit: '+run(['git','-C',wt,'rev-parse','HEAD']))
emit('$ df -k <small-tmp>\n'+run(['df','-k',str(ROOT/'small-tmp')]))
emit('$ service state before\n'+status())
emit('$ database before: auto_vacuum / pages / free pages / event count\n'+snap())
since=run(['date','--iso-8601=seconds']).strip()
emit('$ SQLITE_TMPDIR=<small-tmp> node apps/server/src/bin.ts doctor --fix --base-dir <data-home>\n')
p=subprocess.Popen(cli+['doctor','--fix','--base-dir',home],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
while True:
 b=os.read(p.stdout.fileno(),65536)
 if not b: break
 emit(b.decode(errors='replace'))
rc=p.wait(); emit('Exit status: '+str(rc)+'\n')
emit('$ service state after\n'+status())
emit('$ database after: auto_vacuum / pages / free pages / event count\n'+snap())
j=run(prefix+['journalctl','--user','-u','t3code.service','--since',since,'--no-pager','-o','cat'])
# Only systemd lifecycle messages: no hostnames, application data or credentials.
lines=[x for x in j.splitlines() if x.startswith(('Stopping t3code.service','Stopped t3code.service','Started t3code.service','Starting t3code.service'))]
emit('$ service lifecycle journal during doctor\n'+ ('\n'.join(lines)+'\n' if lines else '(no stop/start entries)\n'))
(out/'terminal.txt').write_text(transcript)
with (out/'terminal.cast').open('w') as f:
 f.write(json.dumps({'version':2,'width':150,'height':42,'timestamp':int(start),'title':side+' doctor disk-space proof'})+'\n')
 for e in events: f.write(json.dumps(e)+'\n')
print('\nCAPTURE_DIR='+str(out))
