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): resume WAITING_CAPACITY missions from their checkpoint
Dennis Heide de Ramirez31c695e6d58b
diff --git a/jarvis/missions/capacity.py b/jarvis/missions/capacity.pyindex 1d89a5ab84..7e4627f609 100644--- a/jarvis/missions/capacity.py+++ b/jarvis/missions/capacity.py@@ -21,10 +21,13 @@ work", AP-22)."""from __future__ import annotations+import asyncioimport jsonimport loggingimport os+import randomimport tempfile+from collections.abc import Awaitable, Callablefrom pathlib import Pathfrom typing import Any, Literal@@ -39,6 +42,15 @@ CHECKPOINT_NAME = "checkpoint.json"#: Bumped when the checkpoint layout changes incompatibly.CHECKPOINT_VERSION = 1+#: How often parked missions are re-checked for returned capacity. The check+#: itself is offline (quota cooldowns, login state), so it costs nothing; a+#: subscription window resets on a scale of minutes to hours.+RESUME_INTERVAL_S = 300.0++#: Random extra delay per tick so instances and windows never fire in lockstep+#: (AP-33).+RESUME_JITTER_S = 60.0+class WorkerCapacityUnavailable(RuntimeError):"""Raised by the worker factory instead of picking a worker that would bill@@ -77,6 +89,17 @@ def pinned_to_subscription(*, configured_is_subscription: bool) -> bool:return True+def worker_family(worker: object) -> str:+ """The provider family a worker bills — the identity a parked mission is+ pinned to. Every built-in worker declares ``family``; anything else falls+ back to its ``provider``/``cli`` attribute."""+ for attr in ("family", "provider", "cli"):+ value = getattr(worker, attr, None)+ if isinstance(value, str) and value.strip():+ return value.strip().lower()+ return type(worker).__name__++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)@@ -93,11 +116,56 @@ def write_checkpoint(mission_dir: Path, data: dict[str, Any]) -> Path:return path+def read_checkpoint(mission_dir: Path) -> dict[str, Any] | None:+ """The stored checkpoint, or None when it is missing or unreadable."""+ path = mission_dir / CHECKPOINT_NAME+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return None+ except (OSError, ValueError):+ log.warning("capacity: unreadable checkpoint %s", path, exc_info=True)+ return None+ return data if isinstance(data, dict) else None+++async def capacity_resume_loop(+ resume_pass: Callable[[], Awaitable[list[str]]],+ *,+ interval_s: float = RESUME_INTERVAL_S,+ jitter_s: float = RESUME_JITTER_S,+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,+ jitter: Callable[[float, float], float] = random.uniform,+) -> None:+ """Run ``resume_pass`` on a jittered timer until cancelled.++ The first pass waits one interval: nothing here belongs on the boot+ critical path (AP-26). A failing pass is logged and the loop carries on —+ one bad tick must not stop every later resume.+ """+ while True:+ await sleep(interval_s + jitter(0.0, jitter_s))+ try:+ resumed = await resume_pass()+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 - logged; the next tick retries+ log.exception("capacity: resume pass failed")+ continue+ if resumed:+ log.info("capacity: resumed %d parked mission(s): %s", len(resumed), resumed)++__all__ = ["CHECKPOINT_NAME","CHECKPOINT_VERSION",+ "RESUME_INTERVAL_S",+ "RESUME_JITTER_S","CapacityWaitReason","WorkerCapacityUnavailable",+ "capacity_resume_loop","pinned_to_subscription",+ "read_checkpoint",+ "worker_family","write_checkpoint",]diff --git a/jarvis/missions/events.py b/jarvis/missions/events.pyindex 5f9442263f..40b1878e52 100644--- a/jarvis/missions/events.py+++ b/jarvis/missions/events.py@@ -181,6 +181,11 @@ class MissionWaitingCapacity(_PayloadBase):files_saved: int = 0checkpoint_path: str = ""error_detail: str | None = None+ # 0 for the first pause; N after the Nth automatic resume parked again.+ resume_attempt: int = 0+ # True when a resume attempt parked again without finishing another step:+ # nothing new to tell, so the voice layer stays silent.+ repeat: bool = Falseclass MissionCancelled(_PayloadBase):diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.pyindex bc7bc52d3c..b898af9afa 100644--- a/jarvis/missions/kontrollierer/orchestrator.py+++ b/jarvis/missions/kontrollierer/orchestrator.py@@ -37,7 +37,12 @@ from typing import Any, Final, Literalfrom ...core.process_utils import NO_WINDOW_CREATIONFLAGSfrom ..budget import BudgetExceeded, BudgetTracker-from ..capacity import WorkerCapacityUnavailable, write_checkpoint+from ..capacity import (+ WorkerCapacityUnavailable,+ read_checkpoint,+ worker_family,+ write_checkpoint,+)from ..critic.escalation import FRONTIER_MODELfrom ..critic.reflections import ReflectionMemoryfrom ..critic.runner import MAX_CRITIC_LOOPS, CriticRunner@@ -148,6 +153,14 @@ _TASK_TIME_BUDGET_S: float = 1380.0# One critic subprocess call (mirrors critic.runner.DEFAULT_TIMEOUT_SECONDS)._CRITIC_TIME_RESERVE_S: float = 240.0+# Leads the first worker prompt of a step resumed from a capacity checkpoint.+_RESUME_NOTE: Final[str] = (+ "RESUMED TASK: this workspace already contains the partial work of an "+ "earlier attempt at this task, which stopped when the provider ran out of "+ "capacity. Inspect it and continue from it; do not start over or redo "+ "finished parts."+)+def _worker_error_is_transient(err: str) -> bool:"""True when a worker's terminal error is a passing condition, not a fault.@@ -395,6 +408,30 @@ def _real_diff_is_empty(diff_text: str) -> bool:_EXTERNAL_VERIFY_MAX_CHARS: Final[int] = 8000+def _plan_from_checkpoint(checkpoint: dict[str, Any] | None) -> MissionPlan | None:+ """The plan a parked mission was running, or None if the checkpoint has none."""+ raw = checkpoint.get("plan") if checkpoint else None+ if not isinstance(raw, dict):+ return None+ try:+ return MissionPlan.model_validate(raw)+ except ValueError: # pydantic.ValidationError is a ValueError+ logger.warning("Checkpoint plan does not validate", exc_info=True)+ return None+++def _done_task_ids(checkpoint: dict[str, Any]) -> set[str]:+ """Task ids a checkpoint records as approved — never run again."""+ steps = checkpoint.get("steps")+ if not isinstance(steps, list):+ return set()+ return {+ str(step["task_id"])+ for step in steps+ if isinstance(step, dict) and step.get("done") is True and step.get("task_id")+ }++def _path_is_within(child: Path, parent: Path) -> bool:"""True if ``child`` is ``parent`` or lives somewhere beneath it.@@ -847,6 +884,12 @@ class Kontrollierer:# 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]] = {}+ # Missions resumed from a capacity checkpoint: the provider family they+ # are pinned to (no other family runs them without approval), which+ # resume attempt this is, and how many steps were done before it.+ self._resume_family: dict[str, str] = {}+ self._resume_attempt: dict[str, int] = {}+ self._resume_done_before: dict[str, int] = {}# 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@@ -990,7 +1033,13 @@ class Kontrollierer:# Error states (FAILED / TIMED_OUT / ESCALATED / ORCHESTRATOR_CRASH)# stay re-runnable ON PURPOSE: a crash_recovery'd mission must still be# retryable to completion (test_recovery_then_rerun_is_idempotent).- if view.state in (MissionState.APPROVED, MissionState.CANCELLED):+ # A parked mission continues only through `resume_mission`, from its+ # checkpoint — a fresh run would re-plan and redo finished steps.+ if view.state in (+ MissionState.APPROVED,+ MissionState.CANCELLED,+ MissionState.WAITING_CAPACITY,+ ):logger.info("run_mission: %s already %s — skipping re-run",mission_id, view.state.value,@@ -1025,6 +1074,25 @@ class Kontrollierer:",".join(step.slug for step in plan.steps),plan.expected_output,)+ return await self._execute_plan(mission_id, view.prompt, plan)++ async def _execute_plan(+ self,+ mission_id: str,+ prompt: str,+ plan: MissionPlan,+ *,+ done_task_ids: frozenset[str] = frozenset(),+ restore_dirs: dict[str, Path] | None = None,+ ) -> MissionState:+ """Run the plan's open steps, then aggregate every step's outcome.++ ``done_task_ids`` are steps a checkpoint records as approved: they are+ not run again and count as approved. ``restore_dirs`` maps an open+ step to the artifacts its earlier attempt archived, restored into the+ fresh workspace before the worker starts (see ``resume_mission``).+ """+ restore_dirs = restore_dirs or {}# Mission directory for reflections + logs.# 2026-05-17 (BUG-LIVE-10): UUID7 IDs share the first 8 hex chars@@ -1040,17 +1108,22 @@ 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] = {}+ step_outcomes: dict[str, str] = {+ tid: TaskOutcome.APPROVED+ for tid in done_task_ids+ if any(step.task_id == tid for step in plan.steps)+ }+ task_outcomes: list[str] = list(step_outcomes.values())async def _run(step: Step) -> None:outcome = await self._run_task_with_critic_loop(mission_id=mission_id,- mission_prompt=view.prompt,+ mission_prompt=prompt,step=step,mission_dir=mission_dir,reflections=reflections,sem=sem,+ restore_dir=restore_dirs.get(step.task_id),)task_outcomes.append(outcome)step_outcomes[step.task_id] = outcome@@ -1064,6 +1137,8 @@ class Kontrollierer:async with asyncio.timeout(self._mission_deadline_s):async with asyncio.TaskGroup() as tg:for step in plan.steps:+ if step.task_id in step_outcomes:+ continue # approved in an earlier runtg.create_task(_run(step), name=f"task-{step.task_id[:13]}")except TimeoutError:# The mission ran past its wall-clock deadline. TaskGroup@@ -1092,7 +1167,7 @@ class Kontrollierer:await self._fail_mission(mission_id, "task_error")return MissionState.FAILEDif all(o == TaskOutcome.APPROVED for o in task_outcomes):- await self._approve_mission(mission_id, plan, prompt=view.prompt)+ await self._approve_mission(mission_id, plan, prompt=prompt)return MissionState.APPROVED# Which task failed determines the failure reason.@@ -1112,7 +1187,7 @@ class Kontrollierer:return await self._park_mission(mission_id,plan,- prompt=view.prompt,+ prompt=prompt,step_outcomes=step_outcomes,partial_artifacts=partial,)@@ -1191,8 +1266,14 @@ class Kontrollierer:mission_dir: Path,reflections: ReflectionMemory,sem: asyncio.Semaphore,+ restore_dir: Path | None = None,) -> str:- """Runs a step through the Worker+Critic loop (max MAX_CRITIC_LOOPS)."""+ """Runs a step through the Worker+Critic loop (max MAX_CRITIC_LOOPS).++ ``restore_dir`` is this step's archived artifacts from a run that was+ parked for capacity; its work is put back into the fresh workspace so+ the worker continues instead of starting over.+ """async with sem:try:# Pre-spawn budget check — do not start a worker if already over.@@ -1256,6 +1337,12 @@ class Kontrollierer:worktree, exc_info=True,)+ restored = False+ if restore_dir is not None:+ restored = await asyncio.to_thread(+ self._restore_task_workspace, worktree, restore_dir+ )+try:return await self._run_iterations(mission_id=mission_id,@@ -1264,6 +1351,7 @@ class Kontrollierer:mission_dir=mission_dir,worktree=worktree,reflections=reflections,+ resumed=restored,)finally:# Archive + teardown run in a worker thread (git and file@@ -1319,9 +1407,11 @@ class Kontrollierer:mission_dir: Path,worktree: Path,reflections: ReflectionMemory,+ resumed: bool = False,) -> str:"""Inner critic-loop body. Extracted so the worktree-finally in the- caller wraps every return path."""+ caller wraps every return path. ``resumed`` means the workspace holds+ restored partial work from a parked run (see ``resume_mission``)."""# Anchor for the per-task time budget (queue wait excluded — the# caller already holds the concurrency semaphore, mirroring# _MISSION_DEADLINE_S semantics).@@ -1350,6 +1440,8 @@ class Kontrollierer:for iteration in range(MAX_CRITIC_LOOPS):# Per-iteration: render reflections, spawn worker, capture diff+logprior_block = reflections.render_for_worker_prompt(n=3)+ if resumed and iteration == 0:+ prior_block = "\n\n".join(b for b in (_RESUME_NOTE, prior_block) if b)# Lead every worker prompt with the artifact-language directive so# generated code defaults to English regardless of the request# language (the German-request -> German-code leak). This is the one@@ -1407,6 +1499,7 @@ class Kontrollierer:# that refuses to switch to a billing fallback parks the task.try:worker = self._worker_factory(step)+ self._check_resume_family(mission_id, worker)except WorkerCapacityUnavailable as exc:logger.warning("Task %s iter %d: no worker capacity (%s) — parking the "@@ -1679,10 +1772,7 @@ class Kontrollierer:if error_class == "provider_quota":self._capacity_wait[mission_id] = {"reason": "provider_quota",- "provider": (- getattr(worker, "provider", None)- or getattr(worker, "cli", None)- ),+ "provider": worker_family(worker),"error_detail": error_detail,}return TaskOutcome.WAITING_CAPACITY@@ -2908,6 +2998,229 @@ class Kontrollierer:)return False+ # --- Capacity resume ----------------------------------------------------++ async def resume_waiting_missions(self) -> list[str]:+ """One pass over parked missions: resume each whose provider has+ capacity again.++ Sequential on purpose — resumed missions must not compete for the one+ subscription window that just came back. Returns the resumed ids.+ """+ resumed: list[str] = []+ for mission_id, _prompt, state in await self._manager.store.list_non_terminal_missions():+ if state != MissionState.WAITING_CAPACITY.value:+ continue+ if mission_id in self._running_missions:+ continue+ if not await self._capacity_is_back(mission_id):+ continue+ # Its own task, shielded: cancelling the timer loop on shutdown+ # must not tear a resumed mission down half-way. The shutdown path+ # (`cancel_all_running`) finalizes it like any in-flight mission.+ task = asyncio.create_task(+ self.resume_mission(mission_id), name=f"mission-resume-{mission_id[:13]}"+ )+ await asyncio.shield(task)+ resumed.append(mission_id)+ return resumed++ async def _capacity_is_back(self, mission_id: str) -> bool:+ """Whether the worker a parked mission is pinned to can run again.++ Asks the worker factory — the same offline rules (quota cooldowns,+ login state, key viability) that parked the mission, so the check+ never calls a provider. A factory answer on a DIFFERENT provider+ family is not capacity: switching needs the user's approval.+ """+ mission_dir = self._isolation_root / f"mission_{mission_id[:13]}"+ checkpoint = await asyncio.to_thread(read_checkpoint, mission_dir)+ plan = _plan_from_checkpoint(checkpoint)+ if checkpoint is None or plan is None:+ return True # resume_mission fails it honestly (checkpoint_missing)+ done = _done_task_ids(checkpoint)+ open_steps = [step for step in plan.steps if step.task_id not in done]+ if not open_steps:+ return True+ try:+ worker = await asyncio.to_thread(self._worker_factory, open_steps[0])+ except WorkerCapacityUnavailable:+ return False+ except Exception: # noqa: BLE001 - a broken probe means "not yet", logged+ logger.warning(+ "Mission %s: capacity probe failed — staying parked", mission_id,+ exc_info=True,+ )+ return False+ pinned = checkpoint.get("provider")+ family = worker_family(worker)+ if isinstance(pinned, str) and pinned and family != pinned:+ logger.warning(+ "Mission %s stays parked: it is pinned to %s, the configured "+ "worker is now %s — switching provider needs approval",+ mission_id, pinned, family,+ )+ return False+ return True++ async def resume_mission(self, mission_id: str) -> MissionState:+ """Continue a WAITING_CAPACITY mission exactly from its checkpoint.++ Steps the checkpoint records as approved are not run again; open+ steps get their archived partial work restored into a fresh workspace,+ and the critic's earlier reflections still lead their prompts. Tracked+ in ``_running_missions`` like ``run_mission`` so cancel and shutdown+ reach it.+ """+ if mission_id in self._running_missions:+ # Already running here (a resume or a run) — that caller owns the+ # mission and its tracking; a second resume must not touch either.+ view = await self._manager.mission(mission_id)+ return view.state if view is not None else MissionState.FAILED+ task = asyncio.current_task()+ if task is not None:+ self._running_missions[mission_id] = task+ try:+ return await self._resume_mission_inner(mission_id)+ finally:+ if self._running_missions.get(mission_id) is task:+ self._running_missions.pop(mission_id, None)+ self._resume_family.pop(mission_id, None)+ self._resume_attempt.pop(mission_id, None)+ self._resume_done_before.pop(mission_id, None)++ async def _resume_mission_inner(self, mission_id: str) -> MissionState:+ view = await self._manager.mission(mission_id)+ if view is None:+ raise KeyError(f"Mission not found: {mission_id}")+ if view.state != MissionState.WAITING_CAPACITY:+ logger.info(+ "resume_mission: %s is %s, not parked — nothing to resume",+ mission_id, view.state.value,+ )+ return view.state++ mission_dir = self._isolation_root / f"mission_{mission_id[:13]}"+ checkpoint = await asyncio.to_thread(read_checkpoint, mission_dir)+ plan = _plan_from_checkpoint(checkpoint)+ if checkpoint is None or plan is None:+ logger.error(+ "resume_mission: %s has no usable checkpoint in %s — cannot "+ "continue exactly where it stopped",+ mission_id, mission_dir,+ )+ await self._fail_mission(mission_id, "checkpoint_missing")+ return MissionState.FAILED++ plan_ids = {step.task_id for step in plan.steps}+ done = _done_task_ids(checkpoint) & plan_ids+ restore_dirs: dict[str, Path] = {}+ for step in plan.steps:+ artifacts = mission_dir / "tasks" / step.task_id[:13] / "artifacts"+ if step.task_id not in done and artifacts.is_dir():+ restore_dirs[step.task_id] = artifacts++ # The claim: only the caller that moves the mission out of+ # WAITING_CAPACITY runs it, so a mission is never resumed twice.+ if not await self._safe_transition(+ mission_id, MissionState.RUNNING, "capacity_resumed"+ ):+ current = await self._manager.mission(mission_id)+ return current.state if current is not None else MissionState.FAILED+ try:+ await self._manager.store.touch_heartbeat(mission_id, now_ms())+ except Exception as hb_exc: # noqa: BLE001 - ownership stamp is advisory+ logger.debug("Resume heartbeat failed (non-fatal): %s", hb_exc)++ pinned = checkpoint.get("provider")+ if isinstance(pinned, str) and pinned:+ self._resume_family[mission_id] = pinned+ attempts = checkpoint.get("resume_attempts")+ self._resume_attempt[mission_id] = (attempts if isinstance(attempts, int) else 0) + 1+ self._resume_done_before[mission_id] = len(done)+ answers = checkpoint.get("task_answers")+ if isinstance(answers, list) and answers:+ self._task_answers[mission_id] = [str(a) for a in answers]++ logger.info(+ "resume_mission: %s resumes on %s — %d/%d step(s) already done, "+ "%d with partial work to restore (attempt %d)",+ mission_id, pinned or "<unknown>", len(done), len(plan.steps),+ len(restore_dirs), self._resume_attempt[mission_id],+ )+ return await self._execute_plan(+ mission_id,+ view.prompt,+ plan,+ done_task_ids=frozenset(done),+ restore_dirs=restore_dirs,+ )++ def _check_resume_family(self, mission_id: str, worker: Any) -> None:+ """A resumed mission runs only on the provider family it was parked+ on; anything else parks it again instead of switching unasked."""+ pinned = self._resume_family.get(mission_id)+ if pinned is None:+ return+ family = worker_family(worker)+ if family != pinned:+ raise WorkerCapacityUnavailable(+ "provider_unavailable",+ pinned,+ f"the configured worker is now {family}; switching needs approval",+ )++ def _restore_task_workspace(self, worktree: Path, artifacts: Path) -> bool:+ """Put a parked step's archived work back into its fresh workspace.++ ``diff.patch`` first (it carries edits to existing files and the full+ content of new ones); when it does not apply — the repository moved+ on since — the ``files/`` deliverable snapshot is copied instead.+ Worker thread only. Returns True when anything was restored.+ """+ try:+ patch = artifacts / "diff.patch"+ if patch.is_file() and patch.stat().st_size > 0:+ result = subprocess.run( # noqa: S603+ ["git", "apply", "--whitespace=nowarn", str(patch)],+ cwd=str(worktree),+ check=False,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=30.0,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ if result.returncode == 0:+ logger.info("Restored partial work into %s from %s", worktree, patch)+ return True+ logger.warning(+ "Partial-work patch %s does not apply (%s) — restoring the "+ "file snapshot instead",+ patch, (result.stderr or "").strip()[:200],+ )+ files_root = artifacts / "files"+ copied = 0+ if files_root.is_dir():+ for src in files_root.rglob("*"):+ if not src.is_file():+ continue+ dst = worktree / src.relative_to(files_root)+ if not _path_is_within(dst, worktree):+ continue+ dst.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(src, dst)+ copied += 1+ if copied:+ logger.info("Restored %d saved file(s) into %s", copied, worktree)+ return copied > 0+ except (OSError, subprocess.SubprocessError):+ # The worker then starts from a clean workspace; the archived work+ # stays on disk untouched.+ logger.warning("Restoring partial work into %s failed", worktree, exc_info=True)+ return False+async def _park_mission(self,mission_id: str,@@ -2924,8 +3237,12 @@ class Kontrollierer:task's ``finally``). The ``MissionWaitingCapacity`` event carries onlycounts and paths, so the voice layer renders it as a static phrase."""- self._task_answers.pop(mission_id, None)+ # Answers of approved read-only steps feed the final summary; they go+ # into the checkpoint so a resumed run can still report them.+ task_answers = self._task_answers.pop(mission_id, [])self._mission_failure_context.pop(mission_id, None)+ attempt = self._resume_attempt.get(mission_id, 0)+ done_before = self._resume_done_before.get(mission_id, 0)wait = self._capacity_wait.pop(mission_id, {})reason = wait.get("reason") or "provider_quota"provider = wait.get("provider")@@ -2966,7 +3283,10 @@ class Kontrollierer:"provider": provider,"error_detail": error_detail,"created_ms": now_ms(),+ "resume_attempts": attempt,+ "plan": plan.model_dump(mode="json"),"steps": steps,+ "task_answers": task_answers,"partial_artifacts": partial_artifacts,},))@@ -2994,6 +3314,8 @@ class Kontrollierer:files_saved=files_saved,checkpoint_path=checkpoint_path,error_detail=error_detail,+ resume_attempt=attempt,+ repeat=attempt > 0 and steps_done <= done_before,),))diff --git a/jarvis/missions/voice/announcer.py b/jarvis/missions/voice/announcer.pyindex c92870eed7..5eabaf799d 100644--- a/jarvis/missions/voice/announcer.py+++ b/jarvis/missions/voice/announcer.py@@ -269,7 +269,10 @@ class MissionAnnouncer: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).+ # for the next turn boundary like a failure (AD-OE5). A resume+ # that parked again with no new step done has nothing new to say.+ if payload.repeat:+ return ("", "normal")return (render_capacity_wait(reason=payload.reason,diff --git a/jarvis/missions/voice/listener.py b/jarvis/missions/voice/listener.pyindex 8e6471c44d..4ab10fba1d 100644--- a/jarvis/missions/voice/listener.py+++ b/jarvis/missions/voice/listener.py@@ -146,6 +146,8 @@ class MissionVoiceListener:return self._readback.render_cancelled(language=lang)if isinstance(payload, MissionWaitingCapacity):+ if payload.repeat:+ return "" # parked again with no new step done: nothing new to sayreturn render_capacity_wait(reason=payload.reason,provider=payload.provider,diff --git a/jarvis/missions/voice/readback.py b/jarvis/missions/voice/readback.pyindex 850a266e9e..545e237182 100644--- a/jarvis/missions/voice/readback.py+++ b/jarvis/missions/voice/readback.py@@ -196,6 +196,9 @@ FAILURE_REASON_PHRASES: Final[dict[str, dict[str, str]]] = {"empty_diff": "Es wurden keine Dateien geschrieben.", # i18n-allow"critic_unavailable": "Der Prüfer ist abgestürzt, die Arbeit liegt im Worktree.", # i18n-allow"worktree_setup_failed": "Ich konnte keinen Arbeitsbereich anlegen.", # i18n-allow+ "checkpoint_missing": (+ "Der gesicherte Zwischenstand fehlt, ich kann nicht fortsetzen." # i18n-allow+ ),"git_missing": "{agents} brauchen eine Git-Installation im PATH.", # i18n-allow"git_not_a_repository": ("{agents} brauchen einen Git-Checkout, bitte über den " # i18n-allow@@ -233,6 +236,7 @@ FAILURE_REASON_PHRASES: Final[dict[str, dict[str, str]]] = {"The reviewer crashed; the work is preserved in the worktree."),"worktree_setup_failed": "I could not create a workspace.",+ "checkpoint_missing": "The saved progress is missing, so I cannot continue.","git_missing": "{agents} require git to be installed and on PATH.","git_not_a_repository": ("{agents} require a git checkout (install via the "diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.pyindex 87b653ca1d..b3530c5498 100644--- a/jarvis/missions/workers/api_agent_worker.py+++ b/jarvis/missions/workers/api_agent_worker.py@@ -249,6 +249,11 @@ class ApiAgentWorker:self.last_session_id: str | None = Noneself.capability_inventory = capability_inventory or WorkerCapabilityInventory.build()+ @property+ def family(self) -> str:+ """Provider family this worker bills (jarvis/missions/capacity.worker_family)."""+ return self.provider+async def spawn(self,prompt: str,diff --git a/jarvis/missions/workers/claude_direct_worker.py b/jarvis/missions/workers/claude_direct_worker.pyindex 651cc5b075..12194a9e2e 100644--- a/jarvis/missions/workers/claude_direct_worker.py+++ b/jarvis/missions/workers/claude_direct_worker.py@@ -275,6 +275,8 @@ class ClaudeDirectWorker:"""cli: ClassVar[Literal["claude", "codex", "python", "browser"]] = "claude"+ # Provider family this worker bills (jarvis/missions/capacity.worker_family).+ family: ClassVar[str] = "claude"def __init__(self,diff --git a/jarvis/missions/workers/codex_direct_worker.py b/jarvis/missions/workers/codex_direct_worker.pyindex a348ffd00b..d527734f74 100644--- a/jarvis/missions/workers/codex_direct_worker.py+++ b/jarvis/missions/workers/codex_direct_worker.py@@ -453,6 +453,8 @@ class CodexDirectWorker:"""cli: ClassVar[Literal["claude", "codex", "python", "browser"]] = "codex"+ # Provider family this worker bills (jarvis/missions/capacity.worker_family).+ family: ClassVar[str] = "codex"def __init__(self,diff --git a/jarvis/missions/workers/gemini_worker.py b/jarvis/missions/workers/gemini_worker.pyindex 567d828667..a71f060944 100644--- a/jarvis/missions/workers/gemini_worker.py+++ b/jarvis/missions/workers/gemini_worker.py@@ -50,7 +50,7 @@ import uuidfrom collections.abc import AsyncIteratorfrom contextlib import suppressfrom pathlib import Path-from typing import Any, Literal+from typing import Any, ClassVar, Literalfrom jarvis.missions.stream_evidence import extract_stream_evidence@@ -284,6 +284,8 @@ class GeminiWorker:"""cli: Literal["claude"] = "claude"+ # Provider family this worker bills (jarvis/missions/capacity.worker_family).+ family: ClassVar[str] = "gemini"def __init__(self,diff --git a/jarvis/missions/workers/google_cli_worker.py b/jarvis/missions/workers/google_cli_worker.pyindex 001a16bf71..dab6011874 100644--- a/jarvis/missions/workers/google_cli_worker.py+++ b/jarvis/missions/workers/google_cli_worker.py@@ -35,7 +35,7 @@ import uuidfrom collections.abc import AsyncIteratorfrom contextlib import suppressfrom pathlib import Path-from typing import Any, Literal+from typing import Any, ClassVar, Literalfrom jarvis.google_cli.auth_service import _oauth_login_presentfrom jarvis.google_cli.isolated_home import (@@ -152,6 +152,8 @@ class GoogleCliWorker:"""cli: Literal["claude"] = "claude"+ # Provider family this worker bills (jarvis/missions/capacity.worker_family).+ family: ClassVar[str] = "antigravity"def __init__(self,diff --git a/jarvis/missions/workers/grok_build_direct_worker.py b/jarvis/missions/workers/grok_build_direct_worker.pyindex bf6c344019..ecfa3ad59a 100644--- a/jarvis/missions/workers/grok_build_direct_worker.py+++ b/jarvis/missions/workers/grok_build_direct_worker.py@@ -232,6 +232,8 @@ class GrokBuildDirectWorker:"""cli: ClassVar[Literal["claude", "codex", "python", "browser"]] = "codex"+ # Provider family this worker bills (jarvis/missions/capacity.worker_family).+ family: ClassVar[str] = "grok-build"def __init__(self,diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 2be81ad1ca..be6c43d283 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1059,6 +1059,7 @@"attempts_timed_out": "Jeder Versuch hat die Zeit überschritten","budget_exceeded": "Das Kostenbudget wurde überschritten","worktree_setup_failed": "Der Arbeitsbereich konnte nicht eingerichtet werden",+ "checkpoint_missing": "Der gesicherte Zwischenstand fehlte, Fortsetzen war nicht möglich","critic_unavailable": "Kein Prüfer verfügbar, um das Ergebnis zu prüfen","critic_rejected": "Der Prüfer hat das Ergebnis abgelehnt","review_time_budget_exhausted": "Die Prüfung hat ihre Zeit überschritten",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 0d4701c7ce..3a72b4ade4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1059,6 +1059,7 @@"attempts_timed_out": "Every attempt ran out of time","budget_exceeded": "The cost budget was exceeded","worktree_setup_failed": "The workspace could not be set up",+ "checkpoint_missing": "The saved progress was missing, so the run could not continue","critic_unavailable": "No reviewer was available to check the result","critic_rejected": "The reviewer rejected the result","review_time_budget_exhausted": "The review ran out of time",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 6c0d8e5a74..5dde2b9fe5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1059,6 +1059,7 @@"attempts_timed_out": "Todos los intentos agotaron el tiempo","budget_exceeded": "Se superó el presupuesto de coste","worktree_setup_failed": "No se pudo preparar el espacio de trabajo",+ "checkpoint_missing": "Faltaba el progreso guardado, así que no se pudo continuar","critic_unavailable": "No había revisor disponible para comprobar el resultado","critic_rejected": "El revisor rechazó el resultado","review_time_budget_exhausted": "La revisión agotó su tiempo",diff --git a/jarvis/ui/web/frontend/src/types/missions.ts b/jarvis/ui/web/frontend/src/types/missions.tsindex 4d365f5c7f..a9cbcb0814 100644--- a/jarvis/ui/web/frontend/src/types/missions.ts+++ b/jarvis/ui/web/frontend/src/types/missions.ts@@ -208,6 +208,8 @@ export interface MissionWaitingCapacity extends BasePayload {files_saved: number;checkpoint_path: string;error_detail: string | null;+ resume_attempt: number;+ repeat: boolean;}export interface MissionBudgetWarning extends BasePayload {diff --git a/jarvis/ui/web/frontend/src/views/MissionsView.tsx b/jarvis/ui/web/frontend/src/views/MissionsView.tsxindex e14f63da4d..2e4c8ef8dc 100644--- a/jarvis/ui/web/frontend/src/views/MissionsView.tsx+++ b/jarvis/ui/web/frontend/src/views/MissionsView.tsx@@ -295,7 +295,9 @@ function ReasoningPanel() {(e) =>e.payload.event_type === "WorkerProgress" ||e.payload.event_type === "WorkerCorrectionRequired" ||- e.payload.event_type === "MissionWaitingCapacity",+ // A resume that parked again with no new step done repeats the+ // card already shown.+ (e.payload.event_type === "MissionWaitingCapacity" && !e.payload.repeat),);}),);diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex dce4988243..174d051af5 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -3325,6 +3325,18 @@ class WebServer:name="mission-recovery-resweep",)+ # Missions parked in WAITING_CAPACITY resume from their checkpoint+ # once their own subscription has capacity again — never on another+ # provider or a paid key (jarvis/missions/capacity.py). Primary+ # instance only, like the sweep: two instances must not both+ # resume one mission.+ from jarvis.missions.capacity import capacity_resume_loop++ self._missions_resume_task = asyncio.create_task(+ capacity_resume_loop(result["kontrollierer"].resume_waiting_missions),+ name="mission-capacity-resume",+ )+async def _init_wiki_integration(self) -> None:"""Phase B5 wiki write-wiring: bootstrap SessionRollupWorker + WikiCurator.@@ -4198,6 +4210,17 @@ class WebServer:passself._missions_resweep_task = None+ # The resume timer stops here; a mission it already resumed runs in its+ # own task and is finalized by cancel_all_running below.+ resume_task = getattr(self, "_missions_resume_task", None)+ if resume_task is not None:+ resume_task.cancel()+ try:+ await asyncio.wait_for(resume_task, timeout=2.0)+ except (TimeoutError, asyncio.CancelledError):+ pass+ self._missions_resume_task = None+cleanup_task = getattr(self, "_missions_cleanup_task", None)if cleanup_task is not None:cleanup_task.cancel()diff --git a/tests/fakes/fake_mission_runtime.py b/tests/fakes/fake_mission_runtime.pynew file mode 100644index 0000000000..4fc6b781ff--- /dev/null+++ b/tests/fakes/fake_mission_runtime.py@@ -0,0 +1,161 @@+"""Fakes for driving ``Kontrollierer`` end-to-end without subprocesses.++Workers yield one synthetic ``result`` event, the critic approves, worktrees+are plain directories that are really created and removed. Per AGENTS.md:+real fakes, never ``unittest.mock``.+"""++from __future__ import annotations++import shutil+from collections.abc import AsyncIterator, Callable+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from jarvis.missions.budget import BudgetTracker+from jarvis.missions.critic.verdict import REQUIRED_AXES, CriticAxis, CriticVerdict+from jarvis.missions.kontrollierer.decomposer import MissionPlan, Step+from jarvis.missions.kontrollierer.orchestrator import Kontrollierer+from jarvis.missions.manager import MissionManager++SESSION_LIMIT_ERROR = "You've hit your session limit · resets 11:10pm"+++@dataclass+class ResultEvent:+ """Stand-in for a worker's terminal stream-json ``result`` record."""++ 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"+++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")+++class FakeMissionWorker:+ """One spawn = one terminal event. Records every spawn.++ ``quota`` makes each spawn end on a spent subscription window;+ ``writes`` maps relative paths to content the spawn writes into its+ workspace before finishing.+ """++ cli = "claude"++ def __init__(+ self,+ *,+ family: str = "claude",+ quota: bool = False,+ writes: dict[str, str] | None = None,+ on_spawn: Callable[[str, Path], None] | None = None,+ ) -> None:+ self.family = family+ self.quota = quota+ self.writes = dict(writes or {})+ self.on_spawn = on_spawn+ self.last_pid = 4242+ self.prompts: list[str] = []++ async def spawn(+ self, prompt: str, *, worktree: Path, log_dir: Path, **_k: Any+ ) -> AsyncIterator[Any]:+ self.prompts.append(prompt)+ if self.on_spawn is not None:+ self.on_spawn(prompt, worktree)+ for rel, text in self.writes.items():+ target = worktree / rel+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(text, encoding="utf-8")+ _write_log(log_dir)+ if self.quota:+ yield ResultEvent(+ is_error=True, subtype="error_during_execution", result=SESSION_LIMIT_ERROR+ )+ else:+ yield ResultEvent()+++class ApprovingCritic:+ 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 FixedPlanDecomposer:+ def __init__(self, plan: MissionPlan) -> None:+ self.plan = plan+ self.calls = 0++ async def decompose(self, _prompt: str) -> MissionPlan:+ self.calls += 1+ return self.plan+++class NoopJob:+ async def __aenter__(self) -> NoopJob:+ return self++ async def __aexit__(self, *_a: object) -> None:+ return None++ def assign(self, _pid: int) -> None:+ return None+++class DirWorktrees:+ """A fresh directory per ``create`` and a real delete on ``remove`` — so a+ resumed step can only see earlier work that was explicitly restored."""++ def __init__(self, base: Path) -> None:+ self._base = base+ self._n = 0++ def create(self, *, task_id: str, **_k: Any) -> Path:+ self._n += 1+ wt = self._base / f"{task_id[:13]}-{self._n}"+ wt.mkdir(parents=True, exist_ok=True)+ return wt++ def remove(self, path: Path, **_k: Any) -> None:+ shutil.rmtree(path, ignore_errors=True)+++def make_kontrollierer(+ manager: MissionManager,+ tmp_path: Path,+ plan: MissionPlan,+ factory: Callable[[Step], Any],+ critic: Any | None = None,+) -> Kontrollierer:+ return Kontrollierer(+ manager=manager,+ decomposer=FixedPlanDecomposer(plan), # type: ignore[arg-type]+ critic_runner=critic or ApprovingCritic(), # type: ignore[arg-type]+ worktree_mgr=DirWorktrees(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=NoopJob,+ isolation_root=tmp_path / "missions",+ )diff --git a/tests/missions/test_capacity_resume.py b/tests/missions/test_capacity_resume.pynew file mode 100644index 0000000000..52dd89299f--- /dev/null+++ b/tests/missions/test_capacity_resume.py@@ -0,0 +1,363 @@+"""Automatic resume of a WAITING_CAPACITY mission from its checkpoint.++The user's rules (2026-10-04): resume once the SAME subscription has capacity+again, continue exactly from the checkpoint, never redo an approved step,+never switch to another provider or a paid key without approval.+"""+from __future__ import annotations++import asyncio+import json+import shutil+import subprocess+from pathlib import Path+from typing import Any++import pytest++from jarvis.missions.capacity import (+ CHECKPOINT_NAME,+ WorkerCapacityUnavailable,+ capacity_resume_loop,+ read_checkpoint,+ worker_family,+)+from jarvis.missions.events import MissionFailed, MissionWaitingCapacity+from jarvis.missions.kontrollierer.decomposer import MissionPlan, Step+from jarvis.missions.manager import MissionManager+from jarvis.missions.state_machine import MissionState+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+from tests.fakes.fake_mission_runtime import FakeMissionWorker, make_kontrollierer+++async def manager(tmp_missions_db: Path):+ m = MissionManager(tmp_missions_db)+ await m.start()+ yield m+ await m.stop()+++class SwitchableFactory:+ """Worker factory whose capacity the test turns on and off.++ While ``capacity`` is False every call parks (as the real factory does+ during a quota cooldown). Records which step each worker was built for.+ """++ def __init__(self, *, capacity: bool = True, family: str = "claude") -> None:+ self.capacity = capacity+ self.family = family+ self.built_for: list[str] = []+ self.workers: list[FakeMissionWorker] = []+ self.writes: dict[str, dict[str, str]] = {}++ def __call__(self, step: Step) -> FakeMissionWorker:+ if not self.capacity:+ raise WorkerCapacityUnavailable("provider_quota", "claude")+ self.built_for.append(step.task_id)+ worker = FakeMissionWorker(family=self.family, writes=self.writes.get(step.task_id))+ self.workers.append(worker)+ return worker+++def _mission_dir(tmp_path: Path, mission_id: str) -> Path:+ return tmp_path / "missions" / f"mission_{mission_id[:13]}"+++def _waits(payloads: list[Any]) -> list[MissionWaitingCapacity]:+ return [p for p in payloads if isinstance(p, MissionWaitingCapacity)]+++async def _payloads(manager: MissionManager, mission_id: str) -> list[Any]:+ return [e.payload for e in await manager.store.events_for_mission(mission_id)]+++async def _state(manager: MissionManager, mission_id: str) -> MissionState:+ view = await manager.mission(mission_id)+ assert view is not None+ return view.state+++async def _park_second_step(+ manager: MissionManager, tmp_path: Path, factory: SwitchableFactory+) -> tuple[Any, str, Step, Step]:+ """Two-step mission: step one is approved, step two hits the spent window."""+ first, second = Step(slug="first", prompt="one"), Step(slug="second", prompt="two")+ plan = MissionPlan(steps=[first, second], n_workers=1)++ def _first_ok_then_parked(step: Step) -> FakeMissionWorker:+ if step.task_id == second.task_id:+ raise WorkerCapacityUnavailable("provider_quota", "claude")+ return factory(step)++ k = make_kontrollierer(manager, tmp_path, plan, _first_ok_then_parked)+ mission_id = await manager.dispatch(prompt="two-part job")+ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY+ # From now on the test's factory decides capacity for every step.+ k._worker_factory = factory+ return k, mission_id, first, second+++# --- Pause and checkpoint -----------------------------------------------------+++async def test_checkpoint_holds_everything_a_resume_needs(+ manager: MissionManager, tmp_path: Path+) -> None:+ factory = SwitchableFactory()+ _k, mission_id, first, second = await _park_second_step(manager, tmp_path, factory)++ checkpoint = read_checkpoint(_mission_dir(tmp_path, mission_id))+ assert checkpoint is not None+ assert checkpoint["provider"] == "claude"+ assert checkpoint["resume_attempts"] == 0+ plan = MissionPlan.model_validate(checkpoint["plan"])+ assert [s.task_id for s in plan.steps] == [first.task_id, second.task_id]+ assert {s["task_id"]: s["done"] for s in checkpoint["steps"]} == {+ first.task_id: True,+ second.task_id: False,+ }+++# --- Resume: exactly from the checkpoint, nothing twice -----------------------+++async def test_resume_runs_only_the_open_step_and_approves(+ manager: MissionManager, tmp_path: Path+) -> None:+ factory = SwitchableFactory()+ k, mission_id, first, second = await _park_second_step(manager, tmp_path, factory)+ assert factory.built_for == [first.task_id]++ assert await k.resume_mission(mission_id) == MissionState.APPROVED++ # Step one ran once in the first run and never again.+ assert factory.built_for == [first.task_id, second.task_id]+ assert await _state(manager, mission_id) == MissionState.APPROVED+ # The plan came from the checkpoint, not from a second decomposition.+ assert k._decomposer.calls == 1 # type: ignore[attr-defined]+++async def test_resume_restores_partial_work_and_tells_the_worker(+ manager: MissionManager, tmp_path: Path+) -> None:+ factory = SwitchableFactory()+ k, mission_id, _first, second = await _park_second_step(manager, tmp_path, factory)+ # The parked step's earlier attempt left a deliverable in its archive.+ task_dir = _mission_dir(tmp_path, mission_id) / "tasks" / second.task_id[:13]+ files = task_dir / "artifacts" / "files"+ files.mkdir(parents=True, exist_ok=True)+ (files / "draft.md").write_text("half done", encoding="utf-8")++ seen: dict[str, str] = {}++ def _record(_prompt: str, worktree: Path) -> None:+ draft = worktree / "draft.md"+ seen["draft"] = draft.read_text(encoding="utf-8") if draft.is_file() else ""++ def _factory(step: Step) -> FakeMissionWorker:+ worker = factory(step)+ worker.on_spawn = _record+ return worker++ k._worker_factory = _factory+ assert await k.resume_mission(mission_id) == MissionState.APPROVED++ assert seen["draft"] == "half done"+ assert "RESUMED TASK" in factory.workers[-1].prompts[0]+++async def test_parked_mission_is_never_rerun_by_run_mission(+ manager: MissionManager, tmp_path: Path+) -> None:+ factory = SwitchableFactory()+ k, mission_id, first, _second = await _park_second_step(manager, tmp_path, factory)++ assert await k.run_mission(mission_id) == MissionState.WAITING_CAPACITY+ assert factory.built_for == [first.task_id]+ assert k._decomposer.calls == 1 # type: ignore[attr-defined]+++async def test_concurrent_resumes_run_the_mission_once(+ manager: MissionManager, tmp_path: Path+) -> None:+ factory = SwitchableFactory()+ k, mission_id, first, second = await _park_second_step(manager, tmp_path, factory)++ results = await asyncio.gather(k.resume_mission(mission_id), k.resume_mission(mission_id))++ assert MissionState.APPROVED in results+ assert factory.built_for.count(second.task_id) == 1+ assert factory.built_for.count(first.task_id) == 1+++async def test_resume_that_hits_the_limit_again_reparks_quietly(+ manager: MissionManager, tmp_path: Path+) -> None:+ factory = SwitchableFactory()+ k, mission_id, _first, _second = await _park_second_step(manager, tmp_path, factory)+ factory.capacity = False # the window is still spent when the resume starts++ assert await k.resume_mission(mission_id) == MissionState.WAITING_CAPACITY++ waits = _waits(await _payloads(manager, mission_id))+ assert [(w.resume_attempt, w.repeat) for w in waits] == [(0, False), (1, True)]+ assert (waits[-1].steps_done, waits[-1].steps_total) == (1, 2)+ checkpoint = read_checkpoint(_mission_dir(tmp_path, mission_id))+ assert checkpoint is not None and checkpoint["resume_attempts"] == 1+ assert [s["done"] for s in checkpoint["steps"]] == [True, False]+++async def test_resume_without_checkpoint_fails_honestly(+ manager: MissionManager, tmp_path: Path+) -> None:+ factory = SwitchableFactory()+ k, mission_id, _first, _second = await _park_second_step(manager, tmp_path, factory)+ (_mission_dir(tmp_path, mission_id) / CHECKPOINT_NAME).unlink()++ assert await k.resume_mission(mission_id) == MissionState.FAILED+ failed = [p for p in await _payloads(manager, mission_id) if isinstance(p, MissionFailed)]+ assert failed[-1].reason == "checkpoint_missing"+++# --- When to resume: same subscription only -----------------------------------+++async def test_resume_pass_waits_until_capacity_is_back(+ manager: MissionManager, tmp_path: Path+) -> None:+ factory = SwitchableFactory()+ k, mission_id, _first, _second = await _park_second_step(manager, tmp_path, factory)+ factory.capacity = False++ assert await k.resume_waiting_missions() == []+ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY++ factory.capacity = True+ assert await k.resume_waiting_missions() == [mission_id]+ assert await _state(manager, mission_id) == MissionState.APPROVED+++async def test_resume_pass_never_switches_provider(+ manager: MissionManager, tmp_path: Path+) -> None:+ """Capacity on another family (e.g. the paid Anthropic key) is not a+ reason to resume — that switch needs the user's approval."""+ factory = SwitchableFactory(family="claude-api")+ k, mission_id, first, _second = await _park_second_step(manager, tmp_path, factory)+ factory.built_for.clear()++ assert await k.resume_waiting_missions() == []+ assert await _state(manager, mission_id) == MissionState.WAITING_CAPACITY+ assert not any(w.prompts for w in factory.workers[1:])+++async def test_resumed_run_parks_again_if_the_worker_family_changes(+ manager: MissionManager, tmp_path: Path+) -> None:+ factory = SwitchableFactory(family="codex")+ k, mission_id, _first, _second = await _park_second_step(manager, tmp_path, factory)++ assert await k.resume_mission(mission_id) == MissionState.WAITING_CAPACITY+ wait = _waits(await _payloads(manager, mission_id))[-1]+ assert (wait.reason, wait.provider) == ("provider_unavailable", "claude")+ assert not any(w.prompts for w in factory.workers[1:])+++# --- Restoring work into a git workspace --------------------------------------+++def _offline_kontrollierer(tmp_path: Path) -> Any:+ """A Kontrollierer for calling workspace helpers; its store is never opened."""+ plan = MissionPlan(steps=[Step(slug="s", prompt="p")], n_workers=1)+ return make_kontrollierer(+ MissionManager(tmp_path / "unused.db"), tmp_path, plan, SwitchableFactory()+ )+++def _git(*args: str, cwd: Path) -> str:+ identity = ["-c", "[email protected]", "-c", "user.name=t"]+ return subprocess.run( # noqa: S603+ ["git", *identity, *args], cwd=cwd, check=True, capture_output=True, text=True+ ).stdout++[email protected](shutil.which("git") is None, reason="needs git")+def test_restore_applies_the_archived_patch(tmp_path: Path) -> None:+ git = _git+ repo = tmp_path / "repo"+ repo.mkdir()+ git("init", "-q", cwd=repo)+ (repo / "notes.txt").write_text("line one\n", encoding="utf-8")+ git("add", "notes.txt", cwd=repo)+ git("commit", "-q", "-m", "notes", cwd=repo)++ # The earlier attempt edited a tracked file and added a new one.+ (repo / "notes.txt").write_text("line one\nline two\n", encoding="utf-8")+ (repo / "new.txt").write_text("fresh\n", encoding="utf-8")+ git("add", "-A", ".", cwd=repo)+ artifacts = tmp_path / "artifacts"+ artifacts.mkdir()+ patch = git("diff", "--cached", "HEAD", cwd=repo)+ (artifacts / "diff.patch").write_text(patch, encoding="utf-8")+ git("reset", "-q", "--hard", "HEAD", cwd=repo)+ assert not (repo / "new.txt").exists()++ assert _offline_kontrollierer(tmp_path)._restore_task_workspace(repo, artifacts) is True+ assert (repo / "notes.txt").read_text(encoding="utf-8") == "line one\nline two\n"+ assert (repo / "new.txt").read_text(encoding="utf-8") == "fresh\n"+++def test_restore_with_nothing_archived_is_a_clean_start(tmp_path: Path) -> None:+ k = _offline_kontrollierer(tmp_path)+ workspace = tmp_path / "ws"+ workspace.mkdir()+ (tmp_path / "artifacts").mkdir()+ assert k._restore_task_workspace(workspace, tmp_path / "artifacts") is False+ assert list(workspace.iterdir()) == []+++# --- The timer -----------------------------------------------------------------+++async def test_resume_loop_keeps_running_after_a_failing_pass() -> None:+ calls: list[int] = []+ sleeps: list[float] = []++ async def _pass() -> list[str]:+ calls.append(len(calls))+ if len(calls) == 1:+ raise RuntimeError("store hiccup")+ return []++ async def _sleep(seconds: float) -> None:+ sleeps.append(seconds)+ if len(sleeps) > 3:+ raise asyncio.CancelledError++ with pytest.raises(asyncio.CancelledError):+ await capacity_resume_loop(+ _pass, interval_s=300.0, jitter_s=60.0, sleep=_sleep, jitter=lambda _a, _b: 7.0+ )+ assert len(calls) == 3+ assert sleeps[0] == 307.0 # waits before the first pass: not on the boot path+++# --- Worker identity --------------------------------------------------------------+++def test_worker_families_tell_billing_apart() -> None:+ assert worker_family(ClaudeDirectWorker()) == "claude"+ assert worker_family(CodexDirectWorker()) == "codex"+ # The Anthropic API key is a different family from the Claude subscription.+ assert worker_family(ApiAgentWorker("claude-api")) == "claude-api"+++def test_checkpoint_is_plain_json(tmp_path: Path) -> None:+ from jarvis.missions.capacity import write_checkpoint++ path = write_checkpoint(tmp_path, {"mission_id": "m", "steps": []})+ assert json.loads(path.read_text(encoding="utf-8"))["mission_id"] == "m"diff --git a/tests/missions/test_capacity_wait.py b/tests/missions/test_capacity_wait.pyindex 4a80b06a7b..5506092f14 100644--- a/tests/missions/test_capacity_wait.py+++ b/tests/missions/test_capacity_wait.py@@ -10,7 +10,6 @@ from __future__ import annotationsimport jsonfrom collections.abc import AsyncIterator-from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -18,16 +17,13 @@ import pytestfrom jarvis.missions import capacityfrom jarvis.missions import init as mi-from jarvis.missions.budget import BudgetTrackerfrom jarvis.missions.capacity import (CHECKPOINT_NAME,WorkerCapacityUnavailable,pinned_to_subscription,)-from jarvis.missions.critic.verdict import REQUIRED_AXES, CriticAxis, CriticVerdictfrom jarvis.missions.events import MissionWaitingCapacityfrom jarvis.missions.kontrollierer.decomposer import MissionPlan, Step-from jarvis.missions.kontrollierer.orchestrator import Kontrolliererfrom jarvis.missions.manager import MissionManagerfrom jarvis.missions.recovery import startup_recoverfrom jarvis.missions.state_machine import MissionState, is_terminal, transition@@ -35,6 +31,11 @@ from jarvis.missions.voice.readback import MAX_VOICE_CHARS, render_capacity_waitfrom jarvis.missions.workers.api_agent_worker import ApiAgentWorkerfrom jarvis.missions.workers.claude_direct_worker import ClaudeDirectWorkerfrom jarvis.missions.workers.codex_direct_worker import CodexDirectWorker+from tests.fakes.fake_mission_runtime import (+ ApprovingCritic,+ FakeMissionWorker,+ make_kontrollierer,+)# --- State machine ------------------------------------------------------------@@ -242,98 +243,6 @@ async def test_pinned_worker_disables_its_cross_backend_fallback(# --- 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--@pytest.fixtureasync def manager(tmp_missions_db: Path):m = MissionManager(tmp_missions_db)@@ -342,31 +251,10 @@ async def manager(tmp_missions_db: Path):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)]@@ -374,9 +262,9 @@ async def _events(manager: MissionManager, mid: str) -> list[Any]:async def test_spent_quota_parks_mission_with_checkpoint(manager: MissionManager, tmp_path: Path) -> None:- worker = _QuotaWorker()+ worker = FakeMissionWorker(quota=True)plan = MissionPlan(steps=[Step(slug="task", prompt="do it")], n_workers=1)- k = _kontrollierer(manager, tmp_path, plan, lambda _s: worker, _ApproveCritic())+ k = make_kontrollierer(manager, tmp_path, plan, lambda _s: worker, ApprovingCritic())mid = await manager.dispatch(prompt="write the report")state = await k.run_mission(mid)@@ -407,8 +295,8 @@ async def test_factory_refusal_parks_without_spawning(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)+ critic = ApprovingCritic()+ k = make_kontrollierer(manager, tmp_path, plan, _factory, critic)mid = await manager.dispatch(prompt="p")assert await k.run_mission(mid) == MissionState.WAITING_CAPACITY@@ -427,10 +315,10 @@ async def test_finished_steps_are_kept_and_counted(def _factory(step: Step) -> Any:if step.task_id == blocked.task_id:raise WorkerCapacityUnavailable("provider_quota", "claude")- return _OkWorker()+ return FakeMissionWorker()plan = MissionPlan(steps=[ok, blocked], n_workers=1)- k = _kontrollierer(manager, tmp_path, plan, _factory, _ApproveCritic())+ k = make_kontrollierer(manager, tmp_path, plan, _factory, ApprovingCritic())mid = await manager.dispatch(prompt="p")assert await k.run_mission(mid) == MissionState.WAITING_CAPACITY@@ -449,7 +337,7 @@ async def test_parked_mission_can_be_cancelled(raise WorkerCapacityUnavailable("provider_quota", "claude")plan = MissionPlan(steps=[Step(slug="task", prompt="x")], n_workers=1)- k = _kontrollierer(manager, tmp_path, plan, _factory, _ApproveCritic())+ k = make_kontrollierer(manager, tmp_path, plan, _factory, ApprovingCritic())mid = await manager.dispatch(prompt="p")await k.run_mission(mid)@@ -468,7 +356,7 @@ async def test_recovery_never_sweeps_a_parked_mission(raise WorkerCapacityUnavailable("provider_quota", "claude")plan = MissionPlan(steps=[Step(slug="task", prompt="x")], n_workers=1)- k = _kontrollierer(manager, tmp_path, plan, _factory, _ApproveCritic())+ k = make_kontrollierer(manager, tmp_path, plan, _factory, ApprovingCritic())mid = await manager.dispatch(prompt="p")await k.run_mission(mid)diff --git a/tests/missions/test_capacity_wait_parity.py b/tests/missions/test_capacity_wait_parity.pyindex 3b3a2f47d8..4a2c48065c 100644--- a/tests/missions/test_capacity_wait_parity.py+++ b/tests/missions/test_capacity_wait_parity.py@@ -70,3 +70,30 @@ def test_ui_locales_cover_badge_and_reasons(lang: str) -> None: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)+++def test_event_fields_python_ts_parity() -> None:+ m = re.search(+ r"export interface MissionWaitingCapacity extends BasePayload \{([^}]+)\}", _MISSIONS_TS+ )+ assert m, "MissionWaitingCapacity interface not found in missions.ts"+ ts_fields = set(re.findall(r"^\s*(\w+):", m.group(1), re.MULTILINE))+ assert ts_fields == set(MissionWaitingCapacity.model_fields)+++def test_repeated_pause_is_not_announced_again() -> None:+ from jarvis.missions.events import EventEnvelope+ from jarvis.missions.voice.listener import MissionVoiceListener+ from jarvis.missions.voice.readback import MissionReadback++ first = MissionWaitingCapacity(reason="provider_quota", provider="claude", steps_total=2)+ again = first.model_copy(update={"resume_attempt": 1, "repeat": True})+ listener = MissionVoiceListener.__new__(MissionVoiceListener)+ listener._readback = MissionReadback()+ listener._announce_critic_loop = False++ def env(payload: MissionWaitingCapacity) -> EventEnvelope:+ return EventEnvelope(mission_id="m", source_actor="kontrollierer", ts_ms=1, payload=payload)++ assert listener._render(env(first), "de")+ assert listener._render(env(again), "de") == ""