Output:
Chunk ID: cde303
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2183
Output:
modules/systray/tests/test_remote_dispatch.py:80:def test_should_offload_defaults_true():
modules/systray/tests/test_remote_dispatch.py:81:    assert remote_dispatch.should_offload({}) is True
modules/systray/tests/test_remote_dispatch.py:84:def test_should_offload_opt_out():
modules/systray/tests/test_remote_dispatch.py:85:    assert remote_dispatch.should_offload({"CDX_NO_OFFLOAD": "1"}) is False
modules/systray/tests/test_remote_dispatch.py:88:def test_should_offload_false_when_already_on_a_node():
modules/systray/tests/test_remote_dispatch.py:89:    assert remote_dispatch.should_offload({"OD_REMOTE_EXEC": "1"}) is False
modules/systray/tests/test_remote_dispatch.py:90:    assert remote_dispatch.should_offload({"HARNESS_SEAT_CONTAINER": "1"}) is False
modules/systray/tests/test_remote_dispatch.py:100:    with pytest.raises(remote_dispatch.OffloadUnavailable):
modules/systray/tests/test_remote_dispatch.py:123:    with pytest.raises(remote_dispatch.OffloadUnavailable):
modules/systray/tests/test_remote_dispatch.py:254:    with pytest.raises(remote_dispatch.OffloadUnavailable, match="mirror push failed"):
modules/systray/tests/test_remote_dispatch.py:282:    with pytest.raises(remote_dispatch.OffloadUnavailable):
modules/systray/tests/test_remote_dispatch.py:599:    with pytest.raises(remote_dispatch.OffloadUnavailable):
modules/systray/command_router.py:510:    def capture_log_path(self, forwarded_argv: list[str]) -> Path | None:
modules/systray/command_router.py:561:    def capture_log_path(self, forwarded_argv: list[str]) -> Path | None:
modules/systray/command_router.py:690:    def main(self, argv: list[str]) -> int:
modules/systray/command_router.py:760:        log_path = self.adapter.capture_log_path(forwarded_argv)
modules/systray/command_router.py:764:        os.execvpe(self.adapter.exec_name, [self.adapter.exec_name, *forwarded_argv], env)
modules/systray/command_router.py:767:    def _run_captured(self, forwarded_argv: list[str], env: dict[str, str], log_path: Path) -> int:
modules/systray/command_router.py:772:        if remote_dispatch.should_offload(env):
modules/systray/command_router.py:775:            except remote_dispatch.OffloadUnavailable as exc:
modules/systray/tests/test_command_router.py:73:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:77:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:114:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:118:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:165:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:171:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:716:        "execvpe",
modules/systray/tests/test_command_router.py:836:    monkeypatch.setattr(command_router.remote_dispatch, "should_offload", lambda env: True)
modules/systray/tests/test_command_router.py:976:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:982:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1025:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1029:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1085:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1091:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1143:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1149:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1203:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1213:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1355:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1359:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1371:def test_capture_log_path_falls_back_when_tray_logs_unwritable(
modules/systray/tests/test_command_router.py:1382:    log_path = command_router.CodexAdapter().capture_log_path(["exec", "hi"])
modules/systray/tests/test_command_router.py:1389:def test_capture_log_path_returns_none_when_no_directory_is_writable(
modules/systray/tests/test_command_router.py:1401:    log_path = command_router.CodexAdapter().capture_log_path(["exec", "hi"])
modules/systray/tests/test_command_router.py:1457:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1461:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1516:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1520:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1572:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1576:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1634:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1638:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1752:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1756:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1813:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1817:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1870:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1875:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/tests/test_command_router.py:1925:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
modules/systray/tests/test_command_router.py:1930:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
modules/systray/remote_dispatch.py:56:class OffloadUnavailable(RuntimeError):
modules/systray/remote_dispatch.py:60:def should_offload(env: dict[str, str] | None = None) -> bool:
modules/systray/remote_dispatch.py:70:def load_registry(path: Path = REGISTRY_PATH) -> dict:
modules/systray/remote_dispatch.py:74:        raise OffloadUnavailable(f"buildbox registry unreadable at {path}: {exc}") from exc
modules/systray/remote_dispatch.py:77:def candidate_hosts(registry: dict, role: str = SEAT_ROLE) -> list[dict]:
modules/systray/remote_dispatch.py:85:        raise OffloadUnavailable(f"no reachable host with role {role} in the registry")
modules/systray/remote_dispatch.py:89:def access_for(host: dict, door: str = DOOR) -> dict:
modules/systray/remote_dispatch.py:92:        raise OffloadUnavailable(f"{host.get('name')}: no usable {door} access door")
modules/systray/remote_dispatch.py:260:        except OffloadUnavailable as exc:
modules/systray/remote_dispatch.py:269:        raise OffloadUnavailable("; ".join(failures) or "no candidate node answered")
modules/systray/remote_dispatch.py:534:def open_session(
modules/systray/remote_dispatch.py:563:            raise OffloadUnavailable(f"{name}: could not prepare mirror: {exc}") from exc
modules/systray/remote_dispatch.py:565:            raise OffloadUnavailable(f"{name}: could not prepare mirror: {made.stderr.strip()}")
modules/systray/remote_dispatch.py:575:            raise OffloadUnavailable(f"{name}: mirror push failed: {exc}") from exc
modules/systray/remote_dispatch.py:577:            raise OffloadUnavailable(f"{name}: mirror push failed: {pushed.stderr.strip()}")


Output:
Chunk ID: 31f510
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2482
Output:
        return None
    return PlacementClaim(host_name=host_name, path=path)

def select_host(
    hosts: list[dict], probe=probe_load, claims: Path | None = None
) -> tuple[dict, dict, PlacementClaim | None]:
    """Least-loaded reachable node, penalised by this workstation's in-flight claims.

    Load average lags a newly started run, so probes alone stack concurrent dispatches on
    one node. The claim held by every live dispatch is what fans them out; equal scores are
    broken at random so simultaneous callers do not walk the same branch. The returned
    claim is live until released.
    """
    directory = claim_dir() if claims is None else Path(claims)
    probed: list[tuple[dict, dict, float]] = []
    failures: list[str] = []
    for host in hosts:
        try:
            access = access_for(host)
        except OffloadUnavailable as exc:
            failures.append(str(exc))
            continue
        load = probe(access)
        if load is None:
            failures.append(f"{host.get('name')}: unreachable or load probe failed")
            continue
        probed.append((host, access, load))
    if not probed:
        raise OffloadUnavailable("; ".join(failures) or "no candidate node answered")

    held: PlacementClaim | None = None
    held_index: int | None = None
    best_index = 0
    for _ in range(2 * len(probed) + 2):
        counts = live_claim_counts(directory)
        if held is not None:
            token = _claim_token(held.host_name)
            counts[token] = max(0, counts.get(token, 0) - 1)
        scored = [
            (
                load + CLAIM_LOAD_PENALTY * counts.get(_claim_token(_host_name(host, access)), 0),
                index,
            )
            for index, (host, access, load) in enumerate(probed)
        ]
        best_score = min(score for score, _index in scored)
        tied = [index for score, index in scored if score <= best_score + 1e-9]
        best_index = random.choice(tied)
        if held_index is not None and held_index in tied:
            break
        if held is not None:
            held.release()
            held = None
            held_index = None
        host, access, _load = probed[best_index]
        claim = acquire_claim(_host_name(host, access), directory)
        if claim is None:
            return host, access, None
        held, held_index = claim, best_index
    index = best_index if held_index is None else held_index
    return probed[index][0], probed[index][1], held

def repo_root(cwd: Path | None = None) -> Path:
    cwd = Path.cwd() if cwd is None else Path(cwd)
    try:
        done = subprocess.run(
            ["/usr/bin/git", "-C", str(cwd), "rev-parse", "--show-toplevel"],
            capture_output=True,
            text=True,
            timeout=PROBE_TIMEOUT_SEC,
        )
    except (OSError, subprocess.SubprocessError):
        return cwd
    root = done.stdout.strip()
    return Path(root) if done.returncode == 0 and root else cwd

def remote_rel_dir(root: Path) -> str:
    """Stable per-source-path directory: two worktrees never share a remote mirror."""
    digest = hashlib.sha256(str(root).encode("utf-8")).hexdigest()[:12]
    return f"{REMOTE_ROOT}/{root.name}-{digest}"

def _exclude_args(exclude_git: bool = False) -> list[str]:
    names = (*SYNC_EXCLUDES, "/.git") if exclude_git else SYNC_EXCLUDES
    return [arg for name in names for arg in ("--exclude", name)]

def push_argv(access: dict, root: Path, rel_dir: str, exclude_git: bool = False) -> list[str]:
    return [
        "rsync",
        "-az",
        "--delete",
        *_exclude_args(exclude_git),
        "-e",
        rsync_shell(access),
        f"{root}/",
        f"{access.get('user', 'user')}@{access['host']}:{rel_dir}/",
    ]

def pull_argv(access: dict, root: Path, rel_dir: str, exclude_git: bool = False) -> list[str]:
    return [
        "rsync",
        "-az",
        "--delete",
        *_exclude_args(exclude_git),
        "-e",
        rsync_shell(access),
        f"{access.get('user', 'user')}@{access['host']}:{rel_dir}/",
        f"{root}/",
    ]

@dataclass(frozen=True)
class GitMirror:
    """Where a linked worktree's git plumbing lives locally and on the node."""

    git_dir: Path
    common_dir: Path
    remote_common: str
    remote_git_dir: str

def git_dirs(root: Path, run=subprocess.run) -> tuple[Path, Path] | None:
    """(gitdir, common dir) for `root`, both absolute. None when `root` is not a checkout."""
    try:
        done = run(
            ["/usr/bin/git", "-C", str(root), "rev-parse", "--absolute-git-dir", "--git-common-dir"],
            capture_output=True,
            text=True,
            timeout=PROBE_TIMEOUT_SEC,
        )
    except (OSError, subprocess.SubprocessError):
        return None
    if done.returncode != 0:
        return None
    lines = done.stdout.splitlines()
    if len(lines) != 2 or not lines[0].strip() or not lines[1].strip():
        return None
    git_dir = Path(lines[0].strip())
    common = Path(lines[1].strip())
    if not common.is_absolute():
        common = Path(root) / common
    return git_dir.resolve(), common.resolve()

def remote_git_common(common_dir: Path) -> str:
    """One mirror per repository: every worktree of a repo shares these objects and refs."""
    digest = hashlib.sha256(str(common_dir).encode("utf-8")).hexdigest()[:12]
    label = common_dir.parent.name or common_dir.name
    return f"{REMOTE_GIT_COMMON_ROOT}/{label}-{digest}"

def git_mirror(root: Path, run=subprocess.run) -> GitMirror | None:
    """None for a plain checkout, whose `.git` directory rides along in the tree rsync."""
    dirs = git_dirs(root, run=run)
    if dirs is None:
        return None
    git_dir, common_dir = dirs
    if git_dir == common_dir:
        return None
    remote_common = remote_git_common(common_dir)
    return GitMirror(
        git_dir=git_dir,
        common_dir=common_dir,
        remote_common=remote_common,
        remote_git_dir=f"{remote_common}/worktrees/{git_dir.name}",
    )

def git_common_push_argv(access: dict, mirror: GitMirror) -> list[str]:
    """No --delete: a concurrent dispatch's remote commit must not lose its objects."""
    return [
        "rsync",
        "-az",
        "--exclude",
        "/worktrees",
        "-e",
        rsync_shell(access),
        f"{mirror.common_dir}/",
        f"{access.get('user', 'user')}@{access['host']}:{mirror.remote_common}/",
    ]

def git_dir_push_argv(access: dict, mirror: GitMirror) -> list[str]:
    return [
        "rsync",
        "-az",
        "--delete",
        "-e",
        rsync_shell(access),
        f"{mirror.git_dir}/",
        f"{access.get('user', 'user')}@{access['host']}:{mirror.remote_git_dir}/",
    ]

def git_pointer_command(rel_dir: str, mirror: GitMirror) -> str:
    """$HOME is resolved on the node: the rsync targets are relative to the remote home."""
    inner = (
        "set -eu\n"
        f'd="$HOME"/{shlex.quote(rel_dir)}\n'
        f'g="$HOME"/{shlex.quote(mirror.remote_git_dir)}\n'
        'printf "gitdir: %s\\n" "$g" > "$d/.git"\n'
        'printf "%s\\n" "$d/.git" > "$g/gitdir"\n'
        'printf "%s\\n" "../.." > "$g/commondir"\n'
        'git -C "$d" rev-parse --show-toplevel > /dev/null\n'
    )
    return f"bash -lc {shlex.quote(inner)}"

def prepare_remote_git(
    access: dict, host_name: str, rel_dir: str, mirror: GitMirror, run=subprocess.run
) -> str | None:
    """Make git work in the node's mirror. Returns a warning on failure, and never raises:
    a run with no git is still useful, a run refused over git is not."""
    steps: list[tuple[str, list[str], int]] = [
        ("objects and refs", git_common_push_argv(access, mirror), SYNC_TIMEOUT_SEC),
        ("worktree gitdir", git_dir_push_argv(access, mirror), SYNC_TIMEOUT_SEC),
        (
            "gitdir pointers",
            [*ssh_argv(access), git_pointer_command(rel_dir, mirror)],
            PROBE_TIMEOUT_SEC,
        ),
    ]
    for what, argv, timeout in steps:
        try:
            done = run(argv, capture_output=True, text=True, timeout=timeout)
        except (OSError, subprocess.SubprocessError) as exc:
            return git_warning_text(host_name, f"mirroring {what} failed: {exc}")
        if done.returncode != 0:
            return git_warning_text(host_name, f"mirroring {what} failed: {done.stderr.strip()}")
    return None

def git_warning_text(host_name: str, detail: str) -> str:
    return (
        f"!!! GIT IS NOT USABLE IN THE MIRROR ON {host_name}: {detail}. "
        "The run continues, but git status/add/commit/log and anything shelling out to git "
        "WILL FAIL on the node — do not expect to commit there."
    )

def remote_command(rel_dir: str, exec_name: str, forwarded_argv: list[str]) -> str:
    """OD_REMOTE_EXEC marks the node-side process so it never re-offloads to itself."""
    inner = (
        f"cd {shlex.quote(rel_dir)} && "
        f"OD_LOCAL_DISPATCH_OK=1 OD_REMOTE_EXEC=1 "
        f"exec {shlex.join([exec_name, *forwarded_argv])}"
    )
    return f"bash -lc {shlex.quote(inner)}"

def remote_run_argv(
    access: dict, rel_dir: str, exec_name: str, forwarded_argv: list[str]
) -> list[str]:
    return [*ssh_argv(access, ("-tt",)), remote_command(rel_dir, exec_name, forwarded_argv)]

@dataclass
class Session:
    host_name: str
    access: dict
    root: Path
    rel_dir: str
    argv: list[str]
    git_warning: str | None = None
    exclude_git: bool = False
    claim: PlacementClaim | None = None

    def release(self) -> None:
        """Drop the placement claim so the node stops looking busy to the next dispatch."""
        if self.claim is not None:
            self.claim.release()
            self.claim = None

    def pull_back(self, run=subprocess.run) -> str | None:
        """Mirror the node's tree home. Returns an error string, never raises."""
        try:


Output:
Chunk ID: f88bb5
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 681
Output:
        try:
            done = run(
                pull_argv(self.access, self.root, self.rel_dir, exclude_git=self.exclude_git),
                capture_output=True,
                text=True,
                timeout=SYNC_TIMEOUT_SEC,
            )
        except (OSError, subprocess.SubprocessError) as exc:
            return f"result sync from {self.host_name} failed: {exc}"
        if done.returncode != 0:
            return f"result sync from {self.host_name} failed: {done.stderr.strip()}"
        return None

def open_session(
    exec_name: str,
    forwarded_argv: list[str],
    cwd: Path | None = None,
    registry_path: Path = REGISTRY_PATH,
    run=subprocess.run,
    probe=probe_load,
    claims: Path | None = None,
) -> Session:
    host, access, claim = select_host(
        candidate_hosts(load_registry(registry_path)), probe=probe, claims=claims
    )
    name = _host_name(host, access)
    try:
        root = repo_root(cwd)
        rel_dir = remote_rel_dir(root)
        mirror = git_mirror(root, run=run)
        remote_dirs = [rel_dir]
        if mirror is not None:
            remote_dirs += [mirror.remote_common, mirror.remote_git_dir]

        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
        if made.returncode != 0:
            raise OffloadUnavailable(f"{name}: could not prepare mirror: {made.stderr.strip()}")

        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
        if pushed.returncode != 0:
            raise OffloadUnavailable(f"{name}: mirror push failed: {pushed.stderr.strip()}")

        git_warning = (
            None if mirror is None else prepare_remote_git(access, name, rel_dir, mirror, run=run)
        )
    except BaseException:
        if claim is not None:
            claim.release()
        raise

    return Session(
        host_name=name,
        access=access,
        root=root,
        rel_dir=rel_dir,
        argv=remote_run_argv(access, rel_dir, exec_name, forwarded_argv),
        git_warning=git_warning,
        exclude_git=mirror is not None,
        claim=claim,
    )


Output:
Chunk ID: 6266a8
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 3448
Output:
    kept: list[str] = []
    drop_value = False
    for index, arg in enumerate(forwarded_argv):
        if index >= options_end:
            kept.append(arg)
            continue
        if drop_value:
            drop_value = False
            continue
        if not has_bypass and arg in {"--sandbox", "-s"}:
            drop_value = True
            continue
        if not has_bypass and (
            arg.startswith("--sandbox=") or (arg.startswith("-s") and len(arg) > 2)
        ):
            continue
        kept.append(arg)
    additions: list[str] = []
    if not has_bypass:
        additions += ["--sandbox", "danger-full-access"]
    if "--skip-git-repo-check" not in kept:
        additions.append("--skip-git-repo-check")
    additions += effort_addition
    return [kept[0], *additions, *kept[1:]]

def _dedupe_paths(paths: list[Path]) -> list[Path]:
    unique: list[Path] = []
    for path in paths:
        if path not in unique:
            unique.append(path)
    return unique

def load_selected_default_from_dirs(
    base_dirs: list[Path],
    default_filename: str | None,
    accounts_dir_name: str,
    account_home_name: str,
) -> SelectedDefault | None:
    if default_filename is None:
        return None

    selected: tuple[float, int, str, Path] | None = None
    for index, base_dir in enumerate(base_dirs):
        default_path = base_dir / default_filename
        try:
            slug = default_path.read_text(encoding="utf-8").strip()
        except OSError:
            continue
        if not slug:
            continue

        account_home = base_dir / accounts_dir_name / slug / account_home_name
        if not account_home.exists():
            continue

        try:
            mtime = os.path.getmtime(default_path)
        except OSError:
            mtime = 0.0

        candidate = (mtime, -index, slug, base_dir)
        if selected is None or candidate > selected:
            selected = candidate

    if selected is None:
        return None
    return SelectedDefault(slug=selected[2], base_dir=selected[3])

def routing_base_dir(base_dirs: list[Path], selected_default: SelectedDefault | None, routing_rules_filename: str) -> Path:
    if selected_default is not None:
        return selected_default.base_dir
    for base_dir in base_dirs:
        if (base_dir / routing_rules_filename).exists():
            return base_dir
    return base_dirs[0]

def apply_selected_default(rules: RoutingRules, selected_default: str | None) -> RoutingRules:
    if selected_default is None:
        return rules
    return replace(
        rules,
        projects={},
        default=selected_default,
        fallback_trigger="broken_only",
    )

def _override_account_spend_capped(resolver: RoutingResolver, slug: str) -> bool:
    caps = resolver.account_caps(slug)
    if not caps:
        return False
    snapshot = resolver.health.get(slug)
    if snapshot is None:
        return False
    return bool(capped_windows(snapshot, caps))

class ToolAdapter:
    def __init__(
        self,
        *,
        tool_name: str,
        exec_name: str,
        accounts_dir_name: str,
        account_home_name: str,
        routing_rules_filename: str,
        health_cache_filename: str,
        health_cache_stale_seconds: int,
        health_snapshot_tool: str,
        registry_kind: AccountRegistryKind,
        config_env_var: str,
        selected_default_filename: str | None = None,
        legacy_tray_dir_name: str | None = None,
    ) -> None:
        self.tool_name = tool_name
        self.exec_name = exec_name
        self.accounts_dir_name = accounts_dir_name
        self.account_home_name = account_home_name
        self.routing_rules_filename = routing_rules_filename
        self.health_cache_filename = health_cache_filename
        self.health_cache_stale_seconds = health_cache_stale_seconds
        self.health_snapshot_tool = health_snapshot_tool
        self.registry_kind = registry_kind
        self.config_env_var = config_env_var
        self.selected_default_filename = selected_default_filename
        self.legacy_tray_dir_name = legacy_tray_dir_name

    def tray_dir(self) -> Path:
        return runtime_dir()

    def candidate_tray_dirs(self) -> list[Path]:
        dirs = [self.tray_dir()]
        if self.legacy_tray_dir_name is not None:
            dirs.append(Path.home() / self.legacy_tray_dir_name)
        return _dedupe_paths(dirs)

    def account_root(self, base_dir: Path) -> Path:
        return base_dir / self.accounts_dir_name

    def account_home(self, base_dir: Path, slug: str) -> Path:
        return self.account_root(base_dir) / slug / self.account_home_name

    def routing_rules_path(self, base_dir: Path) -> Path:
        return base_dir / self.routing_rules_filename

    def health_cache_path(self, base_dir: Path) -> Path:
        return base_dir / self.health_cache_filename

    def known_slugs(self, base_dir: Path) -> set[str]:
        root = self.account_root(base_dir)
        try:
            entries = list(root.iterdir())
        except OSError:
            return set()

        known: set[str] = set()
        for entry in entries:
            if not entry.is_dir():
                continue
            account_home = entry / self.account_home_name
            if account_home.exists():
                known.add(entry.name)
        return known

    def resolve_profile_token(self, base_dir: Path, token: str) -> str | None:
        token = token.strip()
        if not token:
            return None
        known = self.known_slugs(base_dir)
        if token in known:
            return token
        registry = AccountRegistry(base_dir=base_dir, kind=self.registry_kind)
        resolved = registry.resolve_profile_token(token)
        return resolved if resolved in known else None

    def selected_default(self, base_dirs: list[Path]) -> SelectedDefault | None:
        return load_selected_default_from_dirs(
            base_dirs,
            self.selected_default_filename,
            self.accounts_dir_name,
            self.account_home_name,
        )

    def sync_before_exec(self, base_dir: Path) -> list[Path]:
        return []

    def capture_log_path(self, forwarded_argv: list[str]) -> Path | None:
        return None

    def build_env(self, account_home: Path) -> dict[str, str]:
        return {self.config_env_var: str(account_home)}

    def verify_env_support(self, account_home: Path) -> bool:
        return True

    def fetch_health(self, base_dir: Path, slug: str) -> AccountSnapshot:
        return AccountHealthClient().fetch(self.account_home(base_dir, slug))

    def notify_fallback(self, fallback_from: str, slug: str) -> None:
        try:
            subprocess.Popen(
                [
                    "notify-send",
                    self.tool_name,
                    f"{fallback_from} unavailable, using {slug} instead",
                ]
            )
        except OSError:
            pass

    def format_unknown_account(self, slug: str) -> str:
        return f"{self.tool_name}: unknown account '{slug}'"

class CodexAdapter(ToolAdapter):
    def __init__(self) -> None:
        super().__init__(
            tool_name="cdx",
            exec_name="codex",
            accounts_dir_name="accounts",
            account_home_name="CODEX_HOME",
            routing_rules_filename=ROUTING_RULES_FILENAMES[AccountRegistryKind.CODEX],
            health_cache_filename=HEALTH_CACHE_FILENAMES[AccountRegistryKind.CODEX],
            health_cache_stale_seconds=HEALTH_STALE_SECONDS,
            health_snapshot_tool="codex",
            registry_kind=AccountRegistryKind.CODEX,
            config_env_var="CODEX_HOME",
            selected_default_filename="default_slug",
            legacy_tray_dir_name=".codex-tray",
        )

    def sync_before_exec(self, base_dir: Path) -> list[Path]:
        return AccountRegistry(
            base_dir=base_dir,
            legacy_codex_home=Path.home() / ".codex",
        ).sync_all_shared_links()

    def capture_log_path(self, forwarded_argv: list[str]) -> Path | None:
        if not is_exec_invocation(forwarded_argv):
            return None
        logs_dir = _writable_dir(
            self.tray_dir() / "logs" / self.tool_name,
            Path(tempfile.gettempdir()) / f"{self.tool_name}-logs",
        )
        if logs_dir is None:
            print(
                f"{self.tool_name}: no writable log directory; running without capture",
                file=sys.stderr,
            )
            return None
        stamp = time.strftime("%Y%m%d-%H%M%S")
        return logs_dir / f"{stamp}-{os.getpid()}.log"

    def build_env(self, account_home: Path) -> dict[str, str]:
        sqlite_home = account_home.parent / "SQLITE_HOME"
        return {
            "CODEX_HOME": str(account_home),
            "CODEX_SQLITE_HOME": str(sqlite_home),
        }

class ClaudeAdapter(ToolAdapter):
    def __init__(self) -> None:
        super().__init__(
            tool_name="cld",
            exec_name="claude",
            accounts_dir_name="claude-accounts",
            account_home_name="CLAUDE_HOME",
            routing_rules_filename=ROUTING_RULES_FILENAMES[AccountRegistryKind.CLAUDE],
            health_cache_filename=HEALTH_CACHE_FILENAMES[AccountRegistryKind.CLAUDE],
            health_cache_stale_seconds=2 * 60 * 60,
            health_snapshot_tool="claude",
            registry_kind=AccountRegistryKind.CLAUDE,
            config_env_var="CLAUDE_CONFIG_DIR",
            selected_default_filename="claude_default_slug",
        )

    def build_env(self, account_home: Path) -> dict[str, str]:
        return {
            "CLAUDE_CONFIG_DIR": str(account_home),
            "SYSTRAY_CLAUDE_ACCOUNT_HOME": str(account_home),
            "SYSTRAY_CLAUDE_ACCOUNT_SLUG": account_home.parent.name,
        }

    def sync_before_exec(self, base_dir: Path) -> list[Path]:
        return AccountRegistry(
            base_dir=base_dir,
            kind=AccountRegistryKind.CLAUDE,
        ).sync_all_shared_links()

    def verify_env_support(self, account_home: Path) -> bool:
        def auth_status(env: dict[str, str]) -> tuple[int, str, str] | None:
            try:
                result = subprocess.run(
                    [self.exec_name, "auth", "status", "--json"],
                    check=False,
                    capture_output=True,
                    text=True,
                    env=env,
                    timeout=10,
                )
            except OSError:
                return None
            stdout = "" if result.stdout is None else result.stdout.strip()
            stderr = "" if result.stderr is None else result.stderr.strip()
            return result.returncode, stdout, stderr

        probe_env = {**os.environ, self.config_env_var: str(account_home)}
        probe = auth_status(probe_env)
        if probe is None:
            return False
        baseline_env = dict(os.environ)
        baseline_env.pop(self.config_env_var, None)
        baseline = auth_status(baseline_env)
        if baseline is None:
            return False
        if probe != baseline:
            return True
        with tempfile.TemporaryDirectory(prefix="systray-claude-probe-") as control_home:
            control_env = {**os.environ, self.config_env_var: control_home}
            control = auth_status(control_env)
        return control is not None and control != probe

    def fetch_health(self, base_dir: Path, slug: str) -> AccountSnapshot:
        registry = AccountRegistry(base_dir=base_dir, kind=AccountRegistryKind.CLAUDE)
        account = next((item for item in registry.list() if item.slug == slug), None)
        if account is None:
            raise KeyError(slug)
        return ClaudeHealthClient().fetch(account)

def account_spend_cap_block(adapter: ToolAdapter, slug: str) -> AllAccountsCappedError | None:
    base_dirs = adapter.candidate_tray_dirs()
    selected_default = adapter.selected_default(base_dirs)
    base_dir = routing_base_dir(base_dirs, selected_default, adapter.routing_rules_filename)
    known_slugs = adapter.known_slugs(base_dir)
    if slug not in known_slugs:
        return None
    try:
        rules = load_rules(adapter.routing_rules_path(base_dir))
    except (OSError, json.JSONDecodeError, ValueError):
        return None
    health = load_health(
        adapter.health_cache_path(base_dir),
        stale_after_s=adapter.health_cache_stale_seconds,
        tool_name=adapter.tool_name,
        health_snapshot_tool=adapter.health_snapshot_tool,
    )
    resolver = RoutingResolver(rules, health, known_slugs=known_slugs)
    if not _override_account_spend_capped(resolver, slug):
        return None
    return AllAccountsCappedError(resolver.earliest_cap_resume_at((slug,)))

class CommandRouter:
    def __init__(
        self,
        adapter: ToolAdapter,
        *,
        detect_project_name: Callable[[Path | None], str] = detect_project_name,
        parse_account_override: Callable[[list[str]], tuple[str | None, list[str]]] = parse_account_override,
    ) -> None:
        self.adapter = adapter
        self._detect_project_name = detect_project_name
        self._parse_account_override = parse_account_override

    def main(self, argv: list[str]) -> int:
        route_query = len(argv) >= 2 and argv[1] == "route"
        if route_query:
            argv = [argv[0], *argv[2:]]
        canonical_query = False
        if route_query:
            canonical_query, argv = self._extract_flag(argv, "--canonical")
        show_status, usage_json, argv = self._parse_status_flag(argv)
        try:
            account_override, forwarded_argv = self._parse_account_override(argv[1:])
        except ValueError as exc:


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


Output:
Chunk ID: 852f26
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1690
Output:
        except ValueError as exc:
            print(f"{self.adapter.tool_name}: {exc}", file=sys.stderr)
            return 1

        if canonical_query:
            return self._emit_canonical_profile(account_override)

        try:
            if self.adapter.tool_name == "cdx":
                forwarded_argv = normalize_codex_exec_flags(forwarded_argv)
        except ValueError as exc:
            print(f"{self.adapter.tool_name}: {exc}", file=sys.stderr)
            return 1

        resolved = self._resolve_account(account_override, notify_fallback=not route_query)
        if resolved is None:
            if route_query:
                print(json.dumps({"ok": False, "detail": "account route unavailable"}, separators=(",", ":")))
            return 1
        if isinstance(resolved, AllAccountsCappedError):
            payload: dict[str, object] = {
                "ok": False,
                "detail": "rate-limited",
                "reason": "all-accounts-capped",
            }
            if resolved.resume_at is not None:
                payload["resume_at"] = resolved.resume_at
            print(json.dumps(payload, separators=(",", ":")))
            return 75
        base_dir, slug, account_home = resolved

        if route_query:
            route = self._last_route
            print(json.dumps({"account": slug, "chain": list(route.chain), "source": route.source, "project": self._last_project}, separators=(",", ":")))
            return 0

        if show_status:
            return self._print_live_status(slug, account_home, as_json=usage_json)

        try:
            self.adapter.sync_before_exec(base_dir)
        except (OSError, RuntimeError) as exc:
            print(
                f"{self.adapter.tool_name}: failed to synchronize shared Codex state: {exc}",
                file=sys.stderr,
            )
            return 1

        if not self.adapter.verify_env_support(account_home):
            print(
                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)

        os.execvpe(self.adapter.exec_name, [self.adapter.exec_name, *forwarded_argv], env)
        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):
            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,
                )
            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
            filtered.append(arg)
        return show_status, usage_json, filtered

    @staticmethod
    def _extract_flag(argv: list[str], flag: str) -> tuple[bool, list[str]]:
        if flag in argv:
            return True, [arg for arg in argv if arg != flag]
        return False, argv

    def _emit_canonical_profile(self, account_override: str | None) -> int:
        raw_chain = [
            part.strip() for part in (account_override or "").split(",") if part.strip()
        ]
        canonical_parts: list[str] = []
        for part in raw_chain:
            if part == "dynamic":
                canonical_parts.append("dynamic")
                continue
            resolved_slug = None
            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)


