import shlex
import os,subprocess,time,json,signal,shutil,urllib.request
from pathlib import Path
R=Path(__file__).parent;side=os.environ['SIDE'];d=R/(side+'-lifecycle-'+str(int(time.time())));home=d/"home ' space";bin=d/'bin';versions=home/'runtime/versions'
E={**os.environ,'T3CODE_HOME':str(home),'T3CODE_INSTALL_BIN_DIR':str(bin),'T3CODE_DEV_SEED':'0','PATH':str(bin)+':'+os.environ['PATH']}
d.mkdir();f=open(d/'lifecycle.log','w')
def emit(s):
 s=str(s).replace(str(d),'<install>').replace(str(R),'<scratch>');f.write(s+'\n');f.flush();print(s,flush=True)
def cmd(args):
 emit('$ '+shlex.join(args));p=subprocess.run(args,env=E,cwd=d/'project',capture_output=True,text=True,timeout=120);emit(p.stdout+p.stderr);emit('exit='+str(p.returncode));return p
source=next((R/'download-home/runtime/versions').iterdir())
old=versions/'0.1.9';shutil.copytree(source,old,copy_function=os.link)
(old/'t3').unlink();shutil.copy2(R/(side+'-old-t3'),old/'t3')
(old/'.install-complete').unlink();(old/'.install-complete').write_text('0.1.9\n')
bin.mkdir();(d/'project').mkdir();(home/'userdata').mkdir();(home/'userdata/settings.json').write_text('{}')
target=versions/'0.1.10';shutil.copytree(old,target,copy_function=os.link)
(target/'t3').unlink();shutil.copy2(R/('head-target-t3' if side=='head' else 'base-target-t3'),target/'t3')
(target/'.install-complete').unlink();(target/'.install-complete').write_text('0.1.10\n')
launcher=bin/'t3'
def describe():
 emit('Launcher: '+('symlink -> '+os.readlink(launcher) if launcher.is_symlink() else launcher.read_text()))
def legacy():
 launcher.unlink(missing_ok=True);launcher.symlink_to(old/'t3')
# update preinstalled target follows real runUpdate without downloading from production
emit('Linux x64; real standalone CLI; preinstalled source-built target; no running foreground server or system service for this home.')
legacy();describe();cmd(['t3','update','0.1.10','--yes','--base-dir',str(home)]);describe();cmd(['t3','--version'])
# repeat script update, downgrade and reinstall
cmd(['t3','update','0.1.9','--allow-downgrade','--yes','--base-dir',str(home)]);describe();cmd(['t3','--version'])
cmd([str(target/'t3'),'install']);describe();cmd(['t3','--version'])
emit('t3 install migration from legacy symlink:');legacy();cmd([str(target/'t3'),'install']);describe();cmd(['t3','--version'])
# Real server descriptor proves invocation recognition and initializes its own database.
out=open(d/'descriptor-raw.log','w');server=subprocess.Popen(['t3','serve','--port','38796','--base-dir',str(home)],env=E,cwd=d/'project',stdout=out,stderr=out,start_new_session=True)
try:
 for i in range(120):
  try:
   descriptor=json.load(urllib.request.urlopen('http://127.0.0.1:38796/.well-known/t3/environment',timeout=1));break
  except Exception:
   if server.poll() is not None:raise RuntimeError('server stopped before descriptor')
   time.sleep(1)
 emit('GET /.well-known/t3/environment -> capabilities.serverInstallation: '+json.dumps(descriptor.get('capabilities',{}).get('serverInstallation')))
 cmd(['t3','project','add',str(d/'project'),'--title',"spaces 'quotes' $dollar; literal",'--base-dir',str(home)])
finally:
 os.killpg(server.pid,signal.SIGTERM)
 try:server.wait(timeout=20)
 except subprocess.TimeoutExpired:os.killpg(server.pid,signal.SIGKILL);server.wait()
 out.close()
# pruning: aged complete runtime referenced only by a recorded script outside PATH
pinned=versions/'0.1.7';unused=versions/'0.1.6'
for v in [pinned,unused]:
 shutil.copytree(old,v,copy_function=os.link)
 (v/'.install-complete').unlink();(v/'.install-complete').write_text(v.name+'\n');os.utime(v/'.install-complete',(time.time()-7200,time.time()-7200))
