from pathlib import Path
import os
os.chdir(r"C:\Users\decid\Documents\projects\spt-core\.worktrees\ws272-w0")
p = Path(".github/ci/ws272-w0.py")
s = p.read_bytes().decode("utf-8").replace("\r\n", "\n")

def swap(old, new):
    global s
    assert s.count(old) == 1, old[:60]
    s = s.replace(old, new)

swap('''re-ran this driver beside the intended one, two suites interleaved one
nextest.raw (two Summary lines), and the gater voided the window.
"""''',
'''re-ran this driver beside the intended one, two suites interleaved one
nextest.raw (two Summary lines), and the gater voided the window.

The battery runs under a SCRUBBED environment: the perch identity variables an
agent's shell carries (SPT_ENDPOINT_ID and its companions) are dropped from
every leg's child and named once as ENV_SCRUBBED. Mechanism (W0, 2026-09-06):
a driver launched from a live perch inherited SPT_ENDPOINT_ID, and every test
that stops a daemon was refused by the product's own endpoint guard
(DAEMON_STOP_REFUSED) — two reds that were the launcher's, not the tree's.
"""''')

swap('''ACTIVE_STATES = ("in_progress", "queued", "waiting", "pending", "requested")
''',
'''ACTIVE_STATES = ("in_progress", "queued", "waiting", "pending", "requested")
# The perch identity a live agent's shell carries. A battery must never look
# like an endpoint to the binary it tests.
# The identity trio the daemon-stop guard reads (OWL_SESSION_ID / SPT_AGENT_ID /
# SPT_ENDPOINT_ID) plus the perch companions a hosted session exports.
PERCH_ENV = ("OWL_SESSION_ID", "SPT_AGENT_ID", "SPT_ENDPOINT_ID", "SPT_SESSION_NAME",
             "SPT_ADAPTER", "SPT_HOST_PID", "SPT_INJECT_VERIFY_ECHO")


def battery_env(source=None):
    """A copy of the environment with the perch identity removed.

    Returns (env, dropped): `dropped` lists the names that were present so the
    caller can say so once — a silent scrub would hide the launcher's mistake.
    """
    source = dict(os.environ if source is None else source)
    dropped = [name for name in PERCH_ENV if name in source]
    for name in dropped:
        del source[name]
    return source, dropped
''')

swap('''            result = subprocess.run(argv, cwd=root, stdout=log, stderr=subprocess.STDOUT)''',
'''            result = subprocess.run(argv, cwd=root, stdout=log, stderr=subprocess.STDOUT, env=BATTERY_ENV)''')

swap('''    root = Path(__file__).resolve().parents[2]
    lane_lock = claim_pool(root)  # held until this process exits
    if lane_lock is None:
        return 4''',
'''    root = Path(__file__).resolve().parents[2]
    lane_lock = claim_pool(root)  # held until this process exits
    if lane_lock is None:
        return 4
    global BATTERY_ENV
    BATTERY_ENV, dropped = battery_env()
    if dropped:
        print(f"ENV_SCRUBBED: dropped {' '.join(dropped)} from every leg (a battery is not an endpoint)", flush=True)''')

swap('''def leg(root, output, name, argv, guarded=True, xtask=None):''',
'''BATTERY_ENV = None  # set by --run before the first leg


def leg(root, output, name, argv, guarded=True, xtask=None):''')

swap('''        print("PASS lane lock: second driver refused while the holder lives, free once it exits")
''',
'''        print("PASS lane lock: second driver refused while the holder lives, free once it exits")
    tainted = {"OWL_SESSION_ID": "owl", "SPT_AGENT_ID": "a", "SPT_ENDPOINT_ID": "agent", "SPT_HOST_PID": "1", "PATH": "keep", "SPT_HOME": "keep"}
    env, dropped = battery_env(tainted)
    if dropped != ["OWL_SESSION_ID", "SPT_AGENT_ID", "SPT_ENDPOINT_ID", "SPT_HOST_PID"] or "SPT_ENDPOINT_ID" in env or env["PATH"] != "keep" or env["SPT_HOME"] != "keep":
        raise AssertionError(f"env scrub: dropped={dropped} env={env}")
    clean_env, none_dropped = battery_env({"PATH": "keep"})
    if none_dropped or clean_env != {"PATH": "keep"}:
        raise AssertionError(f"env scrub over a clean env: dropped={none_dropped}")
    print("PASS env scrub: perch identity dropped and named, everything else kept, clean env untouched")
''')

p.write_bytes(s.replace("\n", "\r\n").encode("utf-8"))
print("driver env scrub patched")