I’ve now pinned the exact control paths: `_run_captured` still has the current fail-open fallback block, and `main()` directly `execvpe`s when no log path is available. I’ll read the nearby tests in both modules to adjust behavior assertions precisely before patching.


sed -n '560,760p' modules/systray/tests/test_remote_dispatch.py


sed -n '760,980p' modules/systray/tests/test_remote_dispatch.py


sed -n '1000,1250p' modules/systray/tests/test_remote_dispatch.py


sed -n '820,1120p' modules/systray/tests/test_command_router.py


Output:
Chunk ID: c1a9bc
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 591
Output:

    assert host["name"] == "debian1"
    assert not corpse.exists()
    assert not live_pid_wrong_identity.exists()

def test_a_live_claim_is_counted_and_survives_reaping(isolated_claim_dir):
    mine = _plant_claim(
        isolated_claim_dir,
        "debian1",
        os.getpid(),
        remote_dispatch._process_start_ticks(os.getpid()) or "0",
    )
    host, _access, _claim = flat_load_selection(isolated_claim_dir)
    assert host["name"] != "debian1"
    assert mine.exists()

def test_claim_bookkeeping_failure_degrades_to_plain_least_loaded(tmp_path):
    unusable = tmp_path / "not-a-directory"
    unusable.write_text("", encoding="utf-8")
    loads = {"100.0.0.1": 9.0, "100.0.0.2": 0.2, "100.0.0.3": 4.0}
    host, _access, claim = remote_dispatch.select_host(
        remote_dispatch.candidate_hosts(THREE_REACHABLE),
        probe=lambda a: loads[a["host"]],
        claims=unusable,
    )
    assert host["name"] == "debian2"
    assert claim is None