recorded=d/'outside-path/t3';recorded.parent.mkdir();recorded.write_text("#!/bin/sh\nexec '"+str(pinned/'t3').replace(chr(39), chr(39)+chr(92)+chr(39)+chr(39))+"' \"$@\"\n");recorded.chmod(0o755)
with (home/'runtime/launchers').open('a') as a:a.write(str(recorded)+'\n')
emit('Prune setup: 0.1.7 pinned only by recorded script outside PATH; 0.1.6 unreferenced; both complete and aged 2 hours.')
cmd(['t3','update','0.1.9','--allow-downgrade','--yes','--base-dir',str(home)])
emit('After real update pruning: pinned 0.1.7 survives='+str(pinned.exists())+'; unused 0.1.6 survives='+str(unused.exists()))
if pinned.exists():cmd([str(recorded),'--version'])
# service actual trial startup: durable pending state, real launcher, real trial server, IPC commit
legacy()
state={'protocol':4,'activeVersion':'0.1.9','update':{'id':'proof-trial','fromVersion':'0.1.9','targetVersion':'0.1.10','dbPath':str(home/'userdata/statev2.sqlite'),'status':'pending'}}
(home/'runtime/service-state.json').write_text(json.dumps(state));E['T3CODE_PORT']='38795'
out=open(d/'trial-raw.log','w');p=subprocess.Popen([str(old/'t3'),'__service-launcher','--base-dir',str(home)],env=E,cwd=d/'project',stdout=out,stderr=out,start_new_session=True)
try:
 for i in range(120):
  s=json.loads((home/'runtime/service-state.json').read_text())
  if s.get('update',{}).get('status')!='pending':break
  if p.poll() is not None:break
  time.sleep(1)
 for i in range(120):
  try:
   trialDescriptor=json.load(urllib.request.urlopen('http://127.0.0.1:38795/.well-known/t3/environment',timeout=1));break
  except Exception:
   if p.poll() is not None:break
   time.sleep(1)
 emit('Service trial durable state: '+json.dumps(s));describe()
 emit('Trial server log milestones:')
 for l in (d/'trial-raw.log').read_text().splitlines():
  if any(x in l.lower() for x in ['committ','trial','error','starting','ready','listening']):emit(l)
finally:
 os.killpg(p.pid,signal.SIGTERM) if p.poll() is None else None
 try:p.wait(timeout=20)
 except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
 out.close()
# A second real trial repoints the existing launcher (head script) to another newer runtime.
second=versions/'0.1.11';shutil.copytree(old,second,copy_function=os.link)
(second/'t3').unlink();shutil.copy2(R/(side+'-second-target-t3'),second/'t3')
(second/'.install-complete').unlink();(second/'.install-complete').write_text('0.1.11\n')
state={'protocol':4,'activeVersion':'0.1.10','update':{'id':'proof-second-trial','fromVersion':'0.1.10','targetVersion':'0.1.11','dbPath':str(home/'userdata/statev2.sqlite'),'status':'pending'}}
(home/'runtime/service-state.json').write_text(json.dumps(state))
emit('Second trial starts with existing launcher:');describe()
out=open(d/'second-trial-raw.log','w');p=subprocess.Popen([str(target/'t3'),'__service-launcher','--base-dir',str(home)],env=E,cwd=d/'project',stdout=out,stderr=out,start_new_session=True)
try:
 for i in range(120):
  s=json.loads((home/'runtime/service-state.json').read_text())
  if s.get('update',{}).get('status')!='pending':break
  if p.poll() is not None:break
  time.sleep(1)
 for i in range(120):
  try:
   json.load(urllib.request.urlopen('http://127.0.0.1:38795/.well-known/t3/environment',timeout=1));break
  except Exception:
   if p.poll() is not None:break
   time.sleep(1)
 emit('Second service trial durable state: '+json.dumps(s));describe();cmd(['t3','--version'])
finally:
 os.killpg(p.pid,signal.SIGTERM) if p.poll() is None else None
 try:p.wait(timeout=20)
 except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
 out.close()
# install refuses user-edited and foreign launchers without changing bytes
cmd([str(target/'t3'),'install'])
originalLink=os.readlink(launcher) if launcher.is_symlink() else None
original=launcher.read_bytes() if originalLink is None else None
generated=("#!/bin/sh\nexec '"+str(target/'t3').replace(chr(39),chr(39)+chr(92)+chr(39)+chr(39))+"' \"$@\"\n").encode()
launcher.unlink();launcher.write_bytes(generated+b'# user customization\n');launcher.chmod(0o755)
cmd([str(target/'t3'),'install']);emit('Edited launcher preserved='+str(launcher.read_bytes()==generated+b'# user customization\n'))
launcher.write_text("#!/bin/sh\nexec '/usr/bin/true' \"$@\"\n")
foreignBytes=launcher.read_bytes();cmd([str(target/'t3'),'install']);emit('Foreign launcher preserved='+str(launcher.read_bytes()==foreignBytes));launcher.unlink()
if originalLink is None:launcher.write_bytes(original);launcher.chmod(0o755)
else:launcher.symlink_to(originalLink)
# uninstall exact, edited and foreign wrappers via recorded registry
cmd([str(target/'t3'),'install'])
owned=bin/'owned-copy';edited=bin/'edited-wrapper';foreign=bin/'foreign-wrapper'
owned.write_bytes(generated);edited.write_bytes(generated+b'# user customization\n');foreign.write_text("#!/bin/sh\nexec '/usr/bin/true' \"$@\"\n")
emit('Uninstall registry: exact generated script, edited generated script, foreign wrapper; same seeded forms on both commits.')
for x in [owned,edited,foreign]:x.chmod(0o755)
with (home/'runtime/launchers').open('a') as a:
 for x in [owned,edited,foreign]:a.write(str(x)+'\n')
cmd(['t3','uninstall','--yes','--base-dir',str(home)])
for name in ['t3','owned-copy','edited-wrapper','foreign-wrapper']:emit(name+' survives='+str(os.path.lexists(bin/name)))
emit('runtime survives='+str((home/'runtime').exists()));emit('userdata survives='+str((home/'userdata').exists()))
f.close()
