<?php
// Resource-only: final DB lease was already observed by finalize within the approved cap.
$plan=json_decode(file_get_contents(__DIR__.'/execution-plan.json'),true);$lane=getenv('NF_LANE');$worker=json_decode(file_get_contents(__DIR__.'/private/worker-pid.json'),true);$pid=$worker['pid'];$cmd=(string)@file_get_contents('/proc/'.$pid.'/cmdline');
if($cmd!==''&&(strpos($cmd,__DIR__.'/index.php')===false||strpos($cmd,'127.0.0.1:'.$plan['ports'][$lane])===false))throw new RuntimeException('Exact own worker identity');
$files=[];$walk=static function($dir)use(&$walk,&$files){if(!is_dir($dir))return;foreach(scandir($dir)as $n){if($n==='.'||$n==='..')continue;$f=$dir.'/'.$n;if(is_link($f))throw new RuntimeException('Own cache symlink');if(is_dir($f)){$walk($f);rmdir($f);}else{$files[]=['path'=>substr($f,strlen(__DIR__)+1),'sha256'=>hash_file('sha256',$f)];unlink($f);}}};$walk(__DIR__.'/cache');$removed=[];foreach(['auth.json','current-case.json','current-lease.json']as $n){$f=__DIR__.'/private/'.$n;if(is_file($f)){if(is_link($f))throw new RuntimeException('Own auth symlink');$removed[]=['file'=>$n,'sha256'=>hash_file('sha256',$f)];unlink($f);}}
$stopped=$cmd!==''&&posix_kill($pid,SIGTERM);usleep(250000);$open=@fsockopen('127.0.0.1',$plan['ports'][$lane],$n,$e,0.5);if($open){fclose($open);throw new RuntimeException('Own port remains');}$parent=$lane==='B'?10001:112175;if(!is_file('/proc/'.$parent.'/cmdline'))throw new RuntimeException('Original parent missing');
$r=['lane'=>$lane,'own_worker'=>$worker,'stop_sent'=>$stopped,'own_port_closed'=>true,'cache_removed'=>$files,'temporary_credentials_removed'=>$removed,'source_after_final_reference'=>'baseline-final.json','original_parent_alive'=>true,'stateless_token_globally_revoked'=>false,'SQL'=>0,'HTTP'=>0,'DML'=>0,'DDL'=>0];$f=__DIR__.'/private/cleanup.json';$h=fopen($f,'xb');fwrite($h,json_encode($r,JSON_PRETTY_PRINT));fclose($h);chmod($f,0600);echo json_encode(['lane'=>$lane,'worker_stopped'=>$stopped,'port_closed'=>true,'cache_files_removed'=>count($files),'own_temp_credentials_removed'=>count($removed),'SQL'=>0]),PHP_EOL;
