<?php
declare(strict_types=1);
require __DIR__.'/bootstrap.php';
if(($argv[1]??'')==='audit'){echo json_encode(['lane'=>$lane,'retained_owned_counts'=>$counts(),'physical_cleanup_requested'=>false]),"\n";exit;}
$extended=($argv[1]??'')==='extend';$resume=in_array($argv[1]??'',['resume','extend'],true);$saved=$resume?json_decode((string)file_get_contents($runtime.'/private-retention.json'),true):null;
if($resume){$check(($saved['marker']??'')===$marker&&($saved['tenant']??0)===$tenant&&($saved['lane']??'')===$lane,'Exact retained context');$before=$saved['before'];$outputBefore=$saved['output_before'];$ownedIds=$saved['owned_primary_keys'];}
else{$check(array_sum($counts())===0,'New owned tenant collision');$before=$snapshot();$outputBefore=[];foreach(['meal_recommend','meal_recommend_history'] as $t)$outputBefore[$t]=(int)$query('SELECT COUNT(*) n FROM yoshop_'.$t)[0]['n'];}
$boundary=json_decode((string)file_get_contents($base.'/__poc_boundary'),true);$check(($boundary['publisher_capture_mode']??'')==='OWN_WEIGHT_STAFF_POWER_PUBLICATION_ONLY_V1'&&($boundary['weight_model_sha']??'')==='a088d81d1fdebb902d5c52de882f0820efe8021ba70b43c2e436a945b6d93958','Actual boundary/source');
$root=(string)getenv('CATEGORY_ROOT');define('TP_ENV','poc');define('BUSINESS','aizhct');define('ENTERPRISE_NO','10001');require $root.'/vendor/autoload.php';
spl_autoload_register(static function(string $class)use($root):void{foreach(['app\\'=>'app/','cores\\'=>'cores/'] as $prefix=>$dir){if(strpos($class,$prefix)!==0)continue;$file=$root.'/'.$dir.str_replace('\\','/',substr($class,strlen($prefix))).'.php';if(is_file($file))require $file;}},true,true);
require __DIR__.'/external_boundary.php';require __DIR__.'/SqlCoverageRecorder.php';require __DIR__.'/DbWriteAudit.php';
$app=new \think\App($root);$app->setEnvName('poc');$app->setRuntimePath($runtime.'/fixture-runtime/');$app->initialize();\think\App::$store_id=$tenant;
$cfg=$app->config->get('database');foreach($cfg['connections'] as &$c){$c['trigger_sql']=true;$c['debug']=false;}unset($c);$app->config->set($cfg,'database');$app->db->setConfig($app->config);
$log=$app->config->get('log');$log['close']=true;foreach($log['channels'] as &$c)$c['close']=true;unset($c);$app->config->set($log,'log');
$cache=new \think\cache\driver\File($app,['path'=>$runtime.'/cache/','prefix'=>'','expire'=>0]);$token=bin2hex(random_bytes(24));$cache->set($token,['user'=>['store_user_id'=>$tenant,'store_id'=>$tenant,'real_name'=>$marker,'user_name'=>$marker,'is_super'=>1],'store_id'=>$tenant,'is_login'=>true],1800);
if(!$resume)foreach(['queries.jsonl','write-audit.jsonl','private-dml-audit-sql.jsonl','publish-captures.jsonl','robot-captures.jsonl'] as $f)file_put_contents($runtime.'/'.$f,'');
$audit=new DbWriteAudit($runtime);$activeRecorder=null;$app->db->listen(static function($sql,$ms=null)use($audit,&$activeRecorder){$audit->observe($sql);if($activeRecorder!==null&&strpos((string)$sql,'CONNECT:')!==0)$activeRecorder->observe($sql,$ms);});
$uid=0;$sid=0;$map=[];$cases=[];$jobs=[];$original=[];$responses=[];$boundaries=[];$error=null;$started=time();$historyPrefix=[];$date=date('Y-m-d');
if($resume){$uid=(int)$saved['user_id'];$sid=(int)$saved['staff_id'];$map=json_decode((string)file_get_contents($runtime.'/private-owned-map.json'),true);$cases=$saved['actual_cases'];$jobs=$saved['actual_jobs'];$original=$saved['actual_original'];$responses=$saved['responses'];$historyPrefix=$saved['history_prefix'];$started=$saved['started'];$check($saved['date']===$date,'Resume same calendar day required');}
$round=static function($v):string{$v=(string)$v;return bcadd(bcadd($v,bccomp($v,'0',12)<0?'-0.005':'0.005',12),'0',2);};
$insert=static function(string $table,array $data)use($db,$query,$check,$tenant,$marker,&$ownedIds):int{
    $check(in_array($table,['user','staff'],true)&&$data['store_id']===$tenant,'Fixture frozen input');$s=$db->prepare('INSERT INTO yoshop_'.$table.' ('.implode(',',array_keys($data)).') VALUES ('.implode(',',array_fill(0,count($data),'?')).')');$s->execute(array_values($data));
    $pk=$table==='user'?'user_id':'id';$name=$table==='user'?'nick_name':'name';$rows=$query('SELECT '.$pk.' FROM yoshop_'.$table.' WHERE '.$name.'=? AND store_id=?',[$data[$name],$tenant]);$check(count($rows)===1&&(int)$rows[0][$pk]>0,'Owned fixture PK');$id=(int)$rows[0][$pk];$ownedIds[$table][]=$id;return $id;};
