"""Mechanical copy of audited tools into a new, separately sealed fixture batch."""
import json
from pathlib import Path
base=Path(__file__).parent
out=base/'repaired-new-fixture'
out.mkdir(exist_ok=False)
names=['.gitignore','launcher.php','common.php','Gate.php','init.php','Oracle.php','index.php','run.php','resource.php','cleanup-source.php']
for name in names:
    s=(base/name).read_text()
    for old,new in [('cdx-store-activity-crud4-20261011','cdx-store-activity-fixed-20261011'),('CDXACT11W1','CDXACT11W2'),('ROOT_APPROVED_EXACT_ACTIVITY_CRUD4','ROOT_APPROVED_EXACT_ACTIVITY_FIXED'),('18991','18993'),('18992','18994'),('2099-01','2099-02'),('790da44f00e576b9630d450dab6b4c00851fe3fec55eba817c849154be84831f','f26f6dd15e86f3b34e23cde8413b660683cc5656f542b85973581c441c747738'),('自有活动初始说明','自有活动W2初始说明'),('自有活动规则','自有活动W2规则'),('自有活动修改说明','自有活动W2修改说明'),('自有活动修改规则','自有活动W2修改规则')]:
        s=s.replace(old,new)
    if name=='common.php':
        s=s.replace("($lane==='B'?800:600)",'800').replace("$source=static function()use($q,$lane)","$source=static function($full=false)use($q,$lane)")
        s=s.replace("$r['ai_users']=$q(","if($full)$r['ai_users']=$q(").replace("$r['config']=$q(","if($full)$r['config']=$q(")
        s=s.replace("$guard=static function($before,$after,$own=null){", "$guard=static function($before,$after,$own=null){if(!array_key_exists('ai_users',$before)||!array_key_exists('ai_users',$after)){unset($before['ai_users'],$before['config'],$after['ai_users'],$after['config']);}")
    if name=='run.php':
        s=s.replace("$s=$source();if(count($s['actor'])", "$s=$source(true);if(count($s['actor'])")
        s=s.replace("if($mode==='finish'){$s=$source();", "if($mode==='finish'){$s=$source(true);")
        a=s.index("if($mode==='tap-proof'){"); b=s.index("if($mode==='finish')",a)
        s=s[:a]+'''if($mode==='tap-proof'){
 $s=$source();$base=json_decode(file_get_contents(__DIR__.'/private/baseline.json'),true);$guard($base,$s);$meta=json_decode(file_get_contents(__DIR__.'/private/preflight.json'),true);$type=$meta['existing_valid_type']['id'];
 require __DIR__.'/init.php';$proof=[];foreach(['store'=>\\think\\Db::connect(),'ai'=>get_ai_db()]as $which=>$conn){$rp=new ReflectionProperty(\\think\\db\\Connection::class,'linkID');$rp->setAccessible(true);$pdo=$rp->getValue($conn);if(!($pdo instanceof ActPDO)||$pdo->schema!==$which)throw new RuntimeException('Effective native tap missing');$c=$conn->getConfig();$expected=$which==='store'?$cfg:$ai;foreach(['hostname','database','username','password','prefix']as $k)if($c[$k]!==$expected[$k])throw new RuntimeException('Effective config identity');$expectedClass=$lane==='B'?'think\\\\db\\\\connector\\\\Mysql':'app\\\\cores\\\\database\\\\Dm';if(get_class($conn)!==$expectedClass)throw new RuntimeException('Original Driver class');$identity=$conn->query($lane==='B'?'SELECT DATABASE() AS db':'SELECT SYS_CONTEXT(\\'USERENV\\',\\'CURRENT_SCHEMA\\') AS db FROM DUAL');if(($identity[0]['db']??null)!==$c['database'])throw new RuntimeException('Actual DB identity');$row=$which==='store'?$conn->query('SELECT id,uuid FROM ydy_user WHERE id=:actor',['actor'=>[$lane==='B'?97260:2791,1]]):$conn->query('SELECT id,name FROM yoshop_activity_type WHERE id=:type',['type'=>[$type,1]]);$proof[$which]=['class'=>get_class($conn),'native_class'=>get_class($pdo),'config_database'=>$c['database'],'identity'=>$identity,'row'=>$row];}
 $schemas=array_column(ActivityGate::$journal,'schema');if(!in_array('store',$schemas,true)||!in_array('ai',$schemas,true)||ActivityGate::$dml!==0)throw new RuntimeException('Both actual journal scopes');$save('tap-proof.json',['proof'=>$proof,'native'=>ActivityGate::$journal,'source'=>$s,'observer'=>$GLOBALS['ACT_OBSERVER'],'before_first_HTTP_and_DML'=>true]);echo json_encode(['lane'=>$lane,'before_first_write_both_actual_connections_proven'=>true,'native_statements'=>count(ActivityGate::$journal),'natural_state_exact'=>true]),"\\n";exit;
}
''' +s[b:]
        s=s.replace("$before=$stage>=6?", "$before=$stage>=2?").replace("$after=$stage>=6?", "$after=$stage>=2?")
        s=s.replace("if($stage>=2){if($wire['DML_attempts']", "if($stage>=1){if($wire['DML_attempts']")
        s=s.replace("if($stage===1){$meta=", "if($stage===1){if(!is_file(__DIR__.'/private/tap-proof.json'))throw new RuntimeException('Actual dual connection proof before INSERT');$meta=")
        s=s.replace("$noop=$stage===8&&$lane==='B'&&", "$noop=$stage===8&&")
        s=s.replace("'original_MySQL_noop_red'=>$noop", "'canonical_repeat_noop'=>$noop").replace("'original_MySQL_noop'=>$noop", "'canonical_repeat_noop'=>$noop")
        s=s.replace("foreach($allowed['data']as $k=>$v){if((string)$target", "foreach($allowed['data']as $k=>$v){if($lane==='C'&&in_array($k,['register_start','register_end','start_time','end_time'],true))$v.='.000000';if((string)$target")
        s=s.replace("$n++;echo json_encode(['puregate_checks'=>$n,'DB'=>0,'HTTP'=>0]),", "$n++;$pure=['puregate_checks'=>$n,'DB'=>0,'HTTP'=>0];$h=fopen(__DIR__.'/private/puregate.json','xb');fwrite($h,json_encode($pure));fclose($h);chmod(__DIR__.'/private/puregate.json',0600);echo json_encode($pure),")
    (out/name).write_text(s)
plan=json.loads((base/'plan.json').read_text())
plan.update(authorization='ROOT_APPROVED_EXACT_ACTIVITY_FIXED',marker='CDXACT11W2',runtime='/tmp/cdx-store-activity-fixed-20261011',ports={'B':18993,'C':18994},source_sha256='f26f6dd15e86f3b34e23cde8413b660683cc5656f542b85973581c441c747738',total_readonly_hard_cap_per_side=800,observer_select_max_per_side=800,business_read_max_per_side=800)
plan['protection_frequency']={'activity_register_type_actor_11nutrition':'fresh independent before/after every HTTP','all_AI_users_all_config':'fresh start/end only; omitted from intermediate snapshots'}
(out/'plan.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n')
print('New repaired tools created; no DB/HTTP; original sealed files untouched')
