#!/usr/bin/env python3
"""
Non-vacuous real-kernel test suite for 61193 Plan B (`socks-ensure-detached.sh`)
and newbie_kit_v18_3_r13 integrity (Acceptance 1-3 + Frozen Script Hash Lock + 60564 -D Guard + Bootstrap sums).
Supports both direct (`python3 -B test_r13_socks_keep_plan_b_61193.py`) and
unittest (`python3 -B -m unittest test_r13_socks_keep_plan_b_61193.py`) execution.
"""

import hashlib
import os
import signal
import subprocess
import tempfile
import time
import unittest
from pathlib import Path

KIT_DIR = Path(__file__).resolve().parent
WRAPPER_SRC = KIT_DIR / "socks-ensure-detached.sh"


def _make_frozen_workspace(tmp_root: Path):
    """Create realistic frozen scripts (`socks-ensure.sh`, `socks-keep.sh`, `socks90-keep.sh`)."""
    ws = tmp_root / "workspace"
    ws.mkdir(parents=True, exist_ok=True)
    log_dir = tmp_root / "logs"
    log_dir.mkdir(parents=True, exist_ok=True)

    socks_keep = ws / "socks-keep.sh"
    socks90_keep = ws / "socks90-keep.sh"
    socks_ensure = ws / "socks-ensure.sh"

    # Realistic keep loops matching spec: 11080-11086 (-L) and 11090 (-D dynamic)
    socks_keep.write_text(
        "#!/bin/bash\n"
        "# Frozen socks-keep.sh (11080-11086 ssh -L)\n"
        "trap 'exit 0' TERM INT\n"
        "while true; do\n"
        "  # ssh -N -L 127.0.0.1:11080:127.0.0.1:11080\n"
        "  sleep 0.2\n"
        "done\n",
        encoding="utf-8",
    )
    socks90_keep.write_text(
        "#!/bin/bash\n"
        "# Frozen socks90-keep.sh (11090 must be ssh -D dynamic forwarding)\n"
        "trap 'exit 0' TERM INT\n"
        "while true; do\n"
        "  # ssh -N -D 127.0.0.1:11090\n"
        "  sleep 0.2\n"
        "done\n",
        encoding="utf-8",
    )
    # Exact root-cause reproduction from socks-keep-ensure-plan-b.txt:
    # legacy socks-ensure.sh spawns background keep loops via `nohup ... &` inside cron run tree
    socks_ensure.write_text(
        "#!/bin/bash\n"
        "WS=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n"
        "if ! pgrep -f \"(^|[[:space:]]|/)socks-keep\\.sh([[:space:]]|$)\" >/dev/null; then\n"
        "  nohup \"$WS/socks-keep.sh\" >/tmp/test-socks-keep-legacy.log 2>&1 &\n"
        "fi\n"
        "if ! pgrep -f \"(^|[[:space:]]|/)socks90-keep\\.sh([[:space:]]|$)\" >/dev/null; then\n"
        "  nohup \"$WS/socks90-keep.sh\" >/tmp/test-socks90-keep-legacy.log 2>&1 &\n"
        "fi\n",
        encoding="utf-8",
    )
    for f in (socks_keep, socks90_keep, socks_ensure):
        f.chmod(0o755)

    hashes_before = {
        f.name: (hashlib.sha256(f.read_bytes()).hexdigest(), f.stat().st_mtime_ns)
        for f in (socks_ensure, socks_keep, socks90_keep)
    }
    env = os.environ.copy()
    env.update(
        {
            "HOME": str(tmp_root),
            "SOCKS_SCRIPTS_DIR": str(ws),
            "SOCKS_KEEP_LOG": str(log_dir / "socks-keep.log"),
            "SOCKS90_KEEP_LOG": str(log_dir / "socks90-keep.log"),
            "SOCKS_ENSURE_DETACHED_LOG": str(log_dir / "socks-ensure-detached.log"),
            "SOCKS_ENSURE_LOCK": str(log_dir / "socks-ensure-detached.lock"),
        }
    )
    return ws, log_dir, hashes_before, env


def _live_pids_for(ws: Path, script_name: str) -> list[int]:
    """Scan /proc directly for live non-zombie processes running `ws / script_name`."""
    target = str(ws / script_name)
    out = []
    for entry in os.listdir("/proc"):
        if not entry.isdigit():
            continue
        pid = int(entry)
        try:
            stat_txt = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="ignore")
            state_char = stat_txt.rsplit(") ", 1)[1].split(" ", 1)[0]
            if state_char in ("Z", "X"):
                continue
            cmd = Path(f"/proc/{pid}/cmdline").read_bytes().decode("utf-8", errors="ignore").split("\x00")
            if any(arg == target for arg in cmd):
                out.append(pid)
        except OSError:
            continue
    return sorted(out)


