import io, sys

P = r"C:\Users\decid\Documents\projects\spt-core\.spt\preserved\hertz-304-w1-c468e9df\lane_run.py"
src = io.open(P, encoding="utf-8").read()

OLD = '    priv = os.path.join(EVID, "temp", label)\n'
NEW = (
    '    # THE RIG\'S OWN TMP REDIRECT WAS A DEFECT, measured 2026-09-11 after\n'
    '    # w5-lib-full: this base used to be EVID/temp/<label>, which lives INSIDE\n'
    '    # the spt-core checkout. Every tempfile::tempdir() fixture therefore sat\n'
    '    # under a git work tree, git discovery walked up and found the repo, and\n'
    '    # project_id_for_dir (remote-URL FIRST) handed back THIS repo\'s identity\n'
    '    # to cells whose fixture requires a dir outside any repo. Two cells read\n'
    '    # the real slug instead of their folder names and failed; the same cells\n'
    '    # passed in a run with the default TMP 8 minutes earlier, and pass in CI.\n'
    '    # PROVEN, with a control: git -C <old priv> rev-parse --show-toplevel ==\n'
    '    # the spt-core checkout and its remote is the bs-core URL, while the same\n'
    '    # probe from the default TMP answers "not a git repository".\n'
    '    # The base is now OUTSIDE the tree; per-label isolation and reapability\n'
    '    # are unchanged. HERTZ_RIG_TMP_IN_REPO=1 restores the old in-repo\n'
    '    # placement deliberately, as the negative control for that measurement.\n'
    '    if os.environ.get("HERTZ_RIG_TMP_IN_REPO") == "1":\n'
    '        priv = os.path.join(EVID, "temp", label)\n'
    '    else:\n'
    '        base = (os.environ.get("TEMP") or os.environ.get("TMP")\n'
    '                or tempfile.gettempdir())\n'
    '        priv = os.path.join(base, "hertz-304-rig", label)\n'
)

n = src.count(OLD)
if n != 1:
    sys.exit("REFUSING: priv anchor count %d, expected 1" % n)
src = src.replace(OLD, NEW)

IMP_OLD = "import ctypes, json, os, subprocess, sys, time\n"
IMP_NEW = "import ctypes, json, os, subprocess, sys, tempfile, time\n"
if "tempfile" not in src.split("\n\n")[0] and IMP_NEW not in src:
    m = src.count(IMP_OLD)
    if m != 1:
        sys.exit("REFUSING: import anchor count %d, expected 1" % m)
    src = src.replace(IMP_OLD, IMP_NEW, 1)

io.open(P, "w", encoding="utf-8", newline="").write(src)
print("patched")
print("tempfile in imports:", IMP_NEW.strip() in src)
print("env escape hatch present:", "HERTZ_RIG_TMP_IN_REPO" in src)
