Output:
Chunk ID: 84b345
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1083
Output:
from __future__ import annotations

import json
import multiprocessing
import os
import random
import shutil
import subprocess
import sys
from collections import Counter
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import remote_dispatch

REGISTRY = {
    "schema_version": 1,
    "hosts": [
        {
            "name": "debian1",
            "state": "reachable",
            "roles": ["builder", "agent-seat"],
            "access": {
                "tailscale_ip": {
                    "host": "100.0.0.1",
                    "port": 2222,
                    "user": "user",
                    "identity_file": "~/.ssh/id_ed25519_buildbox",
                }
            },
        },
        {
            "name": "debian2",
            "state": "reachable",
            "roles": ["builder", "agent-seat"],
            "access": {"tailscale_ip": {"host": "100.0.0.2", "port": 2222, "user": "user"}},
        },
        {
            "name": "debian3",
            "state": "unreachable",
            "roles": ["builder", "agent-seat"],
            "access": {"tailscale_ip": {"host": "100.0.0.3", "port": 2222, "user": "user"}},
        },
    ],
}

THREE_REACHABLE = {
    "schema_version": 1,
    "hosts": [
        {
            "name": f"debian{n}",
            "state": "reachable",
            "roles": ["agent-seat"],
            "access": {"tailscale_ip": {"host": f"100.0.0.{n}", "user": "user"}},
        }
        for n in (1, 2, 3)
    ],
}

@pytest.fixture(autouse=True)
def isolated_claim_dir(tmp_path_factory, monkeypatch):
    """No test may write placement claims into the real ~/.local/state directory."""
    directory = tmp_path_factory.mktemp("claims")
    monkeypatch.setenv(remote_dispatch.CLAIM_DIR_ENV, str(directory))
    return directory

def write_registry(tmp_path: Path, payload: dict | None = None) -> Path:
    path = tmp_path / "buildbox-hosts.json"
    path.write_text(json.dumps(payload if payload is not None else REGISTRY), encoding="utf-8")
    return path

def test_should_offload_defaults_true():
    assert remote_dispatch.should_offload({}) is True

def test_should_offload_opt_out():
    assert remote_dispatch.should_offload({"CDX_NO_OFFLOAD": "1"}) is False

def test_should_offload_false_when_already_on_a_node():
    assert remote_dispatch.should_offload({"OD_REMOTE_EXEC": "1"}) is False
    assert remote_dispatch.should_offload({"HARNESS_SEAT_CONTAINER": "1"}) is False

def test_candidate_hosts_excludes_unreachable():
    names = [h["name"] for h in remote_dispatch.candidate_hosts(REGISTRY)]
    assert names == ["debian1", "debian2"]

def test_candidate_hosts_raises_when_none_reachable():
    payload = {"hosts": [dict(REGISTRY["hosts"][2])]}
    with pytest.raises(remote_dispatch.OffloadUnavailable):
        remote_dispatch.candidate_hosts(payload)

def test_select_host_picks_least_loaded():
    loads = {"100.0.0.1": 9.5, "100.0.0.2": 0.4}
    host, access, _claim = remote_dispatch.select_host(
        remote_dispatch.candidate_hosts(REGISTRY),
        probe=lambda a: loads[a["host"]],
    )
    assert host["name"] == "debian2"
    assert access["host"] == "100.0.0.2"

def test_select_host_skips_nodes_that_do_not_answer():
    host, _access, _claim = remote_dispatch.select_host(
        remote_dispatch.candidate_hosts(REGISTRY),
        probe=lambda a: None if a["host"] == "100.0.0.2" else 7.0,
    )
    assert host["name"] == "debian1"

def test_select_host_raises_when_no_node_answers():
    with pytest.raises(remote_dispatch.OffloadUnavailable):
        remote_dispatch.select_host(remote_dispatch.candidate_hosts(REGISTRY), probe=lambda a: None)

def test_parse_loadavg():
    assert remote_dispatch.parse_loadavg("0.52 0.31 0.20 1/900 12345\n") == 0.52
    assert remote_dispatch.parse_loadavg("") is None
    assert remote_dispatch.parse_loadavg("garbage") is None

def test_remote_rel_dir_is_stable_and_path_specific():
    a = remote_dispatch.remote_rel_dir(Path("/home/user/Projects/overdeck/.worktrees/one"))
    b = remote_dispatch.remote_rel_dir(Path("/home/user/Projects/overdeck/.worktrees/two"))
    assert a == remote_dispatch.remote_rel_dir(Path("/home/user/Projects/overdeck/.worktrees/one"))
    assert a != b
    assert a.startswith("cdx-offload/one-")


sed -n '220,320p' modules/systray/tests/test_remote_dispatch.py


Output:
Chunk ID: 980006
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 982
Output:
def test_remote_run_argv_forces_a_tty():
    access = REGISTRY["hosts"][1]["access"]["tailscale_ip"]
    argv = remote_dispatch.remote_run_argv(access, "d", "codex", ["exec", "hi"])
    assert "-tt" in argv
    assert argv[0] == "ssh"

def test_open_session_pushes_then_returns_remote_argv(tmp_path, monkeypatch):
    calls: list[list[str]] = []

    def fake_run(argv, **kwargs):
        calls.append(argv)
        return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")

    monkeypatch.setattr(remote_dispatch, "repo_root", lambda cwd=None: tmp_path / "repo")
    session = remote_dispatch.open_session(
        "codex",
        ["exec", "hi"],
        registry_path=write_registry(tmp_path),
        run=fake_run,
        probe=lambda a: 1.0 if a["host"] == "100.0.0.1" else 5.0,
    )
    assert session.host_name == "debian1"
    assert any("mkdir -p" in " ".join(c) for c in calls)
    assert any(c[0] == "rsync" for c in calls)
    assert session.argv[0] == "ssh" and "-tt" in session.argv

def test_open_session_fails_closed_when_the_push_fails(tmp_path, monkeypatch):
    def fake_run(argv, **kwargs):
        rc = 1 if argv[0] == "rsync" else 0
        return subprocess.CompletedProcess(argv, rc, stdout="", stderr="disk full")

    monkeypatch.setattr(remote_dispatch, "repo_root", lambda cwd=None: tmp_path / "repo")
    with pytest.raises(remote_dispatch.OffloadUnavailable, match="mirror push failed"):
        remote_dispatch.open_session(
            "codex",
            ["exec", "hi"],
            registry_path=write_registry(tmp_path),
            run=fake_run,
            probe=lambda a: 1.0,
        )

def test_pull_back_reports_failure_instead_of_raising(tmp_path):
    session = remote_dispatch.Session(
        host_name="debian1",
        access=REGISTRY["hosts"][0]["access"]["tailscale_ip"],
        root=tmp_path,
        rel_dir="cdx-offload/x",
        argv=["ssh"],
    )
    err = session.pull_back(
        run=lambda argv, **kw: subprocess.CompletedProcess(argv, 23, stdout="", stderr="boom")
    )
    assert err is not None and "debian1" in err and "boom" in err
    assert session.pull_back(
        run=lambda argv, **kw: subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
    ) is None

def test_load_registry_missing_file_is_offload_unavailable(tmp_path):
    with pytest.raises(remote_dispatch.OffloadUnavailable):
        remote_dispatch.load_registry(tmp_path / "nope.json")

def test_git_mirror_is_none_for_a_plain_checkout(tmp_path):
    assert remote_dispatch.git_mirror(make_repo(tmp_path)) is None

def test_git_mirror_is_none_outside_a_repository(tmp_path):
    plain = tmp_path / "notrepo"
    plain.mkdir()
    assert remote_dispatch.git_mirror(plain) is None

def test_git_mirror_detects_a_linked_worktree_and_targets_the_common_worktrees_dir(tmp_path):
    root = make_repo(tmp_path)
    wt = add_worktree(root, "alpha")
    mirror = remote_dispatch.git_mirror(wt)
    assert mirror is not None
    assert mirror.git_dir == (root / ".git" / "worktrees" / "alpha").resolve()
    assert mirror.common_dir == (root / ".git").resolve()
    assert mirror.remote_common.startswith("cdx-offload/git-common/repo-")
    assert mirror.remote_git_dir == f"{mirror.remote_common}/worktrees/alpha"

def test_two_worktrees_of_one_repo_share_the_common_mirror_but_not_the_gitdir(tmp_path):
    root = make_repo(tmp_path)
    one = remote_dispatch.git_mirror(add_worktree(root, "one"))
    two = remote_dispatch.git_mirror(add_worktree(root, "two"))
    assert one.remote_common == two.remote_common
    assert one.remote_git_dir != two.remote_git_dir