def _cleanup_ws_procs(ws: Path):
    for name in ("socks-keep.sh", "socks90-keep.sh", "socks-ensure.sh", "socks-ensure-detached.sh"):
        for pid in _live_pids_for(ws, name):
            try:
                os.kill(pid, signal.SIGKILL)
            except OSError:
                pass
    time.sleep(0.1)


def _run_muse_scheduled_job(cmd: list[str], env: dict, timeout_s: float = 2.0):
    """
    Simulate Muse runtime task scheduler faithfully:
    1. Spawn job in its own process group (`start_new_session=True`) with stdout/stderr pipes AND a job-tree liveness pipe FD.
    2. Wait until both main job exits AND all non-detached descendants release the job-tree pipe FD (up to `timeout_s`).
    3. Reap the scheduled job's entire process group (`os.killpg(pgid, SIGKILL)`) on completion/timeout.
    """
    import select
    extra_r, extra_w = os.pipe()
    t0 = time.monotonic()
    deadline = t0 + timeout_s
    timed_out = False
    proc = subprocess.Popen(
        cmd,
        stdin=subprocess.DEVNULL,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env=env,
        start_new_session=True,
        pass_fds=(extra_w,),
    )
    os.close(extra_w)
    pgid = proc.pid
    try:
        out, err = proc.communicate(timeout=max(0.05, deadline - time.monotonic()))
        rc = proc.returncode
        # Wait for all descendants holding job pipe FD to finish or close FDs (exact runtime tree wait!)
        while True:
            rem = deadline - time.monotonic()
            if rem <= 0:
                timed_out = True
                break
            rready, _, _ = select.select([extra_r], [], [], rem)
            if not rready:
                timed_out = True
                break
            chunk = os.read(extra_r, 4096)
            if chunk == b"":
                break
    except subprocess.TimeoutExpired:
        timed_out = True
        rc = -9
        out, err = b"", b""
    finally:
        os.close(extra_r)
        try:
            os.killpg(pgid, signal.SIGKILL)
        except OSError:
            pass
        try:
            proc.wait(timeout=1.0)
        except Exception:
            pass
    elapsed = time.monotonic() - t0
    return rc, timed_out, elapsed, out.decode("utf-8", errors="replace"), err.decode("utf-8", errors="replace")

def test_01_reproduce_legacy_nohup_pipe_hang_and_tree_kill_flap():
    with tempfile.TemporaryDirectory(prefix="planb_neg_") as td:
        ws, _, hashes_before, env = _make_frozen_workspace(Path(td))
        try:
            rc, timed_out, elapsed, _, _ = _run_muse_scheduled_job(
                ["bash", str(ws / "socks-ensure.sh")], env, timeout_s=1.2
            )
            assert timed_out, f"Legacy nohup socks-ensure.sh should hang holding pipe FDs until timeout (got rc={rc}, elapsed={elapsed:.2f}s)"
            # And after runtime kills the scheduled run tree (`killpg`), BOTH loops die -> flap reproduced!
            assert _live_pids_for(ws, "socks-keep.sh") == [], "Legacy child loop survived killpg unexpectedly"
            assert _live_pids_for(ws, "socks90-keep.sh") == [], "Legacy child loop90 survived killpg unexpectedly"
            for fn, (sha0, mt0) in hashes_before.items():
                assert hashlib.sha256((ws / fn).read_bytes()).hexdigest() == sha0
                assert (ws / fn).stat().st_mtime_ns == mt0
        finally:
            _cleanup_ws_procs(ws)
    print("PASS test_01_reproduce_legacy_nohup_pipe_hang_and_tree_kill_flap")


