Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(windows): keep the app's PATH short enough to start programs (#575)

Ruben Lütke775b94e6036a
diff --git a/docs/BUGS.md b/docs/BUGS.md
index ce9e681f23..6ecf4782b8 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -16131,3 +16131,34 @@ does (`tests/unit/speech/conftest.py`), so a developer's real key no longer
flips desktop-path tests. Guards: `tests/unit/realtime/test_factory.py`,
`tests/unit/web/test_voice_mode_route.py`,
`tests/unit/speech/test_realtime_mode.py`.
+
+## BUG-233: every program start from the app failed with WinError 8 once its PATH grew too long (HIGH, FIXED 2026-10-13)
+
+**Symptom.** On Windows an agent chat answered `Could not start codex-cli:
+[WinError 8] Not enough memory resources are available to process this
+command`, the Codex brain logged `CodexBrain CLI: spawn failed` with the same
+error, and the install test on the provider card said the Codex install looks
+broken. The same `codex` ran fine from a terminal, with the npm launcher and
+with the native binary alike (GitHub issue #574). Nothing was short of memory.
+
+**Cause.** For each `CreateProcess` Windows builds one search path from the
+application directory, the system directories and the calling process's
+`PATH`, in a string that holds 32,767 characters. When that overflows, every
+spawn of the process fails with `ERROR_NOT_ENOUGH_MEMORY`, whatever is started
+and whatever environment the child is given; a child that is handed such a
+PATH exits with `STATUS_NO_MEMORY` during its own start-up. Measured on
+Windows 11: with a 26-character application directory the last working PATH is
+32,688 characters and the first failing one 32,689. `ensure_cli_paths` and
+`refresh_from_persistent_path` appended CLI install folders to the app's own
+PATH with no upper bound, and neither looked at the length they inherited.
+
+**Fix.** `jarvis/core/path_augment.py` writes PATH through one bounded writer
+(`_store_path`, budget `_WINDOWS_PATH_BUDGET` = 31,000 characters, Windows
+only). Past the budget `fit_path_entries` gives up empty and repeated entries
+first, then folders that do not exist, then real folders from the end, and a
+CLI folder that still does not fit is left out with a warning. A PATH that is
+already too long when the app starts is repaired by the same call at boot. The
+Codex install test now reports the system's own refusal instead of a broken
+install (`codex_auth.version_spawn_error`). Guards:
+`tests/unit/core/test_path_augment.py` (including a real spawn past the limit
+on Windows), `tests/unit/test_agent_cli_probe.py`.
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 075f9c5d60..146141a664 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -1,5 +1,16 @@
# OS Feature Parity — macOS / Linux Gap Register
+## PATH length budget (issue #574, T2)
+
+On Windows the app keeps its own `PATH` within 31,000 characters: past the
+32,767-character search path Windows builds per program start, every spawn
+from the process fails with `WinError 8`. Repeated entries and folders that do
+not exist are dropped first, real folders from the end last, and an inherited
+PATH that is already too long is repaired at boot. macOS and Linux have no such
+per-variable limit, so the PATH is never shortened there; the budget logic runs
+on every OS in the unit tests, and the real spawn past the limit was verified on
+Windows 11 only.
+
## Local voice and audio topology refresh (issue #464, T2)
Local final transcription uses its configured model independently of the wake
diff --git a/jarvis/agent_cli_probe.py b/jarvis/agent_cli_probe.py
index 9e96eaec46..b78110f3fa 100644
--- a/jarvis/agent_cli_probe.py
+++ b/jarvis/agent_cli_probe.py
@@ -151,10 +151,20 @@ def test_codex(binary_path: str | None = None) -> AgentCliTestResult:
if not status.installed:
return _not_installed("codex", "Install with: npm i -g @openai/codex", t0)
ok = status.version is not None
- message = status.message if ok else (
- f"Found at {status.binary_path}, but 'codex --version' did not answer "
- "— the install looks broken."
- )
+ spawn_error = codex_auth.version_spawn_error(status.binary_path)
+ if ok:
+ message = status.message
+ elif spawn_error:
+ # The host refused to start it, which says nothing about the install.
+ message = (
+ f"Found at {status.binary_path}, but the system could not start it: "
+ f"{spawn_error}"
+ )
+ else:
+ message = (
+ f"Found at {status.binary_path}, but 'codex --version' did not answer "
+ "— the install looks broken."
+ )
return AgentCliTestResult(
cli="codex",
ok=ok,
diff --git a/jarvis/codex_auth.py b/jarvis/codex_auth.py
index e9d8800c8a..86ae21e8a3 100644
--- a/jarvis/codex_auth.py
+++ b/jarvis/codex_auth.py
@@ -62,6 +62,12 @@ _BINARY_CANDIDATES: tuple[str, ...] = ("codex", "codex.cmd", "codex.exe")
# probe is cached too, so a hanging/absent codex never re-pays the 4 s timeout.
_VERSION_CACHE: dict[str, str | None] = {}
+# Why the last ``codex --version`` probe of a binary could not be started at
+# all, keyed like ``_VERSION_CACHE``. A host that refuses the spawn is not a
+# broken install, and an install test that says so sends the user reinstalling
+# a working CLI. (BUG-233)
+_VERSION_SPAWN_ERRORS: dict[str, str] = {}
+
# A dedicated subscription login must not inherit provider, cloud, proxy,
# dynamic-loader, keyring, or agent-session state. Keep this list deliberately
# small: these are OS process essentials, not a denylist that has to predict the
@@ -324,6 +330,15 @@ def clear_version_cache() -> None:
it, so they don't call this).
"""
_VERSION_CACHE.clear()
+ _VERSION_SPAWN_ERRORS.clear()
+
+
+def version_spawn_error(binary: str | None) -> str | None:
+ """Why the host could not start ``binary`` for its version probe, if it could not.
+
+ ``None`` when the probe ran (whatever it answered) or never happened.
+ """
+ return _VERSION_SPAWN_ERRORS.get(binary) if binary else None
# Visible-console flag for the interactive login (Windows only). The desktop app
# runs under pythonw.exe (no console); without a fresh console the user could
@@ -764,9 +779,15 @@ class CodexAuthService:
creationflags=NO_WINDOW_CREATIONFLAGS,
env=self._subprocess_environment(),
)
- except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
+ except subprocess.TimeoutExpired:
+ _VERSION_CACHE[binary] = None
+ return None
+ except OSError as exc:
+ # The spawn itself was refused; keep the reason for the install test.
+ _VERSION_SPAWN_ERRORS[binary] = str(exc)
_VERSION_CACHE[binary] = None
return None
+ _VERSION_SPAWN_ERRORS.pop(binary, None)
out = (proc.stdout or proc.stderr or "").strip()
version = out or None
_VERSION_CACHE[binary] = version
diff --git a/jarvis/core/path_augment.py b/jarvis/core/path_augment.py
index b9017913d6..133abe509b 100644
--- a/jarvis/core/path_augment.py
+++ b/jarvis/core/path_augment.py
@@ -15,6 +15,10 @@ to ``os.environ["PATH"]``. Existing entries keep priority — only *missing*
dirs are appended, so a user-managed PATH always wins and the call is
idempotent. Pure ``stat()`` probes, no subprocess: boot-budget-safe (AP-26).
+The PATH it writes stays inside what the platform can spawn with: see
+``_WINDOWS_PATH_BUDGET``. A PATH that arrives too long is shortened the same
+way, so an app started from such an environment can still launch programs.
+
Cross-platform per CLOUD.md Rule #1: the candidate list covers macOS
(Intel + Apple Silicon Homebrew), Linux (incl. headless), and Windows; a dir
that does not exist on this host is simply skipped.
@@ -31,6 +35,21 @@ from pathlib import Path
log = logging.getLogger(__name__)
+# Windows builds one search path per ``CreateProcess`` from the application
+# directory, the system directories and the CALLER's ``PATH``, in a string that
+# holds 32,767 characters. Past that EVERY spawn of the process fails with
+# ``WinError 8`` ("not enough memory resources"), whatever is being started and
+# whatever environment the child is given; a child handed such a PATH dies
+# during its own start-up instead. The budget leaves room for a long
+# application directory and for the folder a caller adds to one child's PATH.
+# (BUG-233)
+_WINDOWS_PATH_BUDGET = 31_000
+
+# The last over-budget request that changed nothing. Callers ask on every
+# status probe, and re-probing several hundred folders each time to reach the
+# same answer would cost more than the lookup it serves.
+_settled_overflow: tuple[str, tuple[str, ...]] | None = None
+
def _posix_candidates() -> list[str]:
home = Path.home()
@@ -154,6 +173,91 @@ def candidate_dirs() -> list[str]:
return [*base, *_registered_agent_dirs()]
+def _path_budget() -> int | None:
+ """The longest ``PATH`` this platform can spawn with; ``None`` if unbounded."""
+ return _WINDOWS_PATH_BUDGET if sys.platform == "win32" else None
+
+
+def _entry_key(entry: str) -> str:
+ return os.path.normcase(os.path.normpath(entry))
+
+
+def _joined_length(entries: list[str]) -> int:
+ return sum(len(entry) for entry in entries) + max(len(entries) - 1, 0)
+
+
+def fit_path_entries(entries: list[str], budget: int) -> list[str]:
+ """Shorten ``entries`` until their joined ``PATH`` fits ``budget``.
+
+ Gives up the cheapest thing first: empty and repeated entries, then folders
+ that do not exist, and only then real folders from the end, where the
+ lowest-priority ones sit. A list that already fits comes back unchanged, so
+ a healthy PATH is never rewritten.
+ """
+ if _joined_length(entries) <= budget:
+ return entries
+ seen: set[str] = set()
+ unique: list[str] = []
+ for entry in entries:
+ key = _entry_key(entry) if entry else ""
+ if not entry or key in seen:
+ continue
+ seen.add(key)
+ unique.append(entry)
+ if _joined_length(unique) <= budget:
+ return unique
+ existing: list[str] = []
+ for entry in unique:
+ try:
+ if os.path.isdir(entry):
+ existing.append(entry)
+ except OSError: # an unreadable entry cannot be searched either
+ continue
+ while existing and _joined_length(existing) > budget:
+ existing.pop()
+ return existing
+
+
+def _store_path(current: str, added: list[str]) -> list[str]:
+ """Write ``current`` plus ``added`` to ``PATH``; return what of ``added`` got in.
+
+ Inside the platform's budget this is a plain append. Past it the PATH is
+ shortened with :func:`fit_path_entries` first, which is also how a PATH
+ that was already too long when the app started gets repaired.
+ """
+ global _settled_overflow
+
+ entries = current.split(os.pathsep) if current else []
+ budget = _path_budget()
+ if budget is None or _joined_length(entries + added) <= budget:
+ if added:
+ os.environ["PATH"] = os.pathsep.join([current, *added] if current else added)
+ return added
+ request = (current, tuple(added))
+ if request == _settled_overflow:
+ return []
+ fitted = fit_path_entries(entries + added, budget)
+ kept_keys = {_entry_key(entry) for entry in fitted}
+ kept = [entry for entry in added if _entry_key(entry) in kept_keys]
+ value = os.pathsep.join(fitted)
+ if value == current:
+ _settled_overflow = request
+ else:
+ os.environ["PATH"] = value
+ log.warning(
+ "PATH is %d characters long, over the %d-character budget that keeps "
+ "Windows able to start programs: kept %d of %d entries (repeated and "
+ "missing folders go first), %d of %d CLI install dir(s) added",
+ len(current),
+ budget,
+ len(fitted),
+ len(entries) + len(added),
+ len(kept),
+ len(added),
+ )
+ return kept
+
+
def ensure_cli_paths() -> list[str]:
"""Append missing well-known CLI dirs to ``PATH``; return what was added.
@@ -178,9 +282,8 @@ def ensure_cli_paths() -> list[str]:
continue
seen.add(key)
added.append(cand)
+ added = _store_path(current, added)
if added:
- joined = os.pathsep.join(added)
- os.environ["PATH"] = f"{current}{os.pathsep}{joined}" if current else joined
log.info("PATH augmented with %d CLI install dir(s): %s", len(added), added)
return added
@@ -237,9 +340,8 @@ def refresh_from_persistent_path(
continue
seen.add(key)
added.append(entry)
+ added = _store_path(current, added)
if added:
- joined = os.pathsep.join(added)
- os.environ["PATH"] = f"{current}{os.pathsep}{joined}" if current else joined
log.info("PATH refreshed with %d folder(s) from the persistent PATH", len(added))
return added
@@ -264,6 +366,7 @@ def resolve_node_executable() -> str | None:
__all__ = [
"candidate_dirs",
"ensure_cli_paths",
+ "fit_path_entries",
"refresh_from_persistent_path",
"resolve_node_executable",
]
diff --git a/tests/unit/core/test_path_augment.py b/tests/unit/core/test_path_augment.py
index f7067d4445..8eb9d43126 100644
--- a/tests/unit/core/test_path_augment.py
+++ b/tests/unit/core/test_path_augment.py
@@ -150,3 +150,195 @@ def test_posix_candidates_cover_the_mac_report(monkeypatch):
dirs = path_augment.candidate_dirs()
assert any(d.endswith(os.path.join(".claude", "local")) for d in dirs)
assert any(d.endswith(os.path.join(".npm-global", "bin")) for d in dirs)
+
+
+# ---- PATH budget (BUG-233, GitHub issue #574) ------------------------------
+#
+# Windows cannot start ANY program from a process whose PATH no longer fits its
+# search-path string: every spawn fails with WinError 8, "not enough memory".
+# The app appends folders to its own PATH, so it must never be the one that
+# crosses the line, and it must recover when it is started past it.
+
+
+def path_budget(tmp_path, monkeypatch):
+ """A PATH budget of about three test folders, on every OS."""
+ budget = 3 * (len(str(tmp_path)) + 8)
+ monkeypatch.setattr(path_augment, "_path_budget", lambda: budget)
+ monkeypatch.setattr(path_augment, "_settled_overflow", None)
+ return budget
+
+
+def _real_dirs(tmp_path, count: int) -> list[str]:
+ dirs = []
+ for index in range(count):
+ folder = tmp_path / f"d{index}"
+ folder.mkdir()
+ dirs.append(str(folder))
+ return dirs
+
+
+def _dirs_filling(tmp_path, budget: int) -> list[str]:
+ """Real folders whose joined PATH is as long as ``budget`` allows."""
+ dirs: list[str] = []
+ for folder in _real_dirs(tmp_path, 40):
+ if len(os.pathsep.join([*dirs, folder])) > budget:
+ break
+ dirs.append(folder)
+ return dirs
+
+
+def test_only_windows_has_a_path_budget(monkeypatch):
+ monkeypatch.setattr(path_augment.sys, "platform", "win32")
+ assert path_augment._path_budget() == path_augment._WINDOWS_PATH_BUDGET
+ # Room for the application directory and the system directories Windows
+ # puts in front of PATH when it builds the 32,767-character search path.
+ assert path_augment._WINDOWS_PATH_BUDGET <= 32_767 - 1_000
+ for platform in ("linux", "darwin"):
+ monkeypatch.setattr(path_augment.sys, "platform", platform)
+ assert path_augment._path_budget() is None
+
+
+def test_fitting_entries_come_back_untouched():
+ entries = ["a", "", "a", "missing-folder"]
+ assert path_augment.fit_path_entries(entries, 100) is entries
+
+
+def test_repeats_and_blanks_go_before_anything_else(tmp_path):
+ first, second = _real_dirs(tmp_path, 2)
+ ghost = str(tmp_path / "ghost")
+ entries = [first, "", second, first, ghost, second]
+ budget = len(os.pathsep.join([first, second, ghost]))
+
+ assert path_augment.fit_path_entries(entries, budget) == [first, second, ghost]
+
+
+def test_missing_folders_go_before_real_ones(tmp_path):
+ first, second = _real_dirs(tmp_path, 2)
+ ghost = str(tmp_path / "ghost")
+ budget = len(os.pathsep.join([first, second]))
+
+ assert path_augment.fit_path_entries([first, ghost, second], budget) == [first, second]
+
+
+def test_real_folders_are_given_up_from_the_end(tmp_path):
+ dirs = _real_dirs(tmp_path, 4)
+ budget = len(os.pathsep.join(dirs[:2]))
+
+ assert path_augment.fit_path_entries(dirs, budget) == dirs[:2]
+
+
+def test_an_oversized_path_is_repaired_and_still_gains_the_cli_dir(
+ tmp_path, monkeypatch, path_budget
+):
+ cli_dir = tmp_path / "cli"
+ cli_dir.mkdir()
+ monkeypatch.setattr(path_augment, "candidate_dirs", lambda: [str(cli_dir)])
+ (real,) = _real_dirs(tmp_path, 1)
+ bloated = os.pathsep.join([real] * 40)
+ assert len(bloated) > path_budget
+ monkeypatch.setenv("PATH", bloated)
+
+ assert path_augment.ensure_cli_paths() == [str(cli_dir)]
+ assert os.environ["PATH"].split(os.pathsep) == [real, str(cli_dir)]
+
+
+def test_an_oversized_path_is_repaired_with_nothing_to_add(
+ tmp_path, monkeypatch, path_budget
+):
+ monkeypatch.setattr(path_augment, "candidate_dirs", lambda: [])
+ (real,) = _real_dirs(tmp_path, 1)
+ monkeypatch.setenv("PATH", os.pathsep.join([real] * 40))
+
+ assert path_augment.ensure_cli_paths() == []
+ assert os.environ["PATH"] == real
+
+
+def test_a_cli_dir_that_does_not_fit_is_left_out(tmp_path, monkeypatch, path_budget):
+ cli_dir = tmp_path / "cli"
+ cli_dir.mkdir()
+ monkeypatch.setattr(path_augment, "candidate_dirs", lambda: [str(cli_dir)])
+ full = os.pathsep.join(_dirs_filling(tmp_path, path_budget))
+ assert len(full) + len(os.pathsep) + len(str(cli_dir)) > path_budget
+ monkeypatch.setenv("PATH", full)
+
+ assert path_augment.ensure_cli_paths() == []
+ assert os.environ["PATH"] == full
+
+
+def test_a_settled_overflow_is_not_probed_again(tmp_path, monkeypatch, path_budget):
+ """Status probes ask constantly; the same dead end must cost nothing twice."""
+ full = os.pathsep.join(_dirs_filling(tmp_path, path_budget))
+ extra = str(tmp_path / "d39")
+ monkeypatch.setenv("PATH", full)
+
+ assert path_augment._store_path(full, [extra]) == []
+ fits: list[str] = []
+ real_fit = path_augment.fit_path_entries
+ monkeypatch.setattr(
+ path_augment,
+ "fit_path_entries",
+ lambda entries, budget: fits.append("fit") or real_fit(entries, budget),
+ )
+ assert path_augment._store_path(full, [extra]) == []
+ assert fits == []
+ assert os.environ["PATH"] == full
+
+
+def test_the_persistent_path_refresh_respects_the_budget(
+ tmp_path, monkeypatch, path_budget
+):
+ (real,) = _real_dirs(tmp_path, 1)
+ monkeypatch.setenv("PATH", real)
+ registered = []
+ for index in range(30):
+ folder = tmp_path / f"r{index}"
+ folder.mkdir()
+ registered.append(str(folder))
+
+ added = path_augment.refresh_from_persistent_path(lambda: [";".join(registered)])
+
+ assert added == registered[: len(added)]
+ assert added != registered
+ assert len(os.environ["PATH"]) <= path_budget
+ assert os.environ["PATH"].split(os.pathsep) == [real, *added]
+
+
[email protected](sys.platform != "win32", reason="the Windows search-path limit")
+def test_a_process_past_the_windows_limit_can_spawn_again():
+ """The whole failure, for real: WinError 8 first, a working spawn after."""
+ import subprocess
+ import textwrap
+
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ script = textwrap.dedent(
+ """
+ import os, subprocess, sys
+ from jarvis.core import path_augment
+
+ base = os.environ["PATH"]
+ repeat = ";" + os.path.dirname(sys.executable)
+ os.environ["PATH"] = base + repeat * ((32_740 - len(base)) // len(repeat))
+ argv = [sys.executable, "-c", "print('spawned')"]
+ try:
+ subprocess.run(argv, capture_output=True)
+ print("before=ok")
+ except OSError as exc:
+ print(f"before={exc.winerror}")
+ path_augment.ensure_cli_paths()
+ after = subprocess.run(argv, capture_output=True, text=True)
+ print(f"after={after.stdout.strip()} length={len(os.environ['PATH'])}")
+ """
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=120,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ assert "before=8" in result.stdout, result.stdout + result.stderr
+ assert "after=spawned" in result.stdout, result.stdout + result.stderr
diff --git a/tests/unit/test_agent_cli_probe.py b/tests/unit/test_agent_cli_probe.py
index f67f685b83..ccaaf98823 100644
--- a/tests/unit/test_agent_cli_probe.py
+++ b/tests/unit/test_agent_cli_probe.py
@@ -106,6 +106,38 @@ def test_codex_honors_configured_binary_path(monkeypatch):
assert "npm i -g @openai/codex" in result.message
+def test_codex_spawn_refused_by_the_host_is_not_called_a_broken_install(monkeypatch):
+ """GitHub issue #574: Windows refused the spawn and the card blamed the CLI."""
+ refusal = "[WinError 8] Not enough memory resources are available"
+ monkeypatch.setattr(
+ codex_auth.CodexAuthService,
+ "status",
+ lambda self: CodexAuthStatus(installed=True, binary_path="/x/codex"),
+ )
+ monkeypatch.setattr(codex_auth, "clear_version_cache", lambda: None)
+ monkeypatch.setitem(codex_auth._VERSION_SPAWN_ERRORS, "/x/codex", refusal)
+
+ result = agent_cli_probe.test_codex()
+
+ assert result.ok is False
+ assert refusal in result.message
+ assert "broken" not in result.message
+
+
+def test_codex_version_probe_records_why_the_spawn_was_refused(monkeypatch):
+ def refuse(*_args, **_kwargs):
+ raise OSError(8, "Not enough memory resources")
+
+ monkeypatch.setattr(codex_auth, "_VERSION_CACHE", {})
+ monkeypatch.setattr(codex_auth, "_VERSION_SPAWN_ERRORS", {})
+ monkeypatch.setattr(codex_auth.subprocess, "run", refuse)
+
+ assert codex_auth.CodexAuthService()._probe_version("/x/codex") is None
+ assert "Not enough memory" in (codex_auth.version_spawn_error("/x/codex") or "")
+ codex_auth.clear_version_cache()
+ assert codex_auth.version_spawn_error("/x/codex") is None
+
+
def test_antigravity_names_the_resolved_cli_kind(monkeypatch):
from jarvis.google_cli import auth_service as gsvc