$shape=static function($v)use(&$shape){if(is_object($v)){$o=[];foreach(get_object_vars($v) as $k=>$x)$o[$k]=$shape($x);ksort($o);return ['object'=>$o];}if(is_array($v))return ['array'=>array_map($shape,$v)];return gettype($v);};
$request=static function(string $name,string $action,array $body=[],bool $queryId=false)use($base,$token,$check,$shape,&$responses,&$cases):array{$scenario='PILOT_WT_'.$name;$url=$base.'/store/weight.StaffWeight/'.$action;if($queryId){$url.='?'.http_build_query($body);$body=[];}
    $h="Host: store.staff-weight.invalid\r\nAccess-Token: ".$token."\r\nPlatform: POC\r\nContent-Type: application/json\r\nX-Pilot-Scenario: ".$scenario."\r\n";
    $raw=file_get_contents($url,false,stream_context_create(['http'=>['method'=>'POST','header'=>$h,'content'=>json_encode($body,JSON_UNESCAPED_UNICODE),'timeout'=>30,'ignore_errors'=>true]]));$check(is_string($raw)&&strlen($raw)<1048576,'Weight HTTP');$json=json_decode($raw,true);$check(is_array($json),'Weight JSON');preg_match('#^HTTP/\S+\s+(\d+)#',$http_response_header[0]??'',$m);$responses[$scenario]=$raw;
    $case=['scenario'=>$scenario,'method'=>'POST','path'=>'/store/weight.StaffWeight/'.$action,'query_id'=>$queryId,'http_status'=>(int)($m[1]??0),'body'=>$json,'raw_json_shape'=>$shape(json_decode($raw))];$cases[]=$case;return $case;};
$success=static function(array $c)use($check){$check($c['http_status']===200&&($c['body']['status']??0)===200,'Business failure '.$c['scenario']);};
$readFixtureIds=[];
$projectWeight=static function(array $row)use($check,$started,&$readFixtureIds):array{$out=$row;foreach($out as $k=>&$v){if(in_array($k,['id','staff_id','weight_status','store_id','is_delete'],true))$v=(int)$v;
    elseif(in_array($k,['height','weight','body_fat_rate','bmi','energy_value'],true))$v=bcadd((string)$v,'0',2);
    elseif(in_array($k,['create_time','update_time'],true)){$check(in_array((int)$row['id'],$readFixtureIds,true)||(strtotime((string)$v)>=$started-2&&strtotime((string)$v)<=time()+2),'Weight auto datetime window');$v=date('Y-m-d H:i:s',strtotime((string)$v));}}unset($v);return $out;};
