"""One exclusive, bounded Windows browser handoff. Never restart its ledger.""" import argparse import ctypes import json from pathlib import Path import signal import subprocess import time ROOT=Path(__file__).resolve().parents[3] EVIDENCE=ROOT/'.local-s2s-build/windows-browser-paid' REPORT=ROOT/'.local-s2s-build/windows-browser-watch.json' COMPOSE=['docker','compose','--project-directory',str(ROOT),'--env-file',str(ROOT/'.local-s2s-build/windows-browser.env'),'-f',str(ROOT/'docs/evaluation/local-s2s/windows-browser.compose.yml')] class Memory(ctypes.Structure): _fields_=[('length',ctypes.c_ulong),('load',ctypes.c_ulong)]+[(name,ctypes.c_ulonglong) for name in ('total','available','page_total','page_available','virtual_total','virtual_available','extended')] def available(): memory=Memory();memory.length=ctypes.sizeof(memory) if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(memory)):raise OSError('Windows memory query failed') return memory.available def vm_available(): data=subprocess.check_output(COMPOSE+['exec','-T','candidate_db','cat','/proc/meminfo'],text=True,timeout=10) return int(next(line.split()[1] for line in data.splitlines() if line.startswith('MemAvailable:')))*1024 def main(*, enforce_memory=False): state={'stage':'preflight','memory_enforcement':enforce_memory,'minimum_windows_available_bytes':available(),'minimum_vm_available_bytes':vm_available()} def save():REPORT.write_text(json.dumps(state,indent=2)+'\n',encoding='utf-8') if (EVIDENCE/'browser-paid-ledger.json').exists():raise SystemExit('Exclusive ledger already exists; no restart allowed') if enforce_memory: # Admit using this host's measured native peak plus the floor and256MiB margin. trial=json.loads((ROOT/'docs/evaluation/local-s2s/windows-native-retention-20261017.json').read_text()) observed=trial['supervisor'] if observed['exit_code']!=0 or observed['abort'] is not None:raise SystemExit('Missing successful native memory evidence') required=2500*1024**2+(observed['start_windows_available_bytes']-observed['minimum_windows_available_bytes'])+256*1024**2 state['required_windows_start_bytes']=required if state['minimum_windows_available_bytes']1800:state['reason']='handoff_expired_30_minutes';break status=subprocess.check_output(COMPOSE+['ps','--all','--format','json','local-s2s-engine'],text=True,timeout=10) rows=[json.loads(line) for line in status.splitlines() if line.startswith('{')] if rows and rows[0].get('State') not in ('running','created'):state['reason']='engine_exited';break if state['stage']=='starting': logs=subprocess.check_output(COMPOSE+['logs','--no-log-prefix','--tail','10','local-s2s-engine'],text=True,timeout=10) if '"stage": "startup"' in logs: state.update(stage='ready',startup_seconds=round(time.monotonic()-began,3));print('Browser engine ready',flush=True) elif time.monotonic()-began>180:state['reason']='startup_deadline';break save();time.sleep(2) except BaseException as exc: state['reason']=type(exc).__name__ raise finally: if owned:subprocess.run(COMPOSE+['stop','--timeout','5','local-s2s-engine'],timeout=15) state.update(stage='stopped',elapsed_seconds=round(time.monotonic()-began,3));state.setdefault('reason','operator_stop');save() if __name__=='__main__': parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--enforce-memory-floor',action='store_true',help='Opt in to host/VM memory admission and automatic low-memory stop') parser.add_argument('--evidence',type=Path) parser.add_argument('--report',type=Path) parser.add_argument('--compose',type=Path) args=parser.parse_args() if args.evidence:EVIDENCE=args.evidence.resolve() if args.report:REPORT=args.report.resolve() if args.compose:COMPOSE[-1]=str(args.compose.resolve()) main(enforce_memory=args.enforce_memory_floor)