Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(missions): take a correction while a mission runs (#637)

Ruben Lütke05f71556ac38
diff --git a/docs/commands-reference.md b/docs/commands-reference.md
index 2547540cdd..42f8258278 100644
--- a/docs/commands-reference.md
+++ b/docs/commands-reference.md
@@ -371,6 +371,16 @@ Cancel a running Jarvis-Agent mission by id.
- **Desktop UI section:** `agents`
- **Voice example (EN):** "cancel the mission"
+## `mission-amend` — Correct a running mission
+
+Give a mission that is still running the user's correction or changed wish, in their words, without restarting it. The running worker cannot be interrupted: the next attempt gets the correction. Read applies in the result and tell the user that, never that it is already done. A mission that has ended refuses; start a new one for the change.
+
+- **Endpoint:** `POST /api/missions/{mission_id}/amend`
+- **Arguments:** `mission_id` (string; required); `instruction` (string; required)
+- **Requires confirmation:** no
+- **Desktop UI section:** `agents`
+- **Voice example (EN):** "tell the mission to do it differently"
+
## `tasks-list` — List tasks
List scheduled and running tasks (agent routines).
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index e4fbc0f8a2..37e6cf0b3e 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -1130,6 +1130,37 @@ def _build_registry() -> tuple[AppCommand, ...]:
"pt": ("cancela a missão",), # i18n-allow: input vocab
},
),
+ AppCommand(
+ id="mission-amend",
+ title="Correct a running mission",
+ description=(
+ "Give a mission that is still running the user's correction or changed "
+ "wish, in their words, without restarting it. The running worker cannot "
+ "be interrupted: the next attempt gets the correction. Read applies in the "
+ "result and tell the user that, never that it is already done. A mission "
+ "that has ended refuses; start a new one for the change."
+ ),
+ method="POST",
+ path="/api/missions/{mission_id}/amend",
+ params={
+ "type": "object",
+ "properties": {
+ "mission_id": _str_param("Mission id to correct.", min_length=1),
+ "instruction": _str_param(
+ "The correction, complete in itself.", min_length=1, max_length=4000
+ ),
+ },
+ "required": ["mission_id", "instruction"],
+ },
+ path_params=("mission_id",),
+ ui_section="agents",
+ voice_aliases={
+ "de": ("sag der mission sie soll es anders machen",), # i18n-allow: input vocab
+ "en": ("tell the mission to do it differently",),
+ "es": ("dile a la misión que lo haga de otra forma",), # i18n-allow: input vocab
+ "pt": ("diz à missão para fazer de outra forma",), # i18n-allow: input vocab
+ },
+ ),
AppCommand(
id="tasks-list",
title="List tasks",
diff --git a/jarvis/missions/corrections.py b/jarvis/missions/corrections.py
new file mode 100644
index 0000000000..839f6fb81e
--- /dev/null
+++ b/jarvis/missions/corrections.py
@@ -0,0 +1,154 @@
+"""Corrections the user gives a mission while it is running.
+
+A mission's worker is a one-shot process: once started it cannot be told
+anything. What the user says meanwhile ("make it dark mode instead", "leave
+the tests alone") is kept here, next to the mission's other files, and the
+orchestrator hands every correction to the next attempt of every step. A
+correction that arrives while an attempt runs makes the mission take one more
+attempt instead of finishing on a result the user already changed.
+
+The inbox is an append-only file so a correction survives a restart exactly
+like the mission's reflections do.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import threading
+import time
+from dataclasses import asdict, dataclass
+from pathlib import Path
+
+log = logging.getLogger(__name__)
+# Steps of one mission run side by side and may note late corrections at once.
+_unapplied_lock = threading.Lock()
+
+__all__ = [
+ "CORRECTIONS_FILENAME",
+ "Correction",
+ "CorrectionInbox",
+ "render",
+ "with_corrections",
+]
+
+CORRECTIONS_FILENAME = "corrections.jsonl"
+#: One correction is an instruction, not a document.
+MAX_CORRECTION_CHARS = 4000
+
+
+@dataclass(frozen=True, slots=True)
+class Correction:
+ number: int
+ text: str
+ ts_ms: int
+
+ def to_dict(self) -> dict:
+ return asdict(self)
+
+
+class CorrectionInbox:
+ """The corrections of one mission, oldest first."""
+
+ def __init__(self, mission_dir: Path) -> None:
+ self._path = mission_dir / CORRECTIONS_FILENAME
+
+ @property
+ def path(self) -> Path:
+ return self._path
+
+ def read(self) -> list[Correction]:
+ try:
+ lines = self._path.read_text(encoding="utf-8").splitlines()
+ except FileNotFoundError: # no correction was given to this mission yet
+ return []
+ found: list[Correction] = []
+ for line in lines:
+ try:
+ row = json.loads(line)
+ text = str(row["text"]).strip()
+ except (ValueError, KeyError, TypeError): # a line torn by a crash: no correction
+ continue
+ if text:
+ found.append(Correction(len(found) + 1, text, int(row.get("ts_ms") or 0)))
+ return found
+
+ def add(self, text: str) -> Correction:
+ cleaned = " ".join(str(text or "").split())
+ if not cleaned:
+ raise ValueError("A correction needs text.")
+ if len(cleaned) > MAX_CORRECTION_CHARS:
+ raise ValueError(f"A correction is at most {MAX_CORRECTION_CHARS} characters.")
+ self._path.parent.mkdir(parents=True, exist_ok=True)
+ entry = {"text": cleaned, "ts_ms": int(time.time() * 1000)}
+ # A crash can leave a last line without its line end; start a new line
+ # then, or this correction would be glued onto the torn one and lost.
+ torn = False
+ try:
+ with self._path.open("rb") as existing:
+ existing.seek(0, os.SEEK_END)
+ if existing.tell():
+ existing.seek(-1, os.SEEK_END)
+ torn = existing.read(1) != b"\n"
+ except FileNotFoundError: # the first correction of this mission
+ torn = False
+ with self._path.open("a", encoding="utf-8") as handle:
+ if torn:
+ handle.write("\n")
+ handle.write(json.dumps(entry, ensure_ascii=False) + "\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ return self.read()[-1]
+
+ def note_unapplied(self, task_id: str, corrections: list[Correction]) -> None:
+ """Record that a step ended before these corrections could reach an attempt."""
+ if not corrections:
+ return
+ with _unapplied_lock:
+ late = self._late()
+ late.setdefault(task_id, [])
+ late[task_id] = sorted({*late[task_id], *(item.number for item in corrections)})
+ # Written whole and swapped in, so a reader never sees half a file.
+ scratch = self._unapplied_path.with_suffix(".json.tmp")
+ scratch.write_text(json.dumps(late), encoding="utf-8")
+ os.replace(scratch, self._unapplied_path)
+
+ def unapplied(self) -> list[Correction]:
+ """Corrections at least one step finished without, oldest first."""
+ numbers = {number for group in self._late().values() for number in group}
+ return [item for item in self.read() if item.number in numbers]
+
+ @property
+ def _unapplied_path(self) -> Path:
+ return self._path.with_name("corrections-unapplied.json")
+
+ def _late(self) -> dict[str, list[int]]:
+ try:
+ data = json.loads(self._unapplied_path.read_text(encoding="utf-8"))
+ except FileNotFoundError: # nothing came too late so far
+ return {}
+ except ValueError:
+ log.warning("Unreadable record of late corrections: %s", self._unapplied_path)
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def render(corrections: list[Correction]) -> str:
+ """The block a worker and its reviewer read; empty without corrections."""
+ if not corrections:
+ return ""
+ lines = [
+ "USER CORRECTIONS - the user changed this task after it was started. Follow "
+ "them; where they differ from the task below, the corrections win, and a "
+ "later correction wins over an earlier one. Keep everything else of the "
+ "task and of the work already done.",
+ ]
+ lines.extend(f"{item.number}. {item.text}" for item in corrections)
+ return "\n".join(lines)
+
+
+def with_corrections(prompt: str, corrections: list[Correction]) -> str:
+ """``prompt`` as its reviewer should judge it once corrections exist."""
+ block = render(corrections)
+ return f"{prompt}\n\n{block}" if block else prompt
diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.py
index 6e84cee276..64d546ec9f 100644
--- a/jarvis/missions/kontrollierer/orchestrator.py
+++ b/jarvis/missions/kontrollierer/orchestrator.py
@@ -61,6 +61,8 @@ from ..capacity import (
worker_family,
write_checkpoint,
)
+from ..corrections import Correction, CorrectionInbox, with_corrections
+from ..corrections import render as render_corrections
from ..critic.escalation import FRONTIER_MODEL
from ..critic.reflections import ReflectionMemory
from ..critic.runner import MAX_CRITIC_LOOPS, CriticRunner
@@ -1014,6 +1016,43 @@ class Kontrollierer:
finally:
self._running_missions.pop(mission_id, None)
+ def amend_mission(self, mission_id: str, instruction: str) -> dict[str, Any]:
+ """Keep a correction the user gave while the mission runs.
+
+ The running worker cannot be told anything; every later attempt of
+ every step is given the correction, and an attempt it arrived during
+ is followed by one more. Raises ``ValueError`` for an empty or
+ oversized instruction. Blocking file I/O: call off the event loop.
+ """
+ mission_dir = self._isolation_root / f"mission_{mission_id[:13]}"
+ inbox = CorrectionInbox(mission_dir)
+ correction = inbox.add(instruction)
+ logger.info("Mission %s: correction %d recorded", mission_id, correction.number)
+ return {
+ "number": correction.number,
+ "text": correction.text,
+ "running": mission_id in self._running_missions,
+ }
+
+ def mission_corrections(self, mission_id: str) -> dict[str, Any]:
+ """The mission's corrections and the ones a step finished without."""
+ inbox = CorrectionInbox(self._isolation_root / f"mission_{mission_id[:13]}")
+ corrections = inbox.read()
+ if not corrections:
+ return {}
+ return {
+ "corrections": [item.to_dict() for item in corrections],
+ "unapplied_corrections": [item.to_dict() for item in inbox.unapplied()],
+ }
+
+ @staticmethod
+ def _can_start_correction(iteration: int, task_t0: float) -> bool:
+ """Whether one more attempt fits: an attempt left and time to finish it."""
+ if iteration + 1 >= MAX_CRITIC_LOOPS:
+ return False
+ needed_s = _CORRECTION_WORKER_TIMEOUT_S + _CRITIC_TIME_RESERVE_S
+ return time.monotonic() - task_t0 + needed_s <= _TASK_TIME_BUDGET_S
+
def cancel_running_mission(self, mission_id: str) -> bool:
"""Cancel the in-flight ``run_mission`` task for this mission.
@@ -1617,12 +1656,23 @@ class Kontrollierer:
# return EXHAUSTED (the worker was given real feedback and
# still didn't fix things).
critic_ok_count = 0
+ # What the user said about this mission after it started. ``handed``
+ # are the corrections the attempt being judged was given.
+ inbox = CorrectionInbox(mission_dir)
+ handed: list[Correction] = []
for iteration in range(MAX_CRITIC_LOOPS):
# Per-iteration: render reflections, spawn worker, capture diff+log
prior_block = reflections.render_for_worker_prompt(n=3)
if resumed and iteration == 0 and not review_only:
prior_block = "\n\n".join(b for b in (_RESUME_NOTE, prior_block) if b)
+ if not (review_only and iteration == 0):
+ # A restored result that only waits for its review was made
+ # before these corrections; they count as not yet handed.
+ handed = await asyncio.to_thread(inbox.read)
+ prior_block = "\n\n".join(
+ b for b in (prior_block, render_corrections(handed)) 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
@@ -2094,7 +2144,8 @@ class Kontrollierer:
)
try:
verdict = await self._runner.run(
- mission_prompt=mission_prompt,
+ # Judged against the task as the user corrected it.
+ mission_prompt=with_corrections(mission_prompt, handed),
worker_diff=diff_text,
worker_log=critic_log,
prior_reflections=prior_block,
@@ -2224,6 +2275,35 @@ class Kontrollierer:
# Verdict evaluation
if is_approval_valid(verdict):
+ # A correction that arrived while this attempt ran: the result
+ # is good for the task as it was, not as the user changed it.
+ # The next attempt changes the same workspace, so from here on
+ # the step ends as that attempt ends, also when it fails.
+ late = (await asyncio.to_thread(inbox.read))[len(handed):]
+ if late and self._can_start_correction(iteration, task_t0):
+ reflections.append(
+ iteration,
+ "The result was accepted, but the user changed the task while "
+ "this attempt ran. Apply the user's corrections to it.",
+ [],
+ )
+ await self._publish_correction(
+ mission_id=mission_id,
+ worker_id=spawn_result.worker_id,
+ instruction=late[-1].text,
+ iteration=iteration,
+ next_model=(FRONTIER_MODEL if iteration + 1 >= 2 else "sonnet"),
+ # The user asked for this attempt, not the reviewer.
+ source_actor="ui",
+ )
+ continue
+ if late:
+ logger.warning(
+ "Task %s: %d correction(s) arrived too late for another "
+ "attempt and were not applied",
+ step.task_id, len(late),
+ )
+ await asyncio.to_thread(inbox.note_unapplied, step.task_id, late)
# Read-only / informational task: capture the worker's answer
# so the mission speaks it back instead of "Mission
# abgeschlossen." Two shapes qualify — (a) empty diff + real
@@ -4545,11 +4625,12 @@ class Kontrollierer:
instruction: str,
iteration: int,
next_model: str,
+ source_actor: Literal["critic", "ui"] = "critic",
) -> None:
env = EventEnvelope(
mission_id=mission_id,
worker_id=worker_id,
- source_actor="critic",
+ source_actor=source_actor,
ts_ms=now_ms(),
payload=WorkerCorrectionRequired(
worker_id=worker_id,
diff --git a/jarvis/ui/web/missions_routes.py b/jarvis/ui/web/missions_routes.py
index 8f0ea1e7a9..1e3135ef0b 100644
--- a/jarvis/ui/web/missions_routes.py
+++ b/jarvis/ui/web/missions_routes.py
@@ -142,6 +142,12 @@ class CapacityDecisionBody(BaseModel):
model: str | None = None
+class AmendBody(BaseModel):
+ """A correction for a mission that is still running."""
+
+ instruction: str
+
+
class DenyToolApprovalBody(BaseModel):
"""Optional audit reason for denying one paused supervisor tool call."""
@@ -327,6 +333,56 @@ async def get_mission_result(
"artifacts": artifacts,
"artifact_count": len(artifacts),
"truncated": truncated,
+ **await _corrections_of(request, mission_id),
+ }
+
+
+async def _corrections_of(request: Request, mission_id: str) -> dict[str, Any]:
+ """What the user changed while the mission ran, and what came too late."""
+ reader = getattr(_optional_kontrollierer(request), "mission_corrections", None)
+ if reader is None:
+ return {}
+ return await asyncio.to_thread(reader, mission_id)
+
+
[email protected]("/{mission_id}/amend")
+async def amend_mission(mission_id: str, body: AmendBody, request: Request) -> dict[str, Any]:
+ """Give a running mission a correction without restarting it.
+
+ The worker that is running cannot be told anything. The correction is kept
+ with the mission: every later attempt of every step gets it, and an attempt
+ it arrived during is followed by one more. ``409`` once the mission ended.
+ """
+ mgr = _require_manager(request)
+ view = await mgr.store.get_mission_view(mission_id)
+ if view is None:
+ raise HTTPException(status_code=404, detail="Mission not found")
+ state = str(view[1])
+ if state in _VALID_STATES and is_terminal(MissionState(state)):
+ raise HTTPException(
+ status_code=409,
+ detail=f"The mission has ended ({state}); send the change as a new request.",
+ )
+ amender = getattr(_optional_kontrollierer(request), "amend_mission", None)
+ if amender is None:
+ raise HTTPException(status_code=503, detail="Missions cannot take corrections yet")
+ try:
+ correction = await asyncio.to_thread(amender, mission_id, body.instruction)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from None
+ return {
+ "ok": True,
+ "mission_id": mission_id,
+ "state": state,
+ "correction": correction,
+ "applies": (
+ "The running worker cannot be interrupted. The next attempt gets this "
+ "correction, and the attempt running now is followed by one more, in the "
+ "same workspace: if that attempt fails, the mission ends as failed even "
+ "though the earlier result had been accepted. If the mission was in its "
+ "last attempt it finishes without the correction; mission-result then lists "
+ "it under unapplied_corrections."
+ ),
}
diff --git a/tests/missions/api/test_missions_routes.py b/tests/missions/api/test_missions_routes.py
index 286397ce12..400d762f50 100644
--- a/tests/missions/api/test_missions_routes.py
+++ b/tests/missions/api/test_missions_routes.py
@@ -753,3 +753,74 @@ async def test_rerun_allowed_again_after_child_terminal(
assert second != first
children = await manager.store.find_child_missions(src)
assert {c[0] for c in children} == {first, second}
+
+
+# ---------------------------------------------------------------------------
+# Corrections for a running mission
+# ---------------------------------------------------------------------------
+
+
+class _CorrectionsOnly:
+ """The part of the orchestrator the amend and result routes talk to."""
+
+ def __init__(self, root: Path) -> None:
+ self._root = root
+
+ def _inbox(self, mission_id: str):
+ from jarvis.missions.corrections import CorrectionInbox
+
+ return CorrectionInbox(self._root / mission_id[:13])
+
+ def amend_mission(self, mission_id: str, instruction: str) -> dict[str, Any]:
+ correction = self._inbox(mission_id).add(instruction)
+ return {"number": correction.number, "text": correction.text, "running": True}
+
+ def mission_corrections(self, mission_id: str) -> dict[str, Any]:
+ corrections = self._inbox(mission_id).read()
+ if not corrections:
+ return {}
+ return {
+ "corrections": [item.to_dict() for item in corrections],
+ "unapplied_corrections": [],
+ }
+
+
+def test_amend_records_the_correction_and_says_when_it_applies(
+ app_with_manager: FastAPI, tmp_path: Path
+) -> None:
+ with TestClient(app_with_manager) as client:
+ mid = client.post("/api/missions/dispatch", json={"prompt": "build it"}).json()[
+ "mission_id"
+ ]
+ app_with_manager.state.kontrollierer = _CorrectionsOnly(tmp_path / "missions")
+ before = client.get(f"/api/missions/{mid}/result").json()
+ assert "corrections" not in before
+ r = client.post(f"/api/missions/{mid}/amend", json={"instruction": "Make it dark."})
+ assert r.status_code == 200
+ body = r.json()
+ assert body["ok"] is True and body["state"] == MissionState.PENDING.value
+ assert body["correction"] == {"number": 1, "text": "Make it dark.", "running": True}
+ assert "next attempt" in body["applies"]
+ result = client.get(f"/api/missions/{mid}/result").json()
+ assert [item["text"] for item in result["corrections"]] == ["Make it dark."]
+ assert result["unapplied_corrections"] == []
+
+
+def test_amend_refuses_what_it_cannot_apply(app_with_manager: FastAPI, tmp_path: Path) -> None:
+ with TestClient(app_with_manager) as client:
+ mid = client.post("/api/missions/dispatch", json={"prompt": "build it"}).json()[
+ "mission_id"
+ ]
+ # No orchestrator wired yet: nothing could ever read the correction.
+ assert client.post(
+ f"/api/missions/{mid}/amend", json={"instruction": "x"}
+ ).status_code == 503
+ app_with_manager.state.kontrollierer = _CorrectionsOnly(tmp_path / "missions")
+ assert client.post(
+ "/api/missions/unknown/amend", json={"instruction": "x"}
+ ).status_code == 404
+ empty = client.post(f"/api/missions/{mid}/amend", json={"instruction": " "})
+ assert empty.status_code == 422
+ assert client.post(f"/api/missions/{mid}/cancel").status_code == 200
+ ended = client.post(f"/api/missions/{mid}/amend", json={"instruction": "too late"})
+ assert ended.status_code == 409 and "new request" in ended.json()["detail"]
diff --git a/tests/missions/kontrollierer/test_corrections_loop.py b/tests/missions/kontrollierer/test_corrections_loop.py
new file mode 100644
index 0000000000..cef9d8b493
--- /dev/null
+++ b/tests/missions/kontrollierer/test_corrections_loop.py
@@ -0,0 +1,208 @@
+"""A correction given while a mission runs reaches its next attempt."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.missions.kontrollierer import orchestrator
+from jarvis.missions.manager import MissionManager
+from jarvis.missions.state_machine import MissionState
+from tests.missions.kontrollierer.test_loop import (
+ FakeCriticRunner,
+ FakeWorker,
+ _make_approve_verdict,
+ _make_kontrollierer,
+ _make_revise_verdict,
+ manager, # noqa: F401 - the shared MissionManager fixture
+)
+
+_CORRECTION = "Use a dark colour scheme instead of the light one."
+_MARK = "USER CORRECTIONS"
+
+
+class _AmendingWorker(FakeWorker):
+ """A worker during whose chosen attempt the user corrects the mission."""
+
+ def __init__(self, *, amend_during: int) -> None:
+ super().__init__()
+ self._amend_during = amend_during
+ self.kontrollierer = None
+ self.mission_id = ""
+
+ async def spawn(self, prompt, **kwargs):
+ attempt = len(self.spawn_calls)
+ async for event in super().spawn(prompt, **kwargs):
+ yield event
+ if attempt == self._amend_during:
+ self.kontrollierer.amend_mission(self.mission_id, _CORRECTION)
+
+
+async def _run(manager, tmp_path, critic, worker, *, amend_first: bool = False): # noqa: F811
+ k = _make_kontrollierer(
+ manager=manager, tmp_path=tmp_path, critic=critic, worker_factory_fn=lambda step: worker
+ )
+ mid = await manager.dispatch(prompt="build the settings page")
+ if isinstance(worker, _AmendingWorker):
+ worker.kontrollierer, worker.mission_id = k, mid
+ if amend_first:
+ k.amend_mission(mid, _CORRECTION)
+ return k, mid, await k.run_mission(mid)
+
+
+async def test_a_correction_during_an_attempt_is_followed_by_one_more(
+ manager: MissionManager, tmp_path: Path # noqa: F811
+) -> None:
+ critic = FakeCriticRunner(_make_approve_verdict(), _make_approve_verdict())
+ worker = _AmendingWorker(amend_during=0)
+ k, mid, end = await _run(manager, tmp_path, critic, worker)
+ assert end == MissionState.APPROVED
+ first, second = (call["prompt"] for call in worker.spawn_calls)
+ assert _MARK not in first
+ # The step's own task stays; the correction is added in front of it.
+ assert _MARK in second and _CORRECTION in second and second.endswith("do task")
+ # The second result is judged against the task as the user corrected it.
+ assert _CORRECTION not in critic.calls[0]["mission_prompt"]
+ assert _CORRECTION in critic.calls[1]["mission_prompt"]
+ assert k.mission_corrections(mid)["unapplied_corrections"] == []
+
+
+async def test_a_correction_given_before_the_first_attempt_needs_no_extra_one(
+ manager: MissionManager, tmp_path: Path # noqa: F811
+) -> None:
+ critic = FakeCriticRunner(_make_approve_verdict())
+ worker = FakeWorker()
+ k, mid, end = await _run(manager, tmp_path, critic, worker, amend_first=True)
+ assert end == MissionState.APPROVED and len(worker.spawn_calls) == 1
+ assert _CORRECTION in worker.spawn_calls[0]["prompt"]
+ assert _CORRECTION in critic.calls[0]["mission_prompt"]
+ assert [item["text"] for item in k.mission_corrections(mid)["corrections"]] == [_CORRECTION]
+
+
+async def test_without_corrections_nothing_is_added_to_the_task(
+ manager: MissionManager, tmp_path: Path # noqa: F811
+) -> None:
+ critic = FakeCriticRunner(_make_approve_verdict())
+ worker = FakeWorker()
+ k, mid, end = await _run(manager, tmp_path, critic, worker)
+ assert end == MissionState.APPROVED and len(worker.spawn_calls) == 1
+ assert _MARK not in worker.spawn_calls[0]["prompt"]
+ assert critic.calls[0]["mission_prompt"] == "build the settings page"
+ assert k.mission_corrections(mid) == {}
+
+
+async def test_a_correction_during_the_last_attempt_is_reported_as_not_applied(
+ manager: MissionManager, tmp_path: Path # noqa: F811
+) -> None:
+ critic = FakeCriticRunner(
+ _make_revise_verdict("first"), _make_revise_verdict("second"), _make_approve_verdict()
+ )
+ worker = _AmendingWorker(amend_during=orchestrator.MAX_CRITIC_LOOPS - 1)
+ k, mid, end = await _run(manager, tmp_path, critic, worker)
+ assert end == MissionState.APPROVED
+ assert len(worker.spawn_calls) == orchestrator.MAX_CRITIC_LOOPS # no attempt beyond the cap
+ late = k.mission_corrections(mid)["unapplied_corrections"]
+ assert [item["text"] for item in late] == [_CORRECTION]
+
+
+async def test_no_extra_attempt_is_started_without_time_to_finish_it(
+ manager: MissionManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch # noqa: F811
+) -> None:
+ monkeypatch.setattr(orchestrator, "_TASK_TIME_BUDGET_S", 0.0)
+ critic = FakeCriticRunner(_make_approve_verdict(), _make_approve_verdict())
+ worker = _AmendingWorker(amend_during=0)
+ k, mid, end = await _run(manager, tmp_path, critic, worker)
+ assert end == MissionState.APPROVED and len(worker.spawn_calls) == 1
+ assert len(k.mission_corrections(mid)["unapplied_corrections"]) == 1
+
+
+def test_an_empty_or_oversized_correction_is_refused(tmp_path: Path) -> None:
+ from jarvis.missions.corrections import MAX_CORRECTION_CHARS, CorrectionInbox
+
+ inbox = CorrectionInbox(tmp_path / "mission")
+ for bad in ("", " ", "x" * (MAX_CORRECTION_CHARS + 1)):
+ with pytest.raises(ValueError):
+ inbox.add(bad)
+ assert inbox.read() == []
+
+
+def test_corrections_survive_a_restart_and_a_torn_last_line(tmp_path: Path) -> None:
+ from jarvis.missions.corrections import CorrectionInbox, render
+
+ inbox = CorrectionInbox(tmp_path / "mission")
+ inbox.add("First correction\nover two lines")
+ inbox.add("Second correction")
+ with inbox.path.open("a", encoding="utf-8") as handle:
+ handle.write('{"text": "torn') # the app died while writing this one
+ reread = CorrectionInbox(tmp_path / "mission").read()
+ assert [(item.number, item.text) for item in reread] == [
+ (1, "First correction over two lines"),
+ (2, "Second correction"),
+ ]
+ block = render(reread)
+ assert block.index("1. First") < block.index("2. Second")
+ assert "a later correction wins over an earlier one" in block
+ assert render([]) == ""
+
+
+def test_a_correction_added_after_a_torn_line_is_kept_and_returned(tmp_path: Path) -> None:
+ from jarvis.missions.corrections import CorrectionInbox
+
+ inbox = CorrectionInbox(tmp_path / "mission")
+ inbox.add("First correction")
+ with inbox.path.open("a", encoding="utf-8") as handle:
+ handle.write('{"text": "torn') # the app died while writing this one
+ added = inbox.add("Second correction")
+ assert (added.number, added.text) == (2, "Second correction")
+ assert [item.text for item in inbox.read()] == ["First correction", "Second correction"]
+
+
+def test_steps_noting_late_corrections_at_once_lose_none(tmp_path: Path) -> None:
+ from concurrent.futures import ThreadPoolExecutor
+
+ from jarvis.missions.corrections import CorrectionInbox
+
+ inbox = CorrectionInbox(tmp_path / "mission")
+ corrections = [inbox.add(f"Correction {index}") for index in range(12)]
+ with ThreadPoolExecutor(max_workers=12) as pool:
+ list(
+ pool.map(lambda item: inbox.note_unapplied(f"step-{item.number}", [item]), corrections)
+ )
+ assert [item.number for item in inbox.unapplied()] == list(range(1, 13))
+
+
+def test_an_unreadable_record_of_late_corrections_is_reported_not_fatal(
+ tmp_path: Path, caplog: pytest.LogCaptureFixture
+) -> None:
+ from jarvis.missions.corrections import CorrectionInbox
+
+ inbox = CorrectionInbox(tmp_path / "mission")
+ inbox.add("Only correction")
+ inbox.path.with_name("corrections-unapplied.json").write_text("{not json", encoding="utf-8")
+ with caplog.at_level("WARNING"):
+ assert inbox.unapplied() == []
+ assert "Unreadable record of late corrections" in caplog.text
+
+
+async def test_the_extra_attempt_is_recorded_as_the_users_wish_not_the_reviewers(
+ manager: MissionManager, tmp_path: Path # noqa: F811
+) -> None:
+ from jarvis.missions.events import WorkerCorrectionRequired
+
+ critic = FakeCriticRunner(_make_approve_verdict(), _make_approve_verdict())
+ worker = _AmendingWorker(amend_during=0)
+ _k, mid, _end = await _run(manager, tmp_path, critic, worker)
+ asked = [
+ envelope for envelope in await manager.store.events_for_mission(mid)
+ if isinstance(envelope.payload, WorkerCorrectionRequired)
+ ]
+ assert [(e.source_actor, e.payload.correction_instruction) for e in asked] == [
+ ("ui", _CORRECTION)
+ ]