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(missions): contain critic subprocesses in job objects and support nvidia critics

Ruben Lütke594ff749f474
diff --git a/jarvis/missions/critic/runner.py b/jarvis/missions/critic/runner.py
index 5e25a491b5..834c5038a0 100644
--- a/jarvis/missions/critic/runner.py
+++ b/jarvis/missions/critic/runner.py
@@ -26,9 +26,10 @@ import logging
import re
import sys
import time
+from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Final
+from typing import Any, Final
from pydantic import ValidationError
@@ -495,9 +496,31 @@ class CriticRunner:
*,
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
log_triage: TriageFn | None = None,
+ job_factory: Callable[[], Any] | None = None,
) -> None:
self._timeout = timeout_seconds
self._log_triage = log_triage
+ # Per-mission process-containment job (Windows Job Object / POSIX
+ # process-group reaper, see jarvis.missions.isolation.job_object).
+ # None keeps the pre-fix behaviour exactly (graceful no-op) for
+ # callers/tests that construct CriticRunner without one — the
+ # bootstrap path (jarvis.missions.init.bootstrap_missions) passes the
+ # SAME factory the orchestrator's Kontrollierer uses for workers.
+ self._job_factory = job_factory
+
+ @staticmethod
+ def _assign_job(job: Any, pid: int, *, label: str) -> None:
+ """Best-effort: place `pid` in the containment job.
+
+ Mirrors ``ClaudeDirectWorker.spawn``'s ``job.assign(proc.pid)`` — a
+ failure here must never abort the critic run, only log (AP-10).
+ """
+ if job is None:
+ return
+ try:
+ job.assign(pid)
+ except Exception: # noqa: BLE001
+ logger.warning("%s: job.assign(pid=%d) failed", label, pid, exc_info=True)
async def run(
self,
@@ -1362,51 +1385,67 @@ class CriticRunner:
)
t0 = time.perf_counter()
+ # Per-mission process containment (AP-10): mirrors ClaudeDirectWorker,
+ # whose orchestrator wraps the whole spawn in ``async with job:``. A
+ # missing/None factory keeps the pre-fix behaviour exactly (graceful
+ # no-op) — see ``self._job_factory``.
+ job = self._job_factory() if self._job_factory is not None else None
+ if job is not None:
+ await job.__aenter__()
try:
- # create_worker_subprocess sources the Windows flags and degrades
- # CREATE_BREAKAWAY_FROM_JOB gracefully (WinError 5) — same fix as
- # the worker (live mission 019ec61b, 2026-06-14: the critic spawn
- # died on breakaway in the app's restrictive job).
- proc = await create_worker_subprocess(
- cmd,
- cwd=str(worktree),
- env=env,
- stdin=asyncio.subprocess.PIPE,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- )
- except FileNotFoundError as exc:
- logger.warning(
- "CriticRunner: claude binary not found: %s — cmd=%r",
- exc, cmd,
- )
- return None
+ try:
+ # create_worker_subprocess sources the Windows flags and degrades
+ # CREATE_BREAKAWAY_FROM_JOB gracefully (WinError 5) — same fix as
+ # the worker (live mission 019ec61b, 2026-06-14: the critic spawn
+ # died on breakaway in the app's restrictive job).
+ proc = await create_worker_subprocess(
+ cmd,
+ cwd=str(worktree),
+ env=env,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ except FileNotFoundError as exc:
+ logger.warning(
+ "CriticRunner: claude binary not found: %s — cmd=%r",
+ exc, cmd,
+ )
+ return None
- # Write the prompt to stdin then close to signal EOF.
- try:
- assert proc.stdin is not None # noqa: S101 - PIPE always present
- proc.stdin.write(prompt.encode("utf-8"))
- await proc.stdin.drain()
- proc.stdin.close()
- except (BrokenPipeError, ConnectionResetError) as exc:
- logger.warning(
- "CriticRunner: claude stdin write failed: %s", exc
- )
+ self._assign_job(job, proc.pid, label="CriticRunner (claude-direct)")
- try:
- stdout_b, stderr_b = await asyncio.wait_for(
- proc.communicate(), timeout=self._timeout
- )
- except TimeoutError as exc:
- with _suppress(ProcessLookupError):
- proc.kill()
- # Audit-2 H3 -- always wait() after kill() so the transport
- # is torn down and we don't leak a zombie + open pipes.
- with _suppress(Exception):
- await asyncio.wait_for(proc.wait(), timeout=5.0)
- raise CriticTimeout(
- f"Critic (claude-direct) exceeded {self._timeout}s — killed."
- ) from exc
+ # Write the prompt to stdin then close to signal EOF.
+ try:
+ assert proc.stdin is not None # noqa: S101 - PIPE always present
+ proc.stdin.write(prompt.encode("utf-8"))
+ await proc.stdin.drain()
+ proc.stdin.close()
+ except (BrokenPipeError, ConnectionResetError) as exc:
+ logger.warning(
+ "CriticRunner: claude stdin write failed: %s", exc
+ )
+
+ try:
+ stdout_b, stderr_b = await asyncio.wait_for(
+ proc.communicate(), timeout=self._timeout
+ )
+ except TimeoutError as exc:
+ with _suppress(ProcessLookupError):
+ proc.kill()
+ # Audit-2 H3 -- always wait() after kill() so the transport
+ # is torn down and we don't leak a zombie + open pipes. The
+ # job (when present) is closed in the outer finally below,
+ # reaping any grandchild the CLI spawned (e.g. MCP servers)
+ # that a bare proc.kill() would leave orphaned.
+ with _suppress(Exception):
+ await asyncio.wait_for(proc.wait(), timeout=5.0)
+ raise CriticTimeout(
+ f"Critic (claude-direct) exceeded {self._timeout}s — killed."
+ ) from exc
+ finally:
+ if job is not None:
+ await job.__aexit__(None, None, None)
wall_ms = int((time.perf_counter() - t0) * 1000)
if proc.returncode != 0:
@@ -1599,50 +1638,62 @@ class CriticRunner:
)
t0 = time.perf_counter()
+ # Per-mission process containment (AP-10): mirrors ClaudeDirectWorker /
+ # _invoke_via_claude_direct above. A missing/None factory keeps the
+ # pre-fix behaviour exactly (graceful no-op) — see self._job_factory.
+ job = self._job_factory() if self._job_factory is not None else None
+ if job is not None:
+ await job.__aenter__()
try:
- # create_worker_subprocess: breakaway-flag degradation (WinError 5).
- proc = await create_worker_subprocess(
- cmd,
- cwd=str(worktree),
- env=env_for_codex,
- stdin=asyncio.subprocess.PIPE,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- )
- except FileNotFoundError as exc:
- logger.warning(
- "CriticRunner: codex binary not found: %s -- cmd=%r",
- exc, cmd,
- )
- return None
+ try:
+ # create_worker_subprocess: breakaway-flag degradation (WinError 5).
+ proc = await create_worker_subprocess(
+ cmd,
+ cwd=str(worktree),
+ env=env_for_codex,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ except FileNotFoundError as exc:
+ logger.warning(
+ "CriticRunner: codex binary not found: %s -- cmd=%r",
+ exc, cmd,
+ )
+ return None
- try:
- assert proc.stdin is not None # noqa: S101 -- PIPE always present
- proc.stdin.write(prompt.encode("utf-8"))
- await proc.stdin.drain()
- proc.stdin.close()
- except (BrokenPipeError, ConnectionResetError) as exc:
- logger.warning(
- "CriticRunner: codex stdin write failed: %s", exc,
- )
+ self._assign_job(job, proc.pid, label="CriticRunner (codex-direct)")
- try:
- stdout_b, stderr_b = await asyncio.wait_for(
- proc.communicate(), timeout=self._timeout
- )
- except TimeoutError as exc:
- with _suppress(ProcessLookupError):
- proc.kill()
- with _suppress(Exception):
- await asyncio.wait_for(proc.wait(), timeout=5.0)
- with _suppress(OSError):
- __import__("os").unlink(schema_path)
- raise CriticTimeout(
- f"Critic (codex-direct) exceeded {self._timeout}s -- killed."
- ) from exc
+ try:
+ assert proc.stdin is not None # noqa: S101 -- PIPE always present
+ proc.stdin.write(prompt.encode("utf-8"))
+ await proc.stdin.drain()
+ proc.stdin.close()
+ except (BrokenPipeError, ConnectionResetError) as exc:
+ logger.warning(
+ "CriticRunner: codex stdin write failed: %s", exc,
+ )
+
+ try:
+ stdout_b, stderr_b = await asyncio.wait_for(
+ proc.communicate(), timeout=self._timeout
+ )
+ except TimeoutError as exc:
+ with _suppress(ProcessLookupError):
+ proc.kill()
+ with _suppress(Exception):
+ await asyncio.wait_for(proc.wait(), timeout=5.0)
+ with _suppress(OSError):
+ __import__("os").unlink(schema_path)
+ raise CriticTimeout(
+ f"Critic (codex-direct) exceeded {self._timeout}s -- killed."
+ ) from exc
+ finally:
+ with _suppress(OSError):
+ __import__("os").unlink(schema_path)
finally:
- with _suppress(OSError):
- __import__("os").unlink(schema_path)
+ if job is not None:
+ await job.__aexit__(None, None, None)
wall_ms = int((time.perf_counter() - t0) * 1000)
diff --git a/tests/missions/critic/test_runner_job_containment.py b/tests/missions/critic/test_runner_job_containment.py
new file mode 100644
index 0000000000..52986c6f68
--- /dev/null
+++ b/tests/missions/critic/test_runner_job_containment.py
@@ -0,0 +1,247 @@
+"""AP-10: critic subprocesses (claude-direct / codex-direct) must be placed
+in the per-mission containment job, exactly like the heavy worker.
+
+Evidence: both `_invoke_via_claude_direct` and `_invoke_via_codex_direct`
+called `create_worker_subprocess()` WITHOUT a `job` — the subprocess actively
+escapes any ambient job (`CREATE_BREAKAWAY_FROM_JOB`) and never gets one of
+its own, so a crash/cancel of the orchestrator does not reap it. The worker
+path (`ClaudeDirectWorker.spawn`) does this correctly via
+`job.assign(proc.pid)` inside an `async with job:` block the orchestrator
+opens. `CriticRunner` now accepts an optional `job_factory` (bootstrap wires
+in the SAME factory the orchestrator uses) and mirrors that pattern; a
+missing factory (the default) keeps the pre-fix graceful no-op behaviour.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.missions.critic.runner import CriticRunner
+from jarvis.missions.critic.verdict import REQUIRED_AXES
+
+
+def _valid_verdict_json(verdict: str = "approve") -> str:
+ return json.dumps({
+ "verdict": verdict,
+ "axes": {
+ ax: {"status": "pass", "evidence": ["src/x.py:1"]}
+ for ax in REQUIRED_AXES
+ },
+ "issues": [],
+ "correction_instruction": "",
+ "summary": "ok",
+ "summary_de": "ok", # i18n-allow (German value under summary_de field)
+ "confidence": 0.9,
+ "suggested_next_action": "accept",
+ })
+
+
+class _FakeStdin:
+ def __init__(self) -> None:
+ self.written: bytes = b""
+
+ def write(self, data: bytes) -> None:
+ self.written += data
+
+ async def drain(self) -> None:
+ return None
+
+ def close(self) -> None:
+ return None
+
+
+class _FakeProc:
+ def __init__(self, stdout: bytes, *, pid: int, returncode: int = 0) -> None:
+ self._stdout = stdout
+ self.returncode = returncode
+ self.stdin = _FakeStdin()
+ self.pid = pid
+
+ async def communicate(self) -> tuple[bytes, bytes]:
+ return self._stdout, b""
+
+ async def wait(self) -> int:
+ return self.returncode
+
+ def kill(self) -> None:
+ return None
+
+
+class _FakeJob:
+ """Records assign() calls + __aenter__/__aexit__ lifecycle."""
+
+ def __init__(self) -> None:
+ self.assigned_pids: list[int] = []
+ self.entered = False
+ self.exited = False
+
+ async def __aenter__(self) -> _FakeJob:
+ self.entered = True
+ return self
+
+ async def __aexit__(self, *exc_info: Any) -> None:
+ self.exited = True
+
+ def assign(self, pid: int) -> None:
+ self.assigned_pids.append(pid)
+
+
+async def test_claude_direct_assigns_spawned_pid_to_the_job(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(
+ "jarvis.missions.workers.claude_direct_worker._resolve_claude_argv_prefix",
+ lambda: ["claude"],
+ )
+
+ async def fake(*_a: Any, **_k: Any) -> _FakeProc:
+ return _FakeProc(_valid_verdict_json().encode("utf-8"), pid=9001)
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake)
+
+ fake_job = _FakeJob()
+ runner = CriticRunner(job_factory=lambda: fake_job)
+
+ verdict = await runner._invoke_via_claude_direct(
+ prompt="grade this", worktree=tmp_path, env={},
+ model="claude-sonnet-4-6", iteration=0, adversarial_reframe=False,
+ )
+
+ assert verdict is not None and verdict.verdict == "approve"
+ assert fake_job.assigned_pids == [9001]
+ assert fake_job.entered is True
+ assert fake_job.exited is True
+
+
+async def test_claude_direct_without_factory_stays_a_graceful_no_op(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
+) -> None:
+ """Backward compat: CriticRunner() with no job_factory (existing test
+ callers, e.g. tests/missions/critic/test_runner_claude_direct.py) must
+ keep working unchanged."""
+ monkeypatch.setattr(
+ "jarvis.missions.workers.claude_direct_worker._resolve_claude_argv_prefix",
+ lambda: ["claude"],
+ )
+
+ async def fake(*_a: Any, **_k: Any) -> _FakeProc:
+ return _FakeProc(_valid_verdict_json().encode("utf-8"), pid=9002)
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake)
+
+ verdict = await CriticRunner()._invoke_via_claude_direct(
+ prompt="grade this", worktree=tmp_path, env={},
+ model="claude-sonnet-4-6", iteration=0, adversarial_reframe=False,
+ )
+
+ assert verdict is not None and verdict.verdict == "approve"
+
+
+async def test_codex_direct_assigns_spawned_pid_to_the_job(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(
+ "jarvis.missions.workers.codex_direct_worker._resolve_codex_binary",
+ lambda: "codex",
+ )
+ ndjson = (
+ json.dumps({
+ "type": "item.completed",
+ "item": {"type": "agent_message", "text": _valid_verdict_json()},
+ })
+ + "\n"
+ + json.dumps({"type": "turn.completed"})
+ + "\n"
+ )
+
+ async def fake(*_a: Any, **_k: Any) -> _FakeProc:
+ return _FakeProc(ndjson.encode("utf-8"), pid=9101)
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake)
+
+ fake_job = _FakeJob()
+ runner = CriticRunner(job_factory=lambda: fake_job)
+
+ verdict = await runner._invoke_via_codex_direct(
+ prompt="grade this", worktree=tmp_path, env={},
+ model="", iteration=0, adversarial_reframe=False,
+ )
+
+ assert verdict is not None and verdict.verdict == "approve"
+ assert fake_job.assigned_pids == [9101]
+ assert fake_job.entered is True
+ assert fake_job.exited is True
+
+
+async def test_codex_direct_without_factory_stays_a_graceful_no_op(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
+) -> None:
+ monkeypatch.setattr(
+ "jarvis.missions.workers.codex_direct_worker._resolve_codex_binary",
+ lambda: "codex",
+ )
+ ndjson = (
+ json.dumps({
+ "type": "item.completed",
+ "item": {"type": "agent_message", "text": _valid_verdict_json()},
+ })
+ + "\n"
+ + json.dumps({"type": "turn.completed"})
+ + "\n"
+ )
+
+ async def fake(*_a: Any, **_k: Any) -> _FakeProc:
+ return _FakeProc(ndjson.encode("utf-8"), pid=9102)
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake)
+
+ verdict = await CriticRunner()._invoke_via_codex_direct(
+ prompt="grade this", worktree=tmp_path, env={},
+ model="", iteration=0, adversarial_reframe=False,
+ )
+
+ assert verdict is not None and verdict.verdict == "approve"
+
+
+async def test_claude_direct_timeout_still_closes_the_job(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
+) -> None:
+ """The job must be closed (reaping any grandchild) even on the timeout
+ path, which re-raises CriticTimeout."""
+ from jarvis.missions.critic.runner import CriticTimeout
+
+ monkeypatch.setattr(
+ "jarvis.missions.workers.claude_direct_worker._resolve_claude_argv_prefix",
+ lambda: ["claude"],
+ )
+
+ class _HangingProc(_FakeProc):
+ async def communicate(self) -> tuple[bytes, bytes]:
+ await asyncio.sleep(3600)
+ return b"", b"" # pragma: no cover
+
+ async def fake(*_a: Any, **_k: Any) -> _HangingProc:
+ return _HangingProc(b"", pid=9003)
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake)
+
+ fake_job = _FakeJob()
+ runner = CriticRunner(timeout_seconds=0.05, job_factory=lambda: fake_job)
+
+ with pytest.raises(CriticTimeout):
+ await runner._invoke_via_claude_direct(
+ prompt="grade this", worktree=tmp_path, env={},
+ model="claude-sonnet-4-6", iteration=0, adversarial_reframe=False,
+ )
+
+ assert fake_job.assigned_pids == [9003]
+ assert fake_job.exited is True
diff --git a/tests/unit/missions/test_api_critic_provider_model.py b/tests/unit/missions/test_api_critic_provider_model.py
index 8f64d32d73..9b87e710fc 100644
--- a/tests/unit/missions/test_api_critic_provider_model.py
+++ b/tests/unit/missions/test_api_critic_provider_model.py
@@ -49,3 +49,27 @@ def test_same_provider_critic_keeps_primary_model(
prov, model = runner._resolve_api_critic_provider("openrouter", _FREE)
assert prov == "openrouter"
assert model == _FREE
+
+
+def test_nvidia_only_funded_family_is_picked_by_critic(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """AP-22 twin: nvidia is a registered worker family (init.py:560,634) but
+ was previously missing from ``_API_CRITIC_PROVIDERS`` — when it is the
+ ONLY funded API family, the in-process critic must still be able to pick
+ it instead of falling through to the legacy claude-direct critic.
+ """
+ config = JarvisConfig()
+ config.brain.providers["nvidia"] = BrainProviderConfig(
+ model="nvidia/nemotron-nano-9b-v2:free"
+ )
+ monkeypatch.setattr("jarvis.core.config.load_config", lambda: config)
+ monkeypatch.setattr(
+ "jarvis.core.config.get_provider_secret",
+ lambda p: "nvapi-test" if p == "nvidia" else None,
+ )
+
+ prov, model = runner._resolve_api_critic_provider("antigravity", None)
+
+ assert prov == "nvidia"
+ assert model == "nvidia/nemotron-nano-9b-v2:free"