<?php
$lane=$argv[1]??'';if(!in_array($lane,['B','C'],true))exit(78);$base=__DIR__;$expected='/tmp/cdx-nutrition-write8-'.$lane.'-20261011';if(realpath($base)!==$expected)throw new RuntimeException('Exact own cleanup root');$pid=$lane==='B'?2930:2104880;$port=$lane==='B'?18831:18832;$cmd=file_get_contents('/proc/'.$pid.'/cmdline');if(strpos($cmd,$base.'/index-write.php')===false||strpos($cmd,'127.0.0.1:'.$port)===false)throw new RuntimeException('Own PHP PID lease');
$keep=[];foreach(glob($base.'/private-case-*') as $file)if(is_file($file))$keep[basename($file)]=hash_file('sha256',$file);$removed=[];
$drop=static function($path)use(&$drop,&$removed,$base){if(strpos($path,$base.'/')!==0)throw new RuntimeException('Exact descendant');if(is_link($path)||is_file($path)){if(!unlink($path))throw new RuntimeException('Cleanup file failed');$removed[]=substr($path,strlen($base)+1);return;}if(is_dir($path)){foreach(new DirectoryIterator($path) as $item)if(!$item->isDot())$drop($item->getPathname());if(!rmdir($path))throw new RuntimeException('Cleanup dir failed');$removed[]=substr($path,strlen($base)+1).'/';}};
foreach(['private-auth-write.json','private-dispatch.json','private-dispatch-extra.json','source','candidate','cache-write','runtime-write','cache','runtime'] as $target)if(file_exists($base.'/'.$target))$drop($base.'/'.$target);
if(!posix_kill($pid,SIGTERM))throw new RuntimeException('Own worker terminate failed');foreach($keep as $file=>$sha)if(hash_file('sha256',$base.'/'.$file)!==$sha)throw new RuntimeException('Raw evidence cleanup drift');$report=['lane'=>$lane,'passed'=>true,'terminated_own_PID'=>$pid,'own_port'=>$port,'removed_targets'=>['private-auth-write.json','private-dispatch.json','private-dispatch-extra.json','source','candidate','cache-write','runtime-write','cache','runtime'],'removed_entries'=>count($removed),'raw_evidence_files'=>count($keep),'raw_evidence_SHA_unchanged'=>true,'natural_or_marked_DB_cleanup_DML'=>0,'original_parent_PID'=>$lane==='B'?10001:112175,'original_parent_still_alive'=>is_file('/proc/'.($lane==='B'?10001:112175).'/cmdline')];file_put_contents($base.'/private-cleanup-write.json',json_encode($report,JSON_PRETTY_PRINT));chmod($base.'/private-cleanup-write.json',0600);echo json_encode($report),"\n";
