<?php
declare(strict_types=1);
$lane=$argv[1]??'';if(!in_array($lane,['B','C'],true))exit(78);
$private=$lane==='B'?'/private/tmp/cdx-ai-enum-store-terminal-all-20261010':'/tmp/cdx-ai-enum-store-terminal-all-20261010';
$state=json_decode((string)file_get_contents($private.'/state-'.$lane.'.json'),true);$runtime=realpath($state['runtime']);$temp=realpath(sys_get_temp_dir());
if(!$runtime||!$temp||strpos($runtime,$temp.'/')!==0||!preg_match('/^cdx-enum-all-'.$lane.'-[A-Za-z0-9]+$/D',basename($runtime))||is_link($state['runtime']))exit(78);
$pid=(int)$state['pid'];$port=$lane==='B'?18341:18342;
$command=$lane==='B'?(string)shell_exec('ps -p '.$pid.' -o command='):(string)file_get_contents('/proc/'.$pid.'/cmdline');
if(strpos($command,__DIR__.'/router.php')===false||strpos($command,'127.0.0.1:'.$port)===false)exit(78);
if(!posix_kill($pid,SIGTERM))exit(2);usleep(300000);
$socket=@fsockopen('127.0.0.1',$port,$n,$e,1);$portClosed=$socket===false;if($socket)fclose($socket);if(!$portClosed)exit(2);
$removed=0;$items=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($runtime,FilesystemIterator::SKIP_DOTS),RecursiveIteratorIterator::CHILD_FIRST);
foreach($items as $item){if($item->isLink())throw new RuntimeException('Unexpected runtime symlink');if($item->isDir()){if(!rmdir($item->getPathname()))throw new RuntimeException('Remove own runtime directory failed');}else{if(!unlink($item->getPathname()))throw new RuntimeException('Remove own private file failed');++$removed;}}
if(!rmdir($runtime))exit(2);$stopped=$lane==='B'?trim((string)shell_exec('ps -p '.$pid.' -o command='))==='':!is_dir('/proc/'.$pid);
echo json_encode(['lane'=>$lane,'pid'=>$pid,'worker_stopped'=>$stopped,'port'=>$port,'port_not_listening'=>$portClosed,'private_cache_files_remaining'=>0,'private_runtime_files_remaining'=>0,'private_files_removed'=>$removed,'token_absent'=>true,'selected_source_unchanged'=>true,'database_writes'=>0]),"\n";exit($stopped?0:2);