def test_open_session_releases_the_claim_when_the_mirror_push_fails(tmp_path, monkeypatch):
    claims = tmp_path / "claims"

    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):
        remote_dispatch.open_session(
            "codex",
            ["exec", "hi"],
            registry_path=write_registry(tmp_path, THREE_REACHABLE),
            run=fake_run,
            probe=lambda a: 1.0,
            claims=claims,
        )
    assert list(claims.glob("*.claim")) == []

def test_session_release_frees_the_claim_at_the_end_of_a_run(tmp_path, monkeypatch):
    claims = tmp_path / "claims"
    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, THREE_REACHABLE),
        run=lambda argv, **kw: subprocess.CompletedProcess(argv, 0, stdout="", stderr=""),
        probe=lambda a: 1.0,
        claims=claims,
    )
    assert len(list(claims.glob("*.claim"))) == 1
    session.release()
    assert list(claims.glob("*.claim")) == []
    session.release()


Output:
Chunk ID: 761354
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 0
Output:


Output:
Chunk ID: abdb65
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 0
Output:


Output:
Chunk ID: 66a395
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2559
Output:
) -> 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 env: 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

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
    assert captured.err.strip().startswith("cdx: failed to load routing rules:")

def test_codex_router_reports_clean_error_for_malformed_rules_json(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    tray_dir = home / ".local/state/overdeck/systray/runtime"
    tray_dir.mkdir(parents=True)
    (tray_dir / "routing_rules.json").write_text("not-json", encoding="utf-8")
    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
    assert captured.err.strip().startswith("cdx: failed to load routing rules:")

def test_codex_router_reports_clean_error_for_invalid_rules_shape(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",
            "rules": {
                "projects": {},
                "default": "",
                "fallback_chain": [],
                "fallback_trigger": "broken_only",
                "quota_exhausted_threshold_pct": 100,
            },
        },
    )
    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
    assert captured.err.strip().startswith("cdx: failed to load routing rules:")

