#!/usr/bin/env python3 """One cloud-only Root/APT UI acceptance, never a retry or direct approval. Preparation and approval are separate real browser sessions. MCP/SQL only read the root request and prove zero execution artifacts before the UI approval. Existing case directories are never reused; unknown effects stop progress. """ import argparse import hashlib import json import os from pathlib import Path import sys import time import cloud_mvp_acceptance as cloud import cloud_root_evidence import vm_mvp_adapters as adapters sys.path.insert(0,str(Path(__file__).resolve().parent/'browser')) import run_cloud_root as browser def main(): parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--case',choices=browser.CASES,required=True) parser.add_argument('--resume-prepared',action='store_true',help='Only an existing still-pending UI request with zero executable artifacts') args=parser.parse_args() os.umask(0o077);m=cloud.contract;name=args.case m.require(not (Path.home()/'.local/share/rust-discovery/remote-agent').exists(),'notebook must remain development only') installed=m.protected_json(cloud.ROOT/'devstate/remote-vm.json');identity=installed['identity'] settings=dict(tenant_id=cloud.TENANT,**identity);backend=cloud.Backend() def evidence(kind,**extra):return cloud.bootstrap.rpc('server.conf',cloud.server,dict(kind=kind,tenant_id=cloud.TENANT,agent_id=identity['agent_id'],**extra)) m.require(evidence('gate')['unresolved']==0,'unresolved central job; no new attempt') observed=cloud.bootstrap.rpc('server.conf',cloud.bootstrap.server,dict(action='observe',agent_id=identity['agent_id'])) m.require(observed['sync_ready'] and not observed['restore_blocked'],'signed sync required') device=backend.call('inventory.get_device',dict(tenant_id=cloud.TENANT,asset_id=identity['asset_id'])) m.require(device['presence']=='online' and device['agent_id']==identity['agent_id'],'online cloud VM required') peers=cloud.bootstrap.rpc('linux-vm.conf',cloud_root_evidence.inspect_helpers,dict( {k:settings[k] for k in ('tenant_id','asset_id','agent_id')},general_only=name=='query_logs')) m.require(peers['ledger']['integrity']=='ok' and peers['ledger']['faults']==0,'healthy shared helper ledger required') if name in adapters.APT_CASES: apt_peer=peers['apt'];recipe=adapters.RECIPES[name] m.require(apt_peer['fixture_acceptance_ready'] and recipe in apt_peer['bootstrap_recipes'] if name.startswith('apt_native_') else recipe in apt_peer['accepted_recipes'],'actual native bootstrap/acceptance gate required') planning=adapters.planning_from_device(device) if name in adapters.APT_CASES else None request=m.case_input(name,settings,planning=planning) if name=='query_logs': import datetime as dt # Query only the already approved harmless unit's stored start/stop # interval. No extra service mutation is needed to manufacture logs. prior=m.protected_json(cloud.ROOT/'devstate/cloud-root/cases/service_stop/checkpoint.json') prior_payload=prior['job']['payload'] m.require(prior['verified'] and prior_payload['agent_id']==identity['agent_id'],'same VM test-unit history') moment=m.timestamp(prior_payload['not_before']) request['parameters'].update(execution_identity='root',since=(moment-dt.timedelta(minutes=1)).isoformat(), until=(moment+dt.timedelta(minutes=4)).isoformat()) m.require({'rmm.sync.v1','helper.root.v1','root:'+request['action'],request['action']}<=set(device['capabilities']),'native root capability required') folder=cloud.ROOT/'devstate/cloud-root/cases'/name if not args.resume_prepared:folder.mkdir(mode=0o700,parents=True,exist_ok=False) prepared=folder/'prepared.json';preparation=folder/'prepare.json' if args.resume_prepared: previous=m.protected_json(preparation) m.require(previous['case']==name and all(previous[k]==settings[k] for k in settings),'existing preparation target mismatch') request=previous['request'] else: m.write_private(preparation,dict(profile='dev/test',case=name,phase='prepare',request=request,**settings, expected_principal='simulated-testprincipal-a',output_file=str(prepared))) print(name+': prepare through actual UI',flush=True);browser.run(preparation,prepare=True) response=m.protected_json(prepared);plan=response['plan'];pending=response['operation'] m.require(hashlib.sha256(bytes(plan['plan_payload_bytes'])).hexdigest()==plan['plan_hash'] and len(plan['jobs'])==1,'immutable plan bytes') job=plan['jobs'][0];payload=job['payload'] m.require(payload['execution_identity']=='root' and all(payload[k]==settings[k] for k in ('tenant_id','asset_id','agent_id')),'fixed cloud root target') stored=backend.call('jobs.get',dict(tenant_id=cloud.TENANT,operation_id=pending['operation_id'])) gate=evidence('gate',job_id=job['job_id']) m.require(stored['plan_hash']==plan['plan_hash'] and stored['approval_state']=='pending_approval' and stored['job_count']==0 and stored['execution_state'] is None and all(gate[k]==0 for k in ('jobs','outbox','permits')),'pending must have zero executable artifacts') checkpoint=dict(case=name,plan=plan,job=job,request=request,operation_id=pending['operation_id'],preapproval=gate,helper_readiness=peers,stage='pending_approval') path=folder/'checkpoint.json' def save(): # Checkpoint belongs to this exclusive invocation; retain result records # separately and never submit/approve again after an interruption. path.write_text(json.dumps(checkpoint,indent=2));path.chmod(0o600) save() approval=folder/'approve.json' m.write_private(approval,dict(profile='dev/test',case=name,**settings,expected_principal='simulated-testprincipal-a', operation_id=pending['operation_id'],plan_hash=plan['plan_hash'],plan_payload_bytes=plan['plan_payload_bytes'], job_payload=payload,job_payload_hash=job['job_payload_hash'])) print(name+': pending verified 0/0/0; separate actual UI approval',flush=True);browser.run(approval) end=time.monotonic()+420 while True: result=backend.call('jobs.get',dict(tenant_id=cloud.TENANT,job_id=job['job_id'])) if result['state'] in m.TERMINAL or result['state'] in ('unknown','awaiting_reboot'):break m.require(time.monotonic()