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
feat(missions): park missions in WAITING_CAPACITY instead of switching provider
Dennis Heide de Ramirez80f9a5a93718
diff --git a/jarvis/cli_ctl/commands/missions.py b/jarvis/cli_ctl/commands/missions.pyindex cb05aa0fad..3f5f8d78e8 100644--- a/jarvis/cli_ctl/commands/missions.py+++ b/jarvis/cli_ctl/commands/missions.py@@ -12,7 +12,10 @@ app = typer.Typer(no_args_is_help=True, help="Self-healing missions: list, dispadef list_missions(state: str = typer.Option(None, "--state",- help="Comma-separated states: PENDING,RUNNING,APPROVED,FAILED,CANCELLED,TIMED_OUT.",+ help=(+ "Comma-separated states: PENDING,RUNNING,WAITING_CAPACITY,"+ "APPROVED,FAILED,CANCELLED,TIMED_OUT."+ ),),limit: int = typer.Option(100, "--limit"),) -> None:diff --git a/jarvis/missions/capacity.py b/jarvis/missions/capacity.pynew file mode 100644index 0000000000..1d89a5ab84--- /dev/null+++ b/jarvis/missions/capacity.py@@ -0,0 +1,103 @@+"""Capacity policy for mission workers: wait, never switch to something that bills.++When a mission's worker has no capacity left — the subscription's usage window+is spent, its login expired, or it cannot run at all — the mission is parked in+``MissionState.WAITING_CAPACITY`` with a checkpoint of the work done so far. It+is NOT failed, and it is NOT moved to another subscription or to a per-token+API key: the user decided (2026-10-04) that paid API use happens only after an+explicit approval for that one mission, and that a subscription install never+silently changes vendor.++Who is "pinned":++- a mission whose configured worker is itself a subscription CLI (the ``claude``+ CLI, codex over the ChatGPT login, agy, grok build), or+- any install that has connected a subscription recently — the same sticky+ signal :mod:`jarvis.brain.background_policy` uses for background work.++An install that never connected a subscription keeps its cross-family fallback+chain, so a single-key download still works (AGENTS.md "any single key must+work", AP-22).+"""+from __future__ import annotations++import json+import logging+import os+import tempfile+from pathlib import Path+from typing import Any, Literal++log = logging.getLogger(__name__)++CapacityWaitReason = Literal["provider_quota", "provider_auth", "provider_unavailable"]++#: Written into ``<mission_dir>/`` when a mission is parked. Its presence also+#: keeps the mission directory out of the age-based cleanup sweep.+CHECKPOINT_NAME = "checkpoint.json"++#: Bumped when the checkpoint layout changes incompatibly.+CHECKPOINT_VERSION = 1+++class WorkerCapacityUnavailable(RuntimeError):+ """Raised by the worker factory instead of picking a worker that would bill+ another subscription or an API key."""++ def __init__(+ self,+ reason: CapacityWaitReason,+ provider: str,+ detail: str = "",+ ) -> None:+ super().__init__(f"{provider}: {reason}" + (f" ({detail})" if detail else ""))+ self.reason: CapacityWaitReason = reason+ self.provider = provider+ self.detail = detail+++def pinned_to_subscription(*, configured_is_subscription: bool) -> bool:+ """Whether this mission must stay on its configured worker.++ Fails closed: if the subscription signal cannot be read, the mission waits+ rather than risk billing a key nobody approved.+ """+ if configured_is_subscription:+ return True+ try:+ from jarvis.brain.background_policy import subscription_mode++ return subscription_mode()+ except Exception: # noqa: BLE001 - unreadable signal: waiting is the safe answer+ log.warning(+ "capacity: subscription signal unreadable — pinning the mission "+ "to its configured worker",+ exc_info=True,+ )+ return True+++def write_checkpoint(mission_dir: Path, data: dict[str, Any]) -> Path:+ """Atomically write the checkpoint and return its path."""+ mission_dir.mkdir(parents=True, exist_ok=True)+ path = mission_dir / CHECKPOINT_NAME+ payload = {"version": CHECKPOINT_VERSION, **data}+ fd, tmp = tempfile.mkstemp(dir=mission_dir, prefix=".checkpoint.", suffix=".json")+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ json.dump(payload, handle, ensure_ascii=False, indent=2)+ os.replace(tmp, path)+ except BaseException:+ Path(tmp).unlink(missing_ok=True)+ raise+ return path+++__all__ = [+ "CHECKPOINT_NAME",+ "CHECKPOINT_VERSION",+ "CapacityWaitReason",+ "WorkerCapacityUnavailable",+ "pinned_to_subscription",+ "write_checkpoint",+]diff --git a/jarvis/missions/cleanup.py b/jarvis/missions/cleanup.pyindex 69f9df7c6e..613e393f45 100644--- a/jarvis/missions/cleanup.py+++ b/jarvis/missions/cleanup.py@@ -28,6 +28,7 @@ from pathlib import Pathfrom typing import Finalfrom jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.missions.capacity import CHECKPOINT_NAMEfrom jarvis.missions.standalone_run import MARKER_NAMElogger = logging.getLogger(__name__)@@ -128,6 +129,8 @@ def _holds_deliverables(entry: Path) -> bool:"""if (entry / MARKER_NAME).is_file():return True+ if (entry / CHECKPOINT_NAME).is_file():+ return True # a mission parked for capacity resumes from heretasks_dir = entry / "tasks"try:task_dirs = [child for child in tasks_dir.iterdir() if child.is_dir()]diff --git a/jarvis/missions/events.py b/jarvis/missions/events.pyindex 7f765937e1..5f9442263f 100644--- a/jarvis/missions/events.py+++ b/jarvis/missions/events.py@@ -155,6 +155,34 @@ class MissionFailed(_PayloadBase):failed_provider: str | None = None+# Why a mission is parked in WAITING_CAPACITY. Closed vocabulary, mirrored in+# frontend/src/types/missions.ts (CapacityWaitReason) and the voice phrase+# table (CAPACITY_WAIT_PHRASES) — guarded by+# tests/missions/test_capacity_wait_parity.py (AP-4).+CAPACITY_WAIT_REASONS: Final[frozenset[str]] = frozenset({+ "provider_quota", # usage/session window or credit spent+ "provider_auth", # subscription login expired+ "provider_unavailable", # the worker cannot run without a paid fallback+})+++class MissionWaitingCapacity(_PayloadBase):+ """The mission is parked: its worker has no usable capacity right now.++ Every field is a runtime fact (counts, paths, the provider slug), never+ worker text, so the voice layer can render it as a static phrase.+ """++ event_type: Literal["MissionWaitingCapacity"] = "MissionWaitingCapacity"+ reason: Literal["provider_quota", "provider_auth", "provider_unavailable"]+ provider: str | None = None+ steps_done: int = 0+ steps_total: int = 0+ files_saved: int = 0+ checkpoint_path: str = ""+ error_detail: str | None = None++class MissionCancelled(_PayloadBase):event_type: Literal["MissionCancelled"] = "MissionCancelled"cascade: bool = False@@ -194,7 +222,22 @@ class MissionBudgetWarning(_PayloadBase):Payload = Annotated[- MissionDispatched | MissionPlanReady | WorkerSpawned | WorkerProgress | WorkerDraftReady | CriticVerdictReady | WorkerCorrectionRequired | WorkerKilled | MissionApproved | MissionFailed | MissionCancelled | MissionTimedOut | MissionStateChanged | BusStats | MissionBudgetWarning,+ MissionDispatched+ | MissionPlanReady+ | WorkerSpawned+ | WorkerProgress+ | WorkerDraftReady+ | CriticVerdictReady+ | WorkerCorrectionRequired+ | WorkerKilled+ | MissionApproved+ | MissionFailed+ | MissionCancelled+ | MissionTimedOut+ | MissionStateChanged+ | BusStats+ | MissionBudgetWarning+ | MissionWaitingCapacity,Field(discriminator="event_type"),]diff --git a/jarvis/missions/init.py b/jarvis/missions/init.pyindex 5347bdfa9b..84d3b172aa 100644--- a/jarvis/missions/init.py+++ b/jarvis/missions/init.py@@ -34,6 +34,7 @@ from typing import Anyfrom jarvis.core.bus import EventBus as _SpeechEventBusfrom .budget import BudgetTracker+from .capacity import WorkerCapacityUnavailable, pinned_to_subscriptionfrom .cleanup import daily_cleanup_task, startup_sweepfrom .critic.runner import CriticRunnerfrom .event_bus import MissionBus@@ -510,22 +511,13 @@ def _live_subagent_provider(boot_snapshot: str | None) -> str | None:return boot_snapshot-def _claude_cli_auth_viable() -> bool:- """True when the ``claude`` CLI has a REACHABLE auth surface for a worker.-- Binary presence alone is NOT viability (2026-07-06 incident): the worker- must have one of three executable auth surfaces:-- 1. the process-local ``claude_auth_dead`` flag (a worker PROVED the current- credential dead this session — fingerprinted, so a fresh login/key- re-enables Claude instantly);- 2. a live file-backed OAuth bearer for the legacy isolated-config path, or- a native CLI account plus the ``--safe-mode`` capability (preserves the- macOS Keychain while disabling hooks/plugins);- 3. failing that, a classic (non-``sk-ant-oat``) Anthropic API key.+def _claude_subscription_login_state() -> bool | None:+ """The ``claude`` CLI's SUBSCRIPTION login: usable (True), proven dead this+ session (False), or absent (None).- The CLI probes are tightly timed and process-cached. A probe failure is not- fatal: the cross-family worker resolver continues to another usable family.+ Surfaces 1 and 2 of :func:`_claude_cli_auth_viable` — never the classic+ Anthropic API key, which bills per token. A mission pinned to the+ subscription (jarvis/missions/capacity.py) runs Claude only on this."""from jarvis.claude_auth_state import claude_auth_dead, credential_fingerprintfrom jarvis.missions.isolation.env import (@@ -555,6 +547,31 @@ def _claude_cli_auth_viable() -> bool:)except Exception: # noqa: BLE001,S110 — optional native auth pathpass+ return None+++def _claude_cli_auth_viable() -> bool:+ """True when the ``claude`` CLI has a REACHABLE auth surface for a worker.++ Binary presence alone is NOT viability (2026-07-06 incident): the worker+ must have one of three executable auth surfaces:++ 1. the process-local ``claude_auth_dead`` flag (a worker PROVED the current+ credential dead this session — fingerprinted, so a fresh login/key+ re-enables Claude instantly);+ 2. a live file-backed OAuth bearer for the legacy isolated-config path, or+ a native CLI account plus the ``--safe-mode`` capability (preserves the+ macOS Keychain while disabling hooks/plugins);+ 3. failing that, a classic (non-``sk-ant-oat``) Anthropic API key.++ The CLI probes are tightly timed and process-cached. A probe failure is not+ fatal: the cross-family worker resolver continues to another usable family.+ """+ from jarvis.claude_auth_state import claude_auth_dead, credential_fingerprint++ login = _claude_subscription_login_state()+ if login is not None:+ return logintry:from jarvis.core.config import get_jarvis_agent_secret@@ -645,6 +662,8 @@ def reachable_worker_families() -> list[str]:def _cross_family_last_resort_worker(task_text: str,capability_inventory: WorkerCapabilityInventory | None = None,+ *,+ allow_metered: bool = True,) -> Any | None:"""The key-aware, cross-family LAST-resort heavy worker (open-source AP-22/23).@@ -711,6 +730,10 @@ def _cross_family_last_resort_worker(# 3. In-process API worker on whatever single key the user has, crossing# families — the same cross-family set the Brain fallback chain uses.# Viability-gated (not existence-gated): see _api_key_family_viable.+ # Skipped on a subscription install (``allow_metered=False``): a per-token+ # key is billed only after the user approves it (missions/capacity.py).+ if not allow_metered:+ return Nonefrom jarvis.missions.workers.api_agent_worker import supports_api_agent_workerfor prov in ("claude-api", "gemini", "openrouter", "openai", "grok", "nvidia"):@@ -726,10 +749,52 @@ def _cross_family_last_resort_worker(return None+def _pinned_claude_worker(+ capability_inventory: WorkerCapabilityInventory | None,+ *,+ binary_present: bool,+ login: bool | None,+) -> Any:+ """The Claude worker for a mission pinned to the subscription, or a+ :class:`WorkerCapacityUnavailable` that parks the mission.++ ``login`` is :func:`_claude_subscription_login_state`. Never codex, never+ another family, never the Anthropic API key: the user approves paid use per+ mission (jarvis/missions/capacity.py).+ """+ from jarvis.claude_quota_state import claude_in_quota_cooldown++ if not binary_present:+ raise WorkerCapacityUnavailable(+ "provider_unavailable",+ "claude",+ "the claude CLI is not installed; the Anthropic API key needs approval",+ )+ if claude_in_quota_cooldown():+ raise WorkerCapacityUnavailable("provider_quota", "claude")+ if login is not True:+ raise WorkerCapacityUnavailable("provider_auth", "claude")+ return ClaudeDirectWorker(capability_inventory=capability_inventory, backend_fallback=False)+++def _pinned_codex_worker(capability_inventory: WorkerCapabilityInventory | None) -> Any:+ """The codex worker for a pinned mission, or a WorkerCapacityUnavailable."""+ from jarvis.codex_auth_state import codex_needs_reauth+ from jarvis.codex_quota_state import codex_in_quota_cooldown++ if codex_needs_reauth():+ raise WorkerCapacityUnavailable("provider_auth", "codex")+ if codex_in_quota_cooldown():+ raise WorkerCapacityUnavailable("provider_quota", "codex")+ return CodexDirectWorker(capability_inventory=capability_inventory, backend_fallback=False)++def _resolve_api_agent_worker(provider: str,task_text: str,capability_inventory: WorkerCapabilityInventory | None = None,+ *,+ pinned: bool = False,) -> Any:"""Worker for an ``api_agent``-kind Jarvis-Agent provider.@@ -755,6 +820,15 @@ def _resolve_api_agent_worker(provider,)return ApiAgentWorker(provider, capability_inventory=inventory)+ if pinned:+ # A subscription install never crosses to another family on its own+ # (jarvis/missions/capacity.py): park the mission instead.+ from jarvis.api_family_quota_state import api_family_in_cooldown++ raise WorkerCapacityUnavailable(+ "provider_quota" if api_family_in_cooldown(provider) else "provider_unavailable",+ provider,+ )logger.warning("Mission worker: subagent provider %r has no API key configured, ""so it cannot run — trying the user's other provider families "@@ -1164,14 +1238,26 @@ async def bootstrap_missions(live_provider = _live_subagent_provider(sub_jarvis_provider)kind = _select_subagent_worker_kind(live_provider, getattr(step, "model", "") or "")if kind == "claude_direct":- # B3 (open-source AP-22): an Anthropic-API-key-only user has NO `claude`- # 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.missions.workers.claude_direct_worker import (_resolve_claude_binary,)+ # Capacity policy (jarvis/missions/capacity.py): on a subscription+ # install the mission stays on Claude's subscription login — a spent+ # window or a dead login parks it in WAITING_CAPACITY instead of+ # moving it to codex, another family, or the Anthropic API key.+ binary_present = _resolve_claude_binary() is not None+ login = _claude_subscription_login_state() if binary_present else None+ if pinned_to_subscription(+ configured_is_subscription=binary_present and login is not None+ ):+ return _pinned_claude_worker(+ capability_inventory, binary_present=binary_present, login=login+ )+ # B3 (open-source AP-22): an Anthropic-API-key-only user has NO `claude`+ # 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.if _resolve_claude_binary() is None and _api_key_family_viable("claude-api"):logger.info("Mission worker -> ApiAgentWorker('claude-api'): no `claude` CLI "@@ -1218,6 +1304,9 @@ async def bootstrap_missions(# claude-cli MCP config so it can issue the plugin tool calls (AD-OE4).return ClaudeDirectWorker(capability_inventory=capability_inventory)if kind == "codex_direct":+ # The ChatGPT login is a subscription: pinned like Claude above.+ if pinned_to_subscription(configured_is_subscription=True):+ return _pinned_codex_worker(capability_inventory)# If a codex subprocess already proved the ChatGPT login dead this# session, skip codex entirely and run on Claude Max directly (one# path, like grok) — re-spawning the dead provider + double-falling-@@ -1259,7 +1348,12 @@ async def bootstrap_missions(# `_resolve_api_agent_worker` (viability-gated, cross-family# fallback, honest Claude last resort).provider = live_provider or ""- return _resolve_api_agent_worker(provider, task_text, capability_inventory)+ return _resolve_api_agent_worker(+ provider,+ task_text,+ capability_inventory,+ pinned=pinned_to_subscription(configured_is_subscription=False),+ )if kind == "gemini":# B4 (open-source AP-22): no Gemini CLI but a Gemini API key → run the# heavy worker IN-PROCESS via ApiAgentWorker instead of failing on the@@ -1294,8 +1388,13 @@ async def bootstrap_missions(# nested-claude hang; see docs/BUGS.md).# Open-source AP-22/AP-23: try the user's ACTUAL provider family before# the Claude last resort, so an openrouter/gemini/openai-only downloader- # is not dead-ended on the absent `claude` binary.- cross = _cross_family_last_resort_worker(task_text, capability_inventory)+ # is not dead-ended on the absent `claude` binary. A subscription+ # install never lands on a per-token key this way (missions/capacity.py).+ cross = _cross_family_last_resort_worker(+ task_text,+ capability_inventory,+ allow_metered=not pinned_to_subscription(configured_is_subscription=False),+ )if cross is not None:return crossreturn ClaudeDirectWorker(capability_inventory=capability_inventory)diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.pyindex 67001ef652..bc7bc52d3c 100644--- a/jarvis/missions/kontrollierer/orchestrator.py+++ b/jarvis/missions/kontrollierer/orchestrator.py@@ -37,6 +37,7 @@ from typing import Any, Final, Literalfrom ...core.process_utils import NO_WINDOW_CREATIONFLAGSfrom ..budget import BudgetExceeded, BudgetTracker+from ..capacity import WorkerCapacityUnavailable, write_checkpointfrom ..critic.escalation import FRONTIER_MODELfrom ..critic.reflections import ReflectionMemoryfrom ..critic.runner import MAX_CRITIC_LOOPS, CriticRunner@@ -54,6 +55,7 @@ from ..events import (MissionCancelled,MissionFailed,MissionPlanReady,+ MissionWaitingCapacity,WorkerCorrectionRequired,WorkerDraftReady,WorkerKilled,@@ -744,6 +746,11 @@ class TaskOutcome:# stays the generic ERROR -> task_error. (Voice strings live in# readback.FAILURE_REASON_PHRASES; see the deep-dive README.)TIMED_OUT = "timed_out"+ # The worker has no usable capacity (spent window, dead subscription login,+ # nothing it may run on without a paid fallback). The mission is parked in+ # WAITING_CAPACITY with a checkpoint instead of failing — see+ # jarvis/missions/capacity.py.+ WAITING_CAPACITY = "waiting_capacity"class Kontrollierer:@@ -836,6 +843,10 @@ class Kontrollierer:# generic "worktree_setup_failed" fallback. Last write wins, same# convention as `_mission_failure_context`.self._setup_failure_reason: dict[str, str] = {}+ # Per-mission capacity-wait cause (reason, provider, error_detail) —+ # written where a task returns WAITING_CAPACITY, consumed once by+ # `_park_mission`. Last write wins, as above.+ self._capacity_wait: dict[str, dict[str, str | None]] = {}# Per-mission worker answers for read-only/informational tasks (empty# diff + tool evidence). Surfaced as MissionApproved.summary_de so the# voice readback speaks the actual answer instead of "Mission@@ -848,7 +859,7 @@ class Kontrollierer:async def run_mission(self, mission_id: str) -> MissionState:"""Runs a mission end-to-end and returns the final state.- Returns: APPROVED | FAILED | CANCELLED | TIMED_OUT.+ Returns: APPROVED | FAILED | CANCELLED | TIMED_OUT | WAITING_CAPACITY.The in-flight asyncio task is tracked in ``_running_missions`` so anexternal cancel (REST ``POST /api/missions/{id}/cancel``) can abort@@ -1030,6 +1041,7 @@ class Kontrollierer:# Parallel task execution with semaphore limitsem = asyncio.Semaphore(min(plan.n_workers, self._max_workers))task_outcomes: list[str] = []+ step_outcomes: dict[str, str] = {}async def _run(step: Step) -> None:outcome = await self._run_task_with_critic_loop(@@ -1041,6 +1053,7 @@ class Kontrollierer:sem=sem,)task_outcomes.append(outcome)+ step_outcomes[step.task_id] = outcome# Cross-mission concurrency cap: serialise the heavy claude# (worker + critic) phase so a burst of missions cannot overload the@@ -1088,6 +1101,21 @@ class Kontrollierer:# or critic-reject is more recoverable when the user can see the# work the worker actually produced.partial = self._collect_partial_artifacts(mission_id, plan)+ # A task without worker capacity parks the whole mission with a+ # checkpoint — the finished steps are kept, nothing is failed and no+ # provider is switched (jarvis/missions/capacity.py). Only an exceeded+ # budget outranks it: that is a hard stop, not a wait.+ if (+ TaskOutcome.WAITING_CAPACITY in task_outcomes+ and TaskOutcome.BUDGET_EXCEEDED not in task_outcomes+ ):+ return await self._park_mission(+ mission_id,+ plan,+ prompt=view.prompt,+ step_outcomes=step_outcomes,+ partial_artifacts=partial,+ )# Execution/setup failures outrank review outcomes in a multi-task# mission. Otherwise one review time guard can mask a real worker crash# in another step and show the user the wrong terminal cause.@@ -1375,8 +1403,22 @@ class Kontrollierer:mission_id, MissionState.CRITIQUING, f"iter-{iteration}-start")- # Worker spawn (real or fake depending on the factory)- worker = self._worker_factory(step)+ # Worker spawn (real or fake depending on the factory). A factory+ # that refuses to switch to a billing fallback parks the task.+ try:+ worker = self._worker_factory(step)+ except WorkerCapacityUnavailable as exc:+ logger.warning(+ "Task %s iter %d: no worker capacity (%s) — parking the "+ "mission instead of switching provider",+ step.task_id, iteration, exc,+ )+ self._capacity_wait[mission_id] = {+ "reason": exc.reason,+ "provider": exc.provider,+ "error_detail": exc.detail or None,+ }+ return TaskOutcome.WAITING_CAPACITYlog_dir = mission_dir / "tasks" / step.task_id[:13] / "logs"log_dir.mkdir(parents=True, exist_ok=True)@@ -1632,6 +1674,18 @@ class Kontrollierer:# (auth/billing/non-timeout crash) stays ERROR.if is_timeout:return TaskOutcome.TIMED_OUT+ # A spent quota window is not a fault of the work: park+ # the mission with its checkpoint instead of failing it.+ if error_class == "provider_quota":+ self._capacity_wait[mission_id] = {+ "reason": "provider_quota",+ "provider": (+ getattr(worker, "provider", None)+ or getattr(worker, "cli", None)+ ),+ "error_detail": error_detail,+ }+ return TaskOutcome.WAITING_CAPACITYreturn TaskOutcome.ERROR# WorkerDraftReady event — BudgetTracker.bind_to_event_bus@@ -2854,6 +2908,103 @@ class Kontrollierer:)return False+ async def _park_mission(+ self,+ mission_id: str,+ plan: MissionPlan,+ *,+ prompt: str,+ step_outcomes: dict[str, str],+ partial_artifacts: list[str],+ ) -> MissionState:+ """Checkpoint the mission and park it in WAITING_CAPACITY.++ The checkpoint records every step with its outcome and where its+ archived artifacts live (the per-task archive already ran in each+ task's ``finally``). The ``MissionWaitingCapacity`` event carries only+ counts and paths, so the voice layer renders it as a static phrase.+ """+ self._task_answers.pop(mission_id, None)+ self._mission_failure_context.pop(mission_id, None)+ wait = self._capacity_wait.pop(mission_id, {})+ reason = wait.get("reason") or "provider_quota"+ provider = wait.get("provider")+ error_detail = wait.get("error_detail")+ mission_dir = self._isolation_root / f"mission_{mission_id[:13]}"++ steps: list[dict[str, Any]] = []+ files_saved = 0+ for step in plan.steps:+ outcome = step_outcomes.get(step.task_id, "not_started")+ files_dir = mission_dir / "tasks" / step.task_id[:13] / "artifacts" / "files"+ try:+ n_files = sum(1 for p in files_dir.rglob("*") if p.is_file())+ except OSError:+ # Missing or unreadable: nothing countable was saved for it.+ n_files = 0+ files_saved += n_files+ steps.append({+ "task_id": step.task_id,+ "slug": step.slug,+ "prompt": step.prompt,+ "outcome": outcome,+ "done": outcome == TaskOutcome.APPROVED,+ "files_saved": n_files,+ "artifacts_dir": str(files_dir.parent),+ })+ steps_done = sum(1 for st in steps if st["done"])++ checkpoint_path = ""+ try:+ checkpoint_path = str(await asyncio.to_thread(+ write_checkpoint,+ mission_dir,+ {+ "mission_id": mission_id,+ "prompt": prompt,+ "reason": reason,+ "provider": provider,+ "error_detail": error_detail,+ "created_ms": now_ms(),+ "steps": steps,+ "partial_artifacts": partial_artifacts,+ },+ ))+ except OSError:+ # The per-task archives still hold the work; only the index is+ # missing, and the event says so (empty checkpoint_path).+ logger.exception("Mission %s: checkpoint write failed", mission_id)++ if not await self._safe_transition(+ mission_id, MissionState.WAITING_CAPACITY, f"capacity:{reason}"+ ):+ # Cancelled (or otherwise finished) while the tasks wound down.+ current = await self._manager.mission(mission_id)+ return current.state if current is not None else MissionState.FAILED+ await self._manager.store.append_and_publish(+ EventEnvelope(+ mission_id=mission_id,+ source_actor="kontrollierer",+ ts_ms=now_ms(),+ payload=MissionWaitingCapacity(+ reason=reason, # type: ignore[arg-type]+ provider=provider,+ steps_done=steps_done,+ steps_total=len(plan.steps),+ files_saved=files_saved,+ checkpoint_path=checkpoint_path,+ error_detail=error_detail,+ ),+ )+ )+ logger.warning(+ "Mission %s parked in WAITING_CAPACITY (%s, provider=%s): %d/%d "+ "steps done, %d file(s) saved, checkpoint=%s",+ mission_id, reason, provider, steps_done, len(plan.steps),+ files_saved, checkpoint_path or "<none>",+ )+ return MissionState.WAITING_CAPACITY+async def _approve_mission(self, mission_id: str, plan: MissionPlan, *, prompt: str = "") -> None:diff --git a/jarvis/missions/recovery.py b/jarvis/missions/recovery.pyindex 8529937ec6..f9946f0822 100644--- a/jarvis/missions/recovery.py+++ b/jarvis/missions/recovery.py@@ -147,6 +147,11 @@ async def startup_recover(owner_dead_ids: list[str] = []for mission_id, prompt, last_state in stale:+ # A mission parked for capacity is idle ON PURPOSE: no process owns it+ # and its checkpoint holds the work (jarvis/missions/capacity.py). It+ # is not an orphan, so no restart or periodic sweep may fail it.+ if last_state == MissionState.WAITING_CAPACITY.value:+ continueevents = await store.events_for_mission(mission_id)# 1. Reconcile: a terminal event was recorded but the header laggeddiff --git a/jarvis/missions/state_machine.py b/jarvis/missions/state_machine.pyindex 55fd07b85f..1c7fa8d26b 100644--- a/jarvis/missions/state_machine.py+++ b/jarvis/missions/state_machine.py@@ -33,6 +33,12 @@ class MissionState(str, Enum):FAILED = "FAILED"CANCELLED = "CANCELLED"TIMED_OUT = "TIMED_OUT"+ # Parked, not finished: the worker's subscription has no capacity left+ # (quota window spent, login expired, provider unreachable). The work done+ # so far is checkpointed and the mission waits instead of failing or+ # moving to a paid key. Deliberately NOT terminal — see+ # jarvis/missions/capacity.py.+ WAITING_CAPACITY = "WAITING_CAPACITY"class MissionType(str, Enum):@@ -95,6 +101,14 @@ ALLOWED_TRANSITIONS: frozenset[tuple[MissionState, MissionState]] = frozenset((MissionState.RUNNING, MissionState.TIMED_OUT),(MissionState.CRITIQUING, MissionState.TIMED_OUT),(MissionState.LOOPING, MissionState.TIMED_OUT),+ # Capacity pause from any active state, and out of it again: resume,+ # give up, or cancel.+ (MissionState.RUNNING, MissionState.WAITING_CAPACITY),+ (MissionState.CRITIQUING, MissionState.WAITING_CAPACITY),+ (MissionState.LOOPING, MissionState.WAITING_CAPACITY),+ (MissionState.WAITING_CAPACITY, MissionState.RUNNING),+ (MissionState.WAITING_CAPACITY, MissionState.FAILED),+ (MissionState.WAITING_CAPACITY, MissionState.CANCELLED),})diff --git a/jarvis/missions/voice/announcer.py b/jarvis/missions/voice/announcer.pyindex e9e475d249..c92870eed7 100644--- a/jarvis/missions/voice/announcer.py+++ b/jarvis/missions/voice/announcer.py@@ -42,6 +42,7 @@ from jarvis.missions.voice.readback import (FAILURE_REASON_PHRASES,failure_phrase_key,render_agent_brand,+ render_capacity_wait,)from ..event_bus import MissionBus@@ -52,6 +53,7 @@ from ..events import (MissionCancelled,MissionFailed,MissionTimedOut,+ MissionWaitingCapacity,)logger = logging.getLogger(__name__)@@ -264,6 +266,23 @@ class MissionAnnouncer:# (AD-OE6 — no silent drops) but at the next natural turn boundary.return (text, "normal")+ if isinstance(payload, MissionWaitingCapacity):+ # Parked, not failed (jarvis/missions/capacity.py): say why, what+ # is done, what is open, and that paid use needs approval. Queued+ # for the next turn boundary like a failure (AD-OE5).+ return (+ render_capacity_wait(+ reason=payload.reason,+ provider=payload.provider,+ steps_done=payload.steps_done,+ steps_total=payload.steps_total,+ files_saved=payload.files_saved,+ checkpoint_saved=bool(payload.checkpoint_path),+ language=lang,+ ),+ "normal",+ )+if isinstance(payload, MissionCancelled):text = ("Mission abgebrochen."diff --git a/jarvis/missions/voice/listener.py b/jarvis/missions/voice/listener.pyindex 8d0a9b1df0..8e6471c44d 100644--- a/jarvis/missions/voice/listener.py+++ b/jarvis/missions/voice/listener.py@@ -34,10 +34,11 @@ from ..events import (MissionCancelled,MissionFailed,MissionTimedOut,+ MissionWaitingCapacity,WorkerCorrectionRequired,WorkerKilled,)-from .readback import Lang, MissionReadback+from .readback import Lang, MissionReadback, render_capacity_waitlogger = logging.getLogger(__name__)@@ -144,6 +145,17 @@ class MissionVoiceListener:if isinstance(payload, MissionCancelled):return self._readback.render_cancelled(language=lang)+ if isinstance(payload, MissionWaitingCapacity):+ return render_capacity_wait(+ reason=payload.reason,+ provider=payload.provider,+ steps_done=payload.steps_done,+ steps_total=payload.steps_total,+ files_saved=payload.files_saved,+ checkpoint_saved=bool(payload.checkpoint_path),+ language=lang,+ )+if isinstance(payload, MissionBudgetWarning):pct = int(payload.pct_used)if pct >= 80:diff --git a/jarvis/missions/voice/readback.py b/jarvis/missions/voice/readback.pyindex d338b8f571..850a266e9e 100644--- a/jarvis/missions/voice/readback.py+++ b/jarvis/missions/voice/readback.py@@ -307,6 +307,100 @@ def failure_phrase_key(reason: str, error_class: str | None) -> str:return (reason or "").split(":", 1)[0].strip()+# WAITING_CAPACITY readback (jarvis/missions/capacity.py). Built from runtime+# counts only — never worker text (ADR-0009 §1). Keys mirror+# CAPACITY_WAIT_REASONS in jarvis/missions/events.py; parity is guarded by+# tests/missions/test_capacity_wait_parity.py.+CAPACITY_WAIT_PHRASES: Final[dict[str, dict[str, str]]] = {+ "de": {+ "provider_quota": "{provider}-Kapazität momentan ausgeschöpft.", # i18n-allow+ "provider_auth": "Die {provider}-Anmeldung ist abgelaufen.", # i18n-allow+ "provider_unavailable": "{provider} ist momentan nicht nutzbar.", # i18n-allow+ "saved": "Der bisherige Stand wurde gesichert.", # i18n-allow+ "progress": "{done} von {total} Teilschritten erledigt, {open} offen.", # i18n-allow+ "progress_single": "Die Aufgabe selbst ist noch offen.", # i18n-allow+ "file": "1 Datei gespeichert.", # i18n-allow+ "files": "{files} Dateien gespeichert.", # i18n-allow+ "wait": "Die Mission wartet, bis wieder Kapazität verfügbar ist.", # i18n-allow+ "wait_auth": "Die Mission wartet, bis du dich wieder anmeldest.", # i18n-allow+ "paid": (+ "Kostenpflichtige API-Nutzung nur mit deiner ausdrücklichen Freigabe." # i18n-allow+ ),+ },+ "en": {+ "provider_quota": "{provider} capacity is used up for now.",+ "provider_auth": "The {provider} sign-in has expired.",+ "provider_unavailable": "{provider} cannot be used right now.",+ "saved": "The progress so far has been saved.",+ "progress": "{done} of {total} steps done, {open} open.",+ "progress_single": "The task itself is still open.",+ "file": "1 file saved.",+ "files": "{files} files saved.",+ "wait": "The mission is waiting until capacity is available again.",+ "wait_auth": "The mission is waiting until you sign in again.",+ "paid": "Paid API use only with your explicit approval.",+ },+}++_MAX_PROVIDER_CHARS: Final[int] = 40++# Display names for worker provider slugs in the capacity readback. A slug+# without an entry is spoken as-is.+_PROVIDER_DISPLAY: Final[dict[str, str]] = {+ "claude": "Claude",+ "claude-api": "Claude",+ "codex": "ChatGPT",+ "chatgpt": "ChatGPT",+ "openai": "OpenAI",+ "gemini": "Gemini",+ "antigravity": "Gemini",+ "grok": "Grok",+ "openrouter": "OpenRouter",+ "nvidia": "NVIDIA",+}+++def render_capacity_wait(+ *,+ reason: str,+ provider: str | None,+ steps_done: int,+ steps_total: int,+ files_saved: int,+ checkpoint_saved: bool,+ language: Lang = "de",+) -> str:+ """Short readback for a mission parked in WAITING_CAPACITY: why it stopped,+ what is done, what is open, and the options (wait / approve paid use)."""+ table = CAPACITY_WAIT_PHRASES.get(language, CAPACITY_WAIT_PHRASES["en"])+ slug = (provider or "").strip()+ fallback = "KI-Anbieter" if language == "de" else "AI provider" # i18n-allow+ name = (_PROVIDER_DISPLAY.get(slug.lower(), slug) or fallback)[:_MAX_PROVIDER_CHARS]+ head = [table.get(reason, table["provider_unavailable"]).format(provider=name)]+ if checkpoint_saved:+ head.append(table["saved"])+ tail = [table["wait_auth" if reason == "provider_auth" else "wait"], table["paid"]]+ progress = (+ table["progress"].format(+ done=steps_done, total=steps_total, open=max(steps_total - steps_done, 0),+ )+ if steps_total > 1+ else table["progress_single"]+ )+ files = (+ table["file"] if files_saved == 1+ else table["files"].format(files=files_saved) if files_saved > 1+ else ""+ )+ # Why it stopped and the options must survive the length cap; the file+ # count gives way first, then the step count.+ for optional in ([progress, files], [progress], []):+ text = " ".join([*head, *(o for o in optional if o), *tail])+ if len(text) <= MAX_VOICE_CHARS:+ return text+ return _truncate(text)++def _truncate(text: str, max_chars: int = MAX_VOICE_CHARS) -> str:"""Truncate to max_chars; no suffix so TTS does not say '...'.diff --git a/jarvis/missions/workers/claude_direct_worker.py b/jarvis/missions/workers/claude_direct_worker.pyindex 00bda5605d..651cc5b075 100644--- a/jarvis/missions/workers/claude_direct_worker.py+++ b/jarvis/missions/workers/claude_direct_worker.py@@ -281,9 +281,14 @@ class ClaudeDirectWorker:mcp_servers: dict[str, Any] | None = None,*,capability_inventory: WorkerCapabilityInventory | None = None,+ backend_fallback: bool = True,) -> None:self.last_pid: int | None = Noneself.last_session_id: str | None = None+ # False pins this worker to Claude: on a spent window or a dead login it+ # surfaces the error instead of finishing the mission on codex, so the+ # orchestrator can park the mission (jarvis/missions/capacity.py).+ self.backend_fallback = backend_fallback# The legacy mcp_servers argument is folded into the same explicit# inventory every backend receives.self.capability_inventory = capability_inventory or WorkerCapabilityInventory.build(@@ -339,7 +344,7 @@ class ClaudeDirectWorker:timeout_s=timeout_s,first_output_timeout_s=first_output_timeout_s,mission_id=mission_id,- allow_backend_fallback=allow_backend_fallback,+ allow_backend_fallback=allow_backend_fallback and self.backend_fallback,force_default_model=force_default_model,broker_binding=broker_binding,**_unused,@@ -896,6 +901,19 @@ class ClaudeDirectWorker:# discarded, the orchestrator grades it instead), complete the# mission on the codex worker. `allow_backend_fallback=False` on the# nested spawn prevents claude->codex->claude ping-pong.+ if final_result.is_error and not timed_out and not any_tool_use:+ from .codex_direct_worker import _codex_error_is_usage_limited++ if _codex_error_is_usage_limited(final_result.result or ""):+ # Arm the session quota cooldown — also when the codex fallback+ # is off: the worker factory reads it to park pinned missions+ # in WAITING_CAPACITY, and an unpinned factory routes STRAIGHT+ # to codex (no wasted ~16 s Claude probe) until the window+ # resets.+ from jarvis.claude_quota_state import mark_claude_quota_cooldown++ mark_claude_quota_cooldown()+if allow_backend_fallback and final_result.is_error and not timed_out and not any_tool_use:from jarvis.codex_auth_state import codex_needs_reauthfrom jarvis.codex_quota_state import codex_in_quota_cooldown@@ -906,15 +924,6 @@ class ClaudeDirectWorker:_codex_oauth_available,)- if _codex_error_is_usage_limited(final_result.result or ""):- # Arm the session quota cooldown so the worker factory routes- # subsequent missions STRAIGHT to codex (no wasted ~16 s Claude- # probe) until the window resets — the proactive complement to- # this reactive fallback.- from jarvis.claude_quota_state import mark_claude_quota_cooldown-- mark_claude_quota_cooldown()-if (_codex_error_is_usage_limited(final_result.result or "")and _codex_oauth_available()diff --git a/jarvis/missions/workers/codex_direct_worker.py b/jarvis/missions/workers/codex_direct_worker.pyindex 54fdf47324..a348ffd00b 100644--- a/jarvis/missions/workers/codex_direct_worker.py+++ b/jarvis/missions/workers/codex_direct_worker.py@@ -458,11 +458,15 @@ class CodexDirectWorker:self,*,capability_inventory: WorkerCapabilityInventory | None = None,+ backend_fallback: bool = True,) -> None:self.last_pid: int | None = Noneself.last_session_id: str | None = Noneself.last_thread_id: str | None = Noneself.capability_inventory = capability_inventory or WorkerCapabilityInventory.build()+ # False pins this worker to codex: a usage cap or a dead login surfaces+ # as an error instead of finishing on Claude (jarvis/missions/capacity.py).+ self.backend_fallback = backend_fallbackasync def spawn(self,@@ -512,7 +516,7 @@ class CodexDirectWorker:timeout_s=timeout_s,first_output_timeout_s=first_output_timeout_s,mission_id=mission_id,- allow_backend_fallback=allow_backend_fallback,+ allow_backend_fallback=allow_backend_fallback and self.backend_fallback,broker_binding=broker_binding,**_unused,):@@ -894,23 +898,26 @@ class CodexDirectWorker:and not _auth_deadand _codex_error_is_usage_limited(_err))+ # The flags are armed whether or not the fallback runs: a pinned worker+ # (backend_fallback=False) relies on them so the worker factory parks+ # the mission in WAITING_CAPACITY (jarvis/missions/capacity.py).+ if _auth_dead:+ from jarvis.codex_auth_state import mark_codex_needs_reauth++ mark_codex_needs_reauth()+ elif _usage_capped:+ # Proactive complement to the reactive fallback below (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()# `allow_backend_fallback=False` marks a NESTED fallback run (the- # claude worker already fell back to codex) — surface the error- # honestly instead of bouncing codex->claude->codex forever.+ # claude worker already fell back to codex) or a pinned worker —+ # surface the error honestly instead of bouncing codex->claude->codex.if (_auth_dead or _usage_capped) and allow_backend_fallback:- if _auth_dead:- 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->diff --git a/jarvis/ui/web/frontend/src/components/missions/store.ts b/jarvis/ui/web/frontend/src/components/missions/store.tsindex 227189bb89..8d53d926c5 100644--- a/jarvis/ui/web/frontend/src/components/missions/store.ts+++ b/jarvis/ui/web/frontend/src/components/missions/store.ts@@ -195,6 +195,7 @@ function normalizeState(s: string): MissionState {case "FAILED":case "CANCELLED":case "TIMED_OUT":+ case "WAITING_CAPACITY":return upper as MissionState;default:return "PENDING";diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 6c41a19d2a..2be81ad1ca 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -4181,7 +4181,20 @@"timeline_label": "Event-Timeline","no_events": "Noch keine Events für diese Mission.","no_critic_verdicts": "Noch keine Critic-Verdicts für diese Mission.",- "no_missions_yet": "Noch keine Missions. Hauptjarvis dispatched gleich…"+ "no_missions_yet": "Noch keine Missions. Hauptjarvis dispatched gleich…",+ "capacity_wait": {+ "provider_quota": "{provider}-Kapazität momentan ausgeschöpft.",+ "provider_auth": "Die {provider}-Anmeldung ist abgelaufen.",+ "provider_unavailable": "{provider} ist momentan nicht nutzbar.",+ "provider_fallback": "KI-Anbieter",+ "saved": "Der bisherige Stand wurde gesichert.",+ "progress": "{done} von {total} Teilschritten erledigt, {open} offen.",+ "progress_single": "Die Aufgabe selbst ist noch offen.",+ "files": "Gespeicherte Dateien: {files}.",+ "wait": "Die Mission wartet, bis wieder Kapazität verfügbar ist.",+ "wait_auth": "Die Mission wartet, bis du dich wieder anmeldest.",+ "paid": "Kostenpflichtige API-Nutzung nur mit deiner ausdrücklichen Freigabe."+ }},"mission_tool_approvals": {"tab_label": "Freigaben",@@ -4272,7 +4285,8 @@"approved": "fertig","failed": "Fehler","cancelled": "abgebrochen",- "timed_out": "Timeout"+ "timed_out": "Timeout",+ "waiting_capacity": "wartet auf Kapazität"},"mascot_gigi": {"aria_label": "{name}-Maskottchen Gigi",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex b889b98bf9..0d4701c7ce 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -4181,7 +4181,20 @@"timeline_label": "Event timeline","no_events": "No events for this mission yet.","no_critic_verdicts": "No critic verdicts for this mission yet.",- "no_missions_yet": "No missions yet. Main Jarvis will dispatch one shortly…"+ "no_missions_yet": "No missions yet. Main Jarvis will dispatch one shortly…",+ "capacity_wait": {+ "provider_quota": "{provider} capacity is used up for now.",+ "provider_auth": "The {provider} sign-in has expired.",+ "provider_unavailable": "{provider} cannot be used right now.",+ "provider_fallback": "AI provider",+ "saved": "The progress so far has been saved.",+ "progress": "{done} of {total} steps done, {open} open.",+ "progress_single": "The task itself is still open.",+ "files": "Files saved: {files}.",+ "wait": "The mission is waiting until capacity is available again.",+ "wait_auth": "The mission is waiting until you sign in again.",+ "paid": "Paid API use only with your explicit approval."+ }},"mission_tool_approvals": {"tab_label": "Approvals",@@ -4272,7 +4285,8 @@"approved": "done","failed": "error","cancelled": "cancelled",- "timed_out": "timeout"+ "timed_out": "timeout",+ "waiting_capacity": "waiting for capacity"},"mascot_gigi": {"aria_label": "{name} mascot Gigi",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 1cbe250fed..6c0d8e5a74 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -4181,7 +4181,20 @@"timeline_label": "Cronología de eventos","no_events": "Aún no hay eventos para esta misión.","no_critic_verdicts": "Aún no hay veredictos del crítico para esta misión.",- "no_missions_yet": "Aún no hay misiones. Jarvis principal enviará una en breve…"+ "no_missions_yet": "Aún no hay misiones. Jarvis principal enviará una en breve…",+ "capacity_wait": {+ "provider_quota": "La capacidad de {provider} está agotada por ahora.",+ "provider_auth": "El inicio de sesión de {provider} ha caducado.",+ "provider_unavailable": "{provider} no se puede usar ahora mismo.",+ "provider_fallback": "proveedor de IA",+ "saved": "El progreso hasta ahora se ha guardado.",+ "progress": "{done} de {total} pasos hechos, {open} pendientes.",+ "progress_single": "La tarea en sí sigue pendiente.",+ "files": "Archivos guardados: {files}.",+ "wait": "La misión espera hasta que vuelva a haber capacidad.",+ "wait_auth": "La misión espera hasta que vuelvas a iniciar sesión.",+ "paid": "Uso de API de pago solo con tu aprobación explícita."+ }},"mission_tool_approvals": {"tab_label": "Aprobaciones",@@ -4272,7 +4285,8 @@"approved": "listo","failed": "error","cancelled": "cancelado",- "timed_out": "tiempo agotado"+ "timed_out": "tiempo agotado",+ "waiting_capacity": "esperando capacidad"},"mascot_gigi": {"aria_label": "Mascota Gigi de {name}",diff --git a/jarvis/ui/web/frontend/src/types/missions.ts b/jarvis/ui/web/frontend/src/types/missions.tsindex faf4c80125..4d365f5c7f 100644--- a/jarvis/ui/web/frontend/src/types/missions.ts+++ b/jarvis/ui/web/frontend/src/types/missions.ts@@ -14,7 +14,10 @@ export type MissionState =| "APPROVED"| "FAILED"| "CANCELLED"- | "TIMED_OUT";+ | "TIMED_OUT"+ // Parked: the worker's subscription has no capacity left, so the work is+ // checkpointed and the mission waits (jarvis/missions/capacity.py).+ | "WAITING_CAPACITY";export type SourceActor =| "hauptjarvis"@@ -41,7 +44,8 @@ export type EventType =| "MissionTimedOut"| "MissionStateChanged"| "BusStats"- | "MissionBudgetWarning";+ | "MissionBudgetWarning"+ | "MissionWaitingCapacity";export interface BasePayload {event_type: EventType;@@ -192,6 +196,20 @@ export interface BusStats extends BasePayload {active_subs: number;}+/** Mirror of CAPACITY_WAIT_REASONS in jarvis/missions/events.py. */+export type CapacityWaitReason = "provider_quota" | "provider_auth" | "provider_unavailable";++export interface MissionWaitingCapacity extends BasePayload {+ event_type: "MissionWaitingCapacity";+ reason: CapacityWaitReason;+ provider: string | null;+ steps_done: number;+ steps_total: number;+ files_saved: number;+ checkpoint_path: string;+ error_detail: string | null;+}+export interface MissionBudgetWarning extends BasePayload {event_type: "MissionBudgetWarning";mission_id: string;@@ -213,6 +231,7 @@ export type AnyPayload =| MissionCancelled| MissionTimedOut| MissionStateChanged+ | MissionWaitingCapacity| BusStats| MissionBudgetWarning;@@ -407,6 +426,11 @@ export const MISSION_STATE_BADGE: Record<MissionState, MissionStateBadgeMeta> =className: "border-foreground/40 bg-foreground/10 text-foreground",iconName: "Skull",},+ WAITING_CAPACITY: {+ labelKey: "mission_state.waiting_capacity",+ className: "border-warning/40 bg-warning/10 text-warning",+ iconName: "Clock",+ },};export const TERMINAL_STATES: ReadonlySet<MissionState> = new Set([diff --git a/jarvis/ui/web/frontend/src/views/MissionsView.tsx b/jarvis/ui/web/frontend/src/views/MissionsView.tsxindex d009429f6b..e14f63da4d 100644--- a/jarvis/ui/web/frontend/src/views/MissionsView.tsx+++ b/jarvis/ui/web/frontend/src/views/MissionsView.tsx@@ -51,7 +51,7 @@ import {useMissionsStore,} from "@/components/missions/store";import { useMissionWebSocket } from "@/components/missions/useMissionWebSocket";-import { useT } from "@/i18n";+import { fill, useT } from "@/i18n";import { agentBrand } from "@/lib/agentBrand";import { useEventStore } from "@/store/events";import type { MissionPlanReady } from "@/types/missions";@@ -294,7 +294,8 @@ function ReasoningPanel() {return (s.eventsByMission[s.selectedMissionId] ?? []).filter((e) =>e.payload.event_type === "WorkerProgress" ||- e.payload.event_type === "WorkerCorrectionRequired",+ e.payload.event_type === "WorkerCorrectionRequired" ||+ e.payload.event_type === "MissionWaitingCapacity",);}),);@@ -344,6 +345,41 @@ function ReasoningPanel() {</li>);}+ if (env.payload.event_type === "MissionWaitingCapacity") {+ const p = env.payload;+ const provider = p.provider || t("missions_view.capacity_wait.provider_fallback");+ const open = Math.max(p.steps_total - p.steps_done, 0);+ return (+ <li+ key={`${env.event_id}-${idx}`}+ className="rounded border border-warning/40 bg-warning/10 p-2 text-xs"+ >+ <p className="font-medium text-warning">+ {fill(t(`missions_view.capacity_wait.${p.reason}`), { provider })}+ </p>+ <p className="mt-1 text-foreground/90">+ {p.checkpoint_path && `${t("missions_view.capacity_wait.saved")} `}+ {p.steps_total > 1+ ? fill(t("missions_view.capacity_wait.progress"), {+ done: p.steps_done,+ total: p.steps_total,+ open,+ })+ : t("missions_view.capacity_wait.progress_single")}+ {p.files_saved > 0 &&+ ` ${fill(t("missions_view.capacity_wait.files"), { files: p.files_saved })}`}+ </p>+ <p className="mt-1 text-muted-foreground">+ {t(+ p.reason === "provider_auth"+ ? "missions_view.capacity_wait.wait_auth"+ : "missions_view.capacity_wait.wait",+ )}{" "}+ {t("missions_view.capacity_wait.paid")}+ </p>+ </li>+ );+ }return null;})}</ul>diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/missionRows.ts b/jarvis/ui/web/frontend/src/views/sub-agents/missionRows.tsindex fdeaf3df88..15969b978e 100644--- a/jarvis/ui/web/frontend/src/views/sub-agents/missionRows.ts+++ b/jarvis/ui/web/frontend/src/views/sub-agents/missionRows.ts@@ -45,6 +45,8 @@ const STATE_STATUS: Record<string, SubAgentNode["status"]> = {RUNNING: "running",CRITIQUING: "running",LOOPING: "running",+ // Parked for capacity: not landed, resumes from its checkpoint.+ WAITING_CAPACITY: "running",APPROVED: "completed",FAILED: "failed",TIMED_OUT: "failed",diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.pyindex da817dcb72..8ebc633ca2 100644--- a/jarvis/ui/web/outputs_routes.py+++ b/jarvis/ui/web/outputs_routes.py@@ -406,6 +406,8 @@ _STATE_TO_STATUS: dict[str, str] = {# MissionState (state_machine.py) — real DB labels"CRITIQUING": "running","LOOPING": "running",+ # Parked for capacity: not landed yet, resumes from its checkpoint.+ "WAITING_CAPACITY": "running",# Legacy aliases kept for back-compat with older missions on disk"CRITIC_REVIEW": "running","AWAITING_CORRECTION": "running",diff --git a/tests/missions/test_capacity_wait.py b/tests/missions/test_capacity_wait.pynew file mode 100644index 0000000000..4a80b06a7b--- /dev/null+++ b/tests/missions/test_capacity_wait.py@@ -0,0 +1,526 @@+"""WAITING_CAPACITY: a mission without worker capacity is parked, never failed,+never moved to another subscription or a paid API key (missions/capacity.py).++Pins the user's rules (2026-10-04):+- no automatic switch to another subscription or to a per-token key,+- an exhausted quota parks the mission with a checkpoint and a clear message,+- a parked mission survives restarts and the age-based cleanup.+"""+from __future__ import annotations++import json+from collections.abc import AsyncIterator+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import pytest++from jarvis.missions import capacity+from jarvis.missions import init as mi+from jarvis.missions.budget import BudgetTracker+from jarvis.missions.capacity import (+ CHECKPOINT_NAME,+ WorkerCapacityUnavailable,+ pinned_to_subscription,+)+from jarvis.missions.critic.verdict import REQUIRED_AXES, CriticAxis, CriticVerdict+from jarvis.missions.events import MissionWaitingCapacity+from jarvis.missions.kontrollierer.decomposer import MissionPlan, Step+from jarvis.missions.kontrollierer.orchestrator import Kontrollierer+from jarvis.missions.manager import MissionManager+from jarvis.missions.recovery import startup_recover+from jarvis.missions.state_machine import MissionState, is_terminal, transition+from jarvis.missions.voice.readback import MAX_VOICE_CHARS, render_capacity_wait+from jarvis.missions.workers.api_agent_worker import ApiAgentWorker+from jarvis.missions.workers.claude_direct_worker import ClaudeDirectWorker+from jarvis.missions.workers.codex_direct_worker import CodexDirectWorker++# --- State machine ------------------------------------------------------------+++def test_waiting_capacity_is_not_terminal() -> None:+ assert not is_terminal(MissionState.WAITING_CAPACITY)+++ "src", [MissionState.RUNNING, MissionState.CRITIQUING, MissionState.LOOPING]+)+def test_active_states_can_park(src: MissionState) -> None:+ assert transition(src, MissionState.WAITING_CAPACITY)+++ "dst", [MissionState.RUNNING, MissionState.CANCELLED, MissionState.FAILED]+)+def test_parked_mission_can_resume_or_end(dst: MissionState) -> None:+ assert transition(MissionState.WAITING_CAPACITY, dst)+++# --- Pinning signal -----------------------------------------------------------+++def test_subscription_worker_is_always_pinned() -> None:+ assert pinned_to_subscription(configured_is_subscription=True) is True+++def test_key_only_install_is_not_pinned() -> None:+ """No subscription ever seen: the single-key fallback chain stays (AP-22)."""+ assert pinned_to_subscription(configured_is_subscription=False) is False+++def test_connected_subscription_pins_every_worker() -> None:+ from jarvis.brain import background_policy++ background_policy.note_connected("claude-cli")+ assert pinned_to_subscription(configured_is_subscription=False) is True+++def test_unreadable_signal_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:+ def _boom(*_a: object, **_k: object) -> bool:+ raise OSError("marker unreadable")++ monkeypatch.setattr("jarvis.brain.background_policy.subscription_mode", _boom)+ assert pinned_to_subscription(configured_is_subscription=False) is True+++# --- Worker factory: pinned resolution ----------------------------------------+++def _set_claude_world(+ monkeypatch: pytest.MonkeyPatch, *, cooldown: bool = False+) -> None:+ monkeypatch.setattr(+ "jarvis.claude_quota_state.claude_in_quota_cooldown", lambda **_k: cooldown+ )+++def test_pinned_claude_runs_claude_without_backend_fallback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _set_claude_world(monkeypatch)+ worker = mi._pinned_claude_worker(None, binary_present=True, login=True)+ assert isinstance(worker, ClaudeDirectWorker)+ assert worker.backend_fallback is False+++def test_pinned_claude_in_quota_cooldown_parks(monkeypatch: pytest.MonkeyPatch) -> None:+ _set_claude_world(monkeypatch, cooldown=True)+ with pytest.raises(WorkerCapacityUnavailable) as exc:+ mi._pinned_claude_worker(None, binary_present=True, login=True)+ assert exc.value.reason == "provider_quota"+ assert exc.value.provider == "claude"++[email protected]("login", [False, None])+def test_pinned_claude_without_live_login_parks(+ monkeypatch: pytest.MonkeyPatch, login: bool | None+) -> None:+ """A dead or absent subscription login never falls back to the API key."""+ _set_claude_world(monkeypatch)+ with pytest.raises(WorkerCapacityUnavailable) as exc:+ mi._pinned_claude_worker(None, binary_present=True, login=login)+ assert exc.value.reason == "provider_auth"+++def test_pinned_claude_without_cli_does_not_use_the_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _set_claude_world(monkeypatch)+ with pytest.raises(WorkerCapacityUnavailable) as exc:+ mi._pinned_claude_worker(None, binary_present=False, login=None)+ assert exc.value.reason == "provider_unavailable"+++ "reauth,capped,reason",+ [(True, False, "provider_auth"), (False, True, "provider_quota")],+)+def test_pinned_codex_parks_instead_of_switching_to_claude(+ monkeypatch: pytest.MonkeyPatch, reauth: bool, capped: bool, reason: str+) -> None:+ monkeypatch.setattr("jarvis.codex_auth_state.codex_needs_reauth", lambda: reauth)+ monkeypatch.setattr(+ "jarvis.codex_quota_state.codex_in_quota_cooldown", lambda **_k: capped+ )+ with pytest.raises(WorkerCapacityUnavailable) as exc:+ mi._pinned_codex_worker(None)+ assert exc.value.reason == reason+ assert exc.value.provider == "codex"+++def test_pinned_codex_runs_codex_without_backend_fallback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("jarvis.codex_auth_state.codex_needs_reauth", lambda: False)+ monkeypatch.setattr(+ "jarvis.codex_quota_state.codex_in_quota_cooldown", lambda **_k: False+ )+ worker = mi._pinned_codex_worker(None)+ assert isinstance(worker, CodexDirectWorker)+ assert worker.backend_fallback is False+++def test_pinned_api_provider_without_key_does_not_cross_families(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(mi, "_api_key_family_viable", lambda _p: False)+ monkeypatch.setattr(mi, "_assemble_worker_mcp_servers", lambda **_k: ())++ def _forbidden(*_a: object, **_k: object) -> None:+ raise AssertionError("a pinned mission must not cross provider families")++ monkeypatch.setattr(mi, "_cross_family_last_resort_worker", _forbidden)+ with pytest.raises(WorkerCapacityUnavailable) as exc:+ mi._resolve_api_agent_worker("openrouter", "task", pinned=True)+ assert exc.value.provider == "openrouter"+++def test_pinned_api_provider_with_key_runs_on_its_own_key(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The user picked that API provider themselves — running it is no switch."""+ monkeypatch.setattr(mi, "_api_key_family_viable", lambda _p: True)+ monkeypatch.setattr(mi, "_assemble_worker_mcp_servers", lambda **_k: ())+ worker = mi._resolve_api_agent_worker("openrouter", "task", pinned=True)+ assert isinstance(worker, ApiAgentWorker)+ assert worker.provider == "openrouter"+++def test_last_resort_skips_metered_keys_when_not_allowed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ "jarvis.missions.workers.claude_direct_worker._resolve_claude_binary",+ lambda: None,+ )+ monkeypatch.setattr(+ "jarvis.missions.workers.codex_direct_worker._codex_oauth_available",+ lambda: False,+ )+ monkeypatch.setattr(mi, "_api_key_family_viable", lambda _p: True)+ monkeypatch.setattr(mi, "_assemble_worker_mcp_servers", lambda **_k: ())+ assert mi._cross_family_last_resort_worker("t", allow_metered=False) is None+ # Unpinned (key-only install) behaviour is unchanged.+ assert isinstance(mi._cross_family_last_resort_worker("t"), ApiAgentWorker)+++# --- Workers honour backend_fallback=False ------------------------------------++[email protected]("cls", [ClaudeDirectWorker, CodexDirectWorker])+async def test_pinned_worker_disables_its_cross_backend_fallback(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cls: type+) -> None:+ seen: dict[str, Any] = {}++ async def _fake_spawn_bound(self: Any, prompt: str, **kwargs: Any) -> AsyncIterator[Any]:+ seen.update(kwargs)+ if False: # pragma: no cover - makes this an async generator+ yield None++ monkeypatch.setattr(cls, "_spawn_bound", _fake_spawn_bound)+ worker = cls(backend_fallback=False)++ class _Binding:+ def close(self) -> None:+ return None++ async for _ev in worker.spawn(+ "p",+ worktree=tmp_path,+ env={},+ job=None,+ worker_id="w",+ log_dir=tmp_path,+ _broker_binding=_Binding(),+ ):+ pass+ assert seen["allow_backend_fallback"] is False+++# --- Orchestrator: parking with a checkpoint ----------------------------------+++@dataclass+class _ResultEvent:+ type: str = "result"+ cost_usd: float = 0.0+ total_tokens: int = 0+ session_id: str | None = "s"+ is_error: bool = False+ result: str = ""+ subtype: str = "success"+++class _QuotaWorker:+ """Every spawn ends on a spent subscription window with no output."""++ cli = "claude"+ provider = "claude"++ def __init__(self) -> None:+ self.last_pid = 4242+ self.spawns = 0++ async def spawn(self, prompt: str, *, log_dir: Path, **_k: Any) -> AsyncIterator[Any]:+ self.spawns += 1+ _write_log(log_dir)+ yield _ResultEvent(+ is_error=True,+ subtype="error_during_execution",+ result="You've hit your session limit · resets 11:10pm",+ )+++class _OkWorker:+ cli = "claude"++ def __init__(self) -> None:+ self.last_pid = 4243++ async def spawn(self, prompt: str, *, log_dir: Path, **_k: Any) -> AsyncIterator[Any]:+ _write_log(log_dir)+ yield _ResultEvent()+++class _ApproveCritic:+ def __init__(self) -> None:+ self.calls = 0++ async def run(self, **_k: Any) -> CriticVerdict:+ self.calls += 1+ return CriticVerdict(+ verdict="approve",+ axes={ax: CriticAxis(status="pass", evidence=["x:1"]) for ax in REQUIRED_AXES},+ issues=[],+ correction_instruction="",+ summary="ok",+ summary_de="ok",+ confidence=0.9,+ suggested_next_action="accept",+ )+++class _Decomposer:+ def __init__(self, plan: MissionPlan) -> None:+ self._plan = plan++ async def decompose(self, _prompt: str) -> MissionPlan:+ return self._plan+++class _Job:+ async def __aenter__(self) -> _Job:+ return self++ async def __aexit__(self, *_a: object) -> None:+ return None++ def assign(self, _pid: int) -> None:+ return None+++class _Worktrees:+ def __init__(self, base: Path) -> None:+ self._base = base++ def create(self, *, task_id: str, **_k: Any) -> Path:+ wt = self._base / task_id[:13]+ wt.mkdir(parents=True, exist_ok=True)+ return wt++ def remove(self, _path: Path, **_k: Any) -> None:+ return None+++async def manager(tmp_missions_db: Path):+ m = MissionManager(tmp_missions_db)+ await m.start()+ yield m+ await m.stop()+++def _kontrollierer(+ manager: MissionManager, tmp_path: Path, plan: MissionPlan, factory: Any, critic: Any+) -> Kontrollierer:+ return Kontrollierer(+ manager=manager,+ decomposer=_Decomposer(plan), # type: ignore[arg-type]+ critic_runner=critic, # type: ignore[arg-type]+ worktree_mgr=_Worktrees(tmp_path / "worktrees"), # type: ignore[arg-type]+ env_builder=lambda _p: {},+ budget=BudgetTracker(per_mission_usd=10.0, daily_usd=100.0),+ worker_factory=factory,+ job_factory=_Job,+ isolation_root=tmp_path / "missions",+ )+++def _read_json(path: Path) -> dict[str, Any]:+ return json.loads(path.read_text(encoding="utf-8"))+++def _write_log(log_dir: Path) -> None:+ log_dir.mkdir(parents=True, exist_ok=True)+ (log_dir / "stream.jsonl").write_text("{}\n", encoding="utf-8")+++async def _events(manager: MissionManager, mid: str) -> list[Any]:+ return [e.payload for e in await manager.store.events_for_mission(mid)]+++async def test_spent_quota_parks_mission_with_checkpoint(+ manager: MissionManager, tmp_path: Path+) -> None:+ worker = _QuotaWorker()+ plan = MissionPlan(steps=[Step(slug="task", prompt="do it")], n_workers=1)+ k = _kontrollierer(manager, tmp_path, plan, lambda _s: worker, _ApproveCritic())+ mid = await manager.dispatch(prompt="write the report")++ state = await k.run_mission(mid)++ assert state == MissionState.WAITING_CAPACITY+ view = await manager.mission(mid)+ assert view is not None and view.state == MissionState.WAITING_CAPACITY+ payloads = await _events(manager, mid)+ assert not any(p.event_type == "MissionFailed" for p in payloads)+ waits = [p for p in payloads if isinstance(p, MissionWaitingCapacity)]+ assert len(waits) == 1+ wait = waits[0]+ assert wait.reason == "provider_quota"+ assert (wait.steps_done, wait.steps_total) == (0, 1)+ checkpoint = Path(wait.checkpoint_path)+ assert checkpoint.name == CHECKPOINT_NAME+ data = _read_json(checkpoint)+ assert data["version"] == capacity.CHECKPOINT_VERSION+ assert data["prompt"] == "write the report"+ assert data["steps"][0]["prompt"] == "do it"+ assert data["steps"][0]["done"] is False+++async def test_factory_refusal_parks_without_spawning(+ manager: MissionManager, tmp_path: Path+) -> None:+ def _factory(_step: Step) -> Any:+ raise WorkerCapacityUnavailable("provider_auth", "codex")++ plan = MissionPlan(steps=[Step(slug="task", prompt="do it")], n_workers=1)+ critic = _ApproveCritic()+ k = _kontrollierer(manager, tmp_path, plan, _factory, critic)+ mid = await manager.dispatch(prompt="p")++ assert await k.run_mission(mid) == MissionState.WAITING_CAPACITY+ assert critic.calls == 0+ wait = next(+ p for p in await _events(manager, mid) if isinstance(p, MissionWaitingCapacity)+ )+ assert (wait.reason, wait.provider) == ("provider_auth", "codex")+++async def test_finished_steps_are_kept_and_counted(+ manager: MissionManager, tmp_path: Path+) -> None:+ ok, blocked = Step(slug="first", prompt="one"), Step(slug="second", prompt="two")++ def _factory(step: Step) -> Any:+ if step.task_id == blocked.task_id:+ raise WorkerCapacityUnavailable("provider_quota", "claude")+ return _OkWorker()++ plan = MissionPlan(steps=[ok, blocked], n_workers=1)+ k = _kontrollierer(manager, tmp_path, plan, _factory, _ApproveCritic())+ mid = await manager.dispatch(prompt="p")++ assert await k.run_mission(mid) == MissionState.WAITING_CAPACITY+ wait = next(+ p for p in await _events(manager, mid) if isinstance(p, MissionWaitingCapacity)+ )+ assert (wait.steps_done, wait.steps_total) == (1, 2)+ data = _read_json(Path(wait.checkpoint_path))+ assert [s["done"] for s in data["steps"]] == [True, False]+++async def test_parked_mission_can_be_cancelled(+ manager: MissionManager, tmp_path: Path+) -> None:+ def _factory(_step: Step) -> Any:+ raise WorkerCapacityUnavailable("provider_quota", "claude")++ plan = MissionPlan(steps=[Step(slug="task", prompt="x")], n_workers=1)+ k = _kontrollierer(manager, tmp_path, plan, _factory, _ApproveCritic())+ mid = await manager.dispatch(prompt="p")+ await k.run_mission(mid)++ await manager.transition_state(mid, MissionState.CANCELLED, reason="ui_cancel")+ view = await manager.mission(mid)+ assert view is not None and view.state == MissionState.CANCELLED+++# --- Restart and cleanup leave a parked mission alone -------------------------+++async def test_recovery_never_sweeps_a_parked_mission(+ manager: MissionManager, tmp_path: Path+) -> None:+ def _factory(_step: Step) -> Any:+ raise WorkerCapacityUnavailable("provider_quota", "claude")++ plan = MissionPlan(steps=[Step(slug="task", prompt="x")], n_workers=1)+ k = _kontrollierer(manager, tmp_path, plan, _factory, _ApproveCritic())+ mid = await manager.dispatch(prompt="p")+ await k.run_mission(mid)++ far_future = 10**15+ swept = await startup_recover(+ manager.store, now=far_future, owner_alive_fn=lambda _pid, _start: False+ )++ assert mid not in swept+ view = await manager.mission(mid)+ assert view is not None and view.state == MissionState.WAITING_CAPACITY+++def test_cleanup_keeps_a_checkpointed_mission(tmp_path: Path) -> None:+ from jarvis.missions.cleanup import _holds_deliverables++ entry = tmp_path / "mission_019f0000-0000"+ entry.mkdir()+ assert _holds_deliverables(entry) is False+ capacity.write_checkpoint(entry, {"mission_id": "m"})+ assert _holds_deliverables(entry) is True+++# --- Readback -----------------------------------------------------------------++[email protected]("lang", ["de", "en"])+def test_readback_says_why_progress_and_options(lang: str) -> None:+ text = render_capacity_wait(+ reason="provider_quota",+ provider="claude",+ steps_done=1,+ steps_total=3,+ files_saved=2,+ checkpoint_saved=True,+ language=lang, # type: ignore[arg-type]+ )+ assert "Claude" in text+ assert "1" in text and "3" in text and "2" in text+ assert "API" in text+ assert len(text) <= MAX_VOICE_CHARS+++def test_readback_keeps_the_options_under_the_length_cap() -> None:+ text = render_capacity_wait(+ reason="provider_unavailable",+ provider="a-very-long-provider-slug-" * 4,+ steps_done=123,+ steps_total=456,+ files_saved=789,+ checkpoint_saved=True,+ language="de",+ )+ assert len(text) <= MAX_VOICE_CHARS+ assert text.endswith("Freigabe.") # i18n-allow: German TTS phrase under testdiff --git a/tests/missions/test_capacity_wait_parity.py b/tests/missions/test_capacity_wait_parity.pynew file mode 100644index 0000000000..3b3a2f47d8--- /dev/null+++ b/tests/missions/test_capacity_wait_parity.py@@ -0,0 +1,72 @@+"""Five-layer parity for WAITING_CAPACITY (AP-4).++The parked state and its reason vocabulary cross Python (state machine, event+payload, voice phrases), SQL (the state column), TypeScript (missions.ts) and+the UI (badge + i18n). A value added on one side only is the BUG-008 drift+class: the frontend parser rejects the envelope or a badge renders a raw key.+"""+from __future__ import annotations++import json+import re+from pathlib import Path+from typing import get_args++import pytest++from jarvis.missions.events import CAPACITY_WAIT_REASONS, MissionWaitingCapacity+from jarvis.missions.state_machine import MissionState+from jarvis.missions.voice.readback import CAPACITY_WAIT_PHRASES++_FRONTEND = Path(__file__).resolve().parents[2] / "jarvis" / "ui" / "web" / "frontend" / "src"+_MISSIONS_TS = (_FRONTEND / "types" / "missions.ts").read_text(encoding="utf-8")+_LOCALES = ("de", "en", "es")+++def _ts_union(name: str) -> set[str]:+ m = re.search(rf"export type {name}\s*=([^;]+);", _MISSIONS_TS)+ assert m, f"{name} union not found in missions.ts"+ return set(re.findall(r'"([^"]+)"', m.group(1)))+++def _locale(lang: str) -> dict:+ return json.loads((_FRONTEND / "i18n" / "locales" / f"{lang}.json").read_text(encoding="utf-8"))+++def test_mission_state_python_ts_parity() -> None:+ py = {s.value for s in MissionState}+ ts = _ts_union("MissionState")+ assert py == ts, f"state drift — python-only={py - ts}, ts-only={ts - py}"+++def test_reason_vocabulary_python_ts_parity() -> None:+ payload_reasons = set(get_args(MissionWaitingCapacity.model_fields["reason"].annotation))+ assert payload_reasons == set(CAPACITY_WAIT_REASONS)+ assert _ts_union("CapacityWaitReason") == set(CAPACITY_WAIT_REASONS)+++def test_event_type_listed_in_ts() -> None:+ assert "MissionWaitingCapacity" in _ts_union("EventType")++[email protected]("lang", ["de", "en"])+def test_voice_phrases_cover_every_reason(lang: str) -> None:+ assert set(CAPACITY_WAIT_REASONS) <= set(CAPACITY_WAIT_PHRASES[lang])+++def test_voice_phrase_tables_share_keys() -> None:+ assert set(CAPACITY_WAIT_PHRASES["de"]) == set(CAPACITY_WAIT_PHRASES["en"])++[email protected]("lang", _LOCALES)+def test_ui_locales_cover_badge_and_reasons(lang: str) -> None:+ data = _locale(lang)+ assert data["mission_state"]["waiting_capacity"]+ card = data["missions_view"]["capacity_wait"]+ for reason in CAPACITY_WAIT_REASONS:+ assert "{provider}" in card[reason]+++def test_ui_locales_share_capacity_keys() -> None:+ keys = [set(_locale(lang)["missions_view"]["capacity_wait"]) for lang in _LOCALES]+ assert all(k == keys[0] for k in keys)