<?php
declare(strict_types=1);
require __DIR__.'/bootstrap.php';require __DIR__.'/StrictWire.php';$recovery=null;if($lane==='B'&&is_file($runtime.'/private-recovery.json')){$recovery=json_decode(file_get_contents($runtime.'/private-recovery.json'),true);$check($recovery['only_one_committed_tuple']===true&&$recovery['raw_initial_default_and_create_lost']===true,'Exact recovery provenance');$owned=$recovery['owned'];$before=$recovery['before'];$check($snapshot()===$before,'Recovery natural baseline');}else{$before=$snapshot();foreach($tables as $t)$check((int)$query('SELECT COUNT(*) n FROM yoshop_'.$t.' WHERE store_id IN (?,?)',array_values($tenants))[0]['n']===0,'New KV tenant collision');}
define('TP_ENV','poc');define('BUSINESS','aizhct');define('ENTERPRISE_NO','10001');require $root.'/vendor/autoload.php';$app=new \think\App($root);$app->setEnvName('poc');$app->setRuntimePath($runtime.'/fixture-runtime/');$app->initialize();$cache=new \think\cache\driver\File($app,['path'=>$runtime.'/cache/','prefix'=>'','expire'=>0]);$tokens=[];foreach($tenants as $module=>$tenant){$tokens[$module]=bin2hex(random_bytes(24));$cache->set($tokens[$module],['user'=>['store_user_id'=>$tenant,'store_id'=>$tenant,'real_name'=>$marker,'user_name'=>$marker,'is_super'=>1],'store_id'=>$tenant,'is_login'=>true],1800);}
$cases=[];$responses=[];$proofs=[];$errors=[];$expected=[];$updateWindows=[];$state=['owned'=>$owned];file_put_contents($runtime.'/private-owned-map.json',json_encode($state));chmod($runtime.'/private-owned-map.json',0600);
$checkpoint=static function()use($runtime,&$cases,&$responses,&$expected,&$owned,&$errors):void{$path=$runtime.'/private-http-progress.json';file_put_contents($path,json_encode(['cases'=>$cases,'responses'=>$responses,'expected'=>$expected,'owned'=>$owned,'errors'=>$errors],JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));chmod($path,0600);};register_shutdown_function(static function()use($checkpoint,$cache):void{$checkpoint();$cache->clear();});
$shape=static function($v)use(&$shape){if(is_object($v)){$out=[];foreach(get_object_vars($v) as $k=>$x)$out[$k]=$shape($x);ksort($out);return ['object'=>$out];}if(is_array($v))return ['array'=>array_map($shape,$v)];return gettype($v);};
$request=static function(string $module,string $family,string $name,string $action,string $key,array $form=[])use($base,$tokens,$check,$shape,$checkpoint,&$cases,&$responses):array{$method=$action==='detail'?'GET':'POST';$scenario='PILOT_CS_'.strtoupper($module.'_'.$family.'_'.$name);$wirePath='/'.$module.'/client.'.$family.'.setting/'.$action;$canonical='/'.$module.'/client.'.$family.'.Setting/'.$action;$headers='Host: '.$module.".client-settings.invalid\r\nAccess-Token: ".$tokens[$module]."\r\nPlatform: POC\r\nX-Pilot-Scenario: ".$scenario."\r\nContent-Type: application/json\r\n";$start=time();$raw=file_get_contents($base.$wirePath.($method==='GET'?'?'.http_build_query(['key'=>$key]):''),false,stream_context_create(['http'=>['method'=>$method,'header'=>$headers,'content'=>$method==='POST'?json_encode(['key'=>$key,'form'=>$form],JSON_UNESCAPED_UNICODE):'','timeout'=>30,'ignore_errors'=>true]]));$end=time();$body=json_decode((string)$raw,true);preg_match('#^HTTP/\S+\s+(\d+)#',$http_response_header[0]??'',$m);$check(is_array($body)&&strlen($raw)<1048576,'Actual JSON transport');$c=['scenario'=>$scenario,'method'=>$method,'path'=>$canonical,'actual_wire_path'=>$wirePath,'http_status'=>(int)($m[1]??0),'body'=>$body,'raw_json_shape'=>$shape(json_decode($raw))];$cases[]=$c;$responses[$scenario]=['raw'=>$raw,'start'=>$start,'end'=>$end];$checkpoint();return $c;};
$success=static function(array $c)use($check):void{$check($c['http_status']===200&&($c['body']['status']??0)===200,'Actual business success '.$c['scenario']);};
$readRow=static function(string $module,string $family,string $key)use($query,$tenants,$qkey):array{return $query('SELECT * FROM yoshop_'.($family==='h5'?'h5_setting':'wxapp_setting').' WHERE '.$qkey.'=? AND store_id=?',[$key,$tenants[$module]]);};
$verify=static function(string $module,string $family,string $key,array $values,array $c)use($readRow,$check,$marker,$tenants,$runtime,&$owned,&$proofs,&$updateWindows,&$state):void{$r=$readRow($module,$family,$key);$check(count($r)===1,'Independent exact unique tuple');$row=$r[0];$table=$family==='h5'?'h5_setting':'wxapp_setting';$check($row['key']===$key&&(int)$row['store_id']===$tenants[$module]&&$row['describe']===($key==='basic'?'基础设置':'审核开关'),'Original key/store/describe');$check(is_string($row['values'])&&stripos($row['values'],$marker)!==false,'Owned actual JSON MEDIUMTEXT/CLOB marker');$check(strictWireEqual(json_decode($row['values']),json_decode(json_encode($values,JSON_UNESCAPED_UNICODE))),'Full actual persisted JSON values/types/containers');$epoch=(int)$row['update_time'];$check($epoch>=$c['window_start']-2&&$epoch<=$c['window_end']+2,'Actual original Unix update window');$owned[$table][(string)$tenants[$module]][$key]=true;$state['owned'][$table][(string)$tenants[$module]][$key]=true;file_put_contents($runtime.'/private-owned-map.json',json_encode($state));$updateWindows[$module][$table][$key]=[$c['window_start'],$c['window_end']];$proofs[]=['module'=>$module,'family'=>$family,'key'=>$key,'unique_tuple_rows'=>1,'all_five_original_columns_verified'=>true,'full_JSON_value_type_container_verified'=>true,'actual_Unix_window_verified'=>true];};
$write=static function(string $module,string $family,string $name,string $key,array $form,array $stored)use($request,$success,$verify,&$responses,&$expected):void{$c=$request($module,$family,$name,'update',$key,$form);$success($c);$c['window_start']=$responses[$c['scenario']]['start'];$c['window_end']=$responses[$c['scenario']]['end'];$verify($module,$family,$key,$stored,$c);$expected[$module][$family][$key]=$stored;};
$read=static function(string $module,string $family,string $name,string $key,array $want)use($request,$success,$check,&$responses,&$cases):void{$c=$request($module,$family,$name,'detail',$key);$success($c);$expectedData=['detail'=>$want];if($family==='wxapp')$expectedData['domain']=$module.'.client-settings.invalid';$check(strictWireEqual(json_decode($responses[$c['scenario']]['raw'])->data,json_decode(json_encode($expectedData,JSON_UNESCAPED_UNICODE))),'Full actual wire/source/default merge '.$c['scenario']);$cases[count($cases)-1]['complete_original_projection_equal']=true;};
$recoverOwned=static function(string $module)use($query,$tenants,$tables,$check,$marker,&$owned,&$proofs):void{foreach($tables as $table)foreach($query('SELECT * FROM yoshop_'.$table.' WHERE store_id=?',[$tenants[$module]]) as $r){$check(in_array($r['key'],$table==='h5_setting'?['basic']:['basic','examine'],true)&&is_string($r['values'])&&stripos($r['values'],$marker)!==false,'Only independently marker-verified error recovery tuples');$owned[$table][(string)$tenants[$module]][$r['key']]=true;}};
foreach($tenants as $module=>$tenant){$tag=$module==='store'?'S':'T';
    try{$initial=['enabled'=>false,'baseUrl'=>'https://'.strtolower($marker).'-'.$tag.'.invalid/initial/'];if(!($recovery&&$module==='store')){$c=$request($module,'h5','DEFAULT','detail','basic');$success($c);$write($module,'h5','CREATE','basic',$initial,$initial);}else{$expected[$module]['h5']['basic']=$initial;$proofs[]=['module'=>$module,'family'=>'h5','key'=>'basic','recovered_initial_original_row_independently_verified'=>true,'initial_raw_wire_lost_not_claimed'=>true];}$read($module,'h5','DETAIL_COLD','basic',$initial);$read($module,'h5','DETAIL_WARM','basic',$initial);$changed=['enabled'=>true,'baseUrl'=>'https://'.strtolower($marker).'-'.$tag.'.invalid/changed/'];$write($module,'h5','CHANGE','basic',$changed,$changed);$read($module,'h5','DETAIL_INVALIDATED','basic',$changed);$retained=['enabled'=>false,'baseUrl'=>'https://'.strtolower($marker).'-'.$tag.'.invalid/retained/'];$write($module,'h5','RETAIN_DISABLED','basic',$retained,$retained);$read($module,'h5','DETAIL_RETAINED','basic',$retained);}catch(Throwable $e){$errors[]=['module'=>$module,'family'=>'h5','class'=>get_class($e),'message'=>$e->getMessage()];$recoverOwned($module);}
    try{$c=$request($module,'wxapp','DEFAULT','detail','basic');$success($c);$initial=['enabled'=>false,'app_id'=>'NOT_A_REAL_APPID_'.$marker.'_'.$tag,'app_secret'=>'NOT_A_REAL_SECRET_'.$marker.'_'.$tag];$write($module,'wxapp','CREATE','basic',$initial,$initial);$read($module,'wxapp','DETAIL_COLD','basic',$initial);$read($module,'wxapp','DETAIL_WARM','basic',$initial);$changed=$initial;$changed['app_id']='NOT_A_REAL_APPID_'.$marker.'_'.$tag.'_CHANGED';$write($module,'wxapp','PARTIAL_CHANGE','basic',['app_id'=>$changed['app_id'],'IGNORED_FIELD'=>'must_not_persist'],$changed);$read($module,'wxapp','DETAIL_PARTIAL_INVALIDATED','basic',$changed);$retained=$changed;$retained['app_secret']='NOT_A_REAL_SECRET_'.$marker.'_'.$tag.'_RETAINED';$write($module,'wxapp','RETAIN_DISABLED','basic',['enabled'=>false,'app_secret'=>$retained['app_secret']],$retained);$read($module,'wxapp','DETAIL_RETAINED','basic',$retained);
        $examine=['switch'=>0,'version'=>$marker.'_VERSION','versions'=>[$marker.'_1',$marker."_中文'2\\"],'platforms'=>['MP-WEIXIN','APP-PLUS'],'expire_time'=>0,'trial_show_info'=>0,'aifaceview'=>'','aifaceset'=>'','apifacedefault'=>'','withdrawRecord'=>'','details'=>'','recharge'=>'','orderDetail'=>''];$form=['switch'=>0,'version'=>$examine['version'],'versions'=>$examine['versions'],'platforms'=>$examine['platforms'],'IGNORED_FIELD'=>'must_not_persist'];$write($module,'wxapp','EXAMINE_CREATE','examine',$form,$examine);$read($module,'wxapp','EXAMINE_DETAIL','examine',$examine);$examine['versions']=[$marker.'_3'];$examine['platforms']=[];$write($module,'wxapp','EXAMINE_ARRAY_REPLACE','examine',['versions'=>$examine['versions'],'platforms'=>[]],$examine);$read($module,'wxapp','EXAMINE_DETAIL_REPLACED','examine',$examine);$beforeBad=$readRow($module,'wxapp','examine');$c=$request($module,'wxapp','INVALID_KEY_REFUSAL','update',$marker.'_UNKNOWN',['switch'=>0]);$check($c['http_status']===200&&$c['body']['status']===500&&$c['body']['message']==='不支持的设置项','Original invalid WX key refusal');$check($readRow($module,'wxapp','examine')===$beforeBad,'Invalid key original row unchanged');
    }catch(Throwable $e){$errors[]=['module'=>$module,'family'=>'wxapp','class'=>get_class($e),'message'=>$e->getMessage()];$recoverOwned($module);}
}
// A complete rejected run legitimately has no successful-DML listener file.
// Preserve the real HTTP errors instead of masking them with a file() warning.
foreach(['queries.jsonl','write-audit.jsonl'] as $optional)if(!is_file($runtime.'/'.$optional))touch($runtime.'/'.$optional);
$tokensGone=true;foreach($tokens as $token){$cache->delete($token);$tokensGone=$tokensGone&&$cache->get($token)===null;}$cache->clear();$cacheFiles=0;if(is_dir($runtime.'/cache/'))foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($runtime.'/cache/',FilesystemIterator::SKIP_DOTS)) as $f)if($f->isFile())$cacheFiles++;
$after=$snapshot();$private=['lane'=>$lane,'marker'=>$marker,'tenants'=>$tenants,'owned_unique_tuples'=>$owned,'expected_values'=>$expected,'update_windows'=>$updateWindows,'cases'=>$cases,'responses'=>$responses,'before'=>$before,'after'=>$after];file_put_contents($runtime.'/private-retention.json',json_encode($private,JSON_PRETTY_PRINT|JSON_PRESERVE_ZERO_FRACTION|JSON_UNESCAPED_UNICODE));chmod($runtime.'/private-retention.json',0600);
foreach($cases as &$c){$trace=$c['body']['trace_id']??null;$c['trace_format_valid']=is_string($trace)&&preg_match('/^[0-9a-f]{13}$/D',$trace)===1;if($c['trace_format_valid'])$c['body']['trace_id']='VALID_DYNAMIC_TRACE';if($c['body']['status']===500&&substr($c['scenario'],-strlen('INVALID_KEY_REFUSAL'))!=='INVALID_KEY_REFUSAL'){$c['private_unexpected_error_sha256']=hash('sha256',$c['body']['message']);$c['body']['message']='UNEXPECTED_ERROR_FULL_RAW_PRIVATE';}}unset($c);
$events=[];foreach(file($runtime.'/queries.jsonl',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[] as $l)$events[]=json_decode($l,true);$audit=[];foreach(file($runtime.'/write-audit.jsonl',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[] as $l)$audit[]=json_decode($l,true);$fresh=$connect();$counts=[];foreach($tables as $t){$s=$fresh->prepare('SELECT COUNT(*) FROM yoshop_'.$t.' WHERE store_id IN (?,?)');$s->execute(array_values($tenants));$counts[$t]=(int)$s->fetchColumn();}$report=['lane'=>$lane,'cases'=>$cases,'original_proofs'=>$proofs,'errors'=>$errors,'retention'=>['mode'=>'retained-owned','fresh_counts'=>$counts,'natural_two_table_full_sha_unchanged'=>$before===$after,'exact_owned_composite_tuples_only'=>true],'resources'=>['tokens_absent'=>$tokensGone,'cache_files'=>$cacheFiles],'events'=>$events,'write_audit'=>$audit,'loaded_boundary'=>$boundary];file_put_contents($runtime.'/report.json',json_encode($report,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));echo json_encode(['lane'=>$lane,'http_cases'=>count($cases),'errors'=>$errors,'retained'=>$counts,'natural_sha_unchanged'=>$before===$after,'report'=>$runtime.'/report.json']),"\n";exit(count($errors)||$before!==$after||!$tokensGone||$cacheFiles||in_array(false,array_column($audit,'owned_scope_verified'),true)?1:0);
