"""Launch gate-w1.sh detached under a PROVEN scrubbed environment (W0's launcher, re-pointed).

Explicit env without the endpoint identity trio + perch companions + the pool hatch, then the
child's environment is read back with psutil; success is refused unless the read-back agrees.
"""
import os, subprocess, sys, time
from pathlib import Path
import psutil

root = Path(__file__).resolve().parents[1]
outdir = root / ".spt" / "gate-doyle"
TRIO = ("OWL_SESSION_ID", "SPT_AGENT_ID", "SPT_ENDPOINT_ID")
COMPANIONS = ("SPT_SESSION_NAME", "SPT_ADAPTER", "SPT_HOST_PID", "SPT_INJECT_VERIFY_ECHO", "SPT_POOL_UNCHECKED", "SPT_HOME")
env = dict(os.environ)
dropped = [k for k in TRIO + COMPANIONS if env.pop(k, None) is not None]
outdir.mkdir(parents=True, exist_ok=True)
log = open(outdir / "launcher.log", "wb")
flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
bash = r"C:\Program Files\Git\bin\bash.exe"
script = sys.argv[1] if len(sys.argv) > 1 else ".spt/gate-w1.sh"
child = subprocess.Popen(
    [bash, "-lc", f"bash {script}"],
    cwd=str(root), env=env, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
    creationflags=flags, close_fds=True,
)
time.sleep(2)
proc = psutil.Process(child.pid)
seen = proc.environ()
leaked = [k for k in TRIO + COMPANIONS if k in seen]
print(f"driver pid={child.pid} dropped-at-launch={' '.join(dropped) or 'none'}")
print(f"read-back: scrubbed vars in the driver's environment = {leaked or 'NONE'}")
if leaked:
    proc.kill()
    print("LAUNCH REFUSED: scrub did not reach the child; killed it")
    sys.exit(4)
(outdir / "driver.pid").write_text(str(child.pid))
print("LAUNCH PROVEN: driver runs without the endpoint identity")
