<?php
declare(strict_types=1);
$lane=$argv[1]??'';if(!in_array($lane,['B','C'],true))exit(78);$private=$lane==='B'?'/private/tmp/cdx-ai-payment-template-20261010':'/tmp/cdx-ai-payment-template-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||strpos($runtime,$temp.'/')!==0||!preg_match('/^cdx-payment-template-'.$lane.'-[A-Za-z0-9]+$/D',basename($runtime))||is_link($state['runtime']))exit(78);
$audit=json_decode((string)file_get_contents($runtime.'/audit.json'),true);if(empty($audit['all_passed']))throw new RuntimeException('Independent source audit required');$pid=(int)$state['pid'];$port=$lane==='B'?18351:18352;$cmd=$lane==='B'?(string)shell_exec('ps -p '.$pid.' -o command='):(string)file_get_contents('/proc/'.$pid.'/cmdline');if(strpos($cmd,__DIR__.'/router.php')===false||strpos($cmd,'127.0.0.1:'.$port)===false)exit(78);posix_kill($pid,SIGTERM);usleep(300000);$sock=@fsockopen('127.0.0.1',$port,$n,$e,1);if($sock){fclose($sock);exit(2);}
$removed=0;$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($runtime,FilesystemIterator::SKIP_DOTS),RecursiveIteratorIterator::CHILD_FIRST);foreach($it as $item){if($item->isLink())throw new RuntimeException('Unexpected private symlink');if($item->isDir()){if(!rmdir($item->getPathname()))exit(2);}else{if(!unlink($item->getPathname()))exit(2);++$removed;}}if(!rmdir($runtime))exit(2);$gone=$lane==='B'?trim((string)shell_exec('ps -p '.$pid.' -o command='))==='':!is_dir('/proc/'.$pid);echo json_encode(['lane'=>$lane,'pid'=>$pid,'port'=>$port,'worker_stopped'=>$gone,'port_not_listening'=>true,'private_cache_files_remaining'=>0,'private_runtime_files_remaining'=>0,'private_raw_responses_removed'=>true,'private_files_removed'=>$removed,'tokens_absent'=>true,'templates_retained'=>4,'stores_retained'=>2,'payment_binding_writes'=>0,'tripwire_calls'=>0]),"\n";exit($gone?0:2);