def test_02_acceptance_1_two_consecutive_scheduled_runs_exit_0_fast_and_clean_fds():
    with tempfile.TemporaryDirectory(prefix="planb_acc1_") as td:
        ws, _, hashes_before, env = _make_frozen_workspace(Path(td))
        try:
            # Round 1
            rc1, to1, el1, _, err1 = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], env, timeout_s=4.0)
            assert not to1 and rc1 == 0, f"Round 1 failed: rc={rc1} timed_out={to1} err={err1}"
            assert el1 < 3.0, f"Round 1 took too long ({el1:.2f}s)"

            k_pids_1 = _live_pids_for(ws, "socks-keep.sh")
            k90_pids_1 = _live_pids_for(ws, "socks90-keep.sh")
            assert len(k_pids_1) == 1 and len(k90_pids_1) == 1, f"Expected (1,1), got {k_pids_1}, {k90_pids_1}"
            pid_k, pid_90 = k_pids_1[0], k90_pids_1[0]
            assert os.getsid(pid_k) == pid_k and os.getpgid(pid_k) == pid_k, f"SID!=PID for socks-keep: {os.getsid(pid_k)} vs {pid_k}"
            assert os.getsid(pid_90) == pid_90 and os.getpgid(pid_90) == pid_90, f"SID!=PID for socks90-keep: {os.getsid(pid_90)} vs {pid_90}"

            # Verify /dev/null stdin and ZERO inherited pipe: or .lock FDs in /proc/<pid>/fd
            for p in (pid_k, pid_90):
                fd_targets = {int(x): os.readlink(f"/proc/{p}/fd/{x}") for x in os.listdir(f"/proc/{p}/fd")}
                assert fd_targets.get(0) == "/dev/null", f"PID {p} stdin not /dev/null: {fd_targets}"
                assert all("pipe:" not in tgt and ".lock" not in tgt for tgt in fd_targets.values()), (
                    f"Leaked pipe/lock FD in PID {p}: {fd_targets}"
                )

            # Round 2 consecutive run: fast exit 0, zero timeout, same exact PIDs preserved!
            rc2, to2, el2, _, err2 = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], env, timeout_s=4.0)
            assert not to2 and rc2 == 0 and el2 < 3.0, f"Round 2 failed: rc={rc2} timed_out={to2} el={el2:.2f}s err={err2}"
            assert _live_pids_for(ws, "socks-keep.sh") == [pid_k]
            assert _live_pids_for(ws, "socks90-keep.sh") == [pid_90]

            for fn, (sha0, mt0) in hashes_before.items():
                assert hashlib.sha256((ws / fn).read_bytes()).hexdigest() == sha0
                assert (ws / fn).stat().st_mtime_ns == mt0
        finally:
            _cleanup_ws_procs(ws)
    print("PASS test_02_acceptance_1_two_consecutive_scheduled_runs_exit_0_fast_and_clean_fds")


def test_03_plan_a_existing_manual_setsid_loops_preserved_untouched():
    with tempfile.TemporaryDirectory(prefix="planb_plana_") as td:
        ws, log_dir, _, env = _make_frozen_workspace(Path(td))
        try:
            # Start manual Plan A setsid loops directly (simulating live PID 1993 / PID 2393 on Dragon-8)
            for sc, lg in [(ws / "socks-keep.sh", log_dir / "socks-keep.log"), (ws / "socks90-keep.sh", log_dir / "socks90-keep.log")]:
                with open(lg, "ab") as _fh:
                    subprocess.run(
                        ["setsid", "-f", str(sc)],
                        stdin=subprocess.DEVNULL,
                        stdout=_fh,
                        stderr=subprocess.STDOUT,
                        check=True,
                    )
            time.sleep(0.15)
            orig_k = _live_pids_for(ws, "socks-keep.sh")
            orig_90 = _live_pids_for(ws, "socks90-keep.sh")
            assert len(orig_k) == 1 and len(orig_90) == 1

            # Run wrapper twice: must detect existing Plan A loops, NOT kill them, and NOT spawn duplicates
            for _ in range(2):
                rc, to, _, _, _ = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], env, timeout_s=4.0)
                assert not to and rc == 0
                assert _live_pids_for(ws, "socks-keep.sh") == orig_k
                assert _live_pids_for(ws, "socks90-keep.sh") == orig_90
        finally:
            _cleanup_ws_procs(ws)
    print("PASS test_03_plan_a_existing_manual_setsid_loops_preserved_untouched")


def test_04_acceptance_2_kill_single_loop_auto_respawns_with_sid_eq_pid_across_rounds():
    with tempfile.TemporaryDirectory(prefix="planb_acc2_") as td:
        ws, _, _, env = _make_frozen_workspace(Path(td))
        try:
            rc, to, _, _, _ = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], env, timeout_s=4.0)
            assert not to and rc == 0
            k_pid0 = _live_pids_for(ws, "socks-keep.sh")[0]
            k90_pid0 = _live_pids_for(ws, "socks90-keep.sh")[0]

            # Kill socks90-keep.sh ONLY; keep socks-keep.sh untouched
            os.kill(k90_pid0, signal.SIGKILL)
            time.sleep(0.15)
            assert _live_pids_for(ws, "socks90-keep.sh") == []
            assert _live_pids_for(ws, "socks-keep.sh") == [k_pid0]

            # Next scheduled round must respawn ONLY socks90-keep.sh with SID==PID, and survive subsequent rounds
            rc, to, _, _, _ = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], env, timeout_s=4.0)
            assert not to and rc == 0
            assert _live_pids_for(ws, "socks-keep.sh") == [k_pid0], "Surviving fallback loop must not be disturbed"
            k90_pids_new = _live_pids_for(ws, "socks90-keep.sh")
            assert len(k90_pids_new) == 1
            k90_new = k90_pids_new[0]
            assert k90_new != k90_pid0
            assert os.getsid(k90_new) == k90_new, f"Respawned loop must have SID==PID ({os.getsid(k90_new)} vs {k90_new})"

            # Survives multiple subsequent scheduled rounds without restarting or flapping
            for _ in range(2):
                rc, to, _, _, _ = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], env, timeout_s=4.0)
                assert not to and rc == 0
                assert _live_pids_for(ws, "socks-keep.sh") == [k_pid0]
                assert _live_pids_for(ws, "socks90-keep.sh") == [k90_new]
        finally:
            _cleanup_ws_procs(ws)
    print("PASS test_04_acceptance_2_kill_single_loop_auto_respawns_with_sid_eq_pid_across_rounds")


