<?php
declare(strict_types=1);require __DIR__.'/common.php';$state=json_decode(file_get_contents($runtime.'/worker-state.json'),true);$port=$lane==='B'?18901:18902;$check($state['port']===$port,'Own resource port');$socket=@fsockopen('127.0.0.1',$port,$e,$m,1);if($socket){fclose($socket);throw new RuntimeException('Stop own worker first');}
$tokens=json_decode(file_get_contents($runtime.'/tokens.json'),true);$app=ropeApp($root,$runtime,'CLEANUP');foreach($tokens as $token){$app->cache->delete($token);$check(!$app->cache->has($token),'Own token removed');}$check(unlink($runtime.'/tokens.json'),'Own token file removed');
$pins=json_decode(file_get_contents(__DIR__.'/source-frozen-sha.json'),true)['files'];$check(realpath($root)===__DIR__.'/source'&&!is_link($root),'Only own actual temporary source');foreach($pins as $name=>$sha)$check(hash_file('sha256',$root.'/'.$name)===$sha,'Owned temporary source file identity '.$name);
foreach([$runtime.'/cache',$runtime.'/runtime',$root] as $target){$check(strpos($target,__DIR__.'/')===0&&!is_link($target),'Own exact cleanup target');if(!is_dir($target))continue;$iterator=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($target,FilesystemIterator::SKIP_DOTS),RecursiveIteratorIterator::CHILD_FIRST);foreach($iterator as $f){$check(!$f->isLink(),'No cleanup symlink');if($f->isDir())rmdir($f->getPathname());else unlink($f->getPathname());}rmdir($target);}
$result=['lane'=>$lane,'own_worker_stopped'=>true,'own_port_closed'=>true,'own_tokens_removed'=>2,'own_cache_runtime_source_removed'=>true,'retained_marked_store_rows'=>2,'retained_formal_rope_rows'=>4,'business_DELETE'=>0,'DDL'=>0,'no_nonown_signal_sent'=>true];$persist('resource-cleanup.json',$result);echo json_encode($result),"\n";
