<?php
declare(strict_types=1);
$lane=$argv[1]??'';$pid=$lane==='B'?5006:($lane==='C'?2227920:0);$port=$lane==='B'?18871:18872;
if(!$pid||!preg_match('#^/tmp/cdx-store-(?:fl11-B|finance-lower-read10)\.[A-Za-z0-9]+$#D',__DIR__))throw new RuntimeException('Exact owned runtime scope');
$mode=$argv[2]??'stop';
if($mode==='stop'){$cmd=(string)file_get_contents('/proc/'.$pid.'/cmdline');if(strpos($cmd,__DIR__.'/index.php')===false||strpos($cmd,'127.0.0.1:'.$port)===false)throw new RuntimeException('Owned PID drift');if(!posix_kill($pid,15))throw new RuntimeException('Owned stop failed');echo json_encode(['lane'=>$lane,'pid'=>$pid,'TERM_sent'=>true]),"\n";exit;}
if($mode!=='files')throw new RuntimeException('Cleanup mode');
if($socket=@fsockopen('127.0.0.1',$port,$n,$e,1)){fclose($socket);throw new RuntimeException('Owned worker still listening');}
$removed=[];$remove=static function(string $name)use(&$removed){$target=__DIR__.'/'.$name;if(!file_exists($target)&&!is_link($target))return;if(is_dir($target)&&!is_link($target)){$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($target,FilesystemIterator::SKIP_DOTS),RecursiveIteratorIterator::CHILD_FIRST);foreach($it as $file){$path=$file->getPathname();if($file->isLink()||!$file->isDir())unlink($path);else rmdir($path);}rmdir($target);}else unlink($target);$removed[]=$name;};
foreach(['source','cache','runtime','private/request.json','payload.tar.gz','appledouble-quarantine']as $target)$remove($target);
$report=['lane'=>$lane,'owned_pid'=>$pid,'port'=>$port,'port_closed'=>true,'removed'=>$removed,'retained_database_marker'=>'CDXFL11E2F7','database_DML'=>0,'original_parent_preserved'=>is_file('/proc/'.($lane==='B'?10001:112175).'/cmdline')];
file_put_contents(__DIR__.'/private/cleanup.json',json_encode($report,JSON_PRETTY_PRINT));chmod(__DIR__.'/private/cleanup.json',0600);echo json_encode($report),"\n";