def test_05_acceptance_3_concurrent_burst_and_60564_dynamic_guard():
    with tempfile.TemporaryDirectory(prefix="planb_acc3_") as td:
        ws, _, hashes_before, env = _make_frozen_workspace(Path(td))
        try:
            # Fire 8 simultaneous wrapper processes + 2 sequential runs -> strictly 1 + 1 loops, 0 stray ensure procs
            procs = [
                subprocess.Popen(["bash", str(WRAPPER_SRC)], env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                for _ in range(8)
            ]
            for p in procs:
                p.communicate(timeout=5.0)
                assert p.returncode == 0
            assert len(_live_pids_for(ws, "socks-keep.sh")) == 1
            assert len(_live_pids_for(ws, "socks90-keep.sh")) == 1
            assert _live_pids_for(ws, "socks-ensure.sh") == []
            assert _live_pids_for(ws, "socks-ensure-detached.sh") == []

            # Verify frozen script bytes & mtime 100% untouched across entire burst
            for fn, (sha0, mt0) in hashes_before.items():
                assert hashlib.sha256((ws / fn).read_bytes()).hexdigest() == sha0
                assert (ws / fn).stat().st_mtime_ns == mt0

            # Verify 60564 read-only guard on a separate separate temp script misconfigured with `-L 11090`
            _cleanup_ws_procs(ws)
            bad90 = Path(td) / "bad-socks90-keep.sh"
            bad90.write_text("#!/bin/bash\nssh -N -L 127.0.0.1:11090:127.0.0.1:11090\nsleep 5\n", encoding="utf-8")
            bad90.chmod(0o755)
            bad_env = dict(env, SOCKS90_KEEP_SCRIPT=str(bad90))
            rc, to, _, _, err = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], bad_env, timeout_s=4.0)
            assert not to and rc == 2 and "60564" in err, f"Expected rc=2 60564 block on -L 11090, got rc={rc} err={err}"
        finally:
            _cleanup_ws_procs(ws)
    print("PASS test_05_acceptance_3_concurrent_burst_and_60564_dynamic_guard")


def test_06_kit_bootstrap_sums_doc_embed_and_update_programs():
    # 1. Verify DEPLOY-SOCKS-KEEP-PLAN-B.txt embeds exact verbatim copy of socks-ensure-detached.sh
    wrapper_text = WRAPPER_SRC.read_text(encoding="utf-8")
    deploy_doc = (KIT_DIR / "DEPLOY-SOCKS-KEEP-PLAN-B.txt").read_text(encoding="utf-8")
    assert wrapper_text in deploy_doc, "DEPLOY-SOCKS-KEEP-PLAN-B.txt must embed exact full source of socks-ensure-detached.sh"

    # 2. Verify bootstrap.sh FILES list matches sha256sums.txt in a clean target directory (v14 rule #10)
    with tempfile.TemporaryDirectory(prefix="planb_boot_") as td:
        dest = Path(td) / "persistent"
        (dest / "scripts").mkdir(parents=True, exist_ok=True)
        files_out = subprocess.check_output(
            ["bash", "-c", f'sed -n "/^FILES=/,/sha256sums.txt/p" "{KIT_DIR / "bootstrap.sh"}" > "{td}/f.sh"; . "{td}/f.sh"; printf "%s\\n" $FILES'],
            text=True,
        ).splitlines()
        assert "socks-ensure-detached.sh" in files_out
        assert "DEPLOY-SOCKS-KEEP-PLAN-B.txt" in files_out
        for rel in files_out:
            src_f = KIT_DIR / rel
            dst_f = dest / rel
            dst_f.parent.mkdir(parents=True, exist_ok=True)
            dst_f.write_bytes(src_f.read_bytes())
        subprocess.run(["sha256sum", "-c", "sha256sums.txt"], cwd=str(dest), check=True, stdout=subprocess.DEVNULL)

        # 3. Verify update-programs.sh runs cleanly end-to-end and installs socks-ensure-detached.sh
        arena_home = Path(td) / "workspace" / "arena-system"
        ws_root = Path(td) / "workspace"
        up_env = os.environ.copy()
        up_env["SOCKS_WORKSPACE_DIR"] = str(ws_root)
        subprocess.run(["bash", str(KIT_DIR / "update-programs.sh"), str(arena_home)], env=up_env, check=True, stdout=subprocess.DEVNULL)
        installed_wrapper = ws_root / "socks-ensure-detached.sh"
        assert installed_wrapper.is_file() and os.access(installed_wrapper, os.X_OK)
        assert installed_wrapper.read_bytes() == WRAPPER_SRC.read_bytes()
    print("PASS test_06_kit_bootstrap_sums_doc_embed_and_update_programs")



