from pathlib import Path import datetime,hashlib,json,os,shutil,subprocess,zipfile root=Path(__file__).resolve().parents[2];out=Path(__file__).resolve().parent release=root/'outputs/investmoz-parques-QA-20261016';review=release/'para-revisao' sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest() m=json.loads((review/'MANIFESTO-CANDIDATA.json').read_text('utf-8')) a=json.loads((out/'AUTORIZACAO-TEMPO.json').read_text('utf-8')) b=json.loads((out/'FRESH-BACKUP.json').read_text('utf-8')) c=json.loads((out/'ARRANQUE-CLONE-RESTAURADO.json').read_text('utf-8')) f=json.loads((out/'RESTAURO-FICHEIROS.json').read_text('utf-8')) assert a['candidate']==b['candidate']==c['candidate']==f['candidate']==m['candidate']=='parques-operacionais-QA-6aacf653a98e' assert b['restore_verified'] and b['files_verified'] and c['DB_read_only'] and c['kernel_bootstrap']=='passed' assert f['actual_archive_extraction_and_hashes']=='passed' assert (datetime.datetime.now(datetime.timezone.utc)-datetime.datetime.fromisoformat(b['at'])).total_seconds()<3600 assert not(out/'TROCA.json').exists() and not(root/'storage/framework/down').exists() backup=Path(b['private_directory']).resolve() assert backup.parent==Path('C:/Users/macbook/.config/investmoz').resolve() private=json.loads((backup/'backup-proof-private.json').read_text('utf-8')) assert sha(Path(private['dump_path']))==private['sha256'] and sha(Path(private['files_path']))==private['files_sha256'] base=json.loads((release/'ATIVO-ANTES.json').read_text('utf-8')) for n,h in {**base['files'],**base['protected']}.items():assert sha(root/n)==h,n for s in m['sources']:assert(sha(root/s['path'])if(root/s['path']).exists()else None)==s['before_sha256'],s['path'] archive=review/(m['candidate']+'.zip');assert sha(archive)==a['package_sha256'] stage=backup/'candidate-staging';assert not stage.exists();stage.mkdir() with zipfile.ZipFile(archive)as z: assert z.testzip() is None entries=[('candidate/sources/'+s['path'],s['path'],s['candidate_sha256'])for s in m['sources']] entries += [('candidate/build/'+n,'public/build/'+n,h)for n,h in m['build'].items()] for entry,name,h in entries: data=z.read(entry);assert hashlib.sha256(data).hexdigest()==h p=(stage/name).resolve();assert p.is_relative_to(stage.resolve()) p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(data) proofpath=root/'storage/app/private/investmoz-v2/park-profile/readiness.json' assert not proofpath.exists(),'Preserve previous installation evidence' proof={'verified_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'target':b['target'],'restore_target':b['restore_target'], 'code_hash':m['code_hash'],'dump_path':private['dump_path'],'dump_sha256':private['sha256'], 'files_path':private['files_path'],'files_sha256':private['files_sha256'],'restore_verified':True,'files_verified':True, 'restored_boot_verified':True,'qa_passed':True,'compatibility_verified':True, 'QA_receipt_sha256':a['QA_receipt_sha256'],'restored_boot_receipt_sha256':sha(out/'ARRANQUE-CLONE-RESTAURADO.json'), 'active_authorization':{'decision_record':'outputs/investmoz-parques-ativacao-20261016/AUTORIZACAO-TEMPO.json', 'code_hash':m['code_hash'],'migration':m['data']['migration']}} php='C:/laragon/bin/php/php-8.5.11-Win32-vs17-x64/php.exe' def command(args,label): p=subprocess.run(args,cwd=root,capture_output=True,timeout=120) (backup/(label+'.log')).write_bytes(p.stdout+p.stderr) assert p.returncode==0,'Command failed: '+label def artisan(*args):command([php,'artisan',*args],'-'.join(args).replace(':','-')) def put(src,dest): assert dest.resolve().is_relative_to(root.resolve()) dest.parent.mkdir(parents=True,exist_ok=True) temp=dest.with_name(dest.name+'.parks-delivery.tmp');assert not temp.exists() shutil.copy2(src,temp);assert sha(temp)==sha(src);os.replace(temp,dest) build=root/'public/build';old=backup/'build-before-swap' assert build.resolve().is_relative_to(root.resolve()) and old.resolve().is_relative_to(backup) and not old.exists() receipt={'candidate':m['candidate'],'at':datetime.datetime.now(datetime.timezone.utc).isoformat(), 'sources':16,'build_files':162,'active_business_writes':0,'migration_via_shell':False} down=False try: artisan('down');down=True command([php,str(out/'cache-snapshot.php'),'before'],'data-cache-before') for s in m['sources']:put(stage/s['path'],root/s['path']) build.rename(old) shutil.copytree(stage/'public/build',build) for s in m['sources']:assert sha(root/s['path'])==s['candidate_sha256'] actual={p.relative_to(build).as_posix():sha(p)for p in build.rglob('*')if p.is_file()} assert actual==m['build'] proofpath.parent.mkdir(parents=True,exist_ok=True) proofpath.write_text(json.dumps(proof,ensure_ascii=False,indent=2)+'\n','utf-8') cache=b['cache_state'];commands=[] if cache['configuration_cached']:artisan('config:clear');commands.append('config:clear') if cache['routes_cached']:artisan('route:clear');commands.append('route:clear') artisan('view:clear');commands.append('view:clear') command([php,str(out/'cache-snapshot.php'),'after'],'data-cache-after') changed={s['path']for s in m['sources']} for n,h in {**base['files'],**base['protected']}.items(): if not n.startswith('public/build/') and n not in changed:assert sha(root/n)==h,n receipt.update({'cache_commands':commands,'data_cache_preserved':True}) artisan('up');down=False receipt.update({'maintenance_ended':True,'result':'Exact candidate code/build installed; authenticated nominal schema installation pending'}) except BaseException: if down: for s in m['sources']: p=root/s['path'] if s['before_sha256'] is not None:put(backup/'files'/s['path'],p) elif p.is_file() and sha(p)==s['candidate_sha256']:p.unlink() if old.exists(): if build.exists(): detached=backup/'candidate-build-detached-on-reversal' assert not detached.exists() and detached.resolve().is_relative_to(backup) build.rename(detached) old.rename(build) artisan('view:clear');artisan('up') receipt['result']='Reverted before authenticated DDL; business data preserved' (out/'TROCA-REVERTIDA.json').write_text(json.dumps(receipt,indent=2)+'\n','utf-8') raise (out/'TROCA.json').write_text(json.dumps(receipt,indent=2)+'\n','utf-8') print(json.dumps(receipt))