def test_common_push_keeps_sibling_worktrees_out_and_never_deletes():
    access = REGISTRY["hosts"][1]["access"]["tailscale_ip"]
    mirror = remote_dispatch.GitMirror(
        git_dir=Path("/r/.git/worktrees/a"),
        common_dir=Path("/r/.git"),
        remote_common="cdx-offload/git-common/r-abc",


Input:
*** Begin Patch
*** Update File: modules/systray/remote_dispatch.py
@@
 CLAIM_SUFFIX = ".claim"
 CLAIM_LOAD_PENALTY = 1.0
+EXIT_NO_NODE = 80
+EXIT_CREDENTIAL = 81
+EXIT_MIRROR = 82
+EXIT_LAUNCH = 83
+EXIT_UNCONTAINABLE = 84

 class OffloadUnavailable(RuntimeError):
     """No cluster node can take this run."""

+    def __init__(self, message: str, code: int = EXIT_NO_NODE) -> None:
+        super().__init__(message)
+        self.code = code
+
+
+def in_container() -> bool:
+    """Machine-local evidence, not env: an env marker is agent-settable."""
+    for probe in (Path("/run/.containerenv"), Path("/.dockerenv")):
+        if probe.exists():
+            return True
+    try:
+        cgroup = Path("/proc/self/cgroup").read_text(encoding="utf-8")
+    except OSError:
+        return False
+    return "libpod" in cgroup or "docker" in cgroup
+

-def should_offload(env: dict[str, str] | None = None) -> bool:
-    """False when offload is opted out, or when this process is already on a node."""
-    env = os.environ if env is None else env
-    if env.get("CDX_NO_OFFLOAD") == "1":
-        return False
-    return not (
-        env.get("OD_REMOTE_EXEC") == "1" or env.get("HARNESS_SEAT_CONTAINER") == "1"
-    )
+def should_offload() -> bool:
+    return not in_container()

 def load_registry(path: Path = REGISTRY_PATH) -> dict:
     try:
         return json.loads(Path(path).read_text(encoding="utf-8"))
     except (OSError, ValueError) as exc:
-        raise OffloadUnavailable(f"buildbox registry unreadable at {path}: {exc}") from exc
+        raise OffloadUnavailable(
+            f"buildbox registry unreadable at {path}: {exc}", code=EXIT_NO_NODE
+        ) from exc
@@
     hosts = [
         host
         for host in registry.get("hosts", [])
         if host.get("state") == "reachable" and role in (host.get("roles") or [])
     ]
     if not hosts:
-        raise OffloadUnavailable(f"no reachable host with role {role} in the registry")
+        raise OffloadUnavailable(
+            f"no reachable host with role {role} in the registry", code=EXIT_NO_NODE
+        )
     return hosts
@@
 def access_for(host: dict, door: str = DOOR) -> dict:
     access = (host.get("access") or {}).get(door)
     if not access or not access.get("host"):
-        raise OffloadUnavailable(f"{host.get('name')}: no usable {door} access door")
+        raise OffloadUnavailable(
+            f"{host.get('name')}: no usable {door} access door", code=EXIT_NO_NODE
+        )
     return access
@@
     if not probed:
-        raise OffloadUnavailable("; ".join(failures) or "no candidate node answered")
+        raise OffloadUnavailable(
+            "; ".join(failures) or "no candidate node answered", code=EXIT_NO_NODE
+        )
@@
         try:
             made = run(
                 [*ssh_argv(access), f"mkdir -p {shlex.join(remote_dirs)}"],
                 capture_output=True,
                 text=True,
                 timeout=PROBE_TIMEOUT_SEC,
             )
         except (OSError, subprocess.SubprocessError) as exc:
-            raise OffloadUnavailable(f"{name}: could not prepare mirror: {exc}") from exc
+            raise OffloadUnavailable(
+                f"{name}: could not prepare mirror: {exc}", code=EXIT_MIRROR
+            ) from exc
         if made.returncode != 0:
-            raise OffloadUnavailable(f"{name}: could not prepare mirror: {made.stderr.strip()}")
+            raise OffloadUnavailable(
+                f"{name}: could not prepare mirror: {made.stderr.strip()}",
+                code=EXIT_MIRROR,
+            )

         try:
             pushed = run(
                 push_argv(access, root, rel_dir, exclude_git=mirror is not None),
                 capture_output=True,
                 text=True,
                 timeout=SYNC_TIMEOUT_SEC,
             )
         except (OSError, subprocess.SubprocessError) as exc:
-            raise OffloadUnavailable(f"{name}: mirror push failed: {exc}") from exc
+            raise OffloadUnavailable(
+                f"{name}: mirror push failed: {exc}", code=EXIT_MIRROR
+            ) from exc
         if pushed.returncode != 0:
-            raise OffloadUnavailable(f"{name}: mirror push failed: {pushed.stderr.strip()}")
+            raise OffloadUnavailable(
+                f"{name}: mirror push failed: {pushed.stderr.strip()}",
+                code=EXIT_MIRROR,
+            )
*** End Patch


Success. Updated the following files:
M modules/systray/remote_dispatch.py

@@ -53,2 +53,7 @@
 CLAIM_LOAD_PENALTY = 1.0
+EXIT_NO_NODE = 80
+EXIT_CREDENTIAL = 81
+EXIT_MIRROR = 82
+EXIT_LAUNCH = 83
+EXIT_UNCONTAINABLE = 84

@@ -58,11 +63,21 @@

+    def __init__(self, message: str, code: int = EXIT_NO_NODE) -> None:
+        super().__init__(message)
+        self.code = code
+

-def should_offload(env: dict[str, str] | None = None) -> bool:
-    """False when offload is opted out, or when this process is already on a node."""
-    env = os.environ if env is None else env
-    if env.get("CDX_NO_OFFLOAD") == "1":
+def in_container() -> bool:
+    """Machine-local evidence, not env: an env marker is agent-settable."""
+    for probe in (Path("/run/.containerenv"), Path("/.dockerenv")):
+        if probe.exists():
+            return True
+    try:
+        cgroup = Path("/proc/self/cgroup").read_text(encoding="utf-8")
+    except OSError:
         return False
-    return not (
-        env.get("OD_REMOTE_EXEC") == "1" or env.get("HARNESS_SEAT_CONTAINER") == "1"
-    )
+    return "libpod" in cgroup or "docker" in cgroup
+
+
+def should_offload() -> bool:
+    return not in_container()

@@ -73,3 +88,5 @@
     except (OSError, ValueError) as exc:
-        raise OffloadUnavailable(f"buildbox registry unreadable at {path}: {exc}") from exc
+        raise OffloadUnavailable(
+            f"buildbox registry unreadable at {path}: {exc}", code=EXIT_NO_NODE
+        ) from exc

@@ -84,3 +101,5 @@
     if not hosts:
-        raise OffloadUnavailable(f"no reachable host with role {role} in the registry")
+        raise OffloadUnavailable(
+            f"no reachable host with role {role} in the registry", code=EXIT_NO_NODE
+        )
     return hosts
@@ -91,3 +110,5 @@
     if not access or not access.get("host"):
-        raise OffloadUnavailable(f"{host.get('name')}: no usable {door} access door")
+        raise OffloadUnavailable(
+            f"{host.get('name')}: no usable {door} access door", code=EXIT_NO_NODE
+        )
     return access
@@ -268,3 +289,5 @@
     if not probed:
-        raise OffloadUnavailable("; ".join(failures) or "no candidate node answered")
+        raise OffloadUnavailable(
+            "; ".join(failures) or "no candidate node answered", code=EXIT_NO_NODE
+        )

@@ -562,5 +585,10 @@
         except (OSError, subprocess.SubprocessError) as exc:
-            raise OffloadUnavailable(f"{name}: could not prepare mirror: {exc}") from exc
+            raise OffloadUnavailable(
+                f"{name}: could not prepare mirror: {exc}", code=EXIT_MIRROR
+            ) from exc
         if made.returncode != 0:
-            raise OffloadUnavailable(f"{name}: could not prepare mirror: {made.stderr.strip()}")
+            raise OffloadUnavailable(
+                f"{name}: could not prepare mirror: {made.stderr.strip()}",
+                code=EXIT_MIRROR,
+            )

@@ -574,5 +602,10 @@
         except (OSError, subprocess.SubprocessError) as exc:
-            raise OffloadUnavailable(f"{name}: mirror push failed: {exc}") from exc
+            raise OffloadUnavailable(
+                f"{name}: mirror push failed: {exc}", code=EXIT_MIRROR
+            ) from exc
         if pushed.returncode != 0:
-            raise OffloadUnavailable(f"{name}: mirror push failed: {pushed.stderr.strip()}")
+            raise OffloadUnavailable(
+                f"{name}: mirror push failed: {pushed.stderr.strip()}",
+                code=EXIT_MIRROR,
+            )


Output:
Exit code: 0
Wall time: 0 seconds
Output:
Success. Updated the following files:
M modules/systray/remote_dispatch.py


I’ve applied the first pass in `remote_dispatch.py` (container detection, fail-closed semantics, exit code constants, and exception codes). Next I’m patching router flow and the tests in one shot.


Input:
*** Begin Patch
*** Update File: modules/systray/command_router.py
@@
         log_path = self.adapter.capture_log_path(forwarded_argv)
         if log_path is not None:
             return self._run_captured(forwarded_argv, env, log_path)

-        os.execvpe(self.adapter.exec_name, [self.adapter.exec_name, *forwarded_argv], env)
+        if remote_dispatch.in_container():
+            os.execvpe(self.adapter.exec_name, [self.adapter.exec_name, *forwarded_argv], env)
+            return 0
+
+        reason = (
+            "no writable log directory"
+            if is_exec_invocation(forwarded_argv)
+            else "adapter captures no log for these arguments"
+        )
+        print(
+            f"{self.adapter.tool_name}: no containerized path for this invocation ({reason})",
+            file=sys.stderr,
+        )
+        return remote_dispatch.EXIT_UNCONTAINABLE
         return 0

     def _run_captured(self, forwarded_argv: list[str], env: dict[str, str], log_path: Path) -> int:
         started = time.monotonic()
         tool = self.adapter.tool_name
         argv = [self.adapter.exec_name, *forwarded_argv]
         session = None
-        if remote_dispatch.should_offload(env):
+        if remote_dispatch.should_offload():
             try:
                 session = remote_dispatch.open_session(self.adapter.exec_name, forwarded_argv)
             except remote_dispatch.OffloadUnavailable as exc:
-                if env.get("CDX_OFFLOAD_STRICT") == "1":
-                    print(f"{tool}: cluster offload unavailable — {exc}", file=sys.stderr)
-                    return 1
-                print(
-                    f"{tool}: cluster offload unavailable — {exc}; RUNNING ON THE WORKSTATION",
-                    file=sys.stderr,
-                )
+                print(f"{tool}: containment unavailable — {exc}", file=sys.stderr)
+                return exc.code
             else:
                 argv = session.argv
                 print(f"{tool}: running on {session.host_name} ({session.rel_dir})", file=sys.stderr)
                 if session.git_warning is not None:
                     print(f"{tool}: {session.git_warning}", file=sys.stderr)
*** End Patch


Success. Updated the following files:
M modules/systray/command_router.py

@@ -763,3 +763,16 @@

-        os.execvpe(self.adapter.exec_name, [self.adapter.exec_name, *forwarded_argv], env)
+        if remote_dispatch.in_container():
+            os.execvpe(self.adapter.exec_name, [self.adapter.exec_name, *forwarded_argv], env)
+            return 0
+
+        reason = (
+            "no writable log directory"
+            if is_exec_invocation(forwarded_argv)
+            else "adapter captures no log for these arguments"
+        )
+        print(
+            f"{self.adapter.tool_name}: no containerized path for this invocation ({reason})",
+            file=sys.stderr,
+        )
+        return remote_dispatch.EXIT_UNCONTAINABLE
         return 0
@@ -771,3 +784,3 @@
         session = None
-        if remote_dispatch.should_offload(env):
+        if remote_dispatch.should_offload():
             try:
@@ -775,9 +788,4 @@
             except remote_dispatch.OffloadUnavailable as exc:
-                if env.get("CDX_OFFLOAD_STRICT") == "1":
-                    print(f"{tool}: cluster offload unavailable — {exc}", file=sys.stderr)
-                    return 1
-                print(
-                    f"{tool}: cluster offload unavailable — {exc}; RUNNING ON THE WORKSTATION",
-                    file=sys.stderr,
-                )
+                print(f"{tool}: containment unavailable — {exc}", file=sys.stderr)
+                return exc.code
             else:


Output:
Exit code: 0
Wall time: 0 seconds
Output:
Success. Updated the following files:
M modules/systray/command_router.py


Input:
*** Begin Patch
*** Update File: modules/systray/tests/test_remote_dispatch.py
@@
 def write_registry(tmp_path: Path, payload: dict | None = None) -> Path:
     path = tmp_path / "buildbox-hosts.json"
     path.write_text(json.dumps(payload if payload is not None else REGISTRY), encoding="utf-8")
     return path

-def test_should_offload_defaults_true():
-    assert remote_dispatch.should_offload({}) is True
+def test_should_offload_true_when_not_in_container(monkeypatch):
+    monkeypatch.setattr(remote_dispatch, "in_container", lambda: False)
+    assert remote_dispatch.should_offload() is True

-def test_should_offload_opt_out():
-    assert remote_dispatch.should_offload({"CDX_NO_OFFLOAD": "1"}) is False
+def test_should_offload_false_when_in_container(monkeypatch):
+    monkeypatch.setattr(remote_dispatch, "in_container", lambda: True)
+    assert remote_dispatch.should_offload() is False

-def test_should_offload_false_when_already_on_a_node():
-    assert remote_dispatch.should_offload({"OD_REMOTE_EXEC": "1"}) is False
-    assert remote_dispatch.should_offload({"HARNESS_SEAT_CONTAINER": "1"}) is False
+def test_should_offload_ignores_env(monkeypatch):
+    monkeypatch.setenv("CDX_NO_OFFLOAD", "1")
+    monkeypatch.setenv("OD_REMOTE_EXEC", "1")
+    monkeypatch.setenv("HARNESS_SEAT_CONTAINER", "1")
+    monkeypatch.setenv("CDX_OFFLOAD_STRICT", "0")
+
+    monkeypatch.setattr(remote_dispatch, "in_container", lambda: False)
+    assert remote_dispatch.should_offload() is True
+
+    monkeypatch.setattr(remote_dispatch, "in_container", lambda: True)
+    assert remote_dispatch.should_offload() is False
+
+
+def test_access_for_raises_credential_error(remote_dispatch_payload: None = None):
+    host = {
+        "name": "debian1",
+        "access": {},
+    }
+    with pytest.raises(remote_dispatch.OffloadUnavailable) as exc_info:
+        remote_dispatch.access_for(host)
+    assert exc_info.value.code == remote_dispatch.EXIT_NO_NODE
@@
 def test_candidate_hosts_raises_when_none_reachable():
     payload = {"hosts": [dict(REGISTRY["hosts"][2])]}
-    with pytest.raises(remote_dispatch.OffloadUnavailable):
+    with pytest.raises(remote_dispatch.OffloadUnavailable) as exc_info:
         remote_dispatch.candidate_hosts(payload)
+    assert exc_info.value.code == remote_dispatch.EXIT_NO_NODE
@@
 def test_select_host_raises_when_no_node_answers():
-    with pytest.raises(remote_dispatch.OffloadUnavailable):
+    with pytest.raises(remote_dispatch.OffloadUnavailable):
         remote_dispatch.select_host(remote_dispatch.candidate_hosts(REGISTRY), probe=lambda a: None)
@@
 def test_open_session_fails_closed_when_the_push_fails(tmp_path, monkeypatch):
     def fake_run(argv, **kwargs):
         rc = 1 if argv[0] == "rsync" else 0
         return subprocess.CompletedProcess(argv, rc, stdout="", stderr="disk full")

     monkeypatch.setattr(remote_dispatch, "repo_root", lambda cwd=None: tmp_path / "repo")
-    with pytest.raises(remote_dispatch.OffloadUnavailable, match="mirror push failed"):
+    with pytest.raises(remote_dispatch.OffloadUnavailable, match="mirror push failed") as exc_info:
         remote_dispatch.open_session(
             "codex",
             ["exec", "hi"],
             registry_path=write_registry(tmp_path),
             run=fake_run,
             probe=lambda a: 1.0,
         )
+    assert exc_info.value.code == remote_dispatch.EXIT_MIRROR
@@
 def test_load_registry_missing_file_is_offload_unavailable(tmp_path):
-    with pytest.raises(remote_dispatch.OffloadUnavailable):
+    with pytest.raises(remote_dispatch.OffloadUnavailable) as exc_info:
         remote_dispatch.load_registry(tmp_path / "nope.json")
+    assert exc_info.value.code == remote_dispatch.EXIT_NO_NODE
*** End Patch


Success. Updated the following files:
M modules/systray/tests/test_remote_dispatch.py

@@ -79,15 +79,35 @@

-def test_should_offload_defaults_true():
-    assert remote_dispatch.should_offload({}) is True
+def test_should_offload_true_when_not_in_container(monkeypatch):
+    monkeypatch.setattr(remote_dispatch, "in_container", lambda: False)
+    assert remote_dispatch.should_offload() is True

-def test_should_offload_opt_out():
-    assert remote_dispatch.should_offload({"CDX_NO_OFFLOAD": "1"}) is False
+def test_should_offload_false_when_in_container(monkeypatch):
+    monkeypatch.setattr(remote_dispatch, "in_container", lambda: True)
+    assert remote_dispatch.should_offload() is False

-def test_should_offload_false_when_already_on_a_node():
-    assert remote_dispatch.should_offload({"OD_REMOTE_EXEC": "1"}) is False
-    assert remote_dispatch.should_offload({"HARNESS_SEAT_CONTAINER": "1"}) is False
+def test_should_offload_ignores_env(monkeypatch):
+    monkeypatch.setenv("CDX_NO_OFFLOAD", "1")
+    monkeypatch.setenv("OD_REMOTE_EXEC", "1")
+    monkeypatch.setenv("HARNESS_SEAT_CONTAINER", "1")
+    monkeypatch.setenv("CDX_OFFLOAD_STRICT", "0")

+    monkeypatch.setattr(remote_dispatch, "in_container", lambda: False)
+    assert remote_dispatch.should_offload() is True

+    monkeypatch.setattr(remote_dispatch, "in_container", lambda: True)
+    assert remote_dispatch.should_offload() is False
+
+
+def test_access_for_raises_credential_error(remote_dispatch_payload: None = None):
+    host = {
+        "name": "debian1",
+        "access": {},
+    }
+    with pytest.raises(remote_dispatch.OffloadUnavailable) as exc_info:
+        remote_dispatch.access_for(host)
+    assert exc_info.value.code == remote_dispatch.EXIT_NO_NODE
+
+
 def test_candidate_hosts_excludes_unreachable():
@@ -99,4 +119,5 @@
     payload = {"hosts": [dict(REGISTRY["hosts"][2])]}
-    with pytest.raises(remote_dispatch.OffloadUnavailable):
+    with pytest.raises(remote_dispatch.OffloadUnavailable) as exc_info:
         remote_dispatch.candidate_hosts(payload)
+    assert exc_info.value.code == remote_dispatch.EXIT_NO_NODE

@@ -253,3 +274,3 @@
     monkeypatch.setattr(remote_dispatch, "repo_root", lambda cwd=None: tmp_path / "repo")
-    with pytest.raises(remote_dispatch.OffloadUnavailable, match="mirror push failed"):
+    with pytest.raises(remote_dispatch.OffloadUnavailable, match="mirror push failed") as exc_info:
         remote_dispatch.open_session(
@@ -261,2 +282,3 @@
         )
+    assert exc_info.value.code == remote_dispatch.EXIT_MIRROR

@@ -281,4 +303,5 @@
 def test_load_registry_missing_file_is_offload_unavailable(tmp_path):
-    with pytest.raises(remote_dispatch.OffloadUnavailable):
+    with pytest.raises(remote_dispatch.OffloadUnavailable) as exc_info:
         remote_dispatch.load_registry(tmp_path / "nope.json")
+    assert exc_info.value.code == remote_dispatch.EXIT_NO_NODE


Output:
Exit code: 0
Wall time: 0.6 seconds
Output:
Success. Updated the following files:
M modules/systray/tests/test_remote_dispatch.py


Input:
*** Begin Patch
*** Update File: modules/systray/tests/test_command_router.py
@@
 def test_run_captured_releases_the_placement_claim_when_the_run_raises(
     tmp_path: Path,
     monkeypatch: pytest.MonkeyPatch,
     capsys: pytest.CaptureFixture[str],
 ) -> None:
@@
     def boom(*args: object, **kwargs: object) -> int:
         raise OSError("the node went away mid-run")

     monkeypatch.setattr(session, "pull_back", lambda **kwargs: None)
-    monkeypatch.setattr(command_router.remote_dispatch, "should_offload", lambda env: True)
+    monkeypatch.setattr(command_router.remote_dispatch, "should_offload", lambda: True)
     monkeypatch.setattr(
         command_router.remote_dispatch, "open_session", lambda *a, **kw: session
     )
     monkeypatch.setattr(command_router, "supervise", boom)
     router = command_router.CommandRouter(
         command_router.CodexAdapter(),
@@
     assert exit_code == 1
     assert list(claims.glob("*.claim")) == []
     assert "the node went away mid-run" in capsys.readouterr().err

+@pytest.mark.parametrize(
+    "escape_env",
+    [False, True],
+)
+def test_run_or_main_rejects_offload_unavailable(
+    tmp_path: Path,
+    monkeypatch: pytest.MonkeyPatch,
+    capsys: pytest.CaptureFixture[str],
+    escape_env: bool,
+) -> None:
+    if escape_env:
+        for env_name in (
+            "CDX_NO_OFFLOAD",
+            "OD_REMOTE_EXEC",
+            "HARNESS_SEAT_CONTAINER",
+            "CDX_OFFLOAD_STRICT",
+        ):
+            monkeypatch.setenv(env_name, "1" if env_name != "CDX_OFFLOAD_STRICT" else "0")
+    monkeypatch.setattr(command_router.remote_dispatch, "in_container", lambda: False)
+
+    def raise_unavailable(*_args: object, **_kwargs: object) -> None:
+        raise remote_dispatch.OffloadUnavailable(
+            "no usable access door", code=remote_dispatch.EXIT_MIRROR
+        )
+
+    monkeypatch.setattr(
+        command_router.remote_dispatch,
+        "open_session",
+        raise_unavailable,
+    )
+
+    supervised = False
+
+    def fake_supervise(
+        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
+    ) -> int:
+        nonlocal supervised
+        supervised = True
+        return 0
+
+    monkeypatch.setattr(command_router, "supervise", fake_supervise)
+    monkeypatch.setattr(
+        command_router.CodexAdapter,
+        "capture_log_path",
+        lambda self, forwarded_argv: tmp_path / "run.log",
+    )
+    router = command_router.CommandRouter(
+        command_router.CodexAdapter(),
+        detect_project_name=command_router.detect_project_name,
+    )
+    monkeypatch.setattr(
+        router,
+        "_resolve_account",
+        lambda *args, **kwargs: (tmp_path, "acct", tmp_path / "accounts" / "acct" / "CODEX_HOME"),
+    )
+    (tmp_path / "accounts" / "acct" / "CODEX_HOME").mkdir(parents=True)
+
+    with pytest.raises(SystemExit):
+        router.main(["cdx", "exec", "hello"])
+    exit_code = router._run_captured(
+        ["exec", "hello"],
+        {**os.environ, "CODEX_HOME": str(tmp_path / "accounts" / "acct" / "CODEX_HOME")},
+        tmp_path / "run.log",
+    )
+    exit_code_main = router.main(["cdx", "exec", "hello"])
+
+    assert exit_code == remote_dispatch.EXIT_MIRROR
+    assert exit_code_main == remote_dispatch.EXIT_MIRROR
+    assert not supervised
+    assert "cdx: containment unavailable — no usable access door" in capsys.readouterr().err
+
+
+def test_codex_exec_captures_output_to_logfile_and_prints_only_path(
+    home: Path,
+    monkeypatch: pytest.MonkeyPatch,
+    capsys: pytest.CaptureFixture[str],
+) -> None:
+    legacy_home = home / ".codex-tray" / "accounts" / "legacyacct" / "CODEX_HOME"
+    legacy_home.mkdir(parents=True)
+    (home / ".codex-tray" / "accounts.json").write_text(
+        json.dumps({"accounts": [{"slug": "legacyacct", "alias": "Legacy"}]}),
+        encoding="utf-8",
+    )
+    token_payload = base64.urlsafe_b64encode(
+        json.dumps({"email": "legacy@example.com"}).encode()
+    ).decode().rstrip("=")
+    (legacy_home / "auth.json").write_text(
+        json.dumps({"tokens": {"id_token": f"header.{token_payload}.signature"}}),
+        encoding="utf-8",
+    )
+    router = command_router.CommandRouter(
+        command_router.CodexAdapter(),
+        detect_project_name=command_router.detect_project_name,
+    )
+    monkeypatch.setattr(
+        command_router.CodexAdapter,
+        "sync_before_exec",
+        lambda self, base_dir: None,
+    )
+    monkeypatch.setattr(
+        command_router.remote_dispatch,
+        "in_container",
+        lambda: True,
+    )
+
+    run_call: dict[str, object] = {}
+
+    def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[bytes]:
+        if cmd == ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]:
+            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project/.git\n")
+        if cmd == ["git", "rev-parse", "--show-toplevel"]:
+            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project\n")
+        raise AssertionError(f"unexpected subprocess.run {cmd}")
+
+    def fake_supervise(
+        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
+    ) -> int:
+        run_call["cmd"] = argv
+        run_call["key"] = kwargs["key"]
+        log_path.write_bytes(b"codex model output\n")
+        return 7
+
+    monkeypatch.setattr(command_router.subprocess, "run", fake_run)
+    monkeypatch.setattr(command_router, "supervise", fake_supervise)
+
+    exit_code = router.main(
+        ["cdx", "--account", "legacyacct", "exec", "-m", "gpt-5.6-sol", "do the thing"]
+    )
+    captured = capsys.readouterr()
+
+    assert exit_code == 7
+    log_line = captured.out.strip()
+    assert "codex model output" not in captured.out
+    log_path = Path(log_line)
+    assert log_path.parent == home / ".local/state/overdeck/systray/runtime" / "logs" / "cdx"
+    assert log_path.read_bytes() == b"codex model output\n"
+    assert re.fullmatch(
+        rf"cdx: codex exec finished — exit=7 in \d+\.\ds\. The run is COMPLETE; do not wait or poll for it\.\n"
+        rf"cdx: log {re.escape(str(log_path))} \(19 B\)\n",
+        captured.err,
+    )
+    assert run_call["cmd"] == [
+        "codex",
+        "exec",
+        "--sandbox",
+        "danger-full-access",
+        "--skip-git-repo-check",
+        "-c",
+        "model_reasoning_effort=low",
+        "-m",
+        "gpt-5.6-sol",
+        "do the thing",
+    ]
+    assert run_call["key"] == "cdx"
+
+
+def test_cdx_main_with_no_containerized_log_path_returns_uncontainable(
+    tmp_path: Path,
+    monkeypatch: pytest.MonkeyPatch,
+    capsys: pytest.CaptureFixture[str],
+) -> None:
+    router = command_router.CommandRouter(
+        command_router.CodexAdapter(),
+        detect_project_name=command_router.detect_project_name,
+    )
+    account_home = tmp_path / "accounts" / "acct" / "CODEX_HOME"
+    account_home.mkdir(parents=True)
+    monkeypatch.setattr(
+        router,
+        "_resolve_account",
+        lambda *args, **kwargs: (tmp_path, "acct", account_home),
+    )
+    monkeypatch.setattr(
+        command_router.remote_dispatch,
+        "in_container",
+        lambda: False,
+    )
+    monkeypatch.setattr(
+        command_router.CodexAdapter,
+        "capture_log_path",
+        lambda self, forwarded_argv: None,
+    )
+    exec_called = False
+
+    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
+        nonlocal exec_called
+        exec_called = True
+
+    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
+
+    exit_code = router.main(["cdx", "chat"])
+    captured = capsys.readouterr()
+
+    assert exit_code == remote_dispatch.EXIT_UNCONTAINABLE
+    assert exec_called is False
+    assert captured.err.strip() == (
+        "cdx: no containerized path for this invocation (adapter captures no log for these arguments)"
+    )
+
+
 def test_codex_router_explicit_override_missing_everywhere_reports_unknown(
     home: Path,
     monkeypatch: pytest.MonkeyPatch,
*** End Patch


Success. Updated the following files:
M modules/systray/tests/test_command_router.py

@@ -835,3 +835,3 @@
     monkeypatch.setattr(session, "pull_back", lambda **kwargs: None)
-    monkeypatch.setattr(command_router.remote_dispatch, "should_offload", lambda env: True)
+    monkeypatch.setattr(command_router.remote_dispatch, "should_offload", lambda: True)
     monkeypatch.setattr(
@@ -852,2 +852,202 @@

+@pytest.mark.parametrize(
+    "escape_env",
+    [False, True],
+)
+def test_run_or_main_rejects_offload_unavailable(
+    tmp_path: Path,
+    monkeypatch: pytest.MonkeyPatch,
+    capsys: pytest.CaptureFixture[str],
+    escape_env: bool,
+) -> None:
+    if escape_env:
+        for env_name in (
+            "CDX_NO_OFFLOAD",
+            "OD_REMOTE_EXEC",
+            "HARNESS_SEAT_CONTAINER",
+            "CDX_OFFLOAD_STRICT",
+        ):
+            monkeypatch.setenv(env_name, "1" if env_name != "CDX_OFFLOAD_STRICT" else "0")
+    monkeypatch.setattr(command_router.remote_dispatch, "in_container", lambda: False)
+
+    def raise_unavailable(*_args: object, **_kwargs: object) -> None:
+        raise remote_dispatch.OffloadUnavailable(
+            "no usable access door", code=remote_dispatch.EXIT_MIRROR
+        )
+
+    monkeypatch.setattr(
+        command_router.remote_dispatch,
+        "open_session",
+        raise_unavailable,
+    )
+
+    supervised = False
+
+    def fake_supervise(
+        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
+    ) -> int:
+        nonlocal supervised
+        supervised = True
+        return 0
+
+    monkeypatch.setattr(command_router, "supervise", fake_supervise)
+    monkeypatch.setattr(
+        command_router.CodexAdapter,
+        "capture_log_path",
+        lambda self, forwarded_argv: tmp_path / "run.log",
+    )
+    router = command_router.CommandRouter(
+        command_router.CodexAdapter(),
+        detect_project_name=command_router.detect_project_name,
+    )
+    monkeypatch.setattr(
+        router,
+        "_resolve_account",
+        lambda *args, **kwargs: (tmp_path, "acct", tmp_path / "accounts" / "acct" / "CODEX_HOME"),
+    )
+    (tmp_path / "accounts" / "acct" / "CODEX_HOME").mkdir(parents=True)
+
+    with pytest.raises(SystemExit):
+        router.main(["cdx", "exec", "hello"])
+    exit_code = router._run_captured(
+        ["exec", "hello"],
+        {**os.environ, "CODEX_HOME": str(tmp_path / "accounts" / "acct" / "CODEX_HOME")},
+        tmp_path / "run.log",
+    )
+    exit_code_main = router.main(["cdx", "exec", "hello"])
+
+    assert exit_code == remote_dispatch.EXIT_MIRROR
+    assert exit_code_main == remote_dispatch.EXIT_MIRROR
+    assert not supervised
+    assert "cdx: containment unavailable — no usable access door" in capsys.readouterr().err
+
+
+def test_codex_exec_captures_output_to_logfile_and_prints_only_path(
+    home: Path,
+    monkeypatch: pytest.MonkeyPatch,
+    capsys: pytest.CaptureFixture[str],
+) -> None:
+    legacy_home = home / ".codex-tray" / "accounts" / "legacyacct" / "CODEX_HOME"
+    legacy_home.mkdir(parents=True)
+    (home / ".codex-tray" / "accounts.json").write_text(
+        json.dumps({"accounts": [{"slug": "legacyacct", "alias": "Legacy"}]}),
+        encoding="utf-8",
+    )
+    token_payload = base64.urlsafe_b64encode(
+        json.dumps({"email": "legacy@example.com"}).encode()
+    ).decode().rstrip("=")
+    (legacy_home / "auth.json").write_text(
+        json.dumps({"tokens": {"id_token": f"header.{token_payload}.signature"}}),
+        encoding="utf-8",
+    )
+    router = command_router.CommandRouter(
+        command_router.CodexAdapter(),
+        detect_project_name=command_router.detect_project_name,
+    )
+    monkeypatch.setattr(
+        command_router.CodexAdapter,
+        "sync_before_exec",
+        lambda self, base_dir: None,
+    )
+    monkeypatch.setattr(
+        command_router.remote_dispatch,
+        "in_container",
+        lambda: True,
+    )
+
+    run_call: dict[str, object] = {}
+
+    def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[bytes]:
+        if cmd == ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]:
+            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project/.git\n")
+        if cmd == ["git", "rev-parse", "--show-toplevel"]:
+            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project\n")
+        raise AssertionError(f"unexpected subprocess.run {cmd}")
+
+    def fake_supervise(
+        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
+    ) -> int:
+        run_call["cmd"] = argv
+        run_call["key"] = kwargs["key"]
+        log_path.write_bytes(b"codex model output\n")
+        return 7
+
+    monkeypatch.setattr(command_router.subprocess, "run", fake_run)
+    monkeypatch.setattr(command_router, "supervise", fake_supervise)
+
+    exit_code = router.main(
+        ["cdx", "--account", "legacyacct", "exec", "-m", "gpt-5.6-sol", "do the thing"]
+    )
+    captured = capsys.readouterr()
+
+    assert exit_code == 7
+    log_line = captured.out.strip()
+    assert "codex model output" not in captured.out
+    log_path = Path(log_line)
+    assert log_path.parent == home / ".local/state/overdeck/systray/runtime" / "logs" / "cdx"
+    assert log_path.read_bytes() == b"codex model output\n"
+    assert re.fullmatch(
+        rf"cdx: codex exec finished — exit=7 in \d+\.\ds\. The run is COMPLETE; do not wait or poll for it\.\n"
+        rf"cdx: log {re.escape(str(log_path))} \(19 B\)\n",
+        captured.err,
+    )
+    assert run_call["cmd"] == [
+        "codex",
+        "exec",
+        "--sandbox",
+        "danger-full-access",
+        "--skip-git-repo-check",
+        "-c",
+        "model_reasoning_effort=low",
+        "-m",
+        "gpt-5.6-sol",
+        "do the thing",
+    ]
+    assert run_call["key"] == "cdx"
+
+
+def test_cdx_main_with_no_containerized_log_path_returns_uncontainable(
+    tmp_path: Path,
+    monkeypatch: pytest.MonkeyPatch,
+    capsys: pytest.CaptureFixture[str],
+) -> None:
+    router = command_router.CommandRouter(
+        command_router.CodexAdapter(),
+        detect_project_name=command_router.detect_project_name,
+    )
+    account_home = tmp_path / "accounts" / "acct" / "CODEX_HOME"
+    account_home.mkdir(parents=True)
+    monkeypatch.setattr(
+        router,
+        "_resolve_account",
+        lambda *args, **kwargs: (tmp_path, "acct", account_home),
+    )
+    monkeypatch.setattr(
+        command_router.remote_dispatch,
+        "in_container",
+        lambda: False,
+    )
+    monkeypatch.setattr(
+        command_router.CodexAdapter,
+        "capture_log_path",
+        lambda self, forwarded_argv: None,
+    )
+    exec_called = False
+
+    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
+        nonlocal exec_called
+        exec_called = True
+
+    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
+
+    exit_code = router.main(["cdx", "chat"])
+    captured = capsys.readouterr()
+
+    assert exit_code == remote_dispatch.EXIT_UNCONTAINABLE
+    assert exec_called is False
+    assert captured.err.strip() == (
+        "cdx: no containerized path for this invocation (adapter captures no log for these arguments)"
+    )
+
+
 def test_codex_router_explicit_override_missing_everywhere_reports_unknown(


Output:
Exit code: 0
Wall time: 0 seconds
Output:
Success. Updated the following files:
M modules/systray/tests/test_command_router.py


I’ve now patched the router tests. I accidentally inserted a full replacement block in-place, so I’m going to de-duplicate and normalize the edits in `test_command_router.py` to avoid duplicate/inconsistent assertions.


Output:
Chunk ID: a9159e
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 89
Output:
737:def test_codex_exec_captures_output_to_logfile_and_prints_only_path(
816:def test_run_captured_releases_the_placement_claim_when_the_run_raises(
857:def test_run_or_main_rejects_offload_unavailable(
925:def test_codex_exec_captures_output_to_logfile_and_prints_only_path(
1009:def test_cdx_main_with_no_containerized_log_path_returns_uncontainable(


sed -n '720,980p' modules/systray/tests/test_command_router.py


Output:
Chunk ID: 1476cb
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2311
Output:
    exit_code = router.main(
        [
            "cdx",
            "exec",
            "--model=gpt-5.6-sol",
            "--config",
            "model_reasoning_effort=minimal",
            "prompt",
        ]
    )
    captured = capsys.readouterr()

    assert exit_code == 1
    assert captured.out == ""
    assert captured.err == "cdx: invalid reasoning effort 'minimal' for model 'gpt-5.6-sol'\n"

def test_codex_exec_captures_output_to_logfile_and_prints_only_path(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    legacy_home = home / ".codex-tray" / "accounts" / "legacyacct" / "CODEX_HOME"
    legacy_home.mkdir(parents=True)
    (home / ".codex-tray" / "accounts.json").write_text(
        json.dumps({"accounts": [{"slug": "legacyacct", "alias": "Legacy"}]}),
        encoding="utf-8",
    )
    token_payload = base64.urlsafe_b64encode(
        json.dumps({"email": "legacy@example.com"}).encode()
    ).decode().rstrip("=")
    (legacy_home / "auth.json").write_text(
        json.dumps({"tokens": {"id_token": f"header.{token_payload}.signature"}}),
        encoding="utf-8",
    )
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )
    monkeypatch.setattr(
        command_router.CodexAdapter,
        "sync_before_exec",
        lambda self, base_dir: None,
    )

    run_call: dict[str, object] = {}

    def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[bytes]:
        if cmd == ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]:
            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project/.git\n")
        if cmd == ["git", "rev-parse", "--show-toplevel"]:
            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project\n")
        raise AssertionError(f"unexpected subprocess.run {cmd}")

    def fake_supervise(
        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
    ) -> int:
        run_call["cmd"] = argv
        run_call["key"] = kwargs["key"]
        log_path.write_bytes(b"codex model output\n")
        return 7

    monkeypatch.setattr(command_router.subprocess, "run", fake_run)
    monkeypatch.setattr(command_router, "supervise", fake_supervise)

    exit_code = router.main(
        ["cdx", "--account", "legacyacct", "exec", "-m", "gpt-5.6-sol", "do the thing"]
    )
    captured = capsys.readouterr()

    assert exit_code == 7
    log_line = captured.out.strip()
    assert "codex model output" not in captured.out
    log_path = Path(log_line)
    assert log_path.parent == home / ".local/state/overdeck/systray/runtime" / "logs" / "cdx"
    assert log_path.read_bytes() == b"codex model output\n"
    assert re.fullmatch(
        rf"cdx: codex exec finished — exit=7 in \d+\.\ds\. The run is COMPLETE; do not wait or poll for it\.\n"
        rf"cdx: log {re.escape(str(log_path))} \(19 B\)\n",
        captured.err,
    )
    assert run_call["cmd"] == [
        "codex",
        "exec",
        "--sandbox",
        "danger-full-access",
        "--skip-git-repo-check",
        "-c",
        "model_reasoning_effort=low",
        "-m",
        "gpt-5.6-sol",
        "do the thing",
    ]
    assert run_call["key"] == "cdx"

def test_run_captured_releases_the_placement_claim_when_the_run_raises(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    claims = tmp_path / "claims"
    session = remote_dispatch.Session(
        host_name="debian1",
        access={"host": "100.0.0.1", "user": "user"},
        root=tmp_path,
        rel_dir="cdx-offload/x",
        argv=["ssh", "user@100.0.0.1"],
        claim=remote_dispatch.acquire_claim("debian1", claims),
    )
    assert len(list(claims.glob("*.claim"))) == 1

    def boom(*args: object, **kwargs: object) -> int:
        raise OSError("the node went away mid-run")

    monkeypatch.setattr(session, "pull_back", lambda **kwargs: None)
    monkeypatch.setattr(command_router.remote_dispatch, "should_offload", lambda: True)
    monkeypatch.setattr(
        command_router.remote_dispatch, "open_session", lambda *a, **kw: session
    )
    monkeypatch.setattr(command_router, "supervise", boom)
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exit_code = router._run_captured(["exec", "hi"], {}, tmp_path / "run.log")

    assert exit_code == 1
    assert list(claims.glob("*.claim")) == []
    assert "the node went away mid-run" in capsys.readouterr().err

@pytest.mark.parametrize(
    "escape_env",
    [False, True],
)
def test_run_or_main_rejects_offload_unavailable(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
    escape_env: bool,
) -> None:
    if escape_env:
        for env_name in (
            "CDX_NO_OFFLOAD",
            "OD_REMOTE_EXEC",
            "HARNESS_SEAT_CONTAINER",
            "CDX_OFFLOAD_STRICT",
        ):
            monkeypatch.setenv(env_name, "1" if env_name != "CDX_OFFLOAD_STRICT" else "0")
    monkeypatch.setattr(command_router.remote_dispatch, "in_container", lambda: False)

    def raise_unavailable(*_args: object, **_kwargs: object) -> None:
        raise remote_dispatch.OffloadUnavailable(
            "no usable access door", code=remote_dispatch.EXIT_MIRROR
        )

    monkeypatch.setattr(
        command_router.remote_dispatch,
        "open_session",
        raise_unavailable,
    )

    supervised = False

    def fake_supervise(
        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
    ) -> int:
        nonlocal supervised
        supervised = True
        return 0

    monkeypatch.setattr(command_router, "supervise", fake_supervise)
    monkeypatch.setattr(
        command_router.CodexAdapter,
        "capture_log_path",
        lambda self, forwarded_argv: tmp_path / "run.log",
    )
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )
    monkeypatch.setattr(
        router,
        "_resolve_account",
        lambda *args, **kwargs: (tmp_path, "acct", tmp_path / "accounts" / "acct" / "CODEX_HOME"),
    )
    (tmp_path / "accounts" / "acct" / "CODEX_HOME").mkdir(parents=True)

    with pytest.raises(SystemExit):
        router.main(["cdx", "exec", "hello"])
    exit_code = router._run_captured(
        ["exec", "hello"],
        {**os.environ, "CODEX_HOME": str(tmp_path / "accounts" / "acct" / "CODEX_HOME")},
        tmp_path / "run.log",
    )
    exit_code_main = router.main(["cdx", "exec", "hello"])

    assert exit_code == remote_dispatch.EXIT_MIRROR
    assert exit_code_main == remote_dispatch.EXIT_MIRROR
    assert not supervised
    assert "cdx: containment unavailable — no usable access door" in capsys.readouterr().err

def test_codex_exec_captures_output_to_logfile_and_prints_only_path(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    legacy_home = home / ".codex-tray" / "accounts" / "legacyacct" / "CODEX_HOME"
    legacy_home.mkdir(parents=True)
    (home / ".codex-tray" / "accounts.json").write_text(
        json.dumps({"accounts": [{"slug": "legacyacct", "alias": "Legacy"}]}),
        encoding="utf-8",
    )
    token_payload = base64.urlsafe_b64encode(
        json.dumps({"email": "legacy@example.com"}).encode()
    ).decode().rstrip("=")
    (legacy_home / "auth.json").write_text(
        json.dumps({"tokens": {"id_token": f"header.{token_payload}.signature"}}),
        encoding="utf-8",
    )
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )
    monkeypatch.setattr(
        command_router.CodexAdapter,
        "sync_before_exec",
        lambda self, base_dir: None,
    )
    monkeypatch.setattr(
        command_router.remote_dispatch,
        "in_container",
        lambda: True,
    )

    run_call: dict[str, object] = {}

    def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[bytes]:
        if cmd == ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]:
            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project/.git\n")
        if cmd == ["git", "rev-parse", "--show-toplevel"]:
            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project\n")
        raise AssertionError(f"unexpected subprocess.run {cmd}")

    def fake_supervise(
        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
    ) -> int:
        run_call["cmd"] = argv
        run_call["key"] = kwargs["key"]
        log_path.write_bytes(b"codex model output\n")
        return 7

    monkeypatch.setattr(command_router.subprocess, "run", fake_run)
    monkeypatch.setattr(command_router, "supervise", fake_supervise)

    exit_code = router.main(
        ["cdx", "--account", "legacyacct", "exec", "-m", "gpt-5.6-sol", "do the thing"]
    )


sed -n '980,1085p' modules/systray/tests/test_command_router.py


Output:
Chunk ID: 791bbb
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 845
Output:
    )
    captured = capsys.readouterr()

    assert exit_code == 7
    log_line = captured.out.strip()
    assert "codex model output" not in captured.out
    log_path = Path(log_line)
    assert log_path.parent == home / ".local/state/overdeck/systray/runtime" / "logs" / "cdx"
    assert log_path.read_bytes() == b"codex model output\n"
    assert re.fullmatch(
        rf"cdx: codex exec finished — exit=7 in \d+\.\ds\. The run is COMPLETE; do not wait or poll for it\.\n"
        rf"cdx: log {re.escape(str(log_path))} \(19 B\)\n",
        captured.err,
    )
    assert run_call["cmd"] == [
        "codex",
        "exec",
        "--sandbox",
        "danger-full-access",
        "--skip-git-repo-check",
        "-c",
        "model_reasoning_effort=low",
        "-m",
        "gpt-5.6-sol",
        "do the thing",
    ]
    assert run_call["key"] == "cdx"

def test_cdx_main_with_no_containerized_log_path_returns_uncontainable(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )
    account_home = tmp_path / "accounts" / "acct" / "CODEX_HOME"
    account_home.mkdir(parents=True)
    monkeypatch.setattr(
        router,
        "_resolve_account",
        lambda *args, **kwargs: (tmp_path, "acct", account_home),
    )
    monkeypatch.setattr(
        command_router.remote_dispatch,
        "in_container",
        lambda: False,
    )
    monkeypatch.setattr(
        command_router.CodexAdapter,
        "capture_log_path",
        lambda self, forwarded_argv: None,
    )
    exec_called = False

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        nonlocal exec_called
        exec_called = True

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    exit_code = router.main(["cdx", "chat"])
    captured = capsys.readouterr()

    assert exit_code == remote_dispatch.EXIT_UNCONTAINABLE
    assert exec_called is False
    assert captured.err.strip() == (
        "cdx: no containerized path for this invocation (adapter captures no log for these arguments)"
    )

def test_codex_router_explicit_override_missing_everywhere_reports_unknown(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exit_code = router.main(["cdx", "--account", "nope", "chat"])
    captured = capsys.readouterr()

    assert exit_code == 1
    assert captured.err.strip() == "cdx: unknown account 'nope'"

def test_codex_router_reports_clean_error_for_missing_rules_file(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    (home / ".local/state/overdeck/systray/runtime").mkdir(parents=True)
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "zync.is")
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exit_code = router.main(["cdx", "chat"])
    captured = capsys.readouterr()

    assert exit_code == 1


sed -n '1,140p' modules/systray/tests/test_remote_dispatch.py


Output:
Chunk ID: 308d3a
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1085
Output:
from __future__ import annotations

import json
import multiprocessing
import os
import random
import shutil
import subprocess
import sys
from collections import Counter
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import remote_dispatch

REGISTRY = {
    "schema_version": 1,
    "hosts": [
        {
            "name": "debian1",
            "state": "reachable",
            "roles": ["builder", "agent-seat"],
            "access": {
                "tailscale_ip": {
                    "host": "100.0.0.1",
                    "port": 2222,
                    "user": "user",
                    "identity_file": "~/.ssh/id_ed25519_buildbox",
                }
            },
        },
        {
            "name": "debian2",
            "state": "reachable",
            "roles": ["builder", "agent-seat"],
            "access": {"tailscale_ip": {"host": "100.0.0.2", "port": 2222, "user": "user"}},
        },
        {
            "name": "debian3",
            "state": "unreachable",
            "roles": ["builder", "agent-seat"],
            "access": {"tailscale_ip": {"host": "100.0.0.3", "port": 2222, "user": "user"}},
        },
    ],
}

THREE_REACHABLE = {
    "schema_version": 1,
    "hosts": [
        {
            "name": f"debian{n}",
            "state": "reachable",
            "roles": ["agent-seat"],
            "access": {"tailscale_ip": {"host": f"100.0.0.{n}", "user": "user"}},
        }
        for n in (1, 2, 3)
    ],
}

@pytest.fixture(autouse=True)
def isolated_claim_dir(tmp_path_factory, monkeypatch):
    """No test may write placement claims into the real ~/.local/state directory."""
    directory = tmp_path_factory.mktemp("claims")
    monkeypatch.setenv(remote_dispatch.CLAIM_DIR_ENV, str(directory))
    return directory

def write_registry(tmp_path: Path, payload: dict | None = None) -> Path:
    path = tmp_path / "buildbox-hosts.json"
    path.write_text(json.dumps(payload if payload is not None else REGISTRY), encoding="utf-8")
    return path

def test_should_offload_true_when_not_in_container(monkeypatch):
    monkeypatch.setattr(remote_dispatch, "in_container", lambda: False)
    assert remote_dispatch.should_offload() is True

def test_should_offload_false_when_in_container(monkeypatch):
    monkeypatch.setattr(remote_dispatch, "in_container", lambda: True)
    assert remote_dispatch.should_offload() is False

def test_should_offload_ignores_env(monkeypatch):
    monkeypatch.setenv("CDX_NO_OFFLOAD", "1")
    monkeypatch.setenv("OD_REMOTE_EXEC", "1")
    monkeypatch.setenv("HARNESS_SEAT_CONTAINER", "1")
    monkeypatch.setenv("CDX_OFFLOAD_STRICT", "0")

    monkeypatch.setattr(remote_dispatch, "in_container", lambda: False)
    assert remote_dispatch.should_offload() is True

    monkeypatch.setattr(remote_dispatch, "in_container", lambda: True)
    assert remote_dispatch.should_offload() is False

def test_access_for_raises_credential_error(remote_dispatch_payload: None = None):
    host = {
        "name": "debian1",
        "access": {},
    }
    with pytest.raises(remote_dispatch.OffloadUnavailable) as exc_info:
        remote_dispatch.access_for(host)
    assert exc_info.value.code == remote_dispatch.EXIT_NO_NODE

def test_candidate_hosts_excludes_unreachable():
    names = [h["name"] for h in remote_dispatch.candidate_hosts(REGISTRY)]
    assert names == ["debian1", "debian2"]

def test_candidate_hosts_raises_when_none_reachable():
    payload = {"hosts": [dict(REGISTRY["hosts"][2])]}
    with pytest.raises(remote_dispatch.OffloadUnavailable) as exc_info:
        remote_dispatch.candidate_hosts(payload)
    assert exc_info.value.code == remote_dispatch.EXIT_NO_NODE

def test_select_host_picks_least_loaded():
    loads = {"100.0.0.1": 9.5, "100.0.0.2": 0.4}
    host, access, _claim = remote_dispatch.select_host(
        remote_dispatch.candidate_hosts(REGISTRY),
        probe=lambda a: loads[a["host"]],
    )
    assert host["name"] == "debian2"
    assert access["host"] == "100.0.0.2"

def test_select_host_skips_nodes_that_do_not_answer():
    host, _access, _claim = remote_dispatch.select_host(
        remote_dispatch.candidate_hosts(REGISTRY),
        probe=lambda a: None if a["host"] == "100.0.0.2" else 7.0,
    )
    assert host["name"] == "debian1"


Input:
*** Begin Patch
*** Update File: modules/systray/tests/test_command_router.py
@@
 def test_codex_exec_captures_output_to_logfile_and_prints_only_path(
     home: Path,
     monkeypatch: pytest.MonkeyPatch,
     capsys: pytest.CaptureFixture[str],
 ) -> None:
@@
     monkeypatch.setattr(
         command_router.CodexAdapter,
         "sync_before_exec",
         lambda self, base_dir: None,
     )
+    monkeypatch.setattr(
+        command_router.remote_dispatch,
+        "in_container",
+        lambda: True,
+    )
@@
-@pytest.mark.parametrize(
-    "escape_env",
-    [False, True],
-)
-def test_run_or_main_rejects_offload_unavailable(
+@pytest.mark.parametrize("entrypoint", ["_run_captured", "main"])
+@pytest.mark.parametrize("escape_env", [False, True])
+def test_run_or_main_rejects_offload_unavailable(
     tmp_path: Path,
     monkeypatch: pytest.MonkeyPatch,
     capsys: pytest.CaptureFixture[str],
+    entrypoint: str,
     escape_env: bool,
 ) -> None:
     if escape_env:
         for env_name in (
             "CDX_NO_OFFLOAD",
@@
     def raise_unavailable(*_args: object, **_kwargs: object) -> None:
         raise remote_dispatch.OffloadUnavailable(
             "no usable access door", code=remote_dispatch.EXIT_MIRROR
         )

@@
     monkeypatch.setattr(
         command_router.remote_dispatch,
         "open_session",
         raise_unavailable,
     )

-    supervised = False
-
-    def fake_supervise(
-        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
-    ) -> int:
-        nonlocal supervised
-        supervised = True
-        return 0
-
-    monkeypatch.setattr(command_router, "supervise", fake_supervise)
-    monkeypatch.setattr(
-        command_router.CodexAdapter,
-        "capture_log_path",
-        lambda self, forwarded_argv: tmp_path / "run.log",
-    )
+    supervise_called = False
+
+    def fake_supervise(
+        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
+    ) -> int:
+        nonlocal supervise_called
+        supervise_called = True
+        return 0
+
+    monkeypatch.setattr(command_router, "supervise", fake_supervise)
     router = command_router.CommandRouter(
         command_router.CodexAdapter(),
         detect_project_name=command_router.detect_project_name,
     )
-    monkeypatch.setattr(
-        router,
-        "_resolve_account",
-        lambda *args, **kwargs: (tmp_path, "acct", tmp_path / "accounts" / "acct" / "CODEX_HOME"),
-    )
-    (tmp_path / "accounts" / "acct" / "CODEX_HOME").mkdir(parents=True)
+    log_path = tmp_path / "run.log"
+    if entrypoint == "_run_captured":
+        exit_code = router._run_captured(
+            ["exec", "hello"],
+            {**os.environ, "CODEX_HOME": str(tmp_path / "accounts" / "acct" / "CODEX_HOME")},
+            log_path,
+        )
+    else:
+        account_home = tmp_path / "accounts" / "acct" / "CODEX_HOME"
+        account_home.mkdir(parents=True)
+        monkeypatch.setattr(
+            command_router.CodexAdapter,
+            "sync_before_exec",
+            lambda self, base_dir: None,
+        )
+        monkeypatch.setattr(
+            router,
+            "_resolve_account",
+            lambda *args, **kwargs: (tmp_path, "acct", account_home),
+        )
+        monkeypatch.setattr(
+            command_router.CodexAdapter,
+            "capture_log_path",
+            lambda self, forwarded_argv: log_path,
+        )
+        exit_code = router.main(["cdx", "exec", "hello"])

-    with pytest.raises(SystemExit):
-        router.main(["cdx", "exec", "hello"])
-    exit_code = router._run_captured(
-        ["exec", "hello"],
-        {**os.environ, "CODEX_HOME": str(tmp_path / "accounts" / "acct" / "CODEX_HOME")},
-        tmp_path / "run.log",
-    )
-    exit_code_main = router.main(["cdx", "exec", "hello"])
-
-    assert exit_code == remote_dispatch.EXIT_MIRROR
-    assert exit_code_main == remote_dispatch.EXIT_MIRROR
-    assert not supervised
+    assert exit_code == remote_dispatch.EXIT_MIRROR
+    assert not supervise_called
     assert "cdx: containment unavailable — no usable access door" in capsys.readouterr().err
-
-
-def test_codex_exec_captures_output_to_logfile_and_prints_only_path(
-    home: Path,
-    monkeypatch: pytest.MonkeyPatch,
-    capsys: pytest.CaptureFixture[str],
-) -> None:
-    legacy_home = home / ".codex-tray" / "accounts" / "legacyacct" / "CODEX_HOME"
-    legacy_home.mkdir(parents=True)
-    (home / ".codex-tray" / "accounts.json").write_text(
-        json.dumps({"accounts": [{"slug": "legacyacct", "alias": "Legacy"}]}),
-        encoding="utf-8",
-    )
-    token_payload = base64.urlsafe_b64encode(
-        json.dumps({"email": "legacy@example.com"}).encode()
-    ).decode().rstrip("=")
-    (legacy_home / "auth.json").write_text(
-        json.dumps({"tokens": {"id_token": f"header.{token_payload}.signature"}}),
-        encoding="utf-8",
-    )
-    router = command_router.CommandRouter(
-        command_router.CodexAdapter(),
-        detect_project_name=command_router.detect_project_name,
-    )
-    monkeypatch.setattr(
-        command_router.CodexAdapter,
-        "sync_before_exec",
-        lambda self, base_dir: None,
-    )
-    monkeypatch.setattr(
-        command_router.remote_dispatch,
-        "in_container",
-        lambda: True,
-    )
-
-    run_call: dict[str, object] = {}
-
-    def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[bytes]:
-        if cmd == ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]:
-            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project/.git\n")
-        if cmd == ["git", "rev-parse", "--show-toplevel"]:
-            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project\n")
-        raise AssertionError(f"unexpected subprocess.run {cmd}")
-
-    def fake_supervise(
-        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
-    ) -> int:
-        run_call["cmd"] = argv
-        run_call["key"] = kwargs["key"]
-        log_path.write_bytes(b"codex model output\n")
-        return 7
-
-    monkeypatch.setattr(command_router.subprocess, "run", fake_run)
-    monkeypatch.setattr(command_router, "supervise", fake_supervise)
-
-    exit_code = router.main(
-        ["cdx", "--account", "legacyacct", "exec", "-m", "gpt-5.6-sol", "do the thing"]
-    )
-    captured = capsys.readouterr()
-
-    assert exit_code == 7
-    log_line = captured.out.strip()
-    assert "codex model output" not in captured.out
-    log_path = Path(log_line)
-    assert log_path.parent == home / ".local/state/overdeck/systray/runtime" / "logs" / "cdx"
-    assert log_path.read_bytes() == b"codex model output\n"
-    assert re.fullmatch(
-        rf"cdx: codex exec finished — exit=7 in \d+\.\ds\. The run is COMPLETE; do not wait or poll for it\.\n"
-        rf"cdx: log {re.escape(str(log_path))} \(19 B\)\n",
-        captured.err,
-    )
-    assert run_call["cmd"] == [
-        "codex",
-        "exec",
-        "--sandbox",
-        "danger-full-access",
-        "--skip-git-repo-check",
-        "-c",
-        "model_reasoning_effort=low",
-        "-m",
-        "gpt-5.6-sol",
-        "do the thing",
-    ]
-    assert run_call["key"] == "cdx"
*** End Patch


@@ -763,2 +763,7 @@
     )
+    monkeypatch.setattr(
+        command_router.remote_dispatch,
+        "in_container",
+        lambda: True,
+    )

@@ -852,6 +857,4 @@

-@pytest.mark.parametrize(
-    "escape_env",
-    [False, True],
-)
+@pytest.mark.parametrize("entrypoint", ["_run_captured", "main"])
+@pytest.mark.parametrize("escape_env", [False, True])
 def test_run_or_main_rejects_offload_unavailable(
@@ -860,2 +863,3 @@
     capsys: pytest.CaptureFixture[str],
+    entrypoint: str,
     escape_env: bool,
@@ -883,3 +887,3 @@

-    supervised = False
+    supervise_called = False

@@ -888,4 +892,4 @@
     ) -> int:
-        nonlocal supervised
-        supervised = True
+        nonlocal supervise_called
+        supervise_called = True
         return 0
@@ -893,7 +897,2 @@
     monkeypatch.setattr(command_router, "supervise", fake_supervise)
-    monkeypatch.setattr(
-        command_router.CodexAdapter,
-        "capture_log_path",
-        lambda self, forwarded_argv: tmp_path / "run.log",
-    )
     router = command_router.CommandRouter(
@@ -902,106 +901,32 @@
     )
-    monkeypatch.setattr(
-        router,
-        "_resolve_account",
-        lambda *args, **kwargs: (tmp_path, "acct", tmp_path / "accounts" / "acct" / "CODEX_HOME"),
-    )
-    (tmp_path / "accounts" / "acct" / "CODEX_HOME").mkdir(parents=True)
-
-    with pytest.raises(SystemExit):
-        router.main(["cdx", "exec", "hello"])
-    exit_code = router._run_captured(
-        ["exec", "hello"],
-        {**os.environ, "CODEX_HOME": str(tmp_path / "accounts" / "acct" / "CODEX_HOME")},
-        tmp_path / "run.log",
-    )
-    exit_code_main = router.main(["cdx", "exec", "hello"])
+    log_path = tmp_path / "run.log"
+    if entrypoint == "_run_captured":
+        exit_code = router._run_captured(
+            ["exec", "hello"],
+            {**os.environ, "CODEX_HOME": str(tmp_path / "accounts" / "acct" / "CODEX_HOME")},
+            log_path,
+        )
+    else:
+        account_home = tmp_path / "accounts" / "acct" / "CODEX_HOME"
+        account_home.mkdir(parents=True)
+        monkeypatch.setattr(
+            command_router.CodexAdapter,
+            "sync_before_exec",
+            lambda self, base_dir: None,
+        )
+        monkeypatch.setattr(
+            router,
+            "_resolve_account",
+            lambda *args, **kwargs: (tmp_path, "acct", account_home),
+        )
+        monkeypatch.setattr(
+            command_router.CodexAdapter,
+            "capture_log_path",
+            lambda self, forwarded_argv: log_path,
+        )
+        exit_code = router.main(["cdx", "exec", "hello"])

     assert exit_code == remote_dispatch.EXIT_MIRROR
-    assert exit_code_main == remote_dispatch.EXIT_MIRROR
-    assert not supervised
+    assert not supervise_called
     assert "cdx: containment unavailable — no usable access door" in capsys.readouterr().err
-
-
-def test_codex_exec_captures_output_to_logfile_and_prints_only_path(
-    home: Path,
-    monkeypatch: pytest.MonkeyPatch,
-    capsys: pytest.CaptureFixture[str],
-) -> None:
-    legacy_home = home / ".codex-tray" / "accounts" / "legacyacct" / "CODEX_HOME"
-    legacy_home.mkdir(parents=True)
-    (home / ".codex-tray" / "accounts.json").write_text(
-        json.dumps({"accounts": [{"slug": "legacyacct", "alias": "Legacy"}]}),
-        encoding="utf-8",
-    )
-    token_payload = base64.urlsafe_b64encode(
-        json.dumps({"email": "legacy@example.com"}).encode()
-    ).decode().rstrip("=")
-    (legacy_home / "auth.json").write_text(
-        json.dumps({"tokens": {"id_token": f"header.{token_payload}.signature"}}),
-        encoding="utf-8",
-    )
-    router = command_router.CommandRouter(
-        command_router.CodexAdapter(),
-        detect_project_name=command_router.detect_project_name,
-    )
-    monkeypatch.setattr(
-        command_router.CodexAdapter,
-        "sync_before_exec",
-        lambda self, base_dir: None,
-    )
-    monkeypatch.setattr(
-        command_router.remote_dispatch,
-        "in_container",
-        lambda: True,
-    )
-
-    run_call: dict[str, object] = {}
-
-    def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[bytes]:
-        if cmd == ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]:
-            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project/.git\n")
-        if cmd == ["git", "rev-parse", "--show-toplevel"]:
-            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project\n")
-        raise AssertionError(f"unexpected subprocess.run {cmd}")
-
-    def fake_supervise(
-        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
-    ) -> int:
-        run_call["cmd"] = argv
-        run_call["key"] = kwargs["key"]
-        log_path.write_bytes(b"codex model output\n")
-        return 7
-
-    monkeypatch.setattr(command_router.subprocess, "run", fake_run)
-    monkeypatch.setattr(command_router, "supervise", fake_supervise)
-
-    exit_code = router.main(
-        ["cdx", "--account", "legacyacct", "exec", "-m", "gpt-5.6-sol", "do the thing"]
-    )
-    captured = capsys.readouterr()
-
-    assert exit_code == 7
-    log_line = captured.out.strip()
-    assert "codex model output" not in captured.out
-    log_path = Path(log_line)
-    assert log_path.parent == home / ".local/state/overdeck/systray/runtime" / "logs" / "cdx"
-    assert log_path.read_bytes() == b"codex model output\n"
-    assert re.fullmatch(
-        rf"cdx: codex exec finished — exit=7 in \d+\.\ds\. The run is COMPLETE; do not wait or poll for it\.\n"
-        rf"cdx: log {re.escape(str(log_path))} \(19 B\)\n",
-        captured.err,
-    )
-    assert run_call["cmd"] == [
-        "codex",
-        "exec",
-        "--sandbox",
-        "danger-full-access",
-        "--skip-git-repo-check",
-        "-c",
-        "model_reasoning_effort=low",
-        "-m",
-        "gpt-5.6-sol",
-        "do the thing",
-    ]
-    assert run_call["key"] == "cdx"


Output:
Exit code: 0
Wall time: 1.2 seconds
Output:
Success. Updated the following files:
M modules/systray/tests/test_command_router.py


sed -n '730,1010p' modules/systray/tests/test_command_router.py


Output:
Chunk ID: 4db8a7
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2422
Output:
    captured = capsys.readouterr()

    assert exit_code == 1
    assert captured.out == ""
    assert captured.err == "cdx: invalid reasoning effort 'minimal' for model 'gpt-5.6-sol'\n"

def test_codex_exec_captures_output_to_logfile_and_prints_only_path(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    legacy_home = home / ".codex-tray" / "accounts" / "legacyacct" / "CODEX_HOME"
    legacy_home.mkdir(parents=True)
    (home / ".codex-tray" / "accounts.json").write_text(
        json.dumps({"accounts": [{"slug": "legacyacct", "alias": "Legacy"}]}),
        encoding="utf-8",
    )
    token_payload = base64.urlsafe_b64encode(
        json.dumps({"email": "legacy@example.com"}).encode()
    ).decode().rstrip("=")
    (legacy_home / "auth.json").write_text(
        json.dumps({"tokens": {"id_token": f"header.{token_payload}.signature"}}),
        encoding="utf-8",
    )
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )
    monkeypatch.setattr(
        command_router.CodexAdapter,
        "sync_before_exec",
        lambda self, base_dir: None,
    )
    monkeypatch.setattr(
        command_router.remote_dispatch,
        "in_container",
        lambda: True,
    )

    run_call: dict[str, object] = {}

    def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[bytes]:
        if cmd == ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]:
            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project/.git\n")
        if cmd == ["git", "rev-parse", "--show-toplevel"]:
            return subprocess.CompletedProcess(cmd, 0, stdout="/workspace/project\n")
        raise AssertionError(f"unexpected subprocess.run {cmd}")

    def fake_supervise(
        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
    ) -> int:
        run_call["cmd"] = argv
        run_call["key"] = kwargs["key"]
        log_path.write_bytes(b"codex model output\n")
        return 7

    monkeypatch.setattr(command_router.subprocess, "run", fake_run)
    monkeypatch.setattr(command_router, "supervise", fake_supervise)

    exit_code = router.main(
        ["cdx", "--account", "legacyacct", "exec", "-m", "gpt-5.6-sol", "do the thing"]
    )
    captured = capsys.readouterr()

    assert exit_code == 7
    log_line = captured.out.strip()
    assert "codex model output" not in captured.out
    log_path = Path(log_line)
    assert log_path.parent == home / ".local/state/overdeck/systray/runtime" / "logs" / "cdx"
    assert log_path.read_bytes() == b"codex model output\n"
    assert re.fullmatch(
        rf"cdx: codex exec finished — exit=7 in \d+\.\ds\. The run is COMPLETE; do not wait or poll for it\.\n"
        rf"cdx: log {re.escape(str(log_path))} \(19 B\)\n",
        captured.err,
    )
    assert run_call["cmd"] == [
        "codex",
        "exec",
        "--sandbox",
        "danger-full-access",
        "--skip-git-repo-check",
        "-c",
        "model_reasoning_effort=low",
        "-m",
        "gpt-5.6-sol",
        "do the thing",
    ]
    assert run_call["key"] == "cdx"

def test_run_captured_releases_the_placement_claim_when_the_run_raises(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    claims = tmp_path / "claims"
    session = remote_dispatch.Session(
        host_name="debian1",
        access={"host": "100.0.0.1", "user": "user"},
        root=tmp_path,
        rel_dir="cdx-offload/x",
        argv=["ssh", "user@100.0.0.1"],
        claim=remote_dispatch.acquire_claim("debian1", claims),
    )
    assert len(list(claims.glob("*.claim"))) == 1

    def boom(*args: object, **kwargs: object) -> int:
        raise OSError("the node went away mid-run")

    monkeypatch.setattr(session, "pull_back", lambda **kwargs: None)
    monkeypatch.setattr(command_router.remote_dispatch, "should_offload", lambda: True)
    monkeypatch.setattr(
        command_router.remote_dispatch, "open_session", lambda *a, **kw: session
    )
    monkeypatch.setattr(command_router, "supervise", boom)
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exit_code = router._run_captured(["exec", "hi"], {}, tmp_path / "run.log")

    assert exit_code == 1
    assert list(claims.glob("*.claim")) == []
    assert "the node went away mid-run" in capsys.readouterr().err

@pytest.mark.parametrize("entrypoint", ["_run_captured", "main"])
@pytest.mark.parametrize("escape_env", [False, True])
def test_run_or_main_rejects_offload_unavailable(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
    entrypoint: str,
    escape_env: bool,
) -> None:
    if escape_env:
        for env_name in (
            "CDX_NO_OFFLOAD",
            "OD_REMOTE_EXEC",
            "HARNESS_SEAT_CONTAINER",
            "CDX_OFFLOAD_STRICT",
        ):
            monkeypatch.setenv(env_name, "1" if env_name != "CDX_OFFLOAD_STRICT" else "0")
    monkeypatch.setattr(command_router.remote_dispatch, "in_container", lambda: False)

    def raise_unavailable(*_args: object, **_kwargs: object) -> None:
        raise remote_dispatch.OffloadUnavailable(
            "no usable access door", code=remote_dispatch.EXIT_MIRROR
        )

    monkeypatch.setattr(
        command_router.remote_dispatch,
        "open_session",
        raise_unavailable,
    )

    supervise_called = False

    def fake_supervise(
        argv: list[str], env: dict[str, str], log_path: Path, **kwargs: object
    ) -> int:
        nonlocal supervise_called
        supervise_called = True
        return 0

    monkeypatch.setattr(command_router, "supervise", fake_supervise)
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )
    log_path = tmp_path / "run.log"
    if entrypoint == "_run_captured":
        exit_code = router._run_captured(
            ["exec", "hello"],
            {**os.environ, "CODEX_HOME": str(tmp_path / "accounts" / "acct" / "CODEX_HOME")},
            log_path,
        )
    else:
        account_home = tmp_path / "accounts" / "acct" / "CODEX_HOME"
        account_home.mkdir(parents=True)
        monkeypatch.setattr(
            command_router.CodexAdapter,
            "sync_before_exec",
            lambda self, base_dir: None,
        )
        monkeypatch.setattr(
            router,
            "_resolve_account",
            lambda *args, **kwargs: (tmp_path, "acct", account_home),
        )
        monkeypatch.setattr(
            command_router.CodexAdapter,
            "capture_log_path",
            lambda self, forwarded_argv: log_path,
        )
        exit_code = router.main(["cdx", "exec", "hello"])

    assert exit_code == remote_dispatch.EXIT_MIRROR
    assert not supervise_called
    assert "cdx: containment unavailable — no usable access door" in capsys.readouterr().err

def test_cdx_main_with_no_containerized_log_path_returns_uncontainable(
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )
    account_home = tmp_path / "accounts" / "acct" / "CODEX_HOME"
    account_home.mkdir(parents=True)
    monkeypatch.setattr(
        router,
        "_resolve_account",
        lambda *args, **kwargs: (tmp_path, "acct", account_home),
    )
    monkeypatch.setattr(
        command_router.remote_dispatch,
        "in_container",
        lambda: False,
    )
    monkeypatch.setattr(
        command_router.CodexAdapter,
        "capture_log_path",
        lambda self, forwarded_argv: None,
    )
    exec_called = False

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        nonlocal exec_called
        exec_called = True

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)

    exit_code = router.main(["cdx", "chat"])
    captured = capsys.readouterr()

    assert exit_code == remote_dispatch.EXIT_UNCONTAINABLE
    assert exec_called is False
    assert captured.err.strip() == (
        "cdx: no containerized path for this invocation (adapter captures no log for these arguments)"
    )

def test_codex_router_explicit_override_missing_everywhere_reports_unknown(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exit_code = router.main(["cdx", "--account", "nope", "chat"])
    captured = capsys.readouterr()

    assert exit_code == 1
    assert captured.err.strip() == "cdx: unknown account 'nope'"

def test_codex_router_reports_clean_error_for_missing_rules_file(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    (home / ".local/state/overdeck/systray/runtime").mkdir(parents=True)
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "zync.is")
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exit_code = router.main(["cdx", "chat"])
    captured = capsys.readouterr()

    assert exit_code == 1


Input:
*** Begin Patch
*** Update File: modules/systray/tests/test_remote_dispatch.py
@@
-def test_access_for_raises_credential_error(remote_dispatch_payload: None = None):
+def test_access_for_raises_credential_error():
*** End Patch


@@ -102,3 +102,3 @@

-def test_access_for_raises_credential_error(remote_dispatch_payload: None = None):
+def test_access_for_raises_credential_error():
     host = {


Output:
Exit code: 0
Wall time: 2.7 seconds
Output:
Success. Updated the following files:
M modules/systray/tests/test_remote_dispatch.py


I found one small cleanup required in `command_router.py`: an unreachable `return` remains after `execvpe` now that branch is guarded; I’ll remove it while preserving logic flow.


rg -n "if remote_dispatch.in_container|return 0$|no containerized path" modules/systray/command_router.py


Output:
Chunk ID: b25435
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 65
Output:
734:            return 0
764:        if remote_dispatch.in_container():
766:            return 0
774:            f"{self.adapter.tool_name}: no containerized path for this invocation ({reason})",
778:        return 0
870:        return 0
1000:        return 0


sed -n '750,782p' modules/systray/command_router.py


Output:
Chunk ID: 3e2888
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 347
Output:
                f"{self.adapter.tool_name}: unsupported routing: {self.adapter.exec_name} did not honor {self.adapter.config_env_var} for {account_home}",
                file=sys.stderr,
            )
            return 1

        env = {**os.environ, **self.adapter.build_env(account_home)}
        # only this CLI supervises the run; a child that inherited the opt-in would
        # let every gate and suite it spawns raise desktop popups
        env.pop("STALL_GUARD_NOTIFY", None)

        log_path = self.adapter.capture_log_path(forwarded_argv)
        if log_path is not None:
            return self._run_captured(forwarded_argv, env, log_path)

        if remote_dispatch.in_container():
            os.execvpe(self.adapter.exec_name, [self.adapter.exec_name, *forwarded_argv], env)
            return 0

        reason = (
            "no writable log directory"
            if is_exec_invocation(forwarded_argv)
            else "adapter captures no log for these arguments"
        )
        print(
            f"{self.adapter.tool_name}: no containerized path for this invocation ({reason})",
            file=sys.stderr,
        )
        return remote_dispatch.EXIT_UNCONTAINABLE
        return 0

    def _run_captured(self, forwarded_argv: list[str], env: dict[str, str], log_path: Path) -> int:
        started = time.monotonic()
        tool = self.adapter.tool_name


Input:
*** Begin Patch
*** Update File: modules/systray/command_router.py
@@
         print(
             f"{self.adapter.tool_name}: no containerized path for this invocation ({reason})",
             file=sys.stderr,
         )
         return remote_dispatch.EXIT_UNCONTAINABLE
-        return 0
*** End Patch


@@ -777,3 +777,2 @@
         return remote_dispatch.EXIT_UNCONTAINABLE
-        return 0


Output:
Exit code: 0
Wall time: 0.1 seconds
Output:
Success. Updated the following files:
M modules/systray/command_router.py


sed -n '860,910p' modules/systray/command_router.py


Output:
Chunk ID: ff8a64
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 649
Output:
            for candidate_dir in self.adapter.candidate_tray_dirs():
                resolved_slug = self.adapter.resolve_profile_token(candidate_dir, part)
                if resolved_slug is not None:
                    break
            if resolved_slug is None:
                print(f"{self.adapter.tool_name}: unknown account: {part}", file=sys.stderr)
                return 1
            canonical_parts.append(resolved_slug)
        print(json.dumps({"profile": ",".join(canonical_parts)}, separators=(",", ":")))
        return 0

    def _resolve_account(
        self, account_override: str | None, *, notify_fallback: bool = True
    ) -> tuple[Path, str, Path] | AllAccountsCappedError | None:
        if account_override is not None:
            raw_chain = tuple(part.strip() for part in account_override.split(",") if part.strip())
            if not raw_chain:
                print(f"{self.adapter.tool_name}: --profile requires a non-empty account", file=sys.stderr)
                return None
            for candidate_dir in self.adapter.candidate_tray_dirs():
                selected = self.adapter.selected_default([candidate_dir])
                resolved_parts: list[str] = []
                ok = True
                for part in raw_chain:
                    if part == "dynamic":
                        if selected is None:
                            ok = False
                            break
                        resolved_parts.append(selected.slug)
                    else:
                        resolved_slug = self.adapter.resolve_profile_token(candidate_dir, part)
                        if resolved_slug is None or not self.adapter.account_home(
                            candidate_dir, resolved_slug
                        ).exists():
                            ok = False
                            break
                        resolved_parts.append(resolved_slug)
                if not ok:
                    continue
                chain = tuple(resolved_parts)
                slug = chain[0]
                try:
                    rules = load_rules(self.adapter.routing_rules_path(candidate_dir))
                    rules = apply_selected_default(
                        rules,
                        selected.slug if selected is not None else None,
                    )
                    health = load_health(
                        self.adapter.health_cache_path(candidate_dir),
                        stale_after_s=self.adapter.health_cache_stale_seconds,
                        tool_name=self.adapter.tool_name,


sed -n '760,840p' modules/systray/command_router.py


Output:
Chunk ID: fa9f6b
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 842
Output:
        log_path = self.adapter.capture_log_path(forwarded_argv)
        if log_path is not None:
            return self._run_captured(forwarded_argv, env, log_path)

        if remote_dispatch.in_container():
            os.execvpe(self.adapter.exec_name, [self.adapter.exec_name, *forwarded_argv], env)
            return 0

        reason = (
            "no writable log directory"
            if is_exec_invocation(forwarded_argv)
            else "adapter captures no log for these arguments"
        )
        print(
            f"{self.adapter.tool_name}: no containerized path for this invocation ({reason})",
            file=sys.stderr,
        )
        return remote_dispatch.EXIT_UNCONTAINABLE

    def _run_captured(self, forwarded_argv: list[str], env: dict[str, str], log_path: Path) -> int:
        started = time.monotonic()
        tool = self.adapter.tool_name
        argv = [self.adapter.exec_name, *forwarded_argv]
        session = None
        if remote_dispatch.should_offload():
            try:
                session = remote_dispatch.open_session(self.adapter.exec_name, forwarded_argv)
            except remote_dispatch.OffloadUnavailable as exc:
                print(f"{tool}: containment unavailable — {exc}", file=sys.stderr)
                return exc.code
            else:
                argv = session.argv
                print(f"{tool}: running on {session.host_name} ({session.rel_dir})", file=sys.stderr)
                if session.git_warning is not None:
                    print(f"{tool}: {session.git_warning}", file=sys.stderr)
        try:
            returncode = supervise(argv, env, log_path, key=tool)
        except OSError as exc:
            print(f"{tool}: failed to run {self.adapter.exec_name}: {exc}", file=sys.stderr)
            return 1
        finally:
            if session is not None:
                try:
                    sync_error = session.pull_back()
                    if sync_error is not None:
                        print(f"{tool}: {sync_error}", file=sys.stderr)
                finally:
                    session.release()
        self._print_completion(log_path, returncode, time.monotonic() - started)
        # stdout stays the bare log path: callers capture it as `LOG=$(cdx exec ...)`.
        print(str(log_path))
        return returncode

    def _print_completion(self, log_path: Path, exit_code: int, elapsed: float) -> None:
        try:
            size = log_path.stat().st_size
        except OSError:
            size = None
        tool = self.adapter.tool_name
        print(
            f"{tool}: {self.adapter.exec_name} exec finished — exit={exit_code} "
            f"in {_format_duration(elapsed)}. The run is COMPLETE; do not wait or poll for it.",
            file=sys.stderr,
        )
        print(
            f"{tool}: log {log_path}" + (f" ({_format_size(size)})" if size is not None else ""),
            file=sys.stderr,
        )

    @staticmethod
    def _parse_status_flag(argv: list[str]) -> tuple[bool, bool, list[str]]:
        show_status = False
        usage_json = False
        filtered = [argv[0]]
        for arg in argv[1:]:
            if arg in {"--status", "--usage"}:
                show_status = True
                continue
            if arg == "--json":
                usage_json = True
                continue


rg -n "should_offload\(" modules/systray/command_router.py modules/systray/remote_dispatch.py modules/systray/tests/test_command_router.py modules/systray/tests/test_remote_dispatch.py


Output:
Chunk ID: c6dbf9
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 140
Output:
modules/systray/tests/test_remote_dispatch.py:82:    assert remote_dispatch.should_offload() is True
modules/systray/tests/test_remote_dispatch.py:87:    assert remote_dispatch.should_offload() is False
modules/systray/tests/test_remote_dispatch.py:97:    assert remote_dispatch.should_offload() is True
modules/systray/tests/test_remote_dispatch.py:100:    assert remote_dispatch.should_offload() is False
modules/systray/remote_dispatch.py:81:def should_offload() -> bool:
modules/systray/command_router.py:784:        if remote_dispatch.should_offload():


sed -n '1,120p' modules/systray/remote_dispatch.py


Output:
Chunk ID: c9053f
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 950
Output:
"""Run an agent CLI on a cluster node instead of the workstation.

The caller's repository is mirrored to a reachable buildbox, the CLI runs there, and the
tree is mirrored back when it exits. Host choice is by measured load average penalised by
this workstation's in-flight placement claims: load average lags a freshly started run by
tens of seconds, so probes alone put every concurrent dispatch on the same node.

A linked worktree's `.git` is a file naming a workstation-absolute gitdir, so mirroring the
tree alone leaves git unusable on the node. The worktree gitdir and the repository common
dir are mirrored too, and the remote pointers are rewritten to remote paths.

Three limitations of the mirror, by design: a commit made on the node returns as an
uncommitted working-tree change (only the tree is mirrored home, not refs or objects); a
sibling worktree's later dispatch rewrites the shared remote refs, dropping an earlier
node-side commit back to the workstation's ref; and an out-of-tree `core.hooksPath` does
not resolve on the node, so hooks do not run there.
"""

from __future__ import annotations

import hashlib
import json
import os
import random
import re
import shlex
import subprocess
import uuid
from dataclasses import dataclass
from pathlib import Path

REGISTRY_PATH = Path.home() / ".claude" / "buildbox-hosts.json"
REMOTE_ROOT = "cdx-offload"
REMOTE_GIT_COMMON_ROOT = f"{REMOTE_ROOT}/git-common"
SEAT_ROLE = "agent-seat"
DOOR = "tailscale_ip"
SYNC_EXCLUDES = (
    ".worktrees",
    "node_modules",
    "dist",
    "build",
    ".next",
    ".turbo",
    ".cache",
    ".venv",
    "target",
)
PROBE_TIMEOUT_SEC = 10
SYNC_TIMEOUT_SEC = 900
CLAIM_DIR_ENV = "OD_PLACEMENT_CLAIM_DIR"
DEFAULT_CLAIM_DIR_RELPATH = ".local/state/overdeck/placement-claims"
CLAIM_SUFFIX = ".claim"
CLAIM_LOAD_PENALTY = 1.0
EXIT_NO_NODE = 80
EXIT_CREDENTIAL = 81
EXIT_MIRROR = 82
EXIT_LAUNCH = 83
EXIT_UNCONTAINABLE = 84

class OffloadUnavailable(RuntimeError):
    """No cluster node can take this run."""

    def __init__(self, message: str, code: int = EXIT_NO_NODE) -> None:
        super().__init__(message)
        self.code = code

def in_container() -> bool:
    """Machine-local evidence, not env: an env marker is agent-settable."""
    for probe in (Path("/run/.containerenv"), Path("/.dockerenv")):
        if probe.exists():
            return True
    try:
        cgroup = Path("/proc/self/cgroup").read_text(encoding="utf-8")
    except OSError:
        return False
    return "libpod" in cgroup or "docker" in cgroup

def should_offload() -> bool:
    return not in_container()

def load_registry(path: Path = REGISTRY_PATH) -> dict:
    try:
        return json.loads(Path(path).read_text(encoding="utf-8"))
    except (OSError, ValueError) as exc:
        raise OffloadUnavailable(
            f"buildbox registry unreadable at {path}: {exc}", code=EXIT_NO_NODE
        ) from exc

def candidate_hosts(registry: dict, role: str = SEAT_ROLE) -> list[dict]:
    """Reachable hosts carrying `role`. A host in any other state is never contacted."""
    hosts = [
        host
        for host in registry.get("hosts", [])
        if host.get("state") == "reachable" and role in (host.get("roles") or [])
    ]
    if not hosts:
        raise OffloadUnavailable(
            f"no reachable host with role {role} in the registry", code=EXIT_NO_NODE
        )
    return hosts

def access_for(host: dict, door: str = DOOR) -> dict:
    access = (host.get("access") or {}).get(door)
    if not access or not access.get("host"):
        raise OffloadUnavailable(
            f"{host.get('name')}: no usable {door} access door", code=EXIT_NO_NODE
        )
    return access

def _host_name(host: dict, access: dict) -> str:
    return host.get("name") or access["host"]


sed -n '520,590p' modules/systray/remote_dispatch.py