def test_07_wrapper_mutation_without_setsid_must_fail_6obJ5_5_3():
    """6obJ5 5.3 non-vacuous negative check on the wrapper itself:
    Mutating socks-ensure-detached.sh to spawn background child without `setsid -f`
    MUST fail scheduled-run detach checks (`timed_out` and/or `0` surviving loops after `killpg`)."""
    with tempfile.TemporaryDirectory(prefix="planb_mut_") as td:
        ws, _, _, env = _make_frozen_workspace(Path(td))
        mut_wrapper = Path(td) / "mutated-no-setsid.sh"
        orig_w = WRAPPER_SRC.read_text(encoding="utf-8")
        # Strip `setsid -f` and FD-close loop so wrapper launches background child in same session
        broken_w = orig_w.replace(
            """  setsid -f /bin/bash -c '
    for _fd in /proc/self/fd/*; do
      _fd="${_fd##*/}"
      case "$_fd" in
        0|1|2) ;;
        *) eval "exec ${_fd}>&-" 2>/dev/null || true ;;
      esac
    done
    if [ -x "$1" ]; then
      exec "$1"
    else
      exec /bin/bash "$1"
    fi
  ' _ "$script_path" </dev/null >>"$log_path" 2>&1""",
            '  /bin/bash "$script_path" </dev/null >>"$log_path" 2>&1 &',
        )
        assert broken_w != orig_w
        mut_wrapper.write_text(broken_w, encoding="utf-8")
        mut_wrapper.chmod(0o755)
        try:
            rc, timed_out, _, _, _ = _run_muse_scheduled_job(["bash", str(mut_wrapper)], env, timeout_s=1.0)
            surviving_k = _live_pids_for(ws, "socks-keep.sh")
            surviving_90 = _live_pids_for(ws, "socks90-keep.sh")
            # Without `setsid -f` + FD scrub, either job times out holding job pipe OR killpg kills both loops!
            assert timed_out or surviving_k == [] or surviving_90 == [], (
                f"Mutated wrapper without setsid unexpectedly survived scheduled run! rc={rc}, k={surviving_k}, 90={surviving_90}"
            )
        finally:
            _cleanup_ws_procs(ws)
    print("PASS test_07_wrapper_mutation_without_setsid_must_fail_6obJ5_5_3")


def test_08_immediate_crash_exit7_and_unopenable_lock_fail_closed_a65_b3():
    """A65 B3 check:
    1) Keep scripts exiting immediately (rc=7) MUST NOT mask as rc=0 — wrapper MUST return non-zero.
    2) Unopenable lock file path (e.g. /dev/null/impossible.lock) MUST fail closed with non-zero rc."""
    with tempfile.TemporaryDirectory(prefix="planb_b3_") as td:
        ws = Path(td)
        for fn in ("socks-keep.sh", "socks90-keep.sh"):
            p = ws / fn
            p.write_text("#!/bin/bash\nexit 7\n", encoding="utf-8")
            p.chmod(0o755)
        env = dict(
            os.environ,
            SOCKS_WORKSPACE_DIR=str(ws),
            SOCKS_ENSURE_LOCK_FILE=str(ws / "b3.lock"),
            SOCKS_KEEP_LOG=str(ws / "k.log"),
            SOCKS90_KEEP_LOG=str(ws / "k90.log"),
        )
        t0 = time.monotonic()
        r1 = subprocess.run(["bash", str(WRAPPER_SRC)], env=env, capture_output=True, text=True, timeout=5)
        el_b3 = time.monotonic() - t0
        assert r1.returncode != 0, f"Expected non-zero on exit 7 failure, got rc={r1.returncode} out={r1.stdout}"
        assert el_b3 < 1.8, f"Host 61220 §2/§3: exit 7 fast-fail path must be well under 2.0s, got {el_b3:.3f}s"
        assert "[START-FAIL]" in r1.stderr and "ERROR" in r1.stderr

        bad_lock_env = dict(env, SOCKS_ENSURE_LOCK_FILE="/dev/null/impossible.lock")
        r2 = subprocess.run(["bash", str(WRAPPER_SRC)], env=bad_lock_env, capture_output=True, text=True, timeout=5)
        assert r2.returncode != 0, f"Expected fail-closed non-zero on unopenable lock, got rc={r2.returncode}"
        assert "[LOCK-ERROR]" in r2.stderr
    print("PASS test_08_immediate_crash_exit7_and_unopenable_lock_fail_closed_a65_b3")


