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.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-07 16:27)

Ruben Lütkedbbf950c651b
diff --git a/jarvis/codex_quota_state.py b/jarvis/codex_quota_state.py
new file mode 100644
index 0000000000..b1684aabec
--- /dev/null
+++ b/jarvis/codex_quota_state.py
@@ -0,0 +1,72 @@
+"""Process-local codex (ChatGPT) quota-cooldown flag (time-based, self-expiring).
+
+Why this exists: the codex ChatGPT plan can be usage-capped ("You've hit your
+usage limit … try again at Jul 31st") while ``codex status`` still reports
+connected=True — the login is fine, the plan just can't run right now. Without
+a memory of that cap, the worker factory re-picked codex on EVERY mission and
+retry iteration (2026-07-07 incident, mission_019f3cd8-1dd4): each spawn burned
+~28 s until the cap error returned, the in-worker fallback then died on a dead
+Claude login, and after three identical iterations the mission failed — while a
+healthy OpenRouter key sat unused (AP-22).
+
+This is the codex mirror of ``claude_quota_state``: when a codex worker proves
+the plan capped, it arms a cooldown; while armed the worker factory and the
+cross-family last resort skip codex and cross to the next reachable family.
+Unlike ``codex_needs_reauth`` — a boolean cleared only by a codex success after
+``codex login`` — a usage cap resets on the provider's clock, so this cooldown
+is TIME-based: it self-expires after ``_DEFAULT_COOLDOWN_S`` and codex is
+re-probed. A codex success clears it immediately.
+
+Process-local + in-memory, like ``codex_auth_state``: the live app is one
+process, a module global suffices, and it resets on restart (then re-detected on
+the next capped mission). Monotonic clock so it is immune to wall-clock jumps;
+``now_fn`` is injectable for deterministic tests.
+"""
+from __future__ import annotations
+
+import threading
+import time
+from collections.abc import Callable
+
+# Caps range from a rolling few-hour window to a hard until-next-billing-cycle
+# date, and the error copy is not reliably parseable — so mirror the Claude
+# cooldown's middle ground: at most one wasted codex re-probe per ~20 min of
+# continuous mission activity, and codex is back in rotation soon after an
+# early reset.
+_DEFAULT_COOLDOWN_S: float = 20 * 60.0
+
+_lock = threading.Lock()
+_cooldown_until: float = 0.0 # monotonic deadline; 0.0 == not armed
+
+
+def mark_codex_quota_cooldown(
+ *,
+ now_fn: Callable[[], float] = time.monotonic,
+ cooldown_s: float = _DEFAULT_COOLDOWN_S,
+) -> None:
+ """Arm the cooldown after a codex worker proved the ChatGPT plan capped."""
+ global _cooldown_until
+ with _lock:
+ _cooldown_until = now_fn() + cooldown_s
+
+
+def clear_codex_quota_cooldown() -> None:
+ """Clear the cooldown immediately (a codex worker just succeeded)."""
+ global _cooldown_until
+ with _lock:
+ _cooldown_until = 0.0
+
+
+def codex_in_quota_cooldown(
+ *, now_fn: Callable[[], float] = time.monotonic
+) -> bool:
+ """True while the codex plan is presumed capped (cooldown armed)."""
+ with _lock:
+ return now_fn() < _cooldown_until
+
+
+__all__ = [
+ "clear_codex_quota_cooldown",
+ "codex_in_quota_cooldown",
+ "mark_codex_quota_cooldown",
+]
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index 4b140258a3..ab547d1b41 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -508,9 +508,14 @@ def reachable_worker_families() -> list[str]:
if _resolve_claude_binary() is not None and _claude_cli_auth_viable():
families.append("claude")
from jarvis.codex_auth_state import codex_needs_reauth
+ from jarvis.codex_quota_state import codex_in_quota_cooldown
from jarvis.missions.workers.codex_direct_worker import _codex_oauth_available
- if _codex_oauth_available() and not codex_needs_reauth():
+ if (
+ _codex_oauth_available()
+ and not codex_needs_reauth()
+ and not codex_in_quota_cooldown()
+ ):
families.append("codex")
from jarvis.core.config import get_provider_secret
from jarvis.missions.workers.api_agent_worker import supports_api_agent_worker
@@ -567,11 +572,23 @@ def _cross_family_last_resort_worker(task_text: str) -> Any | None:
"view to restore Claude."
)
# 2. ChatGPT subscription via the codex CLI OAuth login (no API key).
+ # Quota-aware since 2026-07-07 (mission_019f3cd8-1dd4): a usage-capped
+ # plan keeps `codex status` connected=True, so login presence alone
+ # re-picked a codex that failed the cap check ~28 s into every mission
+ # while a healthy API key sat unused (AP-22). The cooldown self-expires,
+ # then codex is re-probed; a codex success clears it.
from jarvis.codex_auth_state import codex_needs_reauth
+ from jarvis.codex_quota_state import codex_in_quota_cooldown
from jarvis.missions.workers.codex_direct_worker import _codex_oauth_available
if _codex_oauth_available() and not codex_needs_reauth():
- return CodexDirectWorker()
+ if not codex_in_quota_cooldown():
+ return CodexDirectWorker()
+ logger.warning(
+ "Mission worker: the codex ChatGPT plan is in quota cooldown "
+ "(usage cap hit this session) — skipping codex and crossing "
+ "provider families until the cooldown expires."
+ )
# 3. In-process API worker on whatever single key the user has, crossing
# families — the same cross-family set the Brain fallback chain uses.
from jarvis.core.config import get_provider_secret
@@ -956,11 +973,16 @@ async def bootstrap_missions(
if claude_in_quota_cooldown():
from jarvis.codex_auth_state import codex_needs_reauth
+ from jarvis.codex_quota_state import codex_in_quota_cooldown
from jarvis.missions.workers.codex_direct_worker import (
_codex_oauth_available,
)
- if _codex_oauth_available() and not codex_needs_reauth():
+ if (
+ _codex_oauth_available()
+ and not codex_needs_reauth()
+ and not codex_in_quota_cooldown()
+ ):
logger.warning(
"Mission worker -> CodexDirectWorker: Claude Max is in "
"quota cooldown this session — routing to codex until the "
diff --git a/jarvis/missions/workers/claude_direct_worker.py b/jarvis/missions/workers/claude_direct_worker.py
index 7e67f818e0..b4e55e88c2 100644
--- a/jarvis/missions/workers/claude_direct_worker.py
+++ b/jarvis/missions/workers/claude_direct_worker.py
@@ -768,13 +768,18 @@ class ClaudeDirectWorker:
)
if allow_backend_fallback:
from jarvis.codex_auth_state import codex_needs_reauth
+ from jarvis.codex_quota_state import codex_in_quota_cooldown
from .codex_direct_worker import (
CodexDirectWorker,
_codex_oauth_available,
)
- if _codex_oauth_available() and not codex_needs_reauth():
+ if (
+ _codex_oauth_available()
+ and not codex_needs_reauth()
+ and not codex_in_quota_cooldown()
+ ):
logger.warning(
"ClaudeDirectWorker[%s]: claude auth is dead (%r) with "
"no work delivered — falling back to the codex "
@@ -823,6 +828,7 @@ class ClaudeDirectWorker:
and not any_tool_use
):
from jarvis.codex_auth_state import codex_needs_reauth
+ from jarvis.codex_quota_state import codex_in_quota_cooldown
from .codex_direct_worker import (
CodexDirectWorker,
@@ -843,6 +849,7 @@ class ClaudeDirectWorker:
_codex_error_is_usage_limited(final_result.result or "")
and _codex_oauth_available()
and not codex_needs_reauth()
+ and not codex_in_quota_cooldown()
):
logger.warning(
"ClaudeDirectWorker[%s]: Claude Max quota limit hit (%r) "
diff --git a/jarvis/missions/workers/codex_direct_worker.py b/jarvis/missions/workers/codex_direct_worker.py
index 156f172298..14430fb570 100644
--- a/jarvis/missions/workers/codex_direct_worker.py
+++ b/jarvis/missions/workers/codex_direct_worker.py
@@ -660,10 +660,13 @@ class CodexDirectWorker:
terminal_kind = "success"
# codex ran successfully -> its ChatGPT login is alive; clear any
# stale needs_reauth flag so the session uses codex natively again
- # (e.g. after the user ran `codex login`).
+ # (e.g. after the user ran `codex login`). Same for the quota
+ # cooldown: a success proves the cap reset.
from jarvis.codex_auth_state import clear_codex_needs_reauth
+ from jarvis.codex_quota_state import clear_codex_quota_cooldown
clear_codex_needs_reauth()
+ clear_codex_quota_cooldown()
usage = obj.get("usage", {}) or {}
if isinstance(usage, dict):
in_tok = usage.get("input_tokens") or 0
@@ -725,41 +728,76 @@ class CodexDirectWorker:
# honestly instead of bouncing codex->claude->codex forever.
if (_auth_dead or _usage_capped) and allow_backend_fallback:
if _auth_dead:
- logger.warning(
- "CodexDirectWorker[%s]: codex ChatGPT login expired (%r) — "
- "falling back to the Claude Max OAuth worker so the mission "
- "completes. Run `codex login` to use codex again.",
- worker_id, _err[:160],
- )
from jarvis.codex_auth_state import mark_codex_needs_reauth
mark_codex_needs_reauth()
else:
+ # Proactive complement to this reactive fallback (2026-07-07,
+ # mission_019f3cd8-1dd4): remember the cap so the worker
+ # factory skips codex until the cooldown self-expires, instead
+ # of burning ~28 s per mission re-proving it. A codex success
+ # clears it immediately.
+ from jarvis.codex_quota_state import mark_codex_quota_cooldown
+
+ mark_codex_quota_cooldown()
+ # Viability gate on the nested Claude spawn (2026-07-07 incident):
+ # the fallback used to be HARDCODED to ClaudeDirectWorker, so a
+ # usage-capped codex + a dead Claude login looped codex->claude->
+ # fail on every iteration while a healthy API key sat unused
+ # (AP-22). Only fall back when Claude can actually authenticate;
+ # otherwise surface the honest codex error below — the orchestrator
+ # classifies it transient/auth and retries, and the factory (seeing
+ # the flags armed above) crosses to the user's API-key family.
+ from .claude_direct_worker import (
+ ClaudeDirectWorker,
+ _resolve_claude_binary,
+ )
+
+ _claude_viable = _resolve_claude_binary() is not None
+ if _claude_viable:
+ try:
+ from jarvis.missions import init as _missions_init
+
+ _claude_viable = _missions_init._claude_cli_auth_viable()
+ except Exception: # noqa: BLE001 — unreadable probe => not viable
+ _claude_viable = False
+ if _claude_viable:
logger.warning(
- "CodexDirectWorker[%s]: codex usage/rate limit hit (%r) — "
- "falling back to the Claude Max OAuth worker so the mission "
- "completes. codex resumes automatically once the cap resets.",
- worker_id, _err[:160],
+ "CodexDirectWorker[%s]: codex %s (%r) — falling back to the "
+ "Claude Max OAuth worker so the mission completes. %s",
+ worker_id,
+ "ChatGPT login expired" if _auth_dead
+ else "usage/rate limit hit",
+ _err[:160],
+ "Run `codex login` to use codex again." if _auth_dead
+ else "codex resumes automatically once the cap resets.",
)
- from .claude_direct_worker import ClaudeDirectWorker
-
- async for ev in ClaudeDirectWorker().spawn(
- prompt,
- worktree=worktree,
- env=env,
- job=job,
- worker_id=worker_id,
- log_dir=log_dir,
- model="", # let ClaudeDirectWorker resolve a valid claude model
- allowed_tools=allowed_tools,
- permission_mode="bypassPermissions",
- max_turns=max_turns,
- timeout_s=timeout_s,
- mission_id=mission_id,
- allow_backend_fallback=False, # no codex->claude->codex loop
- ):
- yield ev
- return
+ async for ev in ClaudeDirectWorker().spawn(
+ prompt,
+ worktree=worktree,
+ env=env,
+ job=job,
+ worker_id=worker_id,
+ log_dir=log_dir,
+ model="", # let ClaudeDirectWorker resolve a valid claude model
+ allowed_tools=allowed_tools,
+ permission_mode="bypassPermissions",
+ max_turns=max_turns,
+ timeout_s=timeout_s,
+ mission_id=mission_id,
+ allow_backend_fallback=False, # no codex->claude->codex loop
+ ):
+ yield ev
+ return
+ logger.error(
+ "CodexDirectWorker[%s]: codex %s (%r) and the Claude fallback "
+ "is not auth-viable — surfacing the error honestly; the worker "
+ "factory will cross to another provider family on the retry.",
+ worker_id,
+ "ChatGPT login expired" if _auth_dead
+ else "usage/rate limit hit",
+ _err[:160],
+ )
final = ClaudeResult(
subtype="success"
diff --git a/jarvis/plugins/tool/call_contact.py b/jarvis/plugins/tool/call_contact.py
index 9ffbd7ada8..5345735d49 100644
--- a/jarvis/plugins/tool/call_contact.py
+++ b/jarvis/plugins/tool/call_contact.py
@@ -95,7 +95,14 @@ def _default_call_config() -> dict[str, str] | None:
from_number = getattr(tcfg, "phone_number", None)
public_base_url = getattr(tcfg, "public_base_url", None)
auth_token = cfg.get_secret("twilio_auth_token", env_fallback="TWILIO_AUTH_TOKEN")
- if not (account_sid and auth_token and from_number and public_base_url):
+ # Honor the explicit Enabled switch (wizard step 5 / Telephony UI), just
+ # like the working ``/api/telephony/outbound`` route, which refuses with
+ # 409 "Telephony is disabled" when ``twilio.enabled`` is false
+ # (telephony_routes.py). A filled-but-disabled config is a deliberate
+ # "off" — resolve to None so "call X" honestly no-ops instead of placing
+ # a real outbound call gated only by the generic ask-tier confirmation.
+ enabled = getattr(tcfg, "enabled", False)
+ if not (enabled and account_sid and auth_token and from_number and public_base_url):
return None
return {
"account_sid": str(account_sid),
diff --git a/jarvis/ui/web/feedback_routes.py b/jarvis/ui/web/feedback_routes.py
index a60d0453d7..49d2c17474 100644
--- a/jarvis/ui/web/feedback_routes.py
+++ b/jarvis/ui/web/feedback_routes.py
@@ -2,7 +2,8 @@
Endpoint:
- POST /api/feedback → {"ok": bool, "status": str, "detail": str}
+ POST /api/feedback → {"ok": bool, "status": str, "detail": str,
+ "github_url": str | None}
The endpoint validates the payload, enriches it with system context (app
version, OS, Python, UTC timestamp), and forwards it to a Discord webhook as
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index aa1843154f..167a25ae07 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -281,6 +281,14 @@
"running": "en marcha",
"completed": "llegado",
"failed": "fallo"
+ },
+ "health_degraded": "Proveedor de subagentes degradado",
+ "health_error": "Ningún proveedor de subagentes accesible",
+ "error_class": {
+ "provider_auth": "El inicio de sesión del proveedor no es válido o ha caducado; vuelve a conectarlo en la vista de claves API.",
+ "provider_quota": "Cuota del proveedor agotada; las misiones usan otro proveedor.",
+ "provider_unreachable": "Proveedor temporalmente inaccesible.",
+ "worker_timeout": "El worker alcanzó su límite de tiempo."
}
},
"tasks_view": {
diff --git a/pyproject.toml b/pyproject.toml
index 4b0625f2ff..0b39ac1845 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -490,6 +490,10 @@ ignore = ["S101", "S603", "S607"]
# bandit flags as hardcoded passwords. Both are false positives in a test
# context; the production modules stay under the strict ruleset.
"tests/unit/telephony/*.py" = ["S105", "S106", "S314"]
+# call-contact tests assert on fake Twilio auth-token fixture literals (e.g.
+# "tok_real_secret") that bandit flags as hardcoded passwords — a false
+# positive in a test context, same carve-out as the telephony tests above.
+"tests/unit/plugins/tool/test_call_contact.py" = ["S105", "S106"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
diff --git a/tests/missions/test_reachable_worker_families.py b/tests/missions/test_reachable_worker_families.py
index 62f806bc02..477d6eb977 100644
--- a/tests/missions/test_reachable_worker_families.py
+++ b/tests/missions/test_reachable_worker_families.py
@@ -15,6 +15,7 @@ def _patch_env(
claude_auth_viable: bool = True,
codex_oauth: bool = False,
codex_reauth: bool = False,
+ codex_quota_capped: bool = False,
keys: tuple[str, ...] = (),
) -> None:
monkeypatch.setattr(
@@ -29,6 +30,10 @@ def _patch_env(
monkeypatch.setattr(
"jarvis.codex_auth_state.codex_needs_reauth", lambda: codex_reauth
)
+ monkeypatch.setattr(
+ "jarvis.codex_quota_state.codex_in_quota_cooldown",
+ lambda **_k: codex_quota_capped,
+ )
keyset = {k.strip().lower() for k in keys}
monkeypatch.setattr(
"jarvis.core.config.get_provider_secret",
@@ -62,3 +67,17 @@ def test_dead_claude_is_not_listed(monkeypatch: pytest.MonkeyPatch) -> None:
fams = mi.reachable_worker_families()
assert "claude" not in fams
assert fams == ["codex"]
+
+
+def test_usage_capped_codex_is_not_listed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The 2026-07-07 shape: codex login connected but the ChatGPT plan is
+ usage-capped -> codex absent, the healthy API-key family remains, so the
+ Sub-Agents section health warns honestly instead of staying green."""
+ _patch_env(
+ monkeypatch,
+ codex_oauth=True, codex_quota_capped=True,
+ keys=("openrouter",),
+ )
+ fams = mi.reachable_worker_families()
+ assert "codex" not in fams
+ assert fams == ["openrouter"]
diff --git a/tests/unit/plugins/tool/test_call_contact.py b/tests/unit/plugins/tool/test_call_contact.py
index 3f4ee0b23f..b792864127 100644
--- a/tests/unit/plugins/tool/test_call_contact.py
+++ b/tests/unit/plugins/tool/test_call_contact.py
@@ -321,3 +321,24 @@ def test_default_call_config_returns_none_when_twilio_genuinely_unconfigured(mon
monkeypatch.setattr(real_cfg, "get_secret", lambda key, env_fallback=None: None)
assert call_contact_mod._default_call_config() is None
+
+
+def test_default_call_config_returns_none_when_twilio_disabled(monkeypatch) -> None:
+ """A fully-filled Twilio config that is explicitly DISABLED (``enabled`` is
+ False — the wizard's own step-5 default) must resolve to ``None`` so "call
+ X" honestly no-ops. The working ``/api/telephony/outbound`` route refuses a
+ disabled integration with 409; the resolver must not be more permissive and
+ let a real call go out on an "off" switch, gated only by the ask-tier
+ confirm."""
+ import jarvis.core.config as real_cfg
+
+ fake_config = _FakeJarvisConfig()
+ fake_config.integrations.twilio.enabled = False # everything else stays filled
+ monkeypatch.setattr(real_cfg, "load_config", lambda: fake_config)
+ monkeypatch.setattr(
+ real_cfg,
+ "get_secret",
+ lambda key, env_fallback=None: "tok_real_secret" if key == "twilio_auth_token" else None,
+ )
+
+ assert call_contact_mod._default_call_config() is None