def test_claude_router_execs_with_claude_config_dir(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    write_rules(
        home,
        {
            "filename": "claude_routing_rules.json",
            "rules": {
                "projects": {},
                "default": "avi",
                "fallback_chain": ["roy"],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
            },
        },
    )
    claude_home = home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "avi" / "CLAUDE_HOME"
    claude_home.mkdir(parents=True)
    write_health(
        home,
        {
            "avi": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
        "claude_health_cache.json",
    )
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "unknown")
    monkeypatch.setattr(command_router.ClaudeAdapter, "verify_env_support", lambda self, home: True)
    router = command_router.CommandRouter(
        command_router.ClaudeAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exec_call: dict[str, object] = {}

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["file"] = file
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

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

    with pytest.raises(SystemExit):
        router.main(["cld", "chat"])

    assert exec_call["file"] == "claude"
    assert exec_call["args"] == ["claude", "chat"]
    assert exec_call["env"]["CLAUDE_CONFIG_DIR"] == str(claude_home)

def test_router_keeps_the_notification_opt_in_out_of_the_child_env(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    write_rules(
        home,
        {
            "filename": "claude_routing_rules.json",
            "rules": {
                "projects": {},
                "default": "avi",
                "fallback_chain": ["roy"],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
            },
        },
    )
    (home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "avi" / "CLAUDE_HOME").mkdir(parents=True)
    write_health(
        home,
        {"avi": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20}},
        "claude_health_cache.json",
    )
    monkeypatch.setenv("STALL_GUARD_NOTIFY", "1")
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "unknown")
    monkeypatch.setattr(command_router.ClaudeAdapter, "verify_env_support", lambda self, home: True)
    router = command_router.CommandRouter(
        command_router.ClaudeAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exec_call: dict[str, object] = {}

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["env"] = env
        raise SystemExit(0)

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

    with pytest.raises(SystemExit):
        router.main(["cld", "chat"])

    assert "STALL_GUARD_NOTIFY" not in exec_call["env"]
    assert os.environ["STALL_GUARD_NOTIFY"] == "1"

def test_codex_router_ignores_conflicting_claude_health_cache(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",
            "rules": {
                "projects": {},
                "default": "shared",
                "fallback_chain": [],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
            },
        },
    )
    codex_home = home / ".local/state/overdeck/systray/runtime" / "accounts" / "shared" / "CODEX_HOME"
    codex_home.mkdir(parents=True)
    (home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "shared" / "CLAUDE_HOME").mkdir(parents=True)
    write_health(
        home,
        {
            "shared": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
        "health_cache.json",
    )
    write_health(
        home,
        {
            "shared": {"status": "broken", "primary_used_pct": None, "secondary_used_pct": None},
        },
        "claude_health_cache.json",
    )
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "unknown")
    monkeypatch.setattr(
        command_router.CodexAdapter,
        "sync_before_exec",
        lambda self, base_dir: None,
    )
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exec_call: dict[str, object] = {}

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["file"] = file
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

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

    with pytest.raises(SystemExit):
        router.main(["cdx", "chat"])

    assert exec_call["file"] == "codex"
    assert exec_call["env"]["CODEX_HOME"] == str(codex_home)

def test_claude_router_ignores_conflicting_codex_health_cache(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    write_rules(
        home,
        {
            "filename": "claude_routing_rules.json",
            "rules": {
                "projects": {},
                "default": "shared",
                "fallback_chain": [],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
            },
        },
    )
    (home / ".local/state/overdeck/systray/runtime" / "accounts" / "shared" / "CODEX_HOME").mkdir(parents=True)
    claude_home = home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "shared" / "CLAUDE_HOME"
    claude_home.mkdir(parents=True)
    write_health(


sed -n '1120,1225p' modules/systray/tests/test_command_router.py


sed -n '1225,1435p' modules/systray/tests/test_command_router.py


sed -n '1435,1670p' modules/systray/tests/test_command_router.py


sed -n '1670,1995p' modules/systray/tests/test_command_router.py


Output:
Chunk ID: 3167d6
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 772
Output:
73:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
77:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
114:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
118:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
165:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
171:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
716:        "execvpe",
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(
836:    monkeypatch.setattr(command_router.remote_dispatch, "should_offload", lambda env: True)
846:    exit_code = router._run_captured(["exec", "hi"], {}, tmp_path / "run.log")
976:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
982:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1025:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1029:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1085:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1091:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1143:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1149:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1203:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1213:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1355:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1359:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1389:def test_capture_log_path_returns_none_when_no_directory_is_writable(
1457:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1461:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1516:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1520:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1572:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1576:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1634:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1638:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1752:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1756:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1813:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1817:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1870:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1875:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
1925:    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
1930:    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)


Output:
Chunk ID: 48a2b6
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 933
Output:
    write_health(
        home,
        {
            "shared": {"status": "broken", "primary_used_pct": None, "secondary_used_pct": None},
        },
        "health_cache.json",
    )
    write_health(
        home,
        {
            "shared": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
        "claude_health_cache.json",
    )
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "unknown")
    monkeypatch.setattr(command_router.ClaudeAdapter, "verify_env_support", lambda self, home: True)
    router = command_router.CommandRouter(
        command_router.ClaudeAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exec_call: dict[str, object] = {}

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["file"] = file
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

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

    with pytest.raises(SystemExit):
        router.main(["cld", "chat"])

    assert exec_call["file"] == "claude"
    assert exec_call["env"]["CLAUDE_CONFIG_DIR"] == str(claude_home)

def test_claude_router_notifies_and_uses_fallback_for_broken_default(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    write_rules(
        home,
        {
            "filename": "claude_routing_rules.json",
            "rules": {
                "version": "routing/v2",
                "projects": {
                    "unknown": {"account": "avi", "fallback": ["roy"]},
                },
                "default": "avi",
                "quota_exhausted_threshold_pct": 100,
            },
        },
    )
    claude_default_home = home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "avi" / "CLAUDE_HOME"
    claude_default_home.mkdir(parents=True)
    claude_fallback_home = home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "roy" / "CLAUDE_HOME"
    claude_fallback_home.mkdir(parents=True)
    write_health(
        home,
        {
            "avi": {"status": "broken", "primary_used_pct": None, "secondary_used_pct": None},
            "roy": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
        "claude_health_cache.json",
    )
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "unknown")
    monkeypatch.setattr(
        command_router.ClaudeAdapter,
        "verify_env_support",
        lambda self, account_home: True,
        raising=False,
    )
    router = command_router.CommandRouter(
        command_router.ClaudeAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    exec_call: dict[str, object] = {}
    popen_calls: list[list[str]] = []

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["file"] = file
        exec_call["args"] = args
        exec_call["env"] = env
        raise SystemExit(0)

    def fake_popen(args: list[str]) -> object:
        popen_calls.append(args)
        return object()

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
    monkeypatch.setattr(command_router.subprocess, "Popen", fake_popen)

    with pytest.raises(SystemExit):
        router.main(["cld", "chat"])

    assert exec_call["env"]["CLAUDE_CONFIG_DIR"] == str(claude_fallback_home)
    assert popen_calls == [["notify-send", "cld", "avi unavailable, using roy instead"]]

def test_claude_adapter_build_env_identifies_statusline_account(home: Path) -> None:
    account_home = home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "multideal" / "CLAUDE_HOME"


Output:
Chunk ID: aab05e
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1794
Output:

    assert command_router.ClaudeAdapter().build_env(account_home) == {
        "CLAUDE_CONFIG_DIR": str(account_home),
        "SYSTRAY_CLAUDE_ACCOUNT_HOME": str(account_home),
        "SYSTRAY_CLAUDE_ACCOUNT_SLUG": "multideal",
    }

def test_claude_adapter_verify_env_support_probes_claude_config_dir(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    claude_home = home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "avi" / "CLAUDE_HOME"
    claude_home.mkdir(parents=True)
    run_call: list[dict[str, object]] = []
    responses = iter(
        [
            subprocess.CompletedProcess(
                args=["claude", "auth", "status", "--json"],
                returncode=1,
                stdout='{"loggedIn": false, "authMethod": "none", "apiProvider": "firstParty"}\n',
                stderr="",
            ),
            subprocess.CompletedProcess(
                args=["claude", "auth", "status", "--json"],
                returncode=0,
                stdout='{"loggedIn": true, "authMethod": "claude.ai", "apiProvider": "firstParty"}\n',
                stderr="",
            ),
        ]
    )

    def fake_run(
        cmd: list[str],
        *,
        check: bool,
        capture_output: bool,
        text: bool,
        env: dict[str, str],
        timeout: int,
    ) -> subprocess.CompletedProcess[str]:
        run_call.append({"cmd": cmd, "env": env})
        return next(responses)

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

    adapter = command_router.ClaudeAdapter()

    assert adapter.verify_env_support(claude_home) is True
    assert len(run_call) == 2
    assert run_call[0]["cmd"] == ["claude", "auth", "status", "--json"]
    assert run_call[0]["env"]["CLAUDE_CONFIG_DIR"] == str(claude_home)
    assert run_call[1]["cmd"] == ["claude", "auth", "status", "--json"]
    assert "CLAUDE_CONFIG_DIR" not in run_call[1]["env"]

def test_claude_adapter_accepts_selected_default_with_identical_global_auth(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    claude_home = home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "avi" / "CLAUDE_HOME"
    claude_home.mkdir(parents=True)
    logged_in = subprocess.CompletedProcess(
        args=["claude", "auth", "status", "--json"],
        returncode=0,
        stdout='{"loggedIn": true, "authMethod": "claude.ai"}\n',
        stderr="",
    )
    logged_out = subprocess.CompletedProcess(
        args=["claude", "auth", "status", "--json"],
        returncode=1,
        stdout='{"loggedIn": false, "authMethod": "none"}\n',
        stderr="",
    )
    responses = iter([logged_in, logged_in, logged_out])
    run_call: list[dict[str, object]] = []

    def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
        run_call.append({"cmd": cmd, "env": kwargs["env"]})
        return next(responses)

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

    assert command_router.ClaudeAdapter().verify_env_support(claude_home) is True
    assert len(run_call) == 3
    control_home = Path(run_call[2]["env"]["CLAUDE_CONFIG_DIR"])
    assert control_home != claude_home

def test_claude_router_rejects_unsupported_routing_when_probe_fails(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    write_rules(
        home,
        {
            "filename": "claude_routing_rules.json",
            "rules": {
                "projects": {},
                "default": "avi",
                "fallback_chain": ["roy"],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
            },
        },
    )
    claude_home = home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "avi" / "CLAUDE_HOME"
    claude_home.mkdir(parents=True)
    write_health(
        home,
        {
            "avi": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
        "claude_health_cache.json",
    )
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "unknown")
    monkeypatch.setattr(
        command_router.ClaudeAdapter,
        "verify_env_support",
        lambda self, account_home: False,
        raising=False,
    )
    router = command_router.CommandRouter(
        command_router.ClaudeAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    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(["cld", "chat"])
    captured = capsys.readouterr()

    assert exit_code == 1
    assert exec_called is False
    assert captured.err.strip() == (
        f"cld: unsupported routing: claude did not honor CLAUDE_CONFIG_DIR for {claude_home}"
    )

def test_capture_log_path_falls_back_when_tray_logs_unwritable(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    tray_logs = home / ".local/state/overdeck/systray/runtime" / "logs"
    tray_logs.mkdir(parents=True)
    tray_logs.chmod(0o500)
    fallback_root = home / "tmpdir"
    fallback_root.mkdir()
    monkeypatch.setattr(command_router.tempfile, "gettempdir", lambda: str(fallback_root))

    log_path = command_router.CodexAdapter().capture_log_path(["exec", "hi"])

    assert log_path is not None
    assert log_path.parent == fallback_root / "cdx-logs"
    assert log_path.parent.is_dir()

def test_capture_log_path_returns_none_when_no_directory_is_writable(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    tray_logs = home / ".local/state/overdeck/systray/runtime" / "logs"
    tray_logs.mkdir(parents=True)
    tray_logs.chmod(0o500)
    fallback_root = home / "tmpdir"
    fallback_root.mkdir(mode=0o500)
    monkeypatch.setattr(command_router.tempfile, "gettempdir", lambda: str(fallback_root))

    log_path = command_router.CodexAdapter().capture_log_path(["exec", "hi"])

    assert log_path is None
    assert "no writable log directory" in capsys.readouterr().err

def test_codex_router_all_capped_exits_75_with_resume_at(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",
            "rules": {
                "projects": {},
                "default": "rafa",
                "fallback_chain": ["roy"],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
                "account_caps": {
                    "rafa": {"7d": 10},
                    "roy": {"7d": 10},
                },
            },
        },
    )
    for slug in ("rafa", "roy"):
        (home / ".local/state/overdeck/systray/runtime" / "accounts" / slug / "CODEX_HOME").mkdir(parents=True)
    write_health(
        home,
        {
            "rafa": {
                "status": "ok",


Output:
Chunk ID: 429bb3
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1860
Output:
                "status": "ok",
                "primary_used_pct": 10,
                "secondary_used_pct": 90,
                "secondary_reset_at": 1786365653.0,
            },
            "roy": {
                "status": "ok",
                "primary_used_pct": 10,
                "secondary_used_pct": 95,
                "secondary_reset_at": 1787000000.0,
            },
        },
        "health_cache.json",
    )
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "unknown")
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    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 == 75
    assert exec_called is False
    assert captured.err == ""
    assert json.loads(captured.out) == {
        "ok": False,
        "detail": "rate-limited",
        "reason": "all-accounts-capped",
        "resume_at": "2026-08-10T12:40:53Z",
    }

def test_cld_router_all_capped_exits_75_without_resume_at_when_unknown(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    write_rules(
        home,
        {
            "filename": "claude_routing_rules.json",
            "rules": {
                "projects": {},
                "default": "avi",
                "fallback_chain": [],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
                "account_caps": {"avi": {"7d": 10}},
            },
        },
    )
    (home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "avi" / "CLAUDE_HOME").mkdir(parents=True)
    write_health(
        home,
        {
            "avi": {
                "status": "ok",
                "primary_used_pct": 10,
                "secondary_used_pct": 90,
            },
        },
        "claude_health_cache.json",
    )
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "unknown")
    router = command_router.CommandRouter(
        command_router.ClaudeAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    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(["cld", "route"])
    captured = capsys.readouterr()

    assert exit_code == 75
    assert exec_called is False
    assert captured.err == ""
    assert json.loads(captured.out) == {
        "ok": False,
        "detail": "rate-limited",
        "reason": "all-accounts-capped",
    }
    assert "resume_at" not in captured.out

def test_codex_router_all_quota_exhausted_stays_exit_one_not_all_capped(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",
            "rules": {
                "projects": {},
                "default": "rafa",
                "fallback_chain": ["roy"],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
            },
        },
    )
    for slug in ("rafa", "roy"):
        (home / ".local/state/overdeck/systray/runtime" / "accounts" / slug / "CODEX_HOME").mkdir(parents=True)
    write_health(
        home,
        {
            "rafa": {"status": "ok", "primary_used_pct": 100, "secondary_used_pct": 10},
            "roy": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 100},
        },
        "health_cache.json",
    )
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "unknown")
    router = command_router.CommandRouter(
        command_router.CodexAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    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 == 1
    assert exec_called is False
    assert "all-accounts-capped" not in captured.out
    assert "quota-exhausted" in captured.err

def test_codex_router_explicit_override_refuses_capped_account(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",
            "rules": {
                "projects": {},
                "default": "zync2",
                "fallback_chain": [],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
                "account_caps": {"zync2": {"7d": 10}},
            },
        },
    )
    tray = home / ".local/state/overdeck/systray/runtime"
    (tray / "accounts" / "zync2" / "CODEX_HOME").mkdir(parents=True)
    write_health(
        home,
        {
            "zync2": {
                "status": "ok",
                "primary_used_pct": 10,
                "secondary_used_pct": 91,
                "secondary_reset_at": 1786365653.0,
            },
        },
        "health_cache.json",
    )
    router = command_router.CommandRouter(command_router.CodexAdapter())

    from routing_resolver import AllAccountsCappedError, RoutingResolver, load_rules

    resolved = router._resolve_account("zync2")
    assert isinstance(resolved, AllAccountsCappedError)

    rules = load_rules(tray / "routing_rules.json")
    health = command_router.load_health(tray / "health_cache.json")
    resolver = RoutingResolver(rules, health, known_slugs={"zync2"})
    assert resolver._describe_status("zync2") == "capped(7d=9% left <= 10%)"

    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", "--account", "zync2", "chat"])
    captured = capsys.readouterr()

    assert exit_code == 75
    assert exec_called is False
    assert json.loads(captured.out) == {
        "ok": False,
        "detail": "rate-limited",
        "reason": "all-accounts-capped",
        "resume_at": "2026-08-10T12:40:53Z",
    }

def test_codex_router_explicit_override_skips_capped_chain_entry(home: Path) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",
            "rules": {
                "projects": {},
                "default": "zync2",
                "fallback_chain": [],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
                "account_caps": {
                    "zync2": {"7d": 10},
                    "roy": {"7d": 10},
                },
            },
        },
    )


Output:
Chunk ID: 8b765e
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2063
Output:
    )
    tray = home / ".local/state/overdeck/systray/runtime"
    for slug in ("zync2", "roy"):
        (tray / "accounts" / slug / "CODEX_HOME").mkdir(parents=True)
    write_health(
        home,
        {
            "zync2": {
                "status": "ok",
                "primary_used_pct": 10,
                "secondary_used_pct": 91,
            },
            "roy": {
                "status": "ok",
                "primary_used_pct": 10,
                "secondary_used_pct": 10,
            },
        },
        "health_cache.json",
    )
    router = command_router.CommandRouter(command_router.CodexAdapter())

    resolved = router._resolve_account("zync2,roy")

    assert resolved == (tray, "roy", tray / "accounts" / "roy" / "CODEX_HOME")
    assert router._last_route.slug == "roy"
    assert router._last_route.chain == ("zync2", "roy")

def test_codex_router_explicit_override_all_capped_returns_all_accounts_capped_error(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",
            "rules": {
                "projects": {},
                "default": "zync2",
                "fallback_chain": [],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
                "account_caps": {
                    "zync2": {"7d": 10},
                    "roy": {"7d": 10},
                },
            },
        },
    )
    tray = home / ".local/state/overdeck/systray/runtime"
    for slug in ("zync2", "roy"):
        (tray / "accounts" / slug / "CODEX_HOME").mkdir(parents=True)
    write_health(
        home,
        {
            "zync2": {
                "status": "ok",
                "primary_used_pct": 10,
                "secondary_used_pct": 91,
                "secondary_reset_at": 1786365653.0,
            },
            "roy": {
                "status": "ok",
                "primary_used_pct": 10,
                "secondary_used_pct": 95,
                "secondary_reset_at": 1787000000.0,
            },
        },
        "health_cache.json",
    )
    router = command_router.CommandRouter(command_router.CodexAdapter())

    from routing_resolver import AllAccountsCappedError

    resolved = router._resolve_account("zync2,roy")
    assert isinstance(resolved, AllAccountsCappedError)
    assert resolved.resume_at == "2026-08-10T12:40:53Z"

    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", "--account", "zync2,roy", "chat"])
    captured = capsys.readouterr()

    assert exit_code == 75
    assert exec_called is False
    assert json.loads(captured.out) == {
        "ok": False,
        "detail": "rate-limited",
        "reason": "all-accounts-capped",
        "resume_at": "2026-08-10T12:40:53Z",
    }

def test_codex_router_explicit_override_refuses_broken_account_when_over_cap(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",
            "rules": {
                "projects": {},
                "default": "rafa",
                "fallback_chain": [],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
                "account_caps": {"rafa": {"7d": 10}},
            },
        },
    )
    tray = home / ".local/state/overdeck/systray/runtime"
    (tray / "accounts" / "rafa" / "CODEX_HOME").mkdir(parents=True)
    write_health(
        home,
        {
            "rafa": {
                "status": "broken",
                "primary_used_pct": 100,
                "secondary_used_pct": 91,
                "secondary_reset_at": 1786365653.0,
            },
        },
        "health_cache.json",
    )
    router = command_router.CommandRouter(command_router.CodexAdapter())

    from routing_resolver import AllAccountsCappedError

    resolved = router._resolve_account("rafa")
    assert isinstance(resolved, AllAccountsCappedError)

    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", "--account", "rafa", "chat"])
    captured = capsys.readouterr()

    assert exit_code == 75
    assert exec_called is False
    assert json.loads(captured.out) == {
        "ok": False,
        "detail": "rate-limited",
        "reason": "all-accounts-capped",
        "resume_at": "2026-08-10T12:40:53Z",
    }

def test_codex_router_explicit_override_resolves_broken_account_when_under_cap(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",
            "rules": {
                "projects": {},
                "default": "rafa",
                "fallback_chain": [],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
                "account_caps": {"rafa": {"7d": 10}},
            },
        },
    )
    tray = home / ".local/state/overdeck/systray/runtime"
    (tray / "accounts" / "rafa" / "CODEX_HOME").mkdir(parents=True)
    write_health(
        home,
        {
            "rafa": {
                "status": "broken",
                "primary_used_pct": 100,
                "secondary_used_pct": 80,
            },
        },
        "health_cache.json",
    )
    router = command_router.CommandRouter(command_router.CodexAdapter())

    resolved = router._resolve_account("rafa")
    assert resolved == (tray, "rafa", tray / "accounts" / "rafa" / "CODEX_HOME")

    exec_call: dict[str, object] = {}

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["file"] = file
        exec_call["args"] = args
        raise SystemExit(0)

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
    monkeypatch.setattr(
        command_router.CodexAdapter,
        "sync_before_exec",
        lambda self, base_dir: None,
    )

    with pytest.raises(SystemExit):
        router.main(["cdx", "--account", "rafa", "chat"])

    assert exec_call["file"] == "codex"

def test_codex_router_explicit_override_resolves_quota_exhausted_without_caps(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",
            "rules": {
                "projects": {},
                "default": "rafa",
                "fallback_chain": [],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
            },
        },
    )
    tray = home / ".local/state/overdeck/systray/runtime"
    (tray / "accounts" / "rafa" / "CODEX_HOME").mkdir(parents=True)
    write_health(
        home,
        {
            "rafa": {
                "status": "ok",
                "primary_used_pct": 100,
                "secondary_used_pct": 100,
            },
        },
        "health_cache.json",
    )
    router = command_router.CommandRouter(command_router.CodexAdapter())

    resolved = router._resolve_account("rafa")
    assert resolved == (tray, "rafa", tray / "accounts" / "rafa" / "CODEX_HOME")

    exec_call: dict[str, object] = {}

    def fake_execvpe(file: str, args: list[str], env: dict[str, str]) -> None:
        exec_call["file"] = file
        exec_call["args"] = args
        raise SystemExit(0)

    monkeypatch.setattr(command_router.os, "execvpe", fake_execvpe)
    monkeypatch.setattr(
        command_router.CodexAdapter,
        "sync_before_exec",
        lambda self, base_dir: None,
    )

    with pytest.raises(SystemExit):
        router.main(["cdx", "--account", "rafa", "chat"])

    assert exec_call["file"] == "codex"


sed -n '680,860p' modules/systray/tests/test_command_router.py


Output:
Chunk ID: 03bb55
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1610
Output:
)
def test_codex_rejects_effort_config_without_value(config_flag: list[str]) -> None:
    with pytest.raises(ValueError, match="^model_reasoning_effort requires a value$"):
        command_router.normalize_codex_exec_flags(
            ["exec", "-m", "gpt-5.6-sol", *config_flag, "prompt"]
        )

def test_codex_non_exec_arguments_remain_byte_for_byte_equivalent() -> None:
    argv = ["chat", "-m", "gpt-5.6-sol", "-c", "model_reasoning_effort=max", "prompt"]
    assert command_router.normalize_codex_exec_flags(argv) == argv

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

    monkeypatch.setattr(
        router,
        "_resolve_account",
        lambda *args, **kwargs: pytest.fail("account resolution must not run"),
    )
    monkeypatch.setattr(
        command_router.CodexAdapter,
        "sync_before_exec",
        lambda *args, **kwargs: pytest.fail("synchronization must not run"),
    )
    monkeypatch.setattr(
        command_router.subprocess,
        "run",
        lambda *args, **kwargs: pytest.fail("subprocess must not run"),
    )
    monkeypatch.setattr(
        command_router.os,
        "execvpe",
        lambda *args, **kwargs: pytest.fail("exec must not run"),
    )

    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 env: 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

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,


sed -n '1320,1415p' modules/systray/tests/test_command_router.py


Output:
Chunk ID: 128736
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 780
Output:
        home,
        {
            "filename": "claude_routing_rules.json",
            "rules": {
                "projects": {},
                "default": "avi",
                "fallback_chain": ["roy"],
                "fallback_trigger": "broken_or_quota_exhausted",
                "quota_exhausted_threshold_pct": 100,
            },
        },
    )
    claude_home = home / ".local/state/overdeck/systray/runtime" / "claude-accounts" / "avi" / "CLAUDE_HOME"
    claude_home.mkdir(parents=True)
    write_health(
        home,
        {
            "avi": {"status": "ok", "primary_used_pct": 10, "secondary_used_pct": 20},
        },
        "claude_health_cache.json",
    )
    monkeypatch.setattr(command_router, "detect_project_name", lambda cwd=None: "unknown")
    monkeypatch.setattr(
        command_router.ClaudeAdapter,
        "verify_env_support",
        lambda self, account_home: False,
        raising=False,
    )
    router = command_router.CommandRouter(
        command_router.ClaudeAdapter(),
        detect_project_name=command_router.detect_project_name,
    )

    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(["cld", "chat"])
    captured = capsys.readouterr()

    assert exit_code == 1
    assert exec_called is False
    assert captured.err.strip() == (
        f"cld: unsupported routing: claude did not honor CLAUDE_CONFIG_DIR for {claude_home}"
    )

