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
chore: auto-save WIP via Claude stop-hook safety net (2026-07-06 20:52)
Ruben Lütke3bc86a534af6
diff --git a/jarvis/claude_auth_state.py b/jarvis/claude_auth_state.pynew file mode 100644index 0000000000..d683e97f60--- /dev/null+++ b/jarvis/claude_auth_state.py@@ -0,0 +1,114 @@+"""Process-local Claude auth-dead flag (fingerprinted, self-expiring).++Why this exists (2026-07-06 incident, missions 019f36e5 + 019f38b1): the+Claude Max OAuth access token in ``~/.claude/.credentials.json`` expired and+nothing on the host refreshed it anymore, yet ``claude status`` reported+connected=True (presence-only check) and the worker factory kept routing every+heavy mission to the ``claude`` CLI. Each spawn died in ~15 s with+"Failed to authenticate. API Error: 401 Invalid authentication credentials"+while a healthy codex ChatGPT login and a healthy OpenRouter key were sitting+right there — the AP-22 single-provider brick.++This is the Claude mirror of ``codex_auth_state`` (the 2026-06-08 codex+incident), with two twists:++- TIME-based like ``claude_quota_state``: dead auth does not fix itself, but+ the user can fix it any moment (``claude /login`` refreshes the OAuth file,+ or a fresh API key is saved in-app). A bounded cooldown re-probes Claude+ instead of locking it out until the next app restart.+- FINGERPRINTED: the flag remembers a hash of the credential that produced the+ 401. A caller passing the fingerprint of the credential it WOULD use next+ gets ``False`` as soon as that credential differs — a fresh login/key+ re-enables Claude instantly, while the same dead credential stays flagged+ (no flip-flop inside a mission's retry loop).++Process-local + in-memory, like its two siblings: the live app is one process,+a module global suffices, and it resets on restart (then re-detected on the+next dead-auth mission). Monotonic clock so it is immune to wall-clock jumps;+``now_fn`` is injectable for deterministic tests.+"""+from __future__ import annotations++import hashlib+import threading+import time+from collections.abc import Callable++# 15 minutes: long enough that a mission's 3-iteration retry loop never+# re-probes the same dead credential, short enough that a fixed-out-of-band+# auth (e.g. a key rotated outside the app) costs at most one ~15 s re-probe+# per window.+_DEFAULT_COOLDOWN_S: float = 15 * 60.0++_lock = threading.Lock()+_dead_until: float = 0.0 # monotonic deadline; 0.0 == not armed+_dead_fingerprint: str | None = None+++def credential_fingerprint(credential: str | None) -> str | None:+ """Return a short, non-reversible fingerprint of a credential, or ``None``.++ Never the raw secret — safe to keep in memory next to log statements.+ """+ if not credential:+ return None+ return hashlib.sha256(credential.encode("utf-8")).hexdigest()[:16]+++def mark_claude_auth_dead(+ *,+ fingerprint: str | None = None,+ now_fn: Callable[[], float] = time.monotonic,+ cooldown_s: float = _DEFAULT_COOLDOWN_S,+) -> None:+ """Record that Claude auth is proven dead (a worker just got a 401).++ ``fingerprint`` identifies the credential that produced the failure+ (see :func:`credential_fingerprint`); ``None`` means "unknown credential"+ and flags Claude dead for the whole cooldown regardless of what a caller+ would use next.+ """+ global _dead_until, _dead_fingerprint+ with _lock:+ _dead_until = now_fn() + cooldown_s+ _dead_fingerprint = fingerprint+++def clear_claude_auth_dead() -> None:+ """Clear the flag immediately (a Claude worker just succeeded)."""+ global _dead_until, _dead_fingerprint+ with _lock:+ _dead_until = 0.0+ _dead_fingerprint = None+++def claude_auth_dead(+ *,+ current_fingerprint: str | None = None,+ now_fn: Callable[[], float] = time.monotonic,+) -> bool:+ """True while Claude auth is presumed dead for the credential at hand.++ ``current_fingerprint`` is the fingerprint of the credential the caller+ WOULD use next. When it differs from the one that produced the 401, the+ user has re-authenticated — return ``False`` so Claude re-enters rotation+ instantly. ``None`` (caller cannot tell) trusts the mark.+ """+ with _lock:+ if now_fn() >= _dead_until:+ return False+ if (+ current_fingerprint is not None+ and _dead_fingerprint is not None+ and current_fingerprint != _dead_fingerprint+ ):+ return False+ return True+++__all__ = [+ "claude_auth_dead",+ "clear_claude_auth_dead",+ "credential_fingerprint",+ "mark_claude_auth_dead",+]diff --git a/tests/missions/kontrollierer/test_loop.py b/tests/missions/kontrollierer/test_loop.pyindex e3fa639bc8..1867b18a67 100644--- a/tests/missions/kontrollierer/test_loop.py+++ b/tests/missions/kontrollierer/test_loop.py@@ -1000,6 +1000,97 @@ async def test_worker_timeout_every_iteration_fails_with_timeout_reason()+# --- 2026-07-06 sub-agent auth-failure resilience (expired OAuth token) ---+++@dataclass+class _FakeAuthErrorEvent:+ """The verbatim terminal event of the 2026-07-06 incident: the claude CLI+ ran on an expired OAuth token (injected without an expiresAt check) and+ died before any work."""++ result: str = (+ "Failed to authenticate. API Error: 401 Invalid authentication "+ "credentials"+ )+ type: str = "result"+ is_error: bool = True+ session_id: str | None = "auth-session"+++class _AuthErrorWorker:+ """Models a worker whose provider auth is dead — every spawn 401s."""++ cli = "claude"++ def __init__(self) -> None:+ self.last_pid = 444+ self.spawn_calls: list[dict[str, Any]] = []++ async def spawn(self, prompt, *, worktree, env, job, worker_id, log_dir, **kw): # type: ignore[no-untyped-def]+ self.spawn_calls.append(dict(kw))+ log_dir.mkdir(parents=True, exist_ok=True)+ (log_dir / "stream.jsonl").write_text("", encoding="utf-8")+ yield _FakeAuthErrorEvent()+++async def test_worker_auth_error_retries_with_fresh_factory_pick(+ manager: MissionManager, tmp_path: Path+) -> None:+ """An auth-failure (401) on iter0 must RETRY — the worker factory is+ consulted again and (with the provider flagged auth-dead) picks a+ DIFFERENT family, so the mission completes instead of failing terminally.+ Regression for 2026-07-06: missions 019f36e5 + 019f38b1 died task_error+ while a healthy codex login and OpenRouter key were available (AP-22)."""+ dead_worker = _AuthErrorWorker()+ healthy_worker = FakeWorker()+ factory_calls: list[int] = []++ def _factory(step): # type: ignore[no-untyped-def]+ factory_calls.append(1)+ return dead_worker if len(factory_calls) == 1 else healthy_worker++ critic = FakeCriticRunner(_make_approve_verdict())+ k = _make_kontrollierer(+ manager=manager, tmp_path=tmp_path, critic=critic,+ worker_factory_fn=_factory,+ )+ mid = await manager.dispatch(prompt="build X across a dead provider")++ end = await k.run_mission(mid)+ assert end == MissionState.APPROVED+ # iter0 401'd -> retried on a fresh factory pick; iter1 succeeded.+ assert len(factory_calls) == 2+ assert len(dead_worker.spawn_calls) == 1+ assert len(healthy_worker.spawn_calls) == 1+ # The critic only graded the iteration that actually produced output.+ assert len(critic.calls) == 1+++async def test_worker_auth_error_every_iteration_fails_honestly(+ manager: MissionManager, tmp_path: Path+) -> None:+ """If EVERY family 401s, the mission fails honestly after the retry cap —+ never an infinite loop, and the kill reason stays worker_error."""+ worker = _AuthErrorWorker()+ critic = FakeCriticRunner(_make_approve_verdict())+ k = _make_kontrollierer(+ manager=manager, tmp_path=tmp_path, critic=critic,+ worker_factory_fn=lambda step: worker,+ )+ mid = await manager.dispatch(prompt="task on an all-dead credential set")++ end = await k.run_mission(mid)+ assert end == MissionState.FAILED+ assert len(worker.spawn_calls) == 3 # retried up to MAX_CRITIC_LOOPS+ events = await manager.store.events_for_mission(mid)+ killed = [e.payload for e in events if e.payload.event_type == "WorkerKilled"]+ assert killed+ assert killed[-1].reason == "worker_error" # type: ignore[attr-defined]++@pytest.mark.asyncioasync def test_critic_timeout_retries_then_approves(manager: MissionManager, tmp_path: Path