<?php
declare(strict_types=1);
try{require __DIR__.'/bootstrap.php';require __DIR__.'/RequestGate.php';$start=microtime(true);$scenario=$_SERVER['HTTP_X_PILOT_SCENARIO']??'';$final=strpos($scenario,'PILOT_LF_FINAL_')===0;$cases=json_decode(file_get_contents($runtime.($final?'/cases-FINAL.json':'/cases-NA.json')),true);$case=requestGate($_SERVER,$cases);$path=$case['path'];
 $_SERVER['SCRIPT_FILENAME']=$root.'/public/index.php';$_SERVER['SCRIPT_NAME']='/index.php';$_SERVER['PHP_SELF']='/index.php';$app=guardedApp($root,$runtime,$scenario);$hosts=['store.ledger-read.invalid'=>2147001111,'terminal.ledger-read.invalid'=>2147001112];$app->env->set('store.host',$hosts);$check(getStoreId()===$hosts[$case['host']],'Tenant gate');$before=$small($case['context']);$source=json_decode(file_get_contents(__DIR__.($final?'/source-final-sha.json':'/source-frozen-sha.json')),true)['files'];require __DIR__.'/SqlCoverageRecorder.php';$rec=new SqlCoverageRecorder($runtime.($final?'/queries-final.jsonl':'/queries.jsonl'),$root,$scenario);$ops=[];$app->db->listen(static function($sql,$elapsed=null)use(&$ops,$runtime,$scenario,$rec,$final){if(strpos((string)$sql,'CONNECT:')===0)return;$kind=preg_match('/^\s*CALL\b/i',(string)$sql)?'metadata_CALL':(preg_match('/^\s*SHOW\b/i',(string)$sql)?'metadata_SHOW':'SELECT');$ops[]=$kind;$rec->observe($sql,$elapsed);file_put_contents($runtime.($final?'/db-listen-final.jsonl':'/db-listen.jsonl'),json_encode(['scenario'=>$scenario,'sql'=>$sql,'operation'=>$kind,'layer'=>'ThinkPHP Db.listen debug interpolation only'],JSON_UNESCAPED_UNICODE)."\n",FILE_APPEND|LOCK_EX);chmod($runtime.($final?'/db-listen-final.jsonl':'/db-listen.jsonl'),0600);});register_shutdown_function([$rec,'finish']);
 $http=$app->http;$response=$http->run();$after=$small($case['context']);$actual=[];foreach(get_included_files() as $file){if(strpos($file,$root.'/')!==0)continue;$rel=substr($file,strlen($root)+1);$actual[$rel]=hash_file('sha256',$file);$check(isset($source[$rel])&&$source[$rel]===$actual[$rel],'Original actual source identity '.$rel);}
 $wire=['scenario'=>$scenario,'case'=>$case,'http_status'=>$response->getCode(),'elapsed_ms'=>(microtime(true)-$start)*1000,'raw'=>$response->getContent(),'before'=>$before,'original'=>$after,'source_sha256'=>$actual,'db_listen_operations'=>$ops];$persist('wire-'.$scenario.'.json',$wire);$check($before===$after,'Small independent original rows unchanged');$response->send();$http->end($response);
}catch(Throwable $e){if(isset($persist))$persist('harness-failure-'.preg_replace('/[^A-Z0-9_]/','',strtoupper($scenario??'INIT')).'.json',['class'=>get_class($e),'message'=>$e->getMessage(),'file'=>$e->getFile(),'line'=>$e->getLine()]);http_response_code(500);header('Content-Type: application/json');echo json_encode(['harness_error'=>get_class($e),'message'=>$e->getMessage()]);}
