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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(voice): stop a crashed login from stranding the subscription profile
rubenluetke10-beeped000f922ce0
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex bed85af2ad..387b6c6a1a 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -63,6 +63,57 @@ same shape as P-29 — the feature was reachable only on the maintainer's OS:action failed with "Codex CLI not found" — both sites now share`CodexAuthService._resolve_binary` and its `ensure_cli_paths()` repair.+**Fix pass 2026-08-03 (subscription voice, second round).** The 2026-08-03 pass+above fixed which terminals are offered; this one fixes what happens after one+is launched. Same shape again — a guarantee that held only on Windows.++- **Login containment now binds to the guardian, not to the launcher.** The+ previous pass gave the login a POSIX process-group reaper, but on macOS the+ spawned process is `osascript`, which asks the ALREADY-RUNNING Terminal.app to+ `do script` — so the guardian is a grandchild of Terminal, in no process group+ Jarvis owns. GNOME is the same story through `gnome-terminal-server`. The+ reaper was signalling a group that contained only the launcher, and a Jarvis+ crash still left the guardian holding the profile lock with every later+ Connect reporting a permanent "busy". A process tree cannot cross those+ boundaries and neither can an inherited pipe, so the lifeline is now a+ **parent-liveness lock file**: Jarvis holds it for the whole login, the kernel+ drops it on any kind of death, and the guardian polls it and ends the login if+ it can take it (`jarvis/codex_auth.py::_hold_parent_liveness_lock`,+ `jarvis/codex_login_guard.py::_parent_liveness_lost`, exit code+ `EXIT_PARENT_GONE`). The probe is deliberately conservative — anything it+ cannot read counts as "Jarvis is alive", because ending a healthy login is+ worse than one stale lock.+- **`wezterm` released the profile lock mid-write.** Plain `wezterm start` hands+ the window to a running `wezterm-gui` and returns at once, so `cleanup_login`+ ran its post-check and released the lock while `codex` was still writing+ `auth.json` — exactly the hazard the terminal table's own docstring describes.+ Now `--always-new-process`. Every entry additionally carries the REASON its+ flags keep it in the foreground, pinned per entry by a test.+- **Terminal matching is exact, not prefix.** `startswith` accepted Debian's+ `gnome-terminal.wrapper` for the `gnome-terminal` entry (and handed it flags+ that wrapper rejects) and accepted anything merely beginning with `st`. Both+ launched something that could not host the login, and the failure then+ surfaced as a guardian handshake error. Matching is now exact with a tiny+ justified alias map, and a login whose guardian never wrote its first+ acknowledgement names the TERMINAL as the cause instead of the guardian.+- **The POSIX lifeline no longer swallows a forwarded descriptor.**+ `child_lifeline.py` re-spawns the real child with `close_fds=True`, so the+ profile-lock descriptor the caller passes in was dropped at exec and the lock+ was held by the supervisor rather than by the app-server child it was meant+ for. The supervisor now accepts `--keep-fd N` and forwards it. Harmless today+ because the two processes die together — but the caller's guarantee was simply+ not true, and the first change that lets the supervisor exit first would have+ turned it into two processes writing one profile.+- **Checked, not a defect: the macOS Apple-Silicon PyAV pin.** Base pins+ `av==15.1.0` for that cell with no `python_version` guard while `[local-voice]`+ and `[tts-eval]` carried `python_version < '3.14'` and a comment claiming+ wheels only up to 3.13 — which reads as a broken install on macOS arm64 ++ CPython 3.14. It is not one: the PyPI file list for `av 15.1.0` carries+ `cp311/cp312/cp313/cp314` `macosx_13_0_arm64` wheels. The base pin was right+ and the comment was wrong; the comment is corrected and the redundant guard+ removed. The pin itself stays — `av 16+` raises the Apple-Silicon floor to+ macOS 14, and 15.1 is what keeps the supported macOS 13 floor.+**Fix pass 2026-08-03 (keyboard + pointer, from live Mac reports).** Threedefects of one shape — a surface OFFERS something on every OS and only one OScan actually deliver it, with nothing raising in between:@@ -130,6 +181,7 @@ experiences today.| # | Impact | Area | Gap | Evidence | Behavior off-Windows ||---|---|---|---|---|---|+| P-30 | Medium | Subscription voice | ChatGPT-Live carries its audio ONLY on a WebRTC media track, so the transport needs `aiortc` + PyAV in-process. Upstream publishes no compiler-free Windows ARM64 dependency chain, so base excludes `aiortc` on that one cell — and the same absence occurs anywhere the wheel chain cannot install. `webrtc_available()` exists but is called ONLY inside the endpoint constructor, so no surface asks it before advertising the provider | `pyproject.toml` (the `aiortc` marker), `jarvis/realtime/webrtc_transport.py::webrtc_available`, `jarvis/plugins/realtime/codex_subscription.py::external_login_ready`, `can_open_duplex_session`, `jarvis/ui/web/provider_routes.py::_codex_subscription_status_payload` | **Today, dishonest:** with a valid Codex login the card reports `ready`, `PUT /voice-mode` accepts `realtime`, and the call then fails at connect time with "needs the 'aiortc' package. Install Jarvis's requirements" — advice a Windows ARM64 user can never act on. Every other realtime provider and all standard voice stay available. **Wanted:** the media-stack probe joins the login probe, the card reports `lifecycle_unavailable` with a per-platform reason before the click, and the message stops prescribing an install that cannot work || P-29 | Low | Subscription voice | The dedicated ChatGPT-subscription voice login is an interactive browser flow, so a headless Linux host — and a graphical Linux desktop that ships no terminal emulator able to host the login for its full lifetime — can never CONNECT the profile there (an existing login still reports ready and calls work through the browser voice bridge) | `jarvis/codex_app_server.py::_login_required_state`, `_linux_login_terminal_missing`, `start_codex_subscription_login`, `jarvis/codex_auth.py::_LINUX_LOGIN_TERMINALS` | Both cases report the same `lifecycle_unavailable` truth on every surface (card, activation, voice-mode, Test), each with its own actionable reason — "run Jarvis on a desktop" or "install one of these terminals" — and never an enabled Connect button that can only produce an error toast || P-24 | Medium | Dictation shortcut | The global dictation/call shortcut needs `pynput` on Linux/X11, and `pynput` hard-requires `evdev` — which is published **source-only** (verified on PyPI 2026-07-28: evdev 1.9.3 ships an sdist and no wheels) and compiles against the kernel headers. Putting it in `[full]` would break the one advertised install path on a stock `python:3.11-slim`, so it is the opt-in `[desktop-linux]` extra instead. Wayland is a separate, unfixable-by-install case: the compositor owns global shortcuts by design (the XDG `GlobalShortcuts` portal lets the *compositor* assign the keys, and no wlroots compositor implements it at all) | `pyproject.toml` (`desktop-linux`), `jarvis/platform/probes.py::has_hotkey`, `jarvis/trigger/backends/noop.py::explain_unavailable` | X11 without the extra: no global shortcut, and the log/UI now names the actual cause and the exact `pip install` that fixes it (it used to blame Wayland unconditionally). Wayland: no global shortcut at all — bind a compositor shortcut to `jarvis api dictation start`. On both, dictation still works from the Jarvis Bar, the Dictation view and the CLI, and voice still works via the wake word || P-25 | Medium | Dictation insertion | Pasting the transcript into another application is blocked, silently, in three OS-specific situations: Windows UIPI when the foreground window is elevated and Jarvis is not (`SendInput` reports success and the input is discarded), macOS Secure Input while a password field is focused, and Wayland outright (no synthetic input). Detection exists for the first two; Wayland is refused up front | `jarvis/dictation/insert.py::describe_target`, `jarvis/platform/input_isolation.py::windows_foreground_window_is_elevated`, `macos_secure_input_enabled` | All three degrade to the SAME honest outcome instead of silence: the transcript is left on the clipboard, the result is reported as `clipboard_only`, and the bar plus the Dictation view say why and that Ctrl+V will paste it. macOS Secure Input detection is implemented but has not been verified on real hardware from this machine |diff --git a/jarvis/codex_auth.py b/jarvis/codex_auth.pyindex 743a5a12cc..f0636d80a5 100644--- a/jarvis/codex_auth.py+++ b/jarvis/codex_auth.py@@ -38,6 +38,7 @@ import tempfileimport threadingimport timefrom collections.abc import Callable+from contextlib import suppressfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -123,32 +124,143 @@ _DESKTOP_LAUNCHER_ENV_ALLOWLIST: frozenset[str] = frozenset(#: The login guardian owns the profile lock until the codex child exits, so a#: launcher that returns the moment it has handed the work to a terminal SERVER#: would release that lock while ``auth.json`` is still being written. Every-#: entry therefore uses that terminal's documented foreground / no-fork /-#: no-server form. Matching is on the RESOLVED binary name, so Debian's-#: ``x-terminal-emulator`` alternative resolves to a real entry here too.+#: entry therefore carries that terminal's documented foreground / no-fork /+#: no-server form PLUS the reason those exact flags are what achieves it. The+#: reason is not decoration: it is what a reviewer needs in order to judge a new+#: entry, and ``tests/unit/test_codex_auth.py`` pins one per entry so a future+#: addition cannot be waved through without it.#:#: The list used to hold three names. A desktop without GNOME, KDE or a literal#: ``xterm`` — XFCE, MATE, Cinnamon, or anyone on kitty/alacritty/foot/wezterm —#: could therefore not connect subscription voice AT ALL, while the card happily#: invited the click. ``jarvis/core/interactive_terminal.py`` already knew most#: of these; the two lists disagreeing was the whole defect.-_LINUX_LOGIN_TERMINALS: tuple[tuple[str, tuple[str, ...]], ...] = (- ("gnome-terminal", ("--wait", "--")),- ("konsole", ("--nofork", "-e")),- ("xfce4-terminal", ("--disable-server", "-x")),- ("mate-terminal", ("--disable-factory", "-x")),- ("tilix", ("--new-process", "-e")),- ("terminator", ("--no-dbus", "-x")),- ("kitty", ()),- ("alacritty", ("-e",)),- ("wezterm", ("start", "--")),- ("foot", ()),- ("urxvt", ("-e",)),- ("rxvt", ("-e",)),- ("xterm", ("-e",)),- ("st", ("-e",)),+_LINUX_LOGIN_TERMINALS: tuple[tuple[str, tuple[str, ...], str], ...] = (+ (+ "gnome-terminal",+ ("--wait", "--"),+ "--wait holds the client open until the spawned child exits; without it "+ "the client returns the moment gnome-terminal-server owns the window",+ ),+ ("konsole", ("--nofork", "-e"), "--nofork keeps konsole in the foreground"),+ (+ "xfce4-terminal",+ ("--disable-server", "-x"),+ "--disable-server stops the client handing off to a running instance",+ ),+ (+ "mate-terminal",+ ("--disable-factory", "-x"),+ "--disable-factory stops the client handing off to the factory process",+ ),+ (+ "tilix",+ ("--new-process", "-e"),+ "--new-process stops tilix delegating to its session server",+ ),+ (+ "terminator",+ ("--no-dbus", "-x"),+ "--no-dbus stops terminator delegating to a running instance over D-Bus",+ ),+ (+ "kitty",+ (),+ "kitty runs the command in a fresh foreground process; only the "+ "--single-instance flag would delegate, and it is never passed here",+ ),+ ("alacritty", ("-e",), "alacritty has no daemon mode by default"),+ (+ "wezterm",+ ("start", "--always-new-process", "--"),+ "--always-new-process is REQUIRED: plain `wezterm start` hands the "+ "window to a running wezterm-gui and returns immediately, which would "+ "release the profile lock while codex is still writing auth.json",+ ),+ (+ "foot",+ (),+ "the foot binary is the standalone server-less terminal; its client "+ "counterpart footclient is deliberately not an entry here",+ ),+ ("urxvt", ("-e",), "urxvt is the standalone binary; urxvtc talks to urxvtd"),+ ("rxvt", ("-e",), "rxvt has no daemon mode"),+ ("xterm", ("-e",), "xterm has no daemon mode"),+ ("st", ("-e",), "st has no daemon mode"),)+#: Real-world basenames that ARE one of the supported terminals under a+#: different file name. Deliberately tiny: every entry is a package that ships+#: the same binary, never a guess. Anything not listed here and not an exact+#: match is reported as unsupported rather than launched on a hunch.+_LINUX_LOGIN_TERMINAL_ALIASES: dict[str, str] = {+ "rxvt-unicode": "urxvt",+}+++def _linux_login_terminal_entry(resolved_name: str) -> tuple[str, tuple[str, ...]] | None:+ """Return ``(canonical_name, flags)`` for an EXACT resolved basename.++ Matching used to be ``startswith``, which is why this is now its own+ function with its own test. Two concrete failures came out of the prefix+ rule: Debian's ``x-terminal-emulator`` resolving to+ ``gnome-terminal.wrapper`` matched the ``gnome-terminal`` entry and was+ handed ``--wait --``, flags that wrapper does not accept; and the ``st``+ entry accepted ANY binary whose name merely began with ``st``. Both launched+ something that could not host the login, and the failure then surfaced as a+ guardian handshake error rather than as "this terminal is unsupported".+ """+ name = resolved_name.lower()+ if name.endswith(".exe"): # A Windows shim is never a Linux login terminal.+ name = name[: -len(".exe")]+ canonical = _LINUX_LOGIN_TERMINAL_ALIASES.get(name, name)+ for entry_name, flags, _reason in _LINUX_LOGIN_TERMINALS:+ if canonical == entry_name:+ return entry_name, flags+ return None+++def _hold_parent_liveness_lock(path: Path) -> int:+ """Create the login's parent-liveness file and hold it locked.++ Returns an open descriptor whose exclusive lock the guardian polls. Closing+ it — or dying — tells the guardian that Jarvis is gone and that it must end+ the login instead of holding the profile lock forever.++ Raises ``RuntimeError`` when the lock cannot be taken, because a login+ started without this safety net is exactly the failure it exists to prevent.+ """+ flags = os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)+ flags |= getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)+ try:+ descriptor = os.open(path, flags, 0o600)+ except OSError as exc:+ raise RuntimeError(+ "The subscription-login liveness file could not be created."+ ) from exc+ try:+ # One byte: msvcrt locks a byte RANGE, so an empty file cannot be locked+ # on Windows at all.+ os.write(descriptor, b"1")+ os.lseek(descriptor, 0, os.SEEK_SET)+ if sys.platform == "win32":+ import msvcrt # noqa: PLC0415 - Windows-only, off the import floor++ msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1)+ else:+ import fcntl # noqa: PLC0415 - POSIX-only, off the import floor++ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except (ImportError, OSError, ValueError) as exc:+ with suppress(OSError):+ os.close(descriptor)+ with suppress(OSError):+ path.unlink()+ raise RuntimeError(+ "The subscription-login liveness lock could not be acquired."+ ) from exc+ return descriptor+def _resolve_linux_login_terminal() -> tuple[str, tuple[str, ...]]:"""Pick a Linux terminal able to host the login until Codex exits.@@ -158,10 +270,12 @@ def _resolve_linux_login_terminal() -> tuple[str, tuple[str, ...]]:ships nothing usable — the caller turns that into the card's honest reasoninstead of an unexplained failure."""- supported = ", ".join(name for name, _flags in _LINUX_LOGIN_TERMINALS)+ supported = ", ".join(name for name, _flags, _reason in _LINUX_LOGIN_TERMINALS)candidates = [path- for path in (shutil.which(name) for name, _flags in _LINUX_LOGIN_TERMINALS)+ for path in (+ shutil.which(name) for name, _flags, _reason in _LINUX_LOGIN_TERMINALS+ )if path]generic = shutil.which("x-terminal-emulator")@@ -172,10 +286,9 @@ def _resolve_linux_login_terminal() -> tuple[str, tuple[str, ...]]:resolved = str(Path(candidate).resolve())except OSError: # A dangling alternative symlink is simply not usable.continue- name = Path(resolved).name.lower()- for prefix, flags in _LINUX_LOGIN_TERMINALS:- if name.startswith(prefix):- return resolved, flags+ entry = _linux_login_terminal_entry(Path(resolved).name)+ if entry is not None:+ return resolved, entry[1]if candidates:raise RuntimeError("The available desktop terminal cannot host a Codex login for its "@@ -349,12 +462,16 @@ class _GuardedCodexLoginProcess:acknowledgement: Path,release: Path,process_tree: Any | None = None,+ parent_liveness_fd: int | None = None,) -> None:self._process = processself._acknowledgement = acknowledgementself._release = releaseself._process_tree = process_treeself._process_tree_lock = threading.Lock()+ # Held open for exactly as long as this login may run. The guardian+ # reads it as "Jarvis is still here"; the kernel drops it if we die.+ self._parent_liveness_fd = parent_liveness_fdself.pid = process.pidif process_tree is not None:monitor = threading.Thread(@@ -372,8 +489,18 @@ class _GuardedCodexLoginProcess:with self._process_tree_lock:process_tree = self._process_treeself._process_tree = None+ descriptor = self._parent_liveness_fd+ self._parent_liveness_fd = Noneif process_tree is not None:process_tree.close()+ if descriptor is not None:+ # Reached only once this login is over for good, so the guardian's+ # watchdog has already stopped and cannot mistake this release for+ # a dead Jarvis.+ try:+ os.close(descriptor)+ except OSError: # Already closed by an earlier teardown path.+ passdef _monitor_guardian_exit(self) -> None:try:@@ -698,7 +825,7 @@ class CodexAuthService:def _guarded_login_command(self,binary: str,- ) -> tuple[list[str], Path, Path]:+ ) -> tuple[list[str], Path, Path, Path]:"""Build the fixed guardian argv for one dedicated profile login."""if (self._lifetime_lock_path is None@@ -738,7 +865,8 @@ class CodexAuthService:nonce = secrets.token_hex(16)acknowledgement = guard_directory / f"login-{nonce}.ack"release = guard_directory / f"login-{nonce}.release"- if acknowledgement.exists() or release.exists():+ liveness = guard_directory / f"login-{nonce}.alive"+ if acknowledgement.exists() or release.exists() or liveness.exists():raise RuntimeError("The subscription-login coordination state is not fresh.")environment = self._subprocess_environment()if environment is None:@@ -755,8 +883,9 @@ class CodexAuthService:self._trusted_binary_sha256,str(log_dir),json.dumps(environment, separators=(",", ":"), sort_keys=True),+ str(liveness),]- return command, acknowledgement, release+ return command, acknowledgement, release, livenessdef _read_auth(self) -> dict[str, Any] | None:"""Parse ``<codex-home>/auth.json``; ``None`` if absent/unreadable."""@@ -837,10 +966,35 @@ class CodexAuthService:)log.info("Starting 'codex login' (interactive)")command = self._command(binary, "login")+ # Names the process that HOSTS the guardian, so a login that never comes+ # up can be blamed on the right component instead of on the guardian.+ launch_host: str | None = Noneguard_paths: tuple[Path, Path] | None = None+ parent_liveness_fd: int | None = None+ liveness_path: Path | None = Noneif self._lifetime_lock_path is not None:- command, acknowledgement, release = self._guarded_login_command(binary)+ command, acknowledgement, release, liveness_path = (+ self._guarded_login_command(binary)+ )guard_paths = (acknowledgement, release)+ parent_liveness_fd = _hold_parent_liveness_lock(liveness_path)++ def drop_liveness() -> None:+ """Release the liveness lock on any path that never reaches a login.++ Every failure below must call this. A descriptor left open here+ would tell a guardian that a Jarvis login is in flight when none is,+ which is the inverse of the bug this lock exists to fix.+ """+ nonlocal parent_liveness_fd+ if parent_liveness_fd is not None:+ with suppress(OSError):+ os.close(parent_liveness_fd)+ parent_liveness_fd = None+ if liveness_path is not None:+ with suppress(OSError):+ liveness_path.unlink()+if sys.platform == "win32":# Fresh visible console so the device/OAuth URL is reachable under# pythonw.exe. Do NOT redirect stdio — the output belongs in that@@ -869,7 +1023,12 @@ class CodexAuthService:)command = ["/usr/bin/osascript", "-e", script]else:- resolved_terminal, terminal_flags = _resolve_linux_login_terminal()+ try:+ resolved_terminal, terminal_flags = _resolve_linux_login_terminal()+ except BaseException:+ drop_liveness()+ raise+ launch_host = Path(resolved_terminal).namecommand = [resolved_terminal, *terminal_flags, *terminal_command]kwargs = {"env": environment,@@ -903,6 +1062,7 @@ class CodexAuthService:if not bool(getattr(process_tree, "supports_containment", False)):process_tree.close()if sys.platform == "win32":+ drop_liveness()raise RuntimeError("Windows process-tree containment is unavailable for Codex login.")@@ -940,6 +1100,7 @@ class CodexAuthService:except BaseException:if process_tree is not None:process_tree.close()+ drop_liveness()raiseif process_tree is not None:@@ -951,10 +1112,12 @@ class CodexAuthService:process.terminate()except OSError:pass+ drop_liveness()raise RuntimeError("Process-tree containment could not be established for Codex login.") from excif guard_paths is None:+ drop_liveness()return processif self._login_guard_handoff is None:if process_tree is not None:@@ -964,6 +1127,7 @@ class CodexAuthService:process.terminate()except OSError:pass+ drop_liveness()raise RuntimeError("The subscription-login lock handoff is unavailable.")acknowledgement, release = guard_pathstry:@@ -973,12 +1137,17 @@ class CodexAuthService:release,self._login_guard_handoff,)- return _GuardedCodexLoginProcess(+ handle = _GuardedCodexLoginProcess(process,acknowledgement,release,process_tree,+ parent_liveness_fd,)+ # Ownership moved: the handle closes the descriptor when the login+ # is over for good, so this frame must not.+ parent_liveness_fd = None+ return handleexcept RuntimeError as exc:if process_tree is not None:process_tree.close()@@ -987,7 +1156,13 @@ class CodexAuthService:process.terminate()except OSError:pass- raise self._explain_login_launch_failure(exc, process) from exc+ drop_liveness()+ raise self._explain_login_launch_failure(+ exc,+ process,+ acknowledgement=acknowledgement,+ launch_host=launch_host,+ ) from excexcept BaseException:if process_tree is not None:process_tree.close()@@ -996,29 +1171,55 @@ class CodexAuthService:process.terminate()except OSError:pass+ drop_liveness()raisedef _explain_login_launch_failure(- self, exc: RuntimeError, process: subprocess.Popen[bytes]+ self,+ exc: RuntimeError,+ process: subprocess.Popen[bytes],+ *,+ acknowledgement: Path | None = None,+ launch_host: str | None = None,) -> RuntimeError:"""Name the real cause when a visible login never came up.- On macOS the login rides in Terminal.app via ``osascript``. A denied- Automation (TCC) grant makes osascript exit non-zero immediately, which- reaches the user as "the guardian exited before lock handoff" — true,- useless, and pointing at the wrong component. Every other host keeps- the original message.+ Three different components can swallow this launch, and all three used+ to surface as "the guardian exited before lock handoff" — true, useless,+ and pointing at the wrong one:++ * **macOS Automation (TCC) denied.** The login rides in Terminal.app via+ ``osascript``, and a denied grant makes osascript exit non-zero at+ once.+ * **The terminal could not host the login.** If the guardian never wrote+ even its first ``waiting`` acknowledgement, the guardian never ran —+ so the process that was supposed to host it is the suspect, not the+ guardian. Naming it turns an opaque handshake error into the one+ sentence that identifies the component to replace.+ * Anything else keeps the original message."""- if sys.platform != "darwin" or not self._visible_login:- return exc- if process.poll() in (None, 0):+ if not self._visible_login:return exc- return RuntimeError(- "The ChatGPT login window could not be opened. macOS is blocking "- "Jarvis from controlling Terminal: allow it under System Settings "- "> Privacy & Security > Automation, then connect again. "- f"({exc})"+ if sys.platform == "darwin" and process.poll() not in (None, 0):+ return RuntimeError(+ "The ChatGPT login window could not be opened. macOS is blocking "+ "Jarvis from controlling Terminal: allow it under System Settings "+ "> Privacy & Security > Automation, then connect again. "+ f"({exc})"+ )+ never_acknowledged = acknowledgement is not None and not (+ acknowledgement.exists() or acknowledgement.is_symlink())+ if never_acknowledged and launch_host:+ supported = ", ".join(+ name for name, _flags, _reason in _LINUX_LOGIN_TERMINALS+ )+ return RuntimeError(+ f"The terminal '{launch_host}' could not host the ChatGPT login: "+ "it never started Jarvis's login guardian. Install one of these "+ f"terminals and connect again: {supported}. ({exc})"+ )+ return excdef login_status(self) -> tuple[bool, str]:"""Return the CLI's PII-free login mode for this exact profile.diff --git a/jarvis/codex_login_guard.py b/jarvis/codex_login_guard.pyindex 093a7a83ee..c17bb51370 100644--- a/jarvis/codex_login_guard.py+++ b/jarvis/codex_login_guard.py@@ -1,10 +1,21 @@"""Isolated lifetime guardian for the subscription-voice Codex login.This script is an internal executable, not a user-facing CLI. Invoke it as a-trusted absolute path under ``python -I -S`` with exactly seven positional+trusted absolute path under ``python -I -S`` with exactly eight positionalarguments after the script path: lock path, acknowledgement path, release path,-Codex binary, expected binary SHA-256, log directory, and a strict JSON child-environment. It never reads profile credentials.+Codex binary, expected binary SHA-256, log directory, a strict JSON child+environment, and the parent-liveness lock path. It never reads profile+credentials.++The parent-liveness lock is what stops a dead Jarvis from stranding the profile+lock forever. Process-tree containment cannot do that job here: the guardian is+a grandchild of Terminal.app on macOS and of gnome-terminal-server on GNOME, so+it is not in the process group of anything Jarvis spawned, and it inherits no+descriptor from Jarvis either. A lock file crosses both boundaries, because the+kernel drops the parent's lock when the parent dies for ANY reason — crash,+force-quit, power loss. The guardian polls it, and if it can take that lock+nobody is left to finish the handshake, so it terminates the login and releases+the profile."""from __future__ import annotations@@ -19,6 +30,7 @@ import statimport subprocessimport sysimport tempfile+import threadingimport timefrom collections.abc import Sequencefrom pathlib import Path@@ -27,9 +39,17 @@ from types import ModuleTypeEXIT_INVALID = 2EXIT_UNSAFE = 74EXIT_BUSY = 75+EXIT_PARENT_GONE = 76EXIT_LAUNCH_FAILED = 127RELEASE_TIMEOUT_SECONDS = 30.0+#: How often the guardian checks whether Jarvis is still alive. Slow on+#: purpose: this only has to beat a human noticing "it says busy", and every+#: poll opens a file, so a tight loop would spend real battery for nothing.+PARENT_POLL_SECONDS = 2.0+#: Grace between SIGTERM and SIGKILL for the login child once Jarvis is gone.+PARENT_GONE_GRACE_SECONDS = 5.0+_MAX_ENVIRONMENT_BYTES = 32_768_ALLOWED_ENVIRONMENT_NAMES = frozenset({@@ -269,6 +289,87 @@ def _wait_for_control(return False+def _parent_liveness_lost(path: Path) -> bool:+ """True when the Jarvis process that started this login is gone.++ Jarvis holds an exclusive lock on this file for the whole login, so being+ able to TAKE that lock means exactly one thing: nobody is left who will ever+ publish the release control. The kernel drops the lock on any kind of death,+ which is why this works where an inherited pipe cannot.++ Conservative on every error: an unreadable, missing or unlockable file reads+ as "parent still alive". Killing a healthy login would be far worse than+ leaving one stale lock behind, and the user can always end a stale login by+ closing its terminal.+ """+ flags = os.O_RDWR | getattr(os, "O_BINARY", 0)+ flags |= getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)+ try:+ fd = os.open(path, flags)+ except OSError: # Missing or unreadable is not proof the parent died.+ return False+ try:+ if sys.platform == "win32":+ import msvcrt # noqa: PLC0415 - Windows-only, off the import floor++ try:+ os.lseek(fd, 0, os.SEEK_SET)+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)+ except OSError: # Still held: the parent is alive.+ return False+ try:+ os.lseek(fd, 0, os.SEEK_SET)+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)+ except OSError: # The close below releases it regardless; nothing changes.+ pass+ return True++ import fcntl # noqa: PLC0415 - POSIX-only, off the import floor++ try:+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except OSError: # Still held: the parent is alive.+ return False+ try:+ fcntl.flock(fd, fcntl.LOCK_UN)+ except OSError: # Closing the descriptor below drops the lock anyway.+ pass+ return True+ finally:+ os.close(fd)+++def _terminate_login_child(process: subprocess.Popen[bytes]) -> None:+ """End the login child, escalating once the grace period is spent."""+ try:+ process.terminate()+ except OSError: # Already gone is the outcome this wanted.+ return+ try:+ process.wait(timeout=PARENT_GONE_GRACE_SECONDS)+ return+ except subprocess.TimeoutExpired: # Expected: the grace is spent, escalate below.+ pass+ try:+ process.kill()+ except OSError: # Already gone between the grace and the kill.+ pass+++def _watch_parent_liveness(+ path: Path,+ process: subprocess.Popen[bytes],+ finished: threading.Event,+ parent_gone: threading.Event,+) -> None:+ """Poll the parent lock until the login ends or Jarvis disappears."""+ while not finished.wait(PARENT_POLL_SECONDS):+ if _parent_liveness_lost(path):+ parent_gone.set()+ _terminate_login_child(process)+ return++def _wait_for_child(process: subprocess.Popen[bytes]) -> int:def forward(signum: int, _frame: object) -> None:try:@@ -287,7 +388,7 @@ def _wait_for_child(process: subprocess.Popen[bytes]) -> int:def main(argv: Sequence[str] | None = None) -> int:arguments = tuple(sys.argv[1:] if argv is None else argv)- if len(arguments) != 7:+ if len(arguments) != 8:return EXIT_INVALID(lock_raw,@@ -297,6 +398,7 @@ def main(argv: Sequence[str] | None = None) -> int:binary_sha256,log_dir_raw,environment_raw,+ parent_liveness_raw,) = argumentstry:environment = _strict_environment(environment_raw)@@ -304,13 +406,19 @@ def main(argv: Sequence[str] | None = None) -> int:log_dir = _resolved_absolute_directory(log_dir_raw)acknowledgement = Path(acknowledgement_raw)release = Path(release_raw)+ parent_liveness = Path(parent_liveness_raw)if not acknowledgement.is_absolute() or not release.is_absolute():raise ValueError("coordination path is not absolute")+ if not parent_liveness.is_absolute():+ raise ValueError("parent liveness path is not absolute")if release.exists() or release.is_symlink():raise ValueError("release path is not fresh")_require_outside(log_dir, protected_directory)_require_outside(acknowledgement.parent.resolve(strict=True), protected_directory)_require_outside(release.parent.resolve(strict=True), protected_directory)+ _require_outside(+ parent_liveness.parent.resolve(strict=True), protected_directory+ )lock_module = _load_lock_module()except (ImportError, OSError, RuntimeError, ValueError, json.JSONDecodeError):# Invalid guardian input maps to the stable invalid exit.@@ -365,7 +473,29 @@ def main(argv: Sequence[str] | None = None) -> int:binary_fd = -1except (OSError, ValueError): # A verified launch failure maps to the fixed exit code.return EXIT_LAUNCH_FAILED- child_return_code = _wait_for_child(process)+ # From here on the profile lock is held and the login is live. If Jarvis+ # dies now, nothing else in the system can end this: the guardian is not+ # in any process group Jarvis owns (Terminal.app on macOS,+ # gnome-terminal-server on GNOME), so the watchdog is the only exit.+ finished = threading.Event()+ parent_gone = threading.Event()+ watchdog = threading.Thread(+ target=_watch_parent_liveness,+ args=(parent_liveness, process, finished, parent_gone),+ name="jarvis-login-parent-watchdog",+ daemon=True,+ )+ watchdog.start()+ try:+ child_return_code = _wait_for_child(process)+ finally:+ finished.set()+ if parent_gone.is_set():+ # The lock is released by the `finally` below. Publishing a+ # `finished` acknowledgement would be a lie: nobody is listening,+ # and the next Jarvis start must find this profile free, not+ # mid-handshake.+ return EXIT_PARENT_GONEtry:_atomic_acknowledgement(acknowledgement, "finished")except (OSError, ValueError):diff --git a/jarvis/core/child_lifeline.py b/jarvis/core/child_lifeline.pyindex 7adef14b3f..3ab7034ff7 100644--- a/jarvis/core/child_lifeline.py+++ b/jarvis/core/child_lifeline.py@@ -3,6 +3,15 @@The parent keeps the write end open. If it crashes, the kernel closes that end,this supervisor observes EOF, and the entire process group is killed. Normalshutdown reaches the child through stdin and lets it exit before the supervisor.++``--keep-fd`` forwards an inherited descriptor THROUGH this supervisor into the+real child. Without it the supervisor was the end of the line for every+descriptor above stdio: ``Popen`` closes them at exec, so a lock a caller+believed it had handed to the child was in fact held only here. The two+processes die together today, which is why that never surfaced as a bug — but+the guarantee the caller relies on ("the child holds this lock") was not true,+and the first change that lets this supervisor exit first would turn it into two+processes writing one profile with nothing left to stop them."""from __future__ import annotations@@ -32,8 +41,17 @@ def _watch_parent(lifeline_fd: int, completed: threading.Event) -> None:_kill_process_group()-def run(lifeline_fd: int, command: Sequence[str]) -> int:- """Run ``command`` and kill its process group if ``lifeline_fd`` reaches EOF."""+def run(+ lifeline_fd: int,+ command: Sequence[str],+ keep_fds: Sequence[int] = (),+) -> int:+ """Run ``command`` and kill its process group if ``lifeline_fd`` reaches EOF.++ ``keep_fds`` are descriptors this process inherited that must stay open in+ the real child as well (a held lock, for example). They are re-declared on+ the inner spawn because ``close_fds`` would otherwise drop them at exec.+ """if lifeline_fd < 0 or not command:return 2completed = threading.Event()@@ -45,7 +63,11 @@ def run(lifeline_fd: int, command: Sequence[str]) -> int:)watcher.start()try:- child = subprocess.Popen(list(command), close_fds=True) # noqa: S603+ child = subprocess.Popen( # noqa: S603+ list(command),+ close_fds=True,+ pass_fds=tuple(keep_fds),+ )return int(child.wait())except (OSError, ValueError): # Exit 127 is the supervisor-visible spawn failure signal.return 127@@ -57,16 +79,36 @@ def run(lifeline_fd: int, command: Sequence[str]) -> int:pass+def _parse_keep_fds(args: Sequence[str]) -> tuple[list[int], int]:+ """Read the leading ``--keep-fd N`` pairs; return them and the next index."""+ keep_fds: list[int] = []+ index = 1+ while index + 1 < len(args) and args[index] == "--keep-fd":+ keep_fds.append(int(args[index + 1]))+ index += 2+ return keep_fds, index++def main(argv: Sequence[str] | None = None) -> int:- """Parse the fixed internal ``FD -- command`` contract."""+ """Parse the internal ``FD [--keep-fd N ...] -- command`` contract.++ The ``--keep-fd`` pairs are optional, so an argv built before they existed+ still parses to exactly the old behaviour.+ """args = list(sys.argv[1:] if argv is None else argv)- if len(args) < 3 or args[1] != "--":+ if len(args) < 3:return 2try:lifeline_fd = int(args[0])+ keep_fds, separator = _parse_keep_fds(args)except ValueError: # Invalid internal argv is reported by the documented exit code.return 2- return run(lifeline_fd, args[2:])+ if separator >= len(args) or args[separator] != "--":+ return 2+ command = args[separator + 1 :]+ if not command or any(descriptor < 0 for descriptor in keep_fds):+ return 2+ return run(lifeline_fd, command, keep_fds)if __name__ == "__main__":diff --git a/pyproject.toml b/pyproject.tomlindex ad74bd50d7..17f157ab71 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -433,9 +433,15 @@ local-voice = [# energy VAD plus cloud/browser speech remain available on those cells."webrtcvad-wheels>=2.0; python_version < '3.14' and (sys_platform != 'win32' or platform_machine != 'ARM64')","faster-whisper>=1.0; (sys_platform != 'win32' or platform_machine != 'ARM64') and (sys_platform != 'darwin' or python_version < '3.14')",- # PyAV 16+ raised its Apple-Silicon deployment floor to macOS 14. Version- # 15.1 retains wheels for the supported macOS 13 floor and Python 3.11-3.13.- "av==15.1.0; sys_platform == 'darwin' and platform_machine == 'arm64' and python_version < '3.14'",+ # PyAV 16+ raised its Apple-Silicon deployment floor to macOS 14+ # (macosx_14_0_arm64 wheels). 15.1 is the last line that keeps the supported+ # macOS 13 floor, and it publishes that wheel for the whole CPython 3.11-3.14+ # matrix — verified against the PyPI file list for av 15.1.0, which carries+ # cp311/cp312/cp313/cp314 macosx_13_0_arm64. An earlier comment here claimed+ # 3.11-3.13 and is what made this pin look like a 3.14 install break; it is+ # not one. Base pins the identical requirement unconditionally for that cell,+ # so this line only restates it for an extras-only resolve.+ "av==15.1.0; sys_platform == 'darwin' and platform_machine == 'arm64'",# ONNX-Runtime speech stack (Apache-2.0, torch-free) powering the on-device# Nemotron recogniser and the Piper voices. The >=1.13.3 floor is# LOAD-BEARING, not hygiene: multilingual Nemotron needs the prompt_index@@ -454,7 +460,9 @@ local-voice = [# pulls ctranslate2, which the lockfile guard bans from base).tts-eval = ["faster-whisper>=1.0; (sys_platform != 'win32' or platform_machine != 'ARM64') and (sys_platform != 'darwin' or python_version < '3.14')",- "av==15.1.0; sys_platform == 'darwin' and platform_machine == 'arm64' and python_version < '3.14'",+ # Same Apple-Silicon macOS 13 floor as [local-voice]; see the note there for+ # why this carries no python_version guard.+ "av==15.1.0; sys_platform == 'darwin' and platform_machine == 'arm64'",][project.scripts]diff --git a/tests/unit/core/test_child_lifeline.py b/tests/unit/core/test_child_lifeline.pyindex 0a4c329961..3cddbd72ce 100644--- a/tests/unit/core/test_child_lifeline.py+++ b/tests/unit/core/test_child_lifeline.py@@ -30,3 +30,63 @@ def test_normal_child_completion_disarms_parent_eof(monkeypatch) -> None:def test_main_rejects_malformed_internal_contract() -> None:assert lifeline.main([]) == 2assert lifeline.main(["not-an-fd", "--", "codex"]) == 2+++def test_keep_fd_pairs_are_parsed_and_forwarded(monkeypatch) -> None:+ """A descriptor the caller hands in must survive into the REAL child.++ Without ``pass_fds`` on the inner spawn, ``close_fds`` drops everything+ above stdio at exec, so a lock the caller believed the child was holding+ was held only by this supervisor.+ """+ captured: dict[str, object] = {}++ class _Child:+ def wait(self) -> int:+ return 0++ def _fake_popen(command, **kwargs):+ captured["command"] = command+ captured["pass_fds"] = kwargs.get("pass_fds")+ captured["close_fds"] = kwargs.get("close_fds")+ return _Child()++ monkeypatch.setattr(lifeline.subprocess, "Popen", _fake_popen)+ monkeypatch.setattr(lifeline.os, "read", lambda _fd, _size: b"x")+ monkeypatch.setattr(lifeline.os, "close", lambda _fd: None)++ assert lifeline.main(["9", "--keep-fd", "11", "--keep-fd", "12", "--", "codex", "x"]) == 0++ assert captured["command"] == ["codex", "x"]+ assert captured["pass_fds"] == (11, 12)+ assert captured["close_fds"] is True+++def test_argv_without_keep_fd_keeps_the_original_behaviour(monkeypatch) -> None:+ """The pairs are optional, so an argv built before they existed still runs."""+ captured: dict[str, object] = {}++ class _Child:+ def wait(self) -> int:+ return 0++ def _fake_popen(command, **kwargs):+ captured["command"] = command+ captured["pass_fds"] = kwargs.get("pass_fds")+ return _Child()++ monkeypatch.setattr(lifeline.subprocess, "Popen", _fake_popen)+ monkeypatch.setattr(lifeline.os, "read", lambda _fd, _size: b"x")+ monkeypatch.setattr(lifeline.os, "close", lambda _fd: None)++ assert lifeline.main(["9", "--", "codex", "app-server"]) == 0++ assert captured["command"] == ["codex", "app-server"]+ assert captured["pass_fds"] == ()+++def test_malformed_keep_fd_arguments_are_refused() -> None:+ assert lifeline.main(["9", "--keep-fd", "not-a-number", "--", "codex"]) == 2+ assert lifeline.main(["9", "--keep-fd", "-3", "--", "codex"]) == 2+ assert lifeline.main(["9", "--keep-fd", "11", "codex"]) == 2+ assert lifeline.main(["9", "--keep-fd", "11", "--"]) == 2diff --git a/tests/unit/test_codex_auth.py b/tests/unit/test_codex_auth.pyindex 7580256bc0..ed5a22fd70 100644--- a/tests/unit/test_codex_auth.py+++ b/tests/unit/test_codex_auth.py@@ -413,6 +413,7 @@ def test_guarded_windows_login_closes_job_when_guardian_exits(["guardian.exe"],tmp_path / "login.ack",tmp_path / "login.release",+ tmp_path / "login.alive",),)@@ -779,7 +780,8 @@ def test_logout_returns_false_when_binary_missing(monkeypatch: pytest.MonkeyPatc("terminator", ["--no-dbus", "-x"]),("kitty", []),("alacritty", ["-e"]),- ("wezterm", ["start", "--"]),+ # --always-new-process is load-bearing: see OS-4 in docs/os-parity.md.+ ("wezterm", ["start", "--always-new-process", "--"]),("foot", []),("xterm", ["-e"]),],@@ -840,3 +842,114 @@ def test_graphical_linux_without_a_terminal_does_not_invite_a_login(assert code == "lifecycle_unavailable"assert "terminal emulator" in reason+++def test_every_login_terminal_records_why_its_flags_keep_it_in_the_foreground() -> None:+ """The reason column is the review gate for a new entry, not decoration.++ The guardian holds the profile lock until codex exits, so an entry whose+ launcher returns early releases that lock mid-write. That property cannot be+ checked automatically, so every entry has to carry the argument for it.+ """+ import jarvis.codex_auth as codex_mod++ assert codex_mod._LINUX_LOGIN_TERMINALS+ for name, _flags, reason in codex_mod._LINUX_LOGIN_TERMINALS:+ assert name and name == name.strip()+ assert len(reason) > 20, f"{name} has no usable justification"+++def test_wezterm_always_spawns_its_own_process() -> None:+ """Plain ``wezterm start`` delegates to a running wezterm-gui and returns.++ That would let ``cleanup_login`` run its post-check and release the profile+ lock while codex was still writing auth.json.+ """+ import jarvis.codex_auth as codex_mod++ flags = dict(+ (name, flags) for name, flags, _reason in codex_mod._LINUX_LOGIN_TERMINALS+ )["wezterm"]+ assert "--always-new-process" in flags+++ "rejected",+ [+ # Debian's x-terminal-emulator alternative. It does not accept the+ # gnome-terminal flags, so prefix matching launched something that could+ # never host the login.+ "gnome-terminal.wrapper",+ # The old `st` entry accepted anything merely STARTING with "st".+ "stterm",+ "start-terminal",+ # Client halves of a terminal SERVER: exactly the shape the table exists+ # to keep out.+ "urxvtc",+ "footclient",+ ],+)+def test_terminal_matching_is_exact_not_prefix(rejected: str) -> None:+ import jarvis.codex_auth as codex_mod++ assert codex_mod._linux_login_terminal_entry(rejected) is None+++def test_terminal_matching_resolves_known_package_aliases() -> None:+ import jarvis.codex_auth as codex_mod++ entry = codex_mod._linux_login_terminal_entry("rxvt-unicode")+ assert entry is not None+ assert entry[0] == "urxvt"+ assert codex_mod._linux_login_terminal_entry("URXVT") == ("urxvt", ("-e",))+++def test_a_terminal_that_never_started_the_guardian_is_named_as_the_cause(+ tmp_path: Path,+) -> None:+ """An unusable terminal used to surface as a guardian handshake error.++ The guardian writes its first acknowledgement before anything else, so a+ missing ack file proves the guardian never ran — which points at whatever+ was supposed to host it, not at the guardian.+ """++ class _Process:+ def poll(self) -> int | None:+ return None++ service = CodexAuthService("codex", visible_login=True)+ original = RuntimeError("The subscription-login guardian did not request lock handoff.")++ explained = service._explain_login_launch_failure(+ original,+ _Process(), # type: ignore[arg-type]+ acknowledgement=tmp_path / "never-written.ack",+ launch_host="somebody-elses-terminal",+ )++ assert "somebody-elses-terminal" in str(explained)+ assert "could not host" in str(explained)+++def test_a_guardian_that_did_acknowledge_keeps_the_original_diagnosis(+ tmp_path: Path,+) -> None:++ class _Process:+ def poll(self) -> int | None:+ return None++ acknowledgement = tmp_path / "written.ack"+ acknowledgement.write_text("waiting", encoding="ascii")+ service = CodexAuthService("codex", visible_login=True)+ original = RuntimeError("The subscription-login guardian did not confirm profile ownership.")++ explained = service._explain_login_launch_failure(+ original,+ _Process(), # type: ignore[arg-type]+ acknowledgement=acknowledgement,+ launch_host="kitty",+ )++ assert explained is originaldiff --git a/tests/unit/test_codex_login_guard.py b/tests/unit/test_codex_login_guard.pyindex 5b98f9898e..918d2ac028 100644--- a/tests/unit/test_codex_login_guard.py+++ b/tests/unit/test_codex_login_guard.py@@ -5,6 +5,7 @@ import jsonimport osimport subprocessimport sys+import threadingimport timefrom pathlib import Path@@ -35,6 +36,14 @@ def _environment(profile: Path) -> dict[str, str]:return environment+def _held_liveness(directory: Path, name: str = "parent.alive") -> tuple[Path, int]:+ """A parent-liveness file this test process holds, as Jarvis would."""+ from jarvis.codex_auth import _hold_parent_liveness_lock++ path = directory / name+ return path, _hold_parent_liveness_lock(path)++def _start_guardian(*,lock_path: Path,@@ -42,6 +51,7 @@ def _start_guardian(release: Path,profile: Path,log_dir: Path,+ parent_liveness: Path,) -> subprocess.Popen[bytes]:return subprocess.Popen([@@ -56,6 +66,7 @@ def _start_guardian(hashlib.sha256(Path(sys.executable).read_bytes()).hexdigest(),str(log_dir),json.dumps(_environment(profile), separators=(",", ":")),+ str(parent_liveness),],stdout=subprocess.PIPE,stderr=subprocess.PIPE,@@ -98,20 +109,25 @@ def test_guardian_runs_isolated_launches_fixed_child_and_acknowledges_ready(acknowledgement = coordination / "ack"release = coordination / "release"lock_path = coordination / "profile-process.lock"+ liveness, liveness_fd = _held_liveness(coordination)- process = _start_guardian(- lock_path=lock_path,- acknowledgement=acknowledgement,- release=release,- profile=profile,- log_dir=log_dir,- )- _wait_for_status(acknowledgement, "waiting")- _publish_control(release, "acquire")- _wait_for_status(acknowledgement, "finished")- assert process.poll() is None- _publish_control(release, "release")- stdout, stderr = process.communicate(timeout=10)+ try:+ process = _start_guardian(+ lock_path=lock_path,+ acknowledgement=acknowledgement,+ release=release,+ profile=profile,+ log_dir=log_dir,+ parent_liveness=liveness,+ )+ _wait_for_status(acknowledgement, "waiting")+ _publish_control(release, "acquire")+ _wait_for_status(acknowledgement, "finished")+ assert process.poll() is None+ _publish_control(release, "release")+ stdout, stderr = process.communicate(timeout=10)+ finally:+ os.close(liveness_fd)assert process.returncode == 0assert stdout == b""@@ -132,17 +148,23 @@ def test_guardian_reports_cross_process_contention_without_launching_child(release = coordination / "release"lock_path = coordination / "profile-process.lock"- with ExclusiveProcessLock.acquire(lock_path, protected_directory=profile):- process = _start_guardian(- lock_path=lock_path,- acknowledgement=acknowledgement,- release=release,- profile=profile,- log_dir=log_dir,- )- _wait_for_status(acknowledgement, "waiting")- _publish_control(release, "acquire")- stdout, stderr = process.communicate(timeout=10)+ liveness, liveness_fd = _held_liveness(coordination)++ try:+ with ExclusiveProcessLock.acquire(lock_path, protected_directory=profile):+ process = _start_guardian(+ lock_path=lock_path,+ acknowledgement=acknowledgement,+ release=release,+ profile=profile,+ log_dir=log_dir,+ parent_liveness=liveness,+ )+ _wait_for_status(acknowledgement, "waiting")+ _publish_control(release, "acquire")+ stdout, stderr = process.communicate(timeout=10)+ finally:+ os.close(liveness_fd)assert process.returncode == codex_login_guard.EXIT_BUSYassert stdout == b""@@ -173,6 +195,7 @@ def test_guardian_rejects_non_allowlisted_environment_without_acknowledging(hashlib.sha256(Path(sys.executable).read_bytes()).hexdigest(),str(log_dir),json.dumps(environment),+ str(coordination / "parent.alive"),))@@ -253,3 +276,141 @@ def test_guardian_normalizes_windows_environment_names_and_rejects_aliases(with pytest.raises(ValueError, match="duplicate environment"):codex_login_guard._strict_environment('{"CODEX_HOME":"safe","Path":"one","PATH":"two"}')+++def test_parent_liveness_probe_reads_a_held_lock_as_alive(tmp_path: Path) -> None:+ from jarvis.codex_auth import _hold_parent_liveness_lock++ path = tmp_path / "parent.alive"+ fd = _hold_parent_liveness_lock(path)+ try:+ assert codex_login_guard._parent_liveness_lost(path) is False+ finally:+ os.close(fd)++ # The kernel drops the lock with the holder, which is exactly what a crashed+ # Jarvis looks like from here.+ assert codex_login_guard._parent_liveness_lost(path) is True+++def test_parent_liveness_probe_is_conservative_about_the_unknown(+ tmp_path: Path,+) -> None:+ """Never kill a healthy login on a filesystem hiccup.++ A missing or unreadable file is not proof that Jarvis died, and ending a+ real login is far worse than leaving one stale lock the user can clear by+ closing the terminal.+ """+ assert codex_login_guard._parent_liveness_lost(tmp_path / "absent") is False+++def test_guardian_releases_the_profile_when_jarvis_dies_mid_login(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The macOS/GNOME failure: nothing else can end this login.++ The guardian is a grandchild of Terminal.app (macOS) or of+ gnome-terminal-server (GNOME), so it sits in no process group Jarvis owns+ and inherits no descriptor from it. Before the liveness lock, a Jarvis crash+ left guardian -> codex login running with the profile lock held, and every+ later Connect reported a permanent "busy".+ """+ profile = tmp_path / "profile"+ profile.mkdir()+ log_dir = tmp_path / "logs"+ log_dir.mkdir()+ coordination = _coordination_directory(tmp_path)+ acknowledgement = coordination / "ack"+ release = coordination / "release"+ lock_path = coordination / "profile-process.lock"+ # Present but unlocked == the parent that started this login is gone.+ liveness = coordination / "parent.alive"+ liveness.write_bytes(b"1")+ os.chmod(liveness, 0o600)++ started = threading.Event()++ class _BlockingChild:+ """A login that would sit there forever, exactly like `codex login`."""++ def __init__(self) -> None:+ self._done = threading.Event()+ self.terminated = False++ def terminate(self) -> None:+ self.terminated = True+ self._done.set()++ def kill(self) -> None:+ self._done.set()++ def send_signal(self, _signum: int) -> None:+ return None++ def wait(self, timeout: float | None = None) -> int:+ if not self._done.wait(timeout if timeout is not None else 30.0):+ raise subprocess.TimeoutExpired("codex", timeout or 0)+ return 0++ child = _BlockingChild()++ def _fake_popen(_command, **_kwargs):+ started.set()+ return child++ monkeypatch.setattr(codex_login_guard.subprocess, "Popen", _fake_popen)+ monkeypatch.setattr(codex_login_guard, "PARENT_POLL_SECONDS", 0.05)++ def _drive_handshake() -> None:+ # The guardian refuses a pre-existing release path, so the control can+ # only be published once it has asked for the hand-off.+ _wait_for_status(acknowledgement, "waiting")+ _publish_control(release, "acquire")++ driver = threading.Thread(target=_drive_handshake, daemon=True)+ driver.start()++ result = codex_login_guard.main(+ (+ str(lock_path),+ str(acknowledgement),+ str(release),+ str(Path(sys.executable).resolve()),+ hashlib.sha256(Path(sys.executable).read_bytes()).hexdigest(),+ str(log_dir),+ json.dumps(_environment(profile), separators=(",", ":")),+ str(liveness),+ )+ )++ assert started.is_set(), "the login child never started"+ assert child.terminated, "the login was left running with the profile locked"+ assert result == codex_login_guard.EXIT_PARENT_GONE+ # The profile is free for the next Jarvis start: no permanent "busy".+ with ExclusiveProcessLock.acquire(lock_path, protected_directory=profile):+ pass+++def test_guardian_refuses_an_argv_without_the_liveness_path(tmp_path: Path) -> None:+ """The seven-argument form is gone; accepting it would be a silent downgrade."""+ profile = tmp_path / "profile"+ profile.mkdir()+ log_dir = tmp_path / "logs"+ log_dir.mkdir()+ coordination = _coordination_directory(tmp_path)++ result = codex_login_guard.main(+ (+ str(coordination / "profile-process.lock"),+ str(coordination / "ack"),+ str(coordination / "release"),+ str(Path(sys.executable).resolve()),+ hashlib.sha256(Path(sys.executable).read_bytes()).hexdigest(),+ str(log_dir),+ json.dumps(_environment(profile), separators=(",", ":")),+ )+ )++ assert result == codex_login_guard.EXIT_INVALID