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): API-key family walk gates on key VIABILITY, not existence (BUG-042 defect 3)

Ruben Lütkecf0712e2fc38
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 3ca986d4b5..5a3ead82da 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -3021,7 +3021,9 @@ OAuth login was dead (nothing refreshes `~/.claude` on this host). A healthy
OpenRouter key was configured the whole time — the Brain chatted over it
happily — but no mission ever reached it.
-**Root cause — two AP-22 violations in the worker chain.**
+**Root cause — three AP-22 violations in the worker chain** (the third only
+became visible once the first two were fixed and the live verify mission
+019f3d01 reached the API-key walk):
1. *No memory of the codex cap.* `claude_quota_state` existed for the Claude
direction, but a usage-capped codex was deliberately NOT flagged ("the
next mission retries codex automatically"), so
@@ -3033,6 +3035,15 @@ happily — but no mission ever reached it.
spawn was a guaranteed "Not logged in" terminal error; the orchestrator's
per-iteration factory re-consult never got a chance to cross families
because the factory's picks (codex first) never changed.
+3. *Key existence counted as key viability.* The API-key family walk
+ (`claude-api → gemini → openrouter → openai`) gated each family on
+ `get_provider_secret(prov)` truthiness. The stored anthropic credential
+ was a stale `sk-ant-oat` OAuth bearer — a shape the worker env builder
+ deliberately DROPS (guaranteed 401) and `_claude_cli_auth_viable` refuses
+ — yet its mere existence made the walk pick
+ `ApiAgentWorker('claude-api')`, which 401'd ("invalid x-api-key") on
+ every retry while the healthy openrouter key sat ONE slot further in the
+ SAME loop.
**Fix.** `jarvis/codex_quota_state.py` (new, mirror of
`claude_quota_state`): a time-based, self-expiring cooldown armed by a
@@ -3044,6 +3055,11 @@ factory, seeing the cooldown, crosses to the user's API-key family).
`init.py` (`_cross_family_last_resort_worker`, `reachable_worker_families`,
the proactive claude-cooldown→codex route) and `ClaudeDirectWorker`'s two
claude→codex fallbacks all skip codex while the cooldown is armed.
+`_api_key_family_viable` (init.py) replaces the bare
+`get_provider_secret(prov)` gate everywhere the factory walks API-key
+families: for `claude-api` an `sk-ant-oat` bearer never counts, and a
+classic key a worker fingerprint-flagged dead this session is skipped until
+it changes.
**Guards.** `tests/missions/workers/test_codex_quota_state.py`;
`tests/missions/workers/test_codex_auth_fallback.py` (cap arms cooldown +
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index ab547d1b41..c44e4100d7 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -492,6 +492,38 @@ def _claude_cli_auth_viable() -> bool:
return not claude_auth_dead(current_fingerprint=credential_fingerprint(key))
+def _api_key_family_viable(provider: str) -> bool:
+ """True when *provider* has a USABLE API key for the in-process worker.
+
+ Key EXISTENCE is not key viability (2026-07-07, mission 019f3d01 — the
+ verify run of the codex-cooldown fix): the stored anthropic credential was
+ a stale ``sk-ant-oat`` OAuth bearer — the copy of a login that no longer
+ exists. The worker env builder deliberately DROPS that shape (guaranteed
+ 401) and ``_claude_cli_auth_viable`` refuses it, but the cross-family walk
+ counted its mere existence as a claude-api key and dead-ended every retry
+ on ApiAgentWorker('claude-api') 401s while a healthy openrouter key sat
+ one slot further in the SAME loop (AP-22). Apply the one shared rule here
+ too: an ``sk-ant-oat`` bearer is not an API key, and a classic key a
+ worker already proved dead this session (fingerprinted) is skipped until
+ it changes.
+ """
+ from jarvis.core.config import get_provider_secret
+
+ key = get_provider_secret(provider)
+ if not key:
+ return False
+ if provider == "claude-api":
+ if key.startswith("sk-ant-oat"):
+ return False
+ from jarvis.claude_auth_state import (
+ claude_auth_dead,
+ credential_fingerprint,
+ )
+
+ return not claude_auth_dead(current_fingerprint=credential_fingerprint(key))
+ return True
+
+
def reachable_worker_families() -> list[str]:
"""Which worker families could run a heavy mission RIGHT NOW (cheap,
offline — file reads + process-local flags, never a network probe).
@@ -517,11 +549,10 @@ def reachable_worker_families() -> list[str]:
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
for prov in ("claude-api", "gemini", "openrouter", "openai"):
- if supports_api_agent_worker(prov) and get_provider_secret(prov):
+ if supports_api_agent_worker(prov) and _api_key_family_viable(prov):
families.append(prov)
return families
@@ -591,11 +622,11 @@ def _cross_family_last_resort_worker(task_text: str) -> Any | None:
)
# 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
+ # Viability-gated (not existence-gated): see _api_key_family_viable.
from jarvis.missions.workers.api_agent_worker import supports_api_agent_worker
for prov in ("claude-api", "gemini", "openrouter", "openai"):
- if supports_api_agent_worker(prov) and get_provider_secret(prov):
+ if supports_api_agent_worker(prov) and _api_key_family_viable(prov):
logger.warning(
"Mission worker -> ApiAgentWorker(%r): no Claude CLI / Codex login "
"reachable, crossing to the configured API-key family so the heavy "
@@ -952,11 +983,12 @@ async def bootstrap_missions(
# CLI binary — run the heavy worker IN-PROCESS via ApiAgentWorker on the
# API key instead of failing on the missing binary. The CLI stays
# preferred (subscription-first) whenever the binary IS present.
- from jarvis.core.config import get_provider_secret
from jarvis.missions.workers.claude_direct_worker import (
_resolve_claude_binary,
)
- if _resolve_claude_binary() is None and get_provider_secret("claude-api"):
+ if _resolve_claude_binary() is None and _api_key_family_viable(
+ "claude-api"
+ ):
logger.info(
"Mission worker -> ApiAgentWorker('claude-api'): no `claude` CLI "
"binary, running in-process on the Anthropic API key."
diff --git a/tests/missions/test_reachable_worker_families.py b/tests/missions/test_reachable_worker_families.py
index 477d6eb977..44f845b818 100644
--- a/tests/missions/test_reachable_worker_families.py
+++ b/tests/missions/test_reachable_worker_families.py
@@ -81,3 +81,23 @@ def test_usage_capped_codex_is_not_listed(monkeypatch: pytest.MonkeyPatch) -> No
fams = mi.reachable_worker_families()
assert "codex" not in fams
assert fams == ["openrouter"]
+
+
+def test_stale_oauth_bearer_claude_api_is_not_listed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A stored `sk-ant-oat` bearer is a stale OAuth copy, not an API key —
+ listing claude-api as reachable on its existence alone kept the section
+ green while every ApiAgentWorker('claude-api') spawn 401'd (2026-07-07,
+ mission 019f3d01)."""
+ _patch_env(monkeypatch)
+ monkeypatch.setattr(
+ "jarvis.core.config.get_provider_secret",
+ lambda p: {
+ "claude-api": "sk-ant-oat01-STALE-COPY",
+ "openrouter": "KEY",
+ }.get((p or "").strip().lower()),
+ )
+ fams = mi.reachable_worker_families()
+ assert "claude-api" not in fams
+ assert fams == ["openrouter"]
diff --git a/tests/missions/test_worker_cross_family_fallback.py b/tests/missions/test_worker_cross_family_fallback.py
index 1a90158056..1819d37b8a 100644
--- a/tests/missions/test_worker_cross_family_fallback.py
+++ b/tests/missions/test_worker_cross_family_fallback.py
@@ -131,6 +131,36 @@ def test_usage_capped_codex_crosses_to_api_key(
assert worker.provider == "openrouter"
+def test_stale_oauth_bearer_does_not_count_as_claude_api_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """2026-07-07, mission 019f3d01 (the verify run of the codex-cooldown fix):
+ the stored anthropic credential was a STALE `sk-ant-oat` OAuth bearer — the
+ env builder deliberately drops that shape (guaranteed 401) and
+ _claude_cli_auth_viable refuses it, but the family walk counted its mere
+ EXISTENCE as a claude-api key and dead-ended every retry on
+ ApiAgentWorker('claude-api') 401s while a healthy openrouter key sat one
+ slot further in the SAME loop. Key existence is not key viability."""
+ _patch_env(
+ monkeypatch,
+ claude_binary="/usr/bin/claude",
+ claude_auth_viable=False,
+ codex_oauth=True,
+ codex_quota_capped=True,
+ keys=("openrouter",),
+ )
+ monkeypatch.setattr(
+ "jarvis.core.config.get_provider_secret",
+ lambda p: {
+ "claude-api": "sk-ant-oat01-STALE-COPY",
+ "openrouter": "KEY",
+ }.get((p or "").strip().lower()),
+ )
+ worker = mi._cross_family_last_resort_worker("t")
+ assert isinstance(worker, ApiAgentWorker)
+ assert worker.provider == "openrouter"
+
+
# --- 2026-07-06: a PRESENT `claude` binary with DEAD auth must not dead-end ---