def test_capture_log_path_falls_back_when_tray_logs_unwritable(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    tray_logs = home / ".local/state/overdeck/systray/runtime" / "logs"
    tray_logs.mkdir(parents=True)
    tray_logs.chmod(0o500)
    fallback_root = home / "tmpdir"
    fallback_root.mkdir()
    monkeypatch.setattr(command_router.tempfile, "gettempdir", lambda: str(fallback_root))

    log_path = command_router.CodexAdapter().capture_log_path(["exec", "hi"])

    assert log_path is not None
    assert log_path.parent == fallback_root / "cdx-logs"
    assert log_path.parent.is_dir()

def test_capture_log_path_returns_none_when_no_directory_is_writable(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    tray_logs = home / ".local/state/overdeck/systray/runtime" / "logs"
    tray_logs.mkdir(parents=True)
    tray_logs.chmod(0o500)
    fallback_root = home / "tmpdir"
    fallback_root.mkdir(mode=0o500)
    monkeypatch.setattr(command_router.tempfile, "gettempdir", lambda: str(fallback_root))

    log_path = command_router.CodexAdapter().capture_log_path(["exec", "hi"])

    assert log_path is None
    assert "no writable log directory" in capsys.readouterr().err

def test_codex_router_all_capped_exits_75_with_resume_at(
    home: Path,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    write_rules(
        home,
        {
            "filename": "routing_rules.json",


rg -n "def test_main_" modules/systray/tests/test_command_router.py


Output:
Chunk ID: 024a42
Wall time: 0.0000 seconds
Process exited with code 1
Original token count: 0
Output:


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


Output:
Chunk ID: 8eacde
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 122
Output:
modules/systray/tests/test_remote_dispatch.py:81:    assert remote_dispatch.should_offload({}) is True
modules/systray/tests/test_remote_dispatch.py:85:    assert remote_dispatch.should_offload({"CDX_NO_OFFLOAD": "1"}) is False
modules/systray/tests/test_remote_dispatch.py:89:    assert remote_dispatch.should_offload({"OD_REMOTE_EXEC": "1"}) is False
modules/systray/tests/test_remote_dispatch.py:90:    assert remote_dispatch.should_offload({"HARNESS_SEAT_CONTAINER": "1"}) is False


rg -n "OffloadUnavailable|cluster offload unavailable|capture_log_path.*None|in_container|RUNNING ON THE WORKSTATION" modules/systray/tests/test_command_router.py


Output:
Chunk ID: 74fe81
Wall time: 0.0000 seconds
Process exited with code 1
Original token count: 0
Output:


rg -n "raise OffloadUnavailable" modules/systray/remote_dispatch.py


Output:
Chunk ID: ee3fff
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 187
Output:
74:        raise OffloadUnavailable(f"buildbox registry unreadable at {path}: {exc}") from exc
85:        raise OffloadUnavailable(f"no reachable host with role {role} in the registry")
92:        raise OffloadUnavailable(f"{host.get('name')}: no usable {door} access door")
269:        raise OffloadUnavailable("; ".join(failures) or "no candidate node answered")
563:            raise OffloadUnavailable(f"{name}: could not prepare mirror: {exc}") from exc
565:            raise OffloadUnavailable(f"{name}: could not prepare mirror: {made.stderr.strip()}")
575:            raise OffloadUnavailable(f"{name}: mirror push failed: {exc}") from exc
577:            raise OffloadUnavailable(f"{name}: mirror push failed: {pushed.stderr.strip()}")


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