<?php
require __DIR__.'/common-write.php';$step=(int)getenv('NW_STEP');$check($step>=1&&$step<=11,'Known authorized step');$state=json_decode(file_get_contents(__DIR__.'/private-state.json'),true);$check($state['step']===$step-1,'Strict step order/no replay');$check(!is_file(__DIR__.'/private-sent-'.$step),'Unsent case only');$case=cdxCase($step,$state['ids']);$now=$source();$guard($now);if($step>1){if($lane==='B'&&$step===2&&is_file(__DIR__.'/private-recovered-step1.json')){$last=json_decode(file_get_contents(__DIR__.'/private-recovered-step1.json'),true);$check($last['evidence_status']==='EVIDENCE_INCOMPLETE'&&$now===$last['after'],'Known incident recovery only');}else{$last=json_decode(file_get_contents(__DIR__.'/private-case-'.($step-1).'.wire.json'),true);$check($last['error']===null&&$now===$last['after'],'Last committed source before next step');}}
$request=['token'=>json_decode(file_get_contents(__DIR__.'/private-auth-write.json'),true)['token'],'nonce'=>bin2hex(random_bytes(24)),'case'=>$case];$save('private-dispatch.json',$request);$port=$lane==='B'?18831:18832;$curl=curl_init('http://127.0.0.1:'.$port.$case['path']);curl_setopt_array($curl,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($case['params']),CURLOPT_RETURNTRANSFER=>true,CURLOPT_HTTPHEADER=>['token: '.$request['token'],'X-CDX-Nonce: '.$request['nonce']],CURLOPT_CONNECTTIMEOUT=>5,CURLOPT_TIMEOUT=>40]);$body=curl_exec($curl);$info=curl_getinfo($curl);$error=curl_error($curl);curl_close($curl);$check($body!==false,'Bounded HTTP error, do not retry');file_put_contents(__DIR__.'/private-case-'.$step.'.httpbody',$body);chmod(__DIR__.'/private-case-'.$step.'.httpbody',0600);
$wire=json_decode(file_get_contents(__DIR__.'/private-case-'.$step.'.wire.json'),true);$check($wire!==null,'Wire evidence exists');$summary=['lane'=>$lane,'step'=>$step,'HTTP'=>$info['http_code'],'body_bytes'=>strlen($body),'body_sha256'=>hash('sha256',$body),'business'=>json_decode($body,true),'DML'=>$wire['DML'],'wire_error'=>$wire['error']?['class'=>$wire['error']['class'],'sha256'=>hash('sha256',$wire['error']['message'])]:null,'curl_error'=>$error];$save('private-case-'.$step.'.http.json',$summary);echo json_encode($summary,JSON_UNESCAPED_UNICODE),"\n";$check($wire['error']===null&&$info['http_code']===200&&$body===$wire['body'],'HTTP/native gate/transition success');$expected=in_array($step,[5,7,9],true)?1:0;$summary['contract_pass']=($summary['business']['code']??null)===$expected;$save('private-case-'.$step.'.http.json',$summary);$save('private-state.json',['step'=>$step,'ids'=>$wire['ids']]);
