#!/usr/bin/env python3
"""Stop only server process groups recorded by this evidence run, then remove its before worktree."""
from pathlib import Path
import os,signal,subprocess,time,json,re
R=Path('/tmp/issue-lead-33252-r2/evidence-capture')
report=[]
for side,ports in [('after',[14523,6483]),('before',[16639,8599])]:
 checkout='/home/ubuntu/wt/issue-33252'+('-before' if side=='before' else '')
 run=Path((R/(side+'-location.txt')).read_text().strip())
 group=int((run/'server.pid').read_text())
 ss=subprocess.check_output(['ss','-H','-ltnp'],text=True)
 owners=[]
 for line in ss.splitlines():
  if any(re.search(r':'+str(port)+r'\s',line) for port in ports):
   for pid in re.findall(r'pid=(\d+)',line):
    cwd=os.readlink('/proc/'+pid+'/cwd')
    if not cwd.startswith(checkout):raise RuntimeError('Unexpected port owner: '+cwd)
    owners.append({'pid':int(pid),'cwd':cwd})
 try:os.killpg(group,signal.SIGTERM)
 except ProcessLookupError:pass
 report.append({'side':side,'recordedGroup':group,'confirmedPortOwners':owners})
 time.sleep(1)
subprocess.run(['/home/ubuntu/.npm/_npx/6de2aa2fded2970c/node_modules/agent-browser/bin/agent-browser-linux-x64','--session','evidence-33252-416bebe89473','close'],check=True)
subprocess.run(['git','-C','/home/ubuntu/t3code','worktree','remove','--force','/home/ubuntu/wt/issue-33252-before'],check=True)
(R/'cleanup-report.json').write_text(json.dumps(report,indent=2))
print(json.dumps(report,indent=2))
print('Owned browser closed; both recorded server groups stopped; before worktree removed.')