$deep=static function($a,$b,string $path='$')use(&$deep,$check){if(is_array($b)){$check(is_array($a),'Container '.$path);$ak=array_keys($a);$bk=array_keys($b);sort($ak);sort($bk);$check($ak===$bk,'Full fields '.$path);foreach($b as $k=>$v)$deep($a[$k],$v,$path.'.'.$k);}else $check($a===$b,'Value/type '.$path.' actual='.json_encode($a).' expected='.json_encode($b));};
$saveMap=static function()use($runtime,&$map){file_put_contents($runtime.'/private-owned-map.json',json_encode($map));chmod($runtime.'/private-owned-map.json',0600);};
$checkWeight=static function(int $id,array $wanted)use($query,$check,$projectWeight,$date,$tenant,$marker,&$sid,&$ownedIds,&$map,$saveMap,&$original):array{
    $rows=$query('SELECT * FROM yoshop_staff_weight WHERE id=? AND staff_id=? AND store_id=?',[$id,$sid,$tenant]);$check(count($rows)===1&&$rows[0]['create_by']===$marker,'Original weight owner');$p=$projectWeight($rows[0]);foreach($wanted as $k=>$v)$check($p[$k]===$v,'Original weight '.$k);$check($p['set_date']===$date,'Model forces today');
    if(!in_array($id,$ownedIds['staff_weight']??[],true))$ownedIds['staff_weight'][]=$id;$map['weight_ids']=$ownedIds['staff_weight'];$saveMap();$original[]=['kind'=>'weight','values'=>$p,'all_input_values_verified'=>true];return $rows[0];};
$checkStaff=static function(string $height,string $weight)use($query,$check,$tenant,$marker,&$sid,&$uid,&$original):array{
    $rows=$query('SELECT * FROM yoshop_staff WHERE id=? AND store_id=? AND user_id=? AND name=? AND create_by=?',[$sid,$tenant,$uid,$marker.'_STAFF',$marker]);$check(count($rows)===1,'Positive staff/user owner');$r=$rows[0];$check(bcadd((string)$r['height'],'0',2)===$height&&bcadd((string)$r['weight'],'0',2)===$weight&&(int)$r['is_delete']===0,'Real Staff physical update');$original[]=['kind'=>'staff','height'=>$height,'weight'=>$weight,'is_delete'=>0,'positive_owned_user_verified'=>true];return $r;};
$expected=static function(string $height,string $weight)use($query,$check,$round,$tenant,$date):array{
    $age=(int)date('Y')-1990;$check($age>30&&$age<60,'Stable source age bracket');$ree=bcmul(bcadd(bcmul('11.472',$weight,12),'873.1',12),'0.95',12);$power=$round(bcmul($ree,'1.45',12));
    $out=['staff_id'=>0,'meal_date'=>$date,'gender'=>1,'birthday'=>'1990-01-01','height'=>$height,'weight'=>$weight,'staff_type'=>1,'sport_id'=>0,'sport_event_id'=>0,'age'=>$age,
        'ree'=>$round($ree),'habit'=>2,'habit_ratio'=>'1.45','consume_power'=>$power,'weight_status'=>1,'energy_value'=>'300.00','recommend_energy'=>'-1.00','recommend_power'=>$power,
        'bm'=>'0.00','bmr'=>'0.00','food_hot'=>'0.00','night_expend'=>'0.00','daily_consume'=>'0.00','active_power'=>'0.00','active_time'=>0,'recommend_ratio'=>'0.00',
        'dietary_fiber'=>'25.00','store_id'=>$tenant,'is_delete'=>0,'create_by'=>'system'];
    foreach(['carbohydrate'=>['0.55',4],'protein'=>['0.20',4],'fat'=>['0.25',9]] as $n=>$v){$p=bcmul($power,$v[0],12);$w=bcdiv($p,(string)$v[1],12);$out[$n.'_ratio']=$v[0];$out['recommend_'.$n.'_power']=$round($p);$out['recommend_'.$n.'_weight']=$round($w);
        foreach(['morning'=>'0.30','noon'=>'0.40','night'=>'0.30'] as $meal=>$ratio)$out[$meal.'_'.$n.'_weight']=$round(bcmul($w,$ratio,12));}
    foreach(['morning'=>'0.30','noon'=>'0.40','night'=>'0.30'] as $meal=>$ratio){$out[$meal.'_ratio']=$ratio;$out[$meal.'_power']=$round(bcmul($power,$ratio,12));}
    $vm=$query('SELECT * FROM yoshop_general_vm WHERE gender=1 AND start_age<=? AND end_age>=?',[$age,$age]);$check(count($vm)===1,'GeneralVm unique');foreach(['va','vb1','vb2','vpp','vc','ve','potassium','sodium','calcium','magnesium','iron','zinc'] as $k)$out[$k]=bcadd((string)$vm[0][$k],'0',2);return $out;
};
$job=static function(string $name,string $height,string $weight,bool $execute=true)use($runtime,$root,$app,$check,$expected,$query,$tenant,$date,$saveMap,$gate,$dm,&$sid,&$map,&$ownedIds,&$activeRecorder,&$jobs,&$original,&$historyPrefix):void{
    $published=file($runtime.'/publish-captures.jsonl',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[];$check(count($published)===count($jobs)+1,'Each successful write exactly one publication');$payload=json_decode(end($published),true);$check($payload['action']==='staffPower','Job action');
    if($execute){$activeRecorder=new SqlCoverageRecorder($runtime.'/queries.jsonl',$root,'PILOT_WT_JOB_'.$name);ob_start();try{$ok=(new \app\timer\service\Serve)->doJob($payload);}finally{$raw=ob_get_clean();$activeRecorder->finish();$activeRecorder=null;file_put_contents($runtime.'/private-job-'.$name.'.log',$raw);}$check($ok===true,'Job return (not proof alone)');}
    $rows=$query('SELECT * FROM yoshop_meal_recommend WHERE staff_id=? AND store_id=? AND meal_date=? ORDER BY id',[$sid,$tenant,$date]);$hist=$query('SELECT * FROM yoshop_meal_recommend_history WHERE staff_id=? AND store_id=? AND meal_date=? ORDER BY id',[$sid,$tenant,$date]);$check(count($rows)===1&&count($hist)===count($jobs)+1,'Real recommendation/history committed increment');
    // The retained private state crosses a JSON boundary. PDO_DM 0.0 versus
    // JSON-decoded 0 must not become a false historical-row mutation; compare
    // only actual DECIMAL/INTEGER columns at metadata-defined physical type.
    $physicalHistory=static function(array $list)use($gate,$dm):array{foreach($list as &$r)foreach($gate['metadata']['meal_recommend_history']['columns'] as $c){$k=strtolower($c['column_name']);$t=strtolower($c['data_type']);if($t==='decimal')$r[$k]=bcadd((string)$r[$k],'0',(int)($dm?$c['data_scale']:$c['numeric_scale']));elseif(strpos($t,'int')!==false)$r[$k]=(int)$r[$k];}unset($r);return $list;};
    $check($physicalHistory(array_slice($hist,0,count($historyPrefix)))===$physicalHistory($historyPrefix),'Prior history physical full prefix');$historyPrefix=$hist;$want=$expected($height,$weight);$want['staff_id']=$sid;$keys=array_keys($rows[0]);$keys=array_values(array_diff($keys,['id','create_time','update_time']));$wkeys=array_keys($want);sort($keys);sort($wkeys);$check($keys===$wkeys,'Full recommendation original fields');
    $normalized=[];foreach($want as $k=>$v){$convert=static function($a,$v){return is_int($v)?(int)$a:(is_string($v)&&preg_match('/^-?[0-9]+\.[0-9]{2}$/D',$v)?bcadd((string)$a,'0',2):$a);};$actual=$convert($rows[0][$k],$v);$check($actual===$v&&$convert($hist[count($hist)-1][$k],$v)===$v,'Independent recommend decimal/value '.$k);$normalized[$k]=$actual;}
    $rid=(int)$rows[0]['id'];if(isset($map['current_ids'][0]))$check($map['current_ids'][0]===$rid,'Current PK stable');$map['current_ids']=[$rid];$ownedIds['meal_recommend']=[$rid];$ownedIds['meal_recommend_history']=array_map('intval',array_column($hist,'id'));$saveMap();
    $jobs[]=['scenario'=>$name,'real_serve_service'=>true,'current_rows'=>1,'history_rows'=>count($hist),'prior_history_unchanged'=>true,'full_independent_recommend_values'=>$normalized,'http_count'=>0];
};
try{
    if(!$resume){$uid=$insert('user',['nick_name'=>$marker.'_USER','store_id'=>$tenant]);
        $sid=$insert('staff',['name'=>$marker.'_STAFF','gender'=>1,'birthday'=>'1990-01-01','height'=>'170.00','weight'=>'60.00','staff_type'=>1,'user_id'=>$uid,'store_id'=>$tenant,'create_by'=>$marker]);$map=['staff_id'=>$sid,'user_id'=>$uid,'tenant'=>$tenant,'weight_ids'=>[],'current_ids'=>[]];$saveMap();$checkStaff('170.00','60.00');}
    $u=$query('SELECT * FROM yoshop_user WHERE user_id=? AND store_id=? AND nick_name=?',[$uid,$tenant,$marker.'_USER']);$check(count($u)===1,'Owned user');foreach($u[0] as $k=>$v)if(strpos($k,'balance')!==false||in_array($k,['points','pay_money','expend_money'],true))$check((float)$v===0.0,'User all money zero');
    $form=['staff_id'=>$sid,'height'=>'171.25','weight'=>'61.25','body_fat_rate'=>'18.25','weight_status'=>1,'energy_value'=>'999.99','set_date'=>'2030-03-02'];
    if(!$extended){
    $case=$resume?$cases[0]:$request('ADD_FIRST','add',['form'=>$form]);$success($case);$returned=$case['body']['data']['id']??null;$check(is_string($returned)&&preg_match('/^[1-9][0-9]*$/D',$returned)===1,'Original generated weight ID positive decimal string');$id=(int)$returned;
    $checkWeight($id,['height'=>'171.25','weight'=>'61.25','body_fat_rate'=>'18.25','weight_status'=>1,'energy_value'=>'0.00','bmi'=>'20.76','is_delete'=>0]);$checkStaff('171.25','61.25');
    $detail=$request('DETAIL_FIRST_QUERY','detail',['id'=>$id],true);$success($detail);$row=$query('SELECT * FROM yoshop_staff_weight WHERE id=? AND staff_id=? AND store_id=?',[$id,$sid,$tenant]);$deep($detail['body']['data'],['detail'=>$projectWeight($row[0])]);$cases[count($cases)-1]['full_original_projection_equal']=true;
    $job('ADD_FIRST','171.25','61.25');
    }else{
        $check(count($jobs)===1&&in_array(count($cases),[2,3],true),'Frozen initial green or exact partial duplicate required');$id=(int)$saved['first_weight_id'];
        $detailRead=static function(string $name,int $rid)use($request,$success,$query,$deep,$projectWeight,$tenant,&$sid,&$cases):void{
            $case=$request($name,'detail',['id'=>$rid],true);$success($case);$r=$query('SELECT * FROM yoshop_staff_weight WHERE id=? AND staff_id=? AND store_id=? AND is_delete=0',[$rid,$sid,$tenant]);$deep($case['body']['data'],['detail'=>$r?$projectWeight($r[0]):null]);$cases[count($cases)-1]['full_original_projection_equal']=true;};
        $read=static function(string $name,string $action,array $args=[])use($request,$success,$query,$deep,$projectWeight,$tenant,&$sid,&$cases):void{
            $param=array_merge(['staff_id'=>$sid,'page_size'=>10,'page'=>1],$args);$case=$request($name,$action,$param);$success($case);$where='staff_id=? AND store_id=? AND is_delete=0';$vals=[$sid,$tenant];
            if(!empty($args['start_date'])){$where.=' AND set_date>=?';$vals[]=$args['start_date'];}if(!empty($args['end_date'])){$where.=' AND set_date<=?';$vals[]=$args['end_date'];}
            $rows=$query('SELECT * FROM yoshop_staff_weight WHERE '.$where.' ORDER BY create_time DESC',$vals);$expected=[];foreach($rows as $r){$p=$projectWeight($r);$expected[]=$action==='echartsList'?array_intersect_key($p,array_flip(['id','height','weight','body_fat_rate','set_date'])):$p;}
            if($action==='list'){$last=(int)ceil(count($rows)/10);$page=(int)$param['page'];$expected=['total'=>count($rows),'per_page'=>10,'current_page'=>$page>$last?($last?:1):$page,'last_page'=>$last,'data'=>array_slice($expected,($page-1)*10,10)];}
            $deep($case['body']['data'],['list'=>$expected]);$cases[count($cases)-1]['full_original_projection_equal']=true;$cases[count($cases)-1]['returned_rows']=count($rows);
        };
        // Cross a physical second before each add: create_time-only ordering has
        // no tie-breaker, and MySQL DATETIME(0) differs from DM DATETIME(6).
        $recover=count($cases)===3;
        if($recover){$case=$cases[2];$check($case['scenario']==='PILOT_WT_ADD_DUPLICATE_SAME_INPUT','Only exact partial duplicate recovery');}
        else{usleep(1100000);$case=$request('ADD_DUPLICATE_SAME_INPUT','add',['form'=>$form]);}
        $success($case);$new=$case['body']['data']['id']??null;$check(is_string($new)&&preg_match('/^[1-9][0-9]*$/D',$new),'Duplicate generated ID contract');$dup=(int)$new;$check($dup!==$id,'Original duplicate creates new PK');
        $checkWeight($dup,['height'=>'171.25','weight'=>'61.25','body_fat_rate'=>'18.25','weight_status'=>1,'energy_value'=>'0.00','bmi'=>'20.89','is_delete'=>0]);$checkStaff('171.25','61.25');$job('DUPLICATE_ADD','171.25','61.25',!$recover);
        usleep(1100000);$high=$form;$high['height']='172.125';$high['weight']='62.375';$high['body_fat_rate']='18.555';$high['weight_status']=2;$high['energy_value']='300.125';
        $case=$request('ADD_SCALE_BOUNDARY','add',['form'=>$high]);$success($case);$new=$case['body']['data']['id']??null;$check(is_string($new)&&preg_match('/^[1-9][0-9]*$/D',$new),'Scale add ID contract');$latest=(int)$new;
        $checkWeight($latest,['height'=>'172.13','weight'=>'62.38','body_fat_rate'=>'18.56','weight_status'=>2,'energy_value'=>'300.13','bmi'=>'20.89','is_delete'=>0]);$checkStaff('172.13','62.38');$job('SCALE_ADD','172.13','62.38');$detailRead('DETAIL_SCALE',$latest);$read('LIST_THREE_CURRENT','list');$read('CHART_THREE_CURRENT','echartsList');
        $older=$form;$older['height']='180.00';$older['weight']='70.00';$older['body_fat_rate']='20.00';$older['weight_status']=2;$older['energy_value']='350.125';
        $case=$request('EDIT_OLDER_NOT_STAFF','edit',['id'=>$id,'form'=>$older]);$success($case);$checkWeight($id,['height'=>'180.00','weight'=>'70.00','body_fat_rate'=>'20.00','weight_status'=>2,'energy_value'=>'350.13','bmi'=>'20.76','is_delete'=>0]);$checkStaff('172.13','62.38');$job('EDIT_OLDER','172.13','62.38');$detailRead('DETAIL_OLDER_BMI_PRESERVED',$id);
        $last=$high;$last['height']='175.125';$last['weight']='65.675';$last['body_fat_rate']='17.125';$last['weight_status']=1;$last['energy_value']='999.99';
        $case=$request('EDIT_LATEST_STAFF_SYNC','edit',['id'=>$latest,'form'=>$last]);$success($case);$checkWeight($latest,['height'=>'175.13','weight'=>'65.68','body_fat_rate'=>'17.13','weight_status'=>1,'energy_value'=>'0.00','bmi'=>'20.89','is_delete'=>0]);$checkStaff('175.13','65.68');$job('EDIT_LATEST','175.13','65.68');$detailRead('DETAIL_LATEST',$latest);
        foreach([['LATEST',$latest,'171.25','61.25'],['OLDER',$id,'171.25','61.25'],['LAST_ACTIVE',$dup,'0.00','0.00']] as $step){$case=$request('DELETE_'.$step[0],'delete',['id'=>$step[1]]);$success($case);$checkWeight($step[1],['is_delete'=>1]);$checkStaff($step[2],$step[3]);$job('DELETE_'.$step[0],$step[2],$step[3]);}
        $hBefore=count($historyPrefix);$pubBefore=count(file($runtime.'/publish-captures.jsonl',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[]);
        $case=$request('REPEAT_DELETE_REFUSAL','delete',['id'=>$dup]);$check($case['http_status']===200&&$case['body']['status']===500&&$case['body']['message']==='数据不存在','Repeat delete original refusal');$check(count(file($runtime.'/publish-captures.jsonl',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[])===$pubBefore,'Failed delete published');$check((int)$query('SELECT COUNT(*) n FROM yoshop_meal_recommend_history WHERE staff_id=? AND store_id=?',[$sid,$tenant])[0]['n']===$hBefore,'Failed delete history changed');
        $detailRead('DETAIL_SOFT_DELETED_NULL',$dup);$read('LIST_AFTER_SOFT_DELETE','list');
        $case=$request('ALL_SHARED_MISSING_NAME','all',[]);array_pop($cases);$boundaries[]=['scenario'=>$case['scenario'],'method'=>'POST','path'=>$case['path'],'http_status'=>$case['http_status'],'business_status'=>$case['body']['status']??null,'classification'=>'shared-original-schema-contract-error-not-positive','missing_name_column_confirmed'=>true,'message_sha256'=>hash('sha256',(string)($case['body']['message']??''))];
        $check(($case['body']['status']??200)!==200,'All absent name cannot count success');
        foreach(['2030-03-02','2030-03-03','2030-03-04'] as $index=>$readDate){$s=$db->prepare('INSERT INTO yoshop_staff_weight (staff_id,height,weight,body_fat_rate,weight_status,bmi,energy_value,set_date,store_id,is_delete,create_by,create_time,update_time) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');$s->execute([$sid,'175.00',(string)(66+$index).'.00','19.00',1,'21.55','0.00',$readDate,$tenant,0,$marker.'_READ',$readDate.' 08:00:00',$readDate.' 08:00:00']);
            $r=$query('SELECT id FROM yoshop_staff_weight WHERE staff_id=? AND store_id=? AND set_date=? AND create_by=?',[$sid,$tenant,$readDate,$marker.'_READ']);$check(count($r)===1&&(int)$r[0]['id']>0,'Own three-day read fixture');$rid=(int)$r[0]['id'];$ownedIds['staff_weight'][]=$rid;$readFixtureIds[]=$rid;$map['weight_ids']=$ownedIds['staff_weight'];$saveMap();}
        $read('LIST_BETWEEN_THREE_DAYS','list',['start_date'=>'2030-03-02','end_date'=>'2030-03-04']);$read('CHART_BETWEEN_THREE_DAYS','echartsList',['start_date'=>'2030-03-02','end_date'=>'2030-03-04']);
        $read('LIST_LOWER_BOUND','list',['start_date'=>'2030-03-03']);$read('CHART_UPPER_BOUND','echartsList',['end_date'=>'2030-03-03']);$checkStaff('0.00','0.00');
    }
}catch(Throwable $caught){$error=['class'=>get_class($caught),'message'=>$caught->getMessage(),'file'=>basename($caught->getFile()),'line'=>$caught->getLine()];}
// Retained-owned: never physically delete these approved synthetic business rows.
$cache->delete($token);$cache->clear();$tokenAbsent=$cache->get($token)===null;$cacheFiles=0;if(is_dir($runtime.'/cache/'))foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($runtime.'/cache/',FilesystemIterator::SKIP_DOTS)) as $f)if($f->isFile())$cacheFiles++;
$fresh=$connect();$retained=[];foreach($tables as $table){$s=$fresh->prepare('SELECT COUNT(*) FROM yoshop_'.$table.' WHERE store_id=?');$s->execute([$tenant]);$retained[$table]=(int)$s->fetchColumn();}
$after=$snapshot();$naturalEqual=$before===$after;$outputAfter=[];foreach(['meal_recommend','meal_recommend_history'] as $t)$outputAfter[$t]=(int)$query('SELECT COUNT(*) n FROM yoshop_'.$t)[0]['n'];
$events=[];foreach(file($runtime.'/queries.jsonl',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[] as $line)$events[]=json_decode($line,true);$writeAudit=[];foreach(file($runtime.'/write-audit.jsonl',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[] as $line)$writeAudit[]=json_decode($line,true);
$published=[];foreach(file($runtime.'/publish-captures.jsonl',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[] as $line)$published[]=json_decode($line,true);$robots=[];foreach(file($runtime.'/robot-captures.jsonl',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[] as $line)$robots[]=json_decode($line,true);
$private=['lane'=>$lane,'marker'=>$marker,'tenant'=>$tenant,'user_id'=>$uid,'staff_id'=>$sid,'owned_primary_keys'=>$ownedIds,'date'=>$date,'first_weight_id'=>$id??0,'before'=>$before,'output_before'=>$outputBefore,'started'=>$started,'actual_cases'=>$cases,'actual_original'=>$original,'actual_jobs'=>$jobs,'responses'=>$responses,'history_prefix'=>$historyPrefix];
file_put_contents($runtime.'/private-retention.json',json_encode($private,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_PRESERVE_ZERO_FRACTION));chmod($runtime.'/private-retention.json',0600);
$normalize=static function($v)use(&$normalize,$ownedIds,$sid,$uid){if(!is_array($v))return $v;foreach($v as $k=>&$x){if($k==='staff_id'&&$x===$sid)$x=1;elseif($k==='user_id'&&$x===$uid)$x=1;elseif($k==='id'&&(is_int($x)||(is_string($x)&&preg_match('/^[1-9][0-9]*$/D',$x)))&&in_array((int)$x,$ownedIds['staff_weight']??[],true)){$i=array_search((int)$x,$ownedIds['staff_weight'],true)+1;$x=is_string($x)?(string)$i:$i;}elseif(in_array($k,['create_time','update_time'],true)&&is_string($x))$x='INDEPENDENTLY_VERIFIED_DYNAMIC_TIME';else $x=$normalize($x);}unset($x);return $v;};
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';}unset($c);
$report=['lane'=>$lane,'phase'=>$extended?'extended-crud-real-job-and-read-regression':'initial-add-detail-real-job','marker'=>$marker,'tenant'=>$tenant,'cases'=>$normalize($cases),'boundary_findings'=>$boundaries,'original_proofs'=>$normalize($original),'jobs'=>$normalize($jobs),'published_count'=>count($published),'robot_count'=>count($robots),
    'retention'=>['mode'=>'retained-owned','fresh_pdo_counts'=>$retained,'exact_owned_pk_exclusions_only'=>true,'natural_small_table_sha_unchanged'=>$naturalEqual,'large_output_full_sha'=>false,'large_output_before'=>$outputBefore,'large_output_after'=>$outputAfter],
    'resource_cleanup'=>['token_absent'=>$tokenAbsent,'private_cache_files'=>$cacheFiles],'error'=>$error,'write_audit'=>$writeAudit,'events'=>$events,'scan_metrics'=>$scanMetrics,'loaded_boundary'=>$boundary];
file_put_contents($runtime.'/report.json',json_encode($report,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
echo json_encode(['lane'=>$lane,'phase'=>$report['phase'],'http_cases'=>count($cases),'real_jobs'=>count($jobs),'retained_owned_counts'=>$retained,'natural_small_table_sha_unchanged'=>$naturalEqual,'token_absent'=>$tokenAbsent,'cache_files'=>$cacheFiles,'error'=>$error,'report'=>$runtime.'/report.json']),"\n";
exit($error!==null||!$naturalEqual||!$tokenAbsent||$cacheFiles!==0||in_array(false,array_column($writeAudit,'owned_scope_verified'),true)?1:0);