def test_09_columns25_deep_path_truncation_immunity_and_socks5_probe_a87_vii4():
    """A87 SsUv0 VII.4 & Check 4.2 + B2 check:
    1) With COLUMNS=25 and >125-char workspace directory, /proc/<pid>/cmdline detection stays 100% accurate (0 duplicates).
    2) verify-planb-host-acceptance.sh distinguishes real SOCKS5 05 00 responder (rc=0) from fake -L listener (rc=1)."""
    import socket, threading
    verifier = KIT_DIR / "verify-planb-host-acceptance.sh"
    with tempfile.TemporaryDirectory(prefix="planb_col25_") as td:
        deep_ws = Path(td) / ("d" * 70) / ("sub" * 20) / "workspace"
        deep_ws.mkdir(parents=True, exist_ok=True)
        assert len(str(deep_ws)) > 125
        ws, _, _, env = _make_frozen_workspace(deep_ws)
        env["COLUMNS"] = "25"
        try:
            for _ in range(3):
                rc, timed_out, _, _, _ = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], env)
                assert rc == 0 and not timed_out
            assert len(_live_pids_for(ws, "socks-keep.sh")) == 1
            assert len(_live_pids_for(ws, "socks90-keep.sh")) == 1
        finally:
            _cleanup_ws_procs(ws)

    def _serve_once(reply_bytes: bytes):
        srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        srv.bind(("127.0.0.1", 0))
        srv.listen(1)
        port = srv.getsockname()[1]
        def _worker():
            conn, _ = srv.accept()
            with conn:
                _ = conn.recv(16)
                conn.sendall(reply_bytes)
            srv.close()
        t = threading.Thread(target=_worker, daemon=True)
        t.start()
        return port, t

    p_ok, t_ok = _serve_once(b"\x05\x00")
    ok_res = subprocess.run(["bash", str(verifier), "--probe-socks5", "127.0.0.1", str(p_ok)], capture_output=True, text=True)
    t_ok.join(timeout=2)
    assert ok_res.returncode == 0 and "[SOCKS5-OK]" in ok_res.stdout

    p_bad, t_bad = _serve_once(b"HTTP/1.1 400")
    bad_res = subprocess.run(["bash", str(verifier), "--probe-socks5", "127.0.0.1", str(p_bad)], capture_output=True, text=True)
    t_bad.join(timeout=2)
    assert bad_res.returncode != 0 and "[SOCKS5-FAIL]" in bad_res.stderr
    print("PASS test_09_columns25_deep_path_truncation_immunity_and_socks5_probe_a87_vii4")


def test_10_preexisting_duplicate_loops_fail_closed_rc3_nondestructive_and_strict_sshd_a65_d1_d2():
    """A65 61208 D1 & D2 check:
    1) Pre-existing 2+1 duplicate loops MUST NOT silently return 0 AND MUST NOT destructively kill either loop —
       wrapper logs [DUPLICATE-LOOPS] with both PIDs and exits with distinct rc=3 while preserving all 2+1 PIDs.
    2) With SOCKS_REQUIRE_SSH_D=1, a stub lacking executable 'ssh ... -D ... 11090' is rejected with rc=2."""
    with tempfile.TemporaryDirectory(prefix="planb_d1_") as td:
        ws, _, _, env = _make_frozen_workspace(Path(td))
        d1 = d2 = m90 = None
        try:
            with open(ws / "d1.log", "ab") as f1, open(ws / "d2.log", "ab") as f2, open(ws / "d90.log", "ab") as f90:
                d1 = subprocess.Popen(["bash", str(ws / "socks-keep.sh")], stdin=subprocess.DEVNULL, stdout=f1, stderr=subprocess.STDOUT, start_new_session=True)
                d2 = subprocess.Popen(["bash", str(ws / "socks-keep.sh")], stdin=subprocess.DEVNULL, stdout=f2, stderr=subprocess.STDOUT, start_new_session=True)
                m90 = subprocess.Popen(["bash", str(ws / "socks90-keep.sh")], stdin=subprocess.DEVNULL, stdout=f90, stderr=subprocess.STDOUT, start_new_session=True)
            time.sleep(0.15)
            # Default per host ruling 61220 §4: 0 new duplicates spawned, 0 loops killed, warns and returns rc=0
            rc0, timed_out0, _, out0, err0 = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], env)
            assert not timed_out0 and rc0 == 0 and "[WARN-DUPLICATE-LOOPS]" in (out0 + err0)
            assert sorted(_live_pids_for(ws, "socks-keep.sh")) == sorted([d1.pid, d2.pid])
            assert _live_pids_for(ws, "socks90-keep.sh") == [m90.pid]
            # Strict opt-in mode (SOCKS_STRICT_DUPLICATE_RC3=1): surfaces rc=3 without killing processes
            rc, timed_out, _, out, err = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], dict(env, SOCKS_STRICT_DUPLICATE_RC3="1"))
            assert not timed_out and rc == 3 and "[DUPLICATE-LOOPS]" in (out + err)
            assert sorted(_live_pids_for(ws, "socks-keep.sh")) == sorted([d1.pid, d2.pid])
            assert _live_pids_for(ws, "socks90-keep.sh") == [m90.pid]
        finally:
            _cleanup_ws_procs(ws)

    with tempfile.TemporaryDirectory(prefix="planb_d2_") as td2:
        ws2, _, _, env2 = _make_frozen_workspace(Path(td2))
        stub_no_d = ws2 / "no-d-90.sh"
        stub_no_d.write_text("#!/bin/bash\nwhile :; do sleep 1; done\n", encoding="utf-8")
        stub_no_d.chmod(0o755)
        env2["SOCKS90_KEEP_SCRIPT"] = str(stub_no_d)
        env2["SOCKS_REQUIRE_SSH_D"] = "1"
        try:
            rc2, timed_out2, _, out2, err2 = _run_muse_scheduled_job(["bash", str(WRAPPER_SRC)], env2)
            assert not timed_out2 and rc2 == 2 and "[FATAL-11090-NO-SSH-D]" in (out2 + err2)
        finally:
            _cleanup_ws_procs(ws2)
    print("PASS test_10_preexisting_duplicate_loops_fail_closed_rc3_nondestructive_and_strict_sshd_a65_d1_d2")


