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

Explicit env without the endpoint identity trio + perch companions + the pool hatch + SPT_HOME,
then the child's environment is read back with psutil; success is refused unless the read-back agrees
(a perch-launched battery inherits the endpoint identity and every daemon-stopping arm refuses).
"""
import os, subprocess, sys, time
import pathlib
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", "CARGO_TARGET_DIR")
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-w2.sh"
# FREEZE (todlando 2026-09-07 11:15Z): bash reads a script incrementally by byte offset, so an edit to
# a script file under a RUNNING shell shifts every later byte and the shell resumes mid-line — a mangled
# env prefix yields vacuous green PASSes, not a syntax error. Copy the driver + every script it calls to a
# content-addressed dir and run THAT; an edit to .spt/ lands on the next launch, never the live one.
import hashlib, shutil
frozen_names = [pathlib.Path(script).name, "twohost-web-xbox.sh", "mutate.py", "twohost-web-local.sh"]
frozen_src = {"twohost-web-local.sh": "rig/twohost-web-local.sh"}  # frozen FLAT under its basename
h = hashlib.sha256()
for n in frozen_names:
    h.update((root / ".spt" / frozen_src.get(n, n)).read_bytes())
frozen = root / ".spt" / "frozen" / h.hexdigest()[:12]
frozen.mkdir(parents=True, exist_ok=True)
for n in frozen_names:
    shutil.copyfile(root / ".spt" / frozen_src.get(n, n), frozen / n)
# forward slashes: this path is handed to `bash -lc` as text, and bash eats backslashes (dry-run 11:19Z
# printed C:Usersdecid... "No such file" — the freeze must be TESTED, not assumed; hertz).
env["FROZEN"] = str(frozen).replace("\\", "/")
script = str(frozen / pathlib.Path(script).name).replace("\\", "/")
print(f"frozen scripts -> {frozen} ({', '.join(frozen_names)})")
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)
try:
    proc = psutil.Process(child.pid)
    seen = proc.environ()
except psutil.NoSuchProcess:
    log.close()
    print(f"driver pid={child.pid} EXITED within the settle window; launcher.log tail:")
    print((outdir / "launcher.log").read_text(errors="replace")[-600:])
    sys.exit(3)
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")