def test_11_host_61212_delayed_death_same_pid_and_cross_dir_isolation():
    """Host ruling 61212 + A87 61213 (dKWkD) + A65 61215 (liD6g / wP4Y2):
    (a) Bundled A87 dKWkD script (`a87_planb_spawn_survival_regression.sh`) passes (rc=0) on default wrapper
        and goes RED (rc=1) if survival window is artificially shrunk to 0.05s.
    (b) Mixed 0.30s delayed death (`sleep 0.30; exit 1` on socks-keep + healthy socks90-keep) returns rc=1,
        emits ERROR on stderr, leaves 0 surviving socks-keep, and preserves healthy socks90-keep with SID==PID.
    (c) Same-PID enforcement: a flapping script that forks a replacement PID at 0.10s and exits original PID at 0.20s
        MUST STILL FAIL (`rc=1`) because candidate PID died even though another PID exists at window end!
    (d) Cross-directory isolation: live socks-keep.sh in foreign workspace A never blocks startup in workspace B."""
    a87_script = KIT_DIR / "a87_planb_spawn_survival_regression.sh"
    r_green = subprocess.run(["bash", str(a87_script), str(WRAPPER_SRC)], capture_output=True, text=True, timeout=10)
    assert r_green.returncode == 0, f"dKWkD expected PASS (0), got rc={r_green.returncode}:\n{r_green.stdout}\n{r_green.stderr}"

    env_short = dict(os.environ, SOCKS_START_SETTLE_SEC="0.05")
    r_red = subprocess.run(["bash", str(a87_script), str(WRAPPER_SRC)], env=env_short, capture_output=True, text=True, timeout=10)
    assert r_red.returncode == 1, f"dKWkD with 0.05s window MUST go RED (1), got rc={r_red.returncode}"

    # (b) Mixed delayed death (A65 liD6g)
    with tempfile.TemporaryDirectory(prefix="planb_61212_mix_") as td:
        ws = Path(td)
        keep = ws / "socks-keep.sh"
        keep90 = ws / "socks90-keep.sh"
        keep.write_text("#!/bin/bash\nsleep 0.30\nexit 1\n", encoding="utf-8")
        keep90.write_text("#!/bin/bash\ntrap 'exit 0' TERM INT\nwhile :; do sleep 0.2; done\n", encoding="utf-8")
        keep.chmod(0o755); keep90.chmod(0o755)
        env = dict(os.environ, SOCKS_WORKSPACE_DIR=str(ws), SOCKS_KEEP_LOG=str(ws / "k.log"),
                   SOCKS90_KEEP_LOG=str(ws / "k90.log"), SOCKS_ENSURE_DETACHED_LOG=str(ws / "w.log"),
                   SOCKS_ENSURE_LOCK_FILE=str(ws / "w.lock"))
        try:
            res = subprocess.run(["bash", str(WRAPPER_SRC)], env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=5)
            assert res.returncode == 1 and "ERROR" in res.stderr, f"Expected rc=1 + ERROR on stderr, got rc={res.returncode} err={res.stderr}"
            assert _live_pids_for(ws, "socks-keep.sh") == []
            p90 = _live_pids_for(ws, "socks90-keep.sh")
            assert len(p90) == 1 and os.getsid(p90[0]) == p90[0]
        finally:
            _cleanup_ws_procs(ws)

    # (c) Same-PID spoof check (A87 61213 §3.1 & A65 wP4Y2 #1)
    with tempfile.TemporaryDirectory(prefix="planb_samepid_") as td2:
        ws2 = Path(td2)
        keep2 = ws2 / "socks-keep.sh"
        keep90_2 = ws2 / "socks90-keep.sh"
        keep2.write_text(
            '#!/bin/bash\nif [ "${1:-}" = "--clone" ]; then while :; do sleep 0.2; done; fi\n'
            'sleep 0.12\nsetsid -f /bin/bash "$0" --clone </dev/null >/dev/null 2>&1\nsleep 0.08\nexit 1\n',
            encoding="utf-8",
        )
        keep90_2.write_text("#!/bin/bash\ntrap 'exit 0' TERM INT\nwhile :; do sleep 0.2; done\n", encoding="utf-8")
        keep2.chmod(0o755); keep90_2.chmod(0o755)
        env2 = dict(os.environ, SOCKS_WORKSPACE_DIR=str(ws2), SOCKS_KEEP_LOG=str(ws2 / "k.log"),
                    SOCKS90_KEEP_LOG=str(ws2 / "k90.log"), SOCKS_ENSURE_LOCK_FILE=str(ws2 / "w.lock"))
        try:
            res2 = subprocess.run(["bash", str(WRAPPER_SRC)], env=env2, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=5)
            assert res2.returncode == 1 and "ERROR" in res2.stderr, f"Same-PID check failed: rc={res2.returncode} out={res2.stdout} err={res2.stderr}"
        finally:
            _cleanup_ws_procs(ws2)

    # (d) Cross-directory isolation check (Host 61212 note)
    with tempfile.TemporaryDirectory(prefix="planb_iso_") as td3:
        ws_a = Path(td3) / "foreign_ws_A"
        ws_b = Path(td3) / "target_ws_B"
        ws_a.mkdir(); ws_b.mkdir()
        real_ws_a, _, _, env_a = _make_frozen_workspace(ws_a)
        real_ws_b, _, _, env_b = _make_frozen_workspace(ws_b)
        try:
            ra = subprocess.run(["bash", str(WRAPPER_SRC)], env=env_a, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=5)
            rb = subprocess.run(["bash", str(WRAPPER_SRC)], env=env_b, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=5)
            assert ra.returncode == 0 and rb.returncode == 0
            assert len(_live_pids_for(real_ws_a, "socks-keep.sh")) == 1
            assert len(_live_pids_for(real_ws_b, "socks-keep.sh")) == 1
        finally:
            _cleanup_ws_procs(real_ws_a)
            _cleanup_ws_procs(real_ws_b)
    print("PASS test_11_host_61212_delayed_death_same_pid_and_cross_dir_isolation")

class TestSocksKeepPlanB61193(unittest.TestCase):
    def test_01_case(self):
        test_01_reproduce_legacy_nohup_pipe_hang_and_tree_kill_flap()

    def test_02_case(self):
        test_02_acceptance_1_two_consecutive_scheduled_runs_exit_0_fast_and_clean_fds()

    def test_03_case(self):
        test_03_plan_a_existing_manual_setsid_loops_preserved_untouched()

    def test_04_case(self):
        test_04_acceptance_2_kill_single_loop_auto_respawns_with_sid_eq_pid_across_rounds()

    def test_05_case(self):
        test_05_acceptance_3_concurrent_burst_and_60564_dynamic_guard()

    def test_06_case(self):
        test_06_kit_bootstrap_sums_doc_embed_and_update_programs()

    def test_07_case(self):
        test_07_wrapper_mutation_without_setsid_must_fail_6obJ5_5_3()

    def test_08_case(self):
        test_08_immediate_crash_exit7_and_unopenable_lock_fail_closed_a65_b3()

    def test_09_case(self):
        test_09_columns25_deep_path_truncation_immunity_and_socks5_probe_a87_vii4()

    def test_10_case(self):
        test_10_preexisting_duplicate_loops_fail_closed_rc3_nondestructive_and_strict_sshd_a65_d1_d2()

    def test_11_case(self):
        test_11_host_61212_delayed_death_same_pid_and_cross_dir_isolation()


if __name__ == "__main__":
    test_01_reproduce_legacy_nohup_pipe_hang_and_tree_kill_flap()
    test_02_acceptance_1_two_consecutive_scheduled_runs_exit_0_fast_and_clean_fds()
    test_03_plan_a_existing_manual_setsid_loops_preserved_untouched()
    test_04_acceptance_2_kill_single_loop_auto_respawns_with_sid_eq_pid_across_rounds()
    test_05_acceptance_3_concurrent_burst_and_60564_dynamic_guard()
    test_06_kit_bootstrap_sums_doc_embed_and_update_programs()
    test_07_wrapper_mutation_without_setsid_must_fail_6obJ5_5_3()
    test_08_immediate_crash_exit7_and_unopenable_lock_fail_closed_a65_b3()
    test_09_columns25_deep_path_truncation_immunity_and_socks5_probe_a87_vii4()
    test_10_preexisting_duplicate_loops_fail_closed_rc3_nondestructive_and_strict_sshd_a65_d1_d2()
    test_11_host_61212_delayed_death_same_pid_and_cross_dir_isolation()
    print("ALL 11/11 SOCKS-KEEP PLAN B (61193 + 61212 + dKWkD + liD6g + D1-D3) TESTS PASSED!")
