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
fix(agentic-ide): a dead writer costs the provider, not the brief
Ruben Lütkee834c3282cfe
diff --git a/jarvis/agentic_ide/prompt_composer.py b/jarvis/agentic_ide/prompt_composer.pyindex e37d588e4a..a26c568e55 100644--- a/jarvis/agentic_ide/prompt_composer.py+++ b/jarvis/agentic_ide/prompt_composer.py@@ -34,15 +34,20 @@ What the composed prompt contains, and why each part earns its place:Two-layer construction, because the product must work for a downloader with noAPI key at all (§3):-1. **Composed** — one bounded call to ``resolve_quality_brain``. Deliberately- NOT the full frontier chain: that chain ends in small, fast models so a core- path never dies, and a prompt written by one of those looks fine while being- materially worse. Here the output IS the product, so a chain that cannot- reach a capable model returns nothing and we fall to layer 2 openly.+1. **Composed** — a bounded call to the writer ``jarvis.agentic_ide.writer``+ chose. Deliberately NOT the full frontier chain: that chain ends in small,+ fast models so a core path never dies, and a prompt written by one of those+ looks fine while being materially worse. Here the output IS the product, so+ nothing below the quality tier writes a brief.+ A writer that accepts the job and dies inside it (a depleted key answering+ 429, a CLI printing its own flag error, a hang) hands the brief to the next+ rung instead of ending the composition — one dead credential must not cost+ the feature while another provider is signed in and idle (AP-22). Every+ attempt shares one budget, and the user is told which writer took over.2. **Deterministic fallback** — the same markdown skeleton filled by regex,- used when no provider qualifies, the call fails, times out, or comes back- empty. It is *always* better than the raw transcript, so the feature never- depends on a model being available.+ used when no provider qualifies, or when every writer in the chain fails,+ times out, or comes back empty. It is *always* better than the raw+ transcript, so the feature never depends on a model being available.The composer is honest about which layer produced the result (``composed_by``),because the readback the user hears should not claim more than happened.@@ -120,6 +125,11 @@ COMPOSE_TIMEOUT_S = 90.0# surface; few enough that the agent's context is not flooded with guesses.MAX_FILE_REFERENCES = 5+# The least time a second writer needs to be worth starting. A subscription CLI+# pays a 10-12 s cold process start before it thinks at all, so handing one a+# shorter window buys the deterministic prompt AND the wait.+_MIN_ATTEMPT_S = 20.0+# Speech artefacts the deterministic layer removes. Matching *input vocabulary*# in the supported locales — these are the words people actually say while# thinking, not prose.@@ -193,6 +203,7 @@ class ComposedPrompt:STAGE_START = "start"STAGE_THINKING = "thinking"STAGE_DRAFTING = "drafting"+STAGE_RETRY = "retry"STAGE_READY = "ready"STAGE_FALLBACK = "fallback"STAGE_SENT = "sent"@@ -374,6 +385,42 @@ def _writer_label(brain: object) -> str:return name[:40]+def _retry_message(terminal_name: str, *, reason: str, writer: str) -> str:+ """Said when one writer died and another is taking the brief over.++ Names both halves on purpose. A composition that silently takes twice as+ long looks wedged, and "which model wrote this brief" is a question the+ user is entitled to answer without reading a log file.+ """+ taking_over = f"{writer} is taking over" if writer else "another writer is taking over"+ return f"{terminal_name}'s writer dropped out ({reason}) - {taking_over}."+++def _brief_defect(composed: str) -> str:+ """Why ``composed`` is unusable as a brief, or ``""`` when it is fine.++ Three separate ways an answer arrives without a brief in it, all of which+ used to end the composition and now cost the WRITER rather than the user:++ * Nothing at all came back.+ * It is not a brief. A subscription CLI writes its own errors to stdout, so+ "the process answered" is not "a brief came back" — live 2026-07-26 one+ returned a one-line flag-validation error that shipped as the prompt.+ * It stops mid-sentence. Half a brief READS as a whole one, which is what+ makes it dangerous: the agent starts on an instruction whose second half+ was never written.+ """+ from . import prompt_blueprint as blueprint++ if not composed:+ return "composer returned nothing usable"+ if not blueprint.looks_like_brief(composed):+ return "composer output was not a brief"+ if blueprint.looks_truncated(composed):+ return "composer output was cut off"+ return ""++def announce_delivery(terminal_name: str,*,@@ -459,8 +506,8 @@ def _extract_referenced(text: str) -> list[str]:return seen-def _resolve_writer(): # noqa: ANN202 - Brain | None, avoid an import cycle- """The model that writes prompts, or None when nothing qualifies.+def _resolve_writer(): # noqa: ANN202 - (Brain | None, str), avoid an import cycle+ """The model that writes prompts and where it came from, or ``(None, "")``.Delegates to ``writer.resolve_writer`` so this decision lives in ONE place:the work splitter makes the same choice, and a user who moved briefs onto a@@ -474,8 +521,14 @@ def _resolve_writer(): # noqa: ANN202 - Brain | None, avoid an import cycle"""from .writer import resolve_writer- brain, _source = resolve_writer(cli_timeout_s=COMPOSE_TIMEOUT_S)- return brain+ return resolve_writer(cli_timeout_s=COMPOSE_TIMEOUT_S)+++def _rescue_writer(tried: Sequence[str]): # noqa: ANN202 - (Brain | None, str)+ """The next writer to try after one accepted the job and failed inside it."""+ from .writer import resolve_rescue_writer++ return resolve_rescue_writer(cli_timeout_s=COMPOSE_TIMEOUT_S, exclude=tuple(tried))# How much of the repository's agent instructions to carry. Enough for the@@ -633,8 +686,8 @@ def _strip_wrapper(text: str) -> str:return stripped-async def _resolved_writer(task: asyncio.Task) -> object | None:- """The writer the background probe found, or None. Never raises.+async def _resolved_writer(task: asyncio.Task) -> tuple[object | None, str]:+ """The writer the background probe found, or ``(None, "")``. Never raises.The probe loads the config and asks every subscription candidate whether itis signed in; a broken one there must cost the deterministic prompt, not@@ -644,7 +697,7 @@ async def _resolved_writer(task: asyncio.Task) -> object | None:return await taskexcept Exception: # noqa: BLE001 - resolution never breaks a compositionlogger.info("Agentic IDE writer resolution failed", exc_info=True)- return None+ return None, ""def _discard(task: asyncio.Task) -> None:@@ -762,65 +815,90 @@ async def compose(# subscription CLI the probe is the longer of the two.context_task = asyncio.create_task(_read_context(session, candidates))- writer = brain if writer_task is None else await _resolved_writer(writer_task)+ writer, writer_source = (+ (brain, "") if writer_task is None else await _resolved_writer(writer_task)+ )if writer is None:- # Deliberately NOT falling through to whatever model is left: see the- # module docstring. Plain and honest beats polished and quietly worse.+ # An unhonourable PIN still degrades here rather than quietly landing on+ # a provider the user did not choose: plain and honest beats polished+ # and quietly worse. Surviving a chosen writer is a different question,+ # answered by the loop below._discard(context_task)return degrade("no quality-tier provider reachable")- try:- composed = await asyncio.wait_for(- _compose_once(- brain=writer,- session=session,- said=said,- base_instruction=base_instruction,- terminal_name=terminal_name,- agent_display=agent_display,- candidates=candidates,- kind=kind,- context=context_task,- notify=notify,- attachments=attached,- conversation=spoken_before,- ),- timeout=COMPOSE_TIMEOUT_S,- )- composed = _strip_wrapper(composed)- except TimeoutError:- _discard(context_task)- return degrade(f"composer timed out after {COMPOSE_TIMEOUT_S:g}s")- except Exception as exc: # noqa: BLE001 - any provider failure degrades- logger.info("Agentic IDE prompt composer fell back: {}", exc)- _discard(context_task)- return degrade(f"composer unavailable ({type(exc).__name__})")-- if not composed:- return degrade("composer returned nothing usable")-- if not blueprint.looks_like_brief(composed):- # A subscription CLI writes its own errors to stdout, so "the process- # answered" is not the same as "a brief came back". Live 2026-07-26: one- # returned a one-line flag-validation error that shipped as the composed- # prompt. Anything without a single heading is debris, not a task.- logger.info(- "Agentic IDE prompt composer returned something that is not a brief "- "({} chars) — falling back",- len(composed),- )- return degrade("composer output was not a brief")+ # A writer that accepts the job and then dies inside it — a depleted key+ # answering 429, a CLI printing its own flag error to stdout, a provider+ # hanging — used to end the composition on the raw spoken sentence while a+ # second, signed-in provider sat idle. Measured on the dev box 2026-08-02:+ # every composition for days. That is the single-provider brick of AP-22,+ # so a failed attempt crosses to the next rung.+ #+ # All attempts share ONE budget. The user is waiting through the whole+ # sequence, and three full timeouts in a row is not a rescue — it is the+ # same fallback three times slower.+ deadline = started + COMPOSE_TIMEOUT_S+ tried: list[str] = [writer_source] if writer_source else []+ composed = ""+ reason = ""++ while True:+ remaining = deadline - time.monotonic()+ if remaining < _MIN_ATTEMPT_S:+ _discard(context_task)+ return degrade(reason or f"composer timed out after {COMPOSE_TIMEOUT_S:g}s")- if blueprint.looks_truncated(composed):- # Half a brief reads as a whole one, which is exactly what makes it- # dangerous: the agent starts on an instruction whose second half was- # never written. The plain deterministic prompt is worse but complete.- logger.info(- "Agentic IDE prompt composer produced a truncated brief ({} chars) "- "— falling back",- len(composed),+ try:+ composed = _strip_wrapper(+ await asyncio.wait_for(+ _compose_once(+ brain=writer,+ session=session,+ said=said,+ base_instruction=base_instruction,+ terminal_name=terminal_name,+ agent_display=agent_display,+ candidates=candidates,+ kind=kind,+ context=context_task,+ notify=notify,+ attachments=attached,+ conversation=spoken_before,+ ),+ timeout=remaining,+ )+ )+ except TimeoutError:+ composed, reason = "", f"composer timed out after {COMPOSE_TIMEOUT_S:g}s"+ except Exception as exc: # noqa: BLE001 - any provider failure crosses over+ logger.info("Agentic IDE prompt composer failed on {}: {}", writer_source, exc)+ composed, reason = "", f"composer unavailable ({type(exc).__name__})"+ else:+ reason = _brief_defect(composed)+ if not reason:+ break+ logger.info(+ "Agentic IDE prompt composer: {} from {} ({} chars)",+ reason,+ writer_source or "the pinned writer",+ len(composed),+ )++ if writer_task is None:+ # The caller pinned this model explicitly. Substituting another one+ # is not ours to decide.+ _discard(context_task)+ return degrade(reason)++ nxt, nxt_source = await asyncio.to_thread(_rescue_writer, tried)+ if nxt is None:+ _discard(context_task)+ return degrade(reason)+ writer, writer_source = nxt, nxt_source+ tried.append(nxt_source)+ notify(+ STAGE_RETRY,+ _retry_message(terminal_name, reason=reason, writer=_writer_label(nxt)),)- return degrade("composer output was cut off")# Keep only the references that survive an existence check — the model may# echo a candidate that was renamed, or invent one outright. A dead @path@@ -858,6 +936,7 @@ __all__ = ["STAGE_DRAFTING","STAGE_FALLBACK","STAGE_READY",+ "STAGE_RETRY","STAGE_SENT","STAGE_START","STAGE_THINKING",diff --git a/jarvis/agentic_ide/work_split.py b/jarvis/agentic_ide/work_split.pyindex 994bc8fed8..5a75febd04 100644--- a/jarvis/agentic_ide/work_split.py+++ b/jarvis/agentic_ide/work_split.py@@ -36,6 +36,7 @@ from __future__ import annotationsimport asyncioimport jsonimport re+import timefrom collections.abc import Sequencefrom dataclasses import dataclassfrom pathlib import Path@@ -57,6 +58,10 @@ from loguru import logger#: is a reprieve, not a target: a healthy split still returns in a few seconds.SPLIT_TIMEOUT_S = 60.0+#: The least time a second planner needs to be worth starting. A subscription+#: CLI pays a 10-12 s cold process start before it thinks at all.+_MIN_ATTEMPT_S = 20.0+#: A fleet larger than this is not a split any model plans usefully, and the#: deterministic layer runs out of real directories long before it. Above the#: cap the areas repeat by index, which stays honest (each agent still gets its@@ -93,8 +98,8 @@ class WorkSplit:"""Why the fallback was used, when it was. Empty on the happy path."""-def _resolve_splitter() -> Any:- """The model that plans a split, or None when nothing qualifies.+def _resolve_splitter() -> tuple[Any, str]:+ """The model that plans a split, or ``(None, "")`` when nothing qualifies.Shares ``writer.resolve_writer`` with the prompt composer on purpose: thesetwo are the Agentic IDE's only billed calls, and a user who moved briefs@@ -102,8 +107,20 @@ def _resolve_splitter() -> Any:"""from .writer import resolve_writer- brain, _source = resolve_writer(cli_timeout_s=SPLIT_TIMEOUT_S)- return brain+ return resolve_writer(cli_timeout_s=SPLIT_TIMEOUT_S)+++def _rescue_splitter(tried: Sequence[str]) -> tuple[Any, str]:+ """The next planner after one accepted the job and failed inside it.++ Same reasoning as the composer's rescue: a depleted key answering 429 must+ cost the provider, not the fleet. A crude by-directory split while a+ signed-in provider sits idle is the invisible degradation this module's own+ docstring warns about.+ """+ from .writer import resolve_rescue_writer++ return resolve_rescue_writer(cli_timeout_s=SPLIT_TIMEOUT_S, exclude=tuple(tried))_SYSTEM_PROMPT = (@@ -361,7 +378,14 @@ async def split(said, folder=folder, count=wanted, note="fleet larger than the planning cap")- planner = brain if brain is not None else _resolve_splitter()+ pinned = brain is not None+ if pinned:+ planner, planner_source = brain, ""+ else:+ # Off the event loop: this loads the config and probes every+ # subscription candidate for a sign-in, and a fan-out has N panes+ # waiting behind it.+ planner, planner_source = await asyncio.to_thread(_resolve_splitter)if planner is None:return _fallback(said,@@ -378,59 +402,71 @@ async def split(except Exception: # noqa: BLE001 - a profile is context, never requiredprofile_lines = []- try:- areas = await asyncio.to_thread(_top_level_areas, folder)- payload = await asyncio.wait_for(- _llm_split(- brain=planner,- system_prompt=_SYSTEM_PROMPT,- user_block=_user_block(- instruction=said,- count=wanted,- folder=folder,- areas=areas,- profile=profile_lines,- conversation=tuple(conversation or ()),- ),- ),- timeout=timeout_s,- )- except TimeoutError:- return _fallback(- said,- folder=folder,- count=wanted,- note=f"the planner timed out after {timeout_s:g}s",- )- except Exception as exc: # noqa: BLE001 - any provider failure degrades- logger.info("Agentic IDE work split fell back: {}", exc)- return _fallback(- said,- folder=folder,- count=wanted,- note=f"the planner was unavailable ({type(exc).__name__})",- )+ areas = await asyncio.to_thread(_top_level_areas, folder)+ user_block = _user_block(+ instruction=said,+ count=wanted,+ folder=folder,+ areas=areas,+ profile=profile_lines,+ conversation=tuple(conversation or ()),+ )- parsed = _parse(payload, count=wanted, instruction=said)- if parsed is None:- logger.info(- "Agentic IDE work split: planner answer rejected "- "(wanted {} distinct assignments) — splitting deterministically",- wanted,- )- return _fallback(- said,- folder=folder,- count=wanted,- note="the planner's answer was incomplete or overlapping",- )+ # One budget across every attempt: a planner that dies hands the plan to the+ # next rung rather than dropping the fleet onto the by-directory split while+ # a working provider sits idle (AP-22) — but N full timeouts in a row would+ # be the same crude split, only minutes later.+ deadline = time.monotonic() + timeout_s+ tried: list[str] = [planner_source] if planner_source else []+ note = ""++ while True:+ remaining = deadline - time.monotonic()+ if remaining < _MIN_ATTEMPT_S:+ return _fallback(+ said,+ folder=folder,+ count=wanted,+ note=note or f"the planner timed out after {timeout_s:g}s",+ )- logger.info(- "Agentic IDE work split: {} areas planned ({})",- len(parsed),- ", ".join(a.area for a in parsed),- )- return WorkSplit(assignments=tuple(parsed), split_by="llm")+ try:+ payload = await asyncio.wait_for(+ _llm_split(brain=planner, system_prompt=_SYSTEM_PROMPT, user_block=user_block),+ timeout=remaining,+ )+ except TimeoutError:+ note = f"the planner timed out after {timeout_s:g}s"+ except Exception as exc: # noqa: BLE001 - any provider failure crosses over+ logger.info(+ "Agentic IDE work split failed on {}: {}", planner_source or "the planner", exc+ )+ note = f"the planner was unavailable ({type(exc).__name__})"+ else:+ parsed = _parse(payload, count=wanted, instruction=said)+ if parsed is not None:+ logger.info(+ "Agentic IDE work split: {} areas planned ({})",+ len(parsed),+ ", ".join(a.area for a in parsed),+ )+ return WorkSplit(assignments=tuple(parsed), split_by="llm")+ logger.info(+ "Agentic IDE work split: answer from {} rejected (wanted {} distinct assignments)",+ planner_source or "the planner",+ wanted,+ )+ note = "the planner's answer was incomplete or overlapping"++ if pinned:+ # The caller chose this model; substituting one is not ours to do.+ return _fallback(said, folder=folder, count=wanted, note=note)++ nxt, nxt_source = await asyncio.to_thread(_rescue_splitter, tried)+ if nxt is None:+ return _fallback(said, folder=folder, count=wanted, note=note)+ planner, planner_source = nxt, nxt_source+ tried.append(nxt_source)__all__ = [diff --git a/jarvis/agentic_ide/writer.py b/jarvis/agentic_ide/writer.pyindex c8ef90e073..d7738c048f 100644--- a/jarvis/agentic_ide/writer.py+++ b/jarvis/agentic_ide/writer.py@@ -27,11 +27,26 @@ per install. Nothing in this module names a vendor: the subscription rung asksthe provider cards which providers bill that way (AP-21/22), so whichever CLIthe user connected is the one that writes.+**Choosing a writer and surviving one are different questions**+(``resolve_rescue_writer``). The order above answers "who should write this",+and a pin that cannot be honoured there degrades openly — that half is+unchanged. What it does NOT answer is what happens when the chosen writer+accepts the job and dies inside it: a depleted key answering 429, a CLI+returning its own flag error on stdout, a provider timing out. Measured on the+dev box 2026-08-02: the writer resolved to a key whose prepayment credits were+gone, so EVERY composition ended on the raw spoken sentence while a signed-in+subscription sat unused. Treating a runtime failure as "the user gets no+brief" is the single-provider brick AP-22 exists to forbid, so a dead call+crosses to the next rung instead. That is not a silent substitution: the+composer names the writer that ended up writing, and the rung that died.+Never raises. Every failure here costs a rougher prompt; none of them may costthe user their instruction."""+from __future__ import annotations+from collections.abc import Sequencefrom typing import Anyfrom loguru import logger@@ -106,6 +121,49 @@ def resolve_writer(*, cli_timeout_s: float | None = None) -> tuple[Any | None, sreturn _api_writer(config)+# The rungs a dead call may cross to, best first. Deliberately the same three+# the pins name, so "who writes" and "who rescues" can never drift apart.+_RESCUE_ORDER = ("tool_model", "subscription", "api")+++def resolve_rescue_writer(+ *, cli_timeout_s: float | None = None, exclude: Sequence[str] = ()+) -> tuple[Any | None, str]:+ """The next writer to try after one accepted the job and failed inside it.++ ``exclude`` is the sources already tried, in the ``rung`` or ``rung:name``+ shape ``resolve_writer`` returns; only the rung part is compared, because+ re-probing the same tier with a different model name would just spend the+ same dead credential twice.++ Returns ``(None, "")`` when nothing is left, and the caller then uses its+ deterministic layer. Only reached AFTER a real failure — an unhonourable+ pin still degrades at resolution time rather than quietly landing on a+ provider the user did not choose.+ """+ tried = {str(source).split(":", 1)[0] for source in exclude if source}+ try:+ config = _load_config()+ except Exception: # noqa: BLE001 - a rescue never breaks a turn+ logger.info("Agentic IDE rescue writer could not be resolved", exc_info=True)+ return None, ""++ for rung in _RESCUE_ORDER:+ if rung in tried:+ continue+ if rung == "tool_model":+ brain, source = _tool_model_writer(config)+ elif rung == "subscription":+ brain = _try_subscription(config, cli_timeout_s)+ source = f"subscription:{getattr(brain, 'name', None) or 'subscription'}"+ else:+ brain, source = _api_writer(config)+ if brain is not None:+ logger.info("Agentic IDE brief falls across to {} after a failed writer", source)+ return brain, source+ return None, ""++def _try_subscription(config: Any, cli_timeout_s: float | None) -> Any | None:"""A connected subscription brain, or None. A failure here is not fatal."""try:@@ -151,4 +209,4 @@ def _tool_model_writer(config: Any) -> tuple[Any | None, str]:return brain, f"tool_model:{name}"-__all__ = ["resolve_writer"]+__all__ = ["resolve_rescue_writer", "resolve_writer"]diff --git a/tests/unit/agentic_ide/test_composer_progress.py b/tests/unit/agentic_ide/test_composer_progress.pyindex 0cae1c0feb..eed83fc07b 100644--- a/tests/unit/agentic_ide/test_composer_progress.py+++ b/tests/unit/agentic_ide/test_composer_progress.py@@ -40,7 +40,7 @@ class _StreamingBrain:@pytest.fixture(autouse=True)def _writer_available(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: _Writer())+ monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: (_Writer(), "test"))def _session(tmp_path) -> object: # noqa: ANN001 - pytest tmp_path@@ -195,7 +195,7 @@ async def test_degrading_is_announced_rather_than_hidden("""A plain brief is a fine outcome; a plain brief passed off as a writtenone is not — the readback afterwards would claim more than happened."""seen: list[prompt_composer.ComposeNotice] = []- monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: None)+ monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: (None, ""))result = await prompt_composer.compose("review the wake word detection",diff --git a/tests/unit/agentic_ide/test_composer_writer_rescue.py b/tests/unit/agentic_ide/test_composer_writer_rescue.pynew file mode 100644index 0000000000..9a9fc24000--- /dev/null+++ b/tests/unit/agentic_ide/test_composer_writer_rescue.py@@ -0,0 +1,230 @@+"""A writer that dies mid-call costs the WRITER, not the brief.++Resolving a writer and surviving one are different questions. The first has+guards in ``test_writer_resolution.py``; this file covers what actually broke+the feature on the dev box (2026-08-02): the resolved writer was a key whose+prepayment credits were gone, it answered 429 on every call, and the composer+handed the agent the raw spoken sentence for days while a signed-in+subscription sat unused. One dead credential must not brick the feature when+another provider is right there (AP-22).+"""+from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path++import pytest++from jarvis.agentic_ide import file_index, prompt_composer++BRIEF = "## Task\nMake the wake path faster.\n\n## Done when\n- It is faster."+++@dataclass+class _Profile:+ lines: list[str] = field(default_factory=lambda: ["Folder: /work/project"])++ def summary_lines(self) -> list[str]:+ return self.lines+++@dataclass+class _Session:+ folder: str+ profile: _Profile = field(default_factory=_Profile)+++class _Writer:+ """A resolved Brain. Which one it is only matters through its name."""++ def __init__(self, name: str) -> None:+ self.name = name+++def workspace(tmp_path: Path) -> _Session:+ (tmp_path / "jarvis").mkdir(parents=True)+ (tmp_path / "jarvis" / "wake.py").write_text("x")+ file_index.reset_cache()+ file_index._CACHE[str(tmp_path)] = file_index.build_index(tmp_path) # noqa: SLF001+ return _Session(folder=str(tmp_path))+++def _writers(+ monkeypatch: pytest.MonkeyPatch, first: str, rescue: tuple[object, str]+) -> list[str]:+ """Wire a first writer and what the rescue offers. Returns the calls made."""+ used: list[str] = []+ monkeypatch.setattr(+ prompt_composer, "_resolve_writer", lambda: (_Writer(first), f"{first}-rung")+ )+ monkeypatch.setattr(prompt_composer, "_rescue_writer", lambda tried: rescue)+ return used+++async def test_a_depleted_writer_hands_the_brief_to_the_next_one(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The exact live failure, end to end: 429 on the first writer must produce+ a real brief from the second, not the raw sentence."""+ seen: list[str] = []++ async def _compose(*, brain: object, **_kwargs: object) -> str:+ name = getattr(brain, "name", "?")+ seen.append(name)+ if name == "depleted":+ raise RuntimeError("429 RESOURCE_EXHAUSTED")+ return BRIEF++ _writers(monkeypatch, "depleted", (_Writer("working"), "tool_model:working"))+ monkeypatch.setattr(prompt_composer, "_llm_compose", _compose)++ result = await prompt_composer.compose(+ "make the wake path faster", session=workspace, terminal_name="Kai"+ )++ assert seen == ["depleted", "working"]+ assert result.composed_by == "llm"+ assert "## Task" in result.text+++async def test_the_user_is_told_which_writer_took_over(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A composition that silently takes twice as long looks wedged, and which+ model wrote a brief is not a log-file-only question."""+ notices: list[prompt_composer.ComposeNotice] = []++ async def _compose(*, brain: object, **_kwargs: object) -> str:+ if getattr(brain, "name", "") == "depleted":+ raise RuntimeError("429 RESOURCE_EXHAUSTED")+ return BRIEF++ _writers(monkeypatch, "depleted", (_Writer("working"), "tool_model:working"))+ monkeypatch.setattr(prompt_composer, "_llm_compose", _compose)++ await prompt_composer.compose(+ "make the wake path faster",+ session=workspace,+ terminal_name="Kai",+ on_progress=notices.append,+ )++ retries = [n for n in notices if n.stage == prompt_composer.STAGE_RETRY]+ assert len(retries) == 1+ assert "working" in retries[0].message+ assert retries[0].terminal == "Kai"+++async def test_debris_from_a_cli_also_crosses_over(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A CLI that prints its own flag error to stdout "answered" without writing+ a brief. That is the provider failing, so the next one gets a turn."""++ async def _compose(*, brain: object, **_kwargs: object) -> str:+ if getattr(brain, "name", "") == "broken-cli":+ return 'Error: invalid model selection (--model "x" --effort "")'+ return BRIEF++ _writers(monkeypatch, "broken-cli", (_Writer("working"), "api"))+ monkeypatch.setattr(prompt_composer, "_llm_compose", _compose)++ result = await prompt_composer.compose(+ "make the wake path faster", session=workspace, terminal_name="Kai"+ )++ assert result.composed_by == "llm"+ assert "## Task" in result.text+++async def test_the_dead_rung_is_named_so_it_is_not_retried(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Re-probing the tier that just died spends the same dead credential."""+ excluded: list[tuple[str, ...]] = []++ async def _boom(**_kwargs: object) -> str:+ raise RuntimeError("429 RESOURCE_EXHAUSTED")++ monkeypatch.setattr(+ prompt_composer, "_resolve_writer", lambda: (_Writer("depleted"), "api")+ )+ monkeypatch.setattr(+ prompt_composer,+ "_rescue_writer",+ lambda tried: excluded.append(tuple(tried)) or (None, ""),+ )+ monkeypatch.setattr(prompt_composer, "_llm_compose", _boom)++ await prompt_composer.compose(+ "make the wake path faster", session=workspace, terminal_name="Kai"+ )++ assert excluded == [("api",)]+++async def test_nothing_left_still_delivers_the_deterministic_prompt(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The contract that outranks everything: the instruction always arrives."""++ async def _boom(**_kwargs: object) -> str:+ raise RuntimeError("429 RESOURCE_EXHAUSTED")++ _writers(monkeypatch, "depleted", (None, ""))+ monkeypatch.setattr(prompt_composer, "_llm_compose", _boom)++ result = await prompt_composer.compose(+ "make the wake path faster", session=workspace, terminal_name="Kai"+ )++ assert result.composed_by == "fallback"+ assert "make the wake path faster" in result.text+++async def test_a_caller_pinned_model_is_never_substituted(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """``brain=`` is the caller deciding. A fan-out reusing one resolved writer+ across five panes must not have each pane wander off to its own provider."""++ async def _boom(**_kwargs: object) -> str:+ raise RuntimeError("429 RESOURCE_EXHAUSTED")++ monkeypatch.setattr(+ prompt_composer, "_rescue_writer", lambda tried: pytest.fail("substituted a pin")+ )+ monkeypatch.setattr(prompt_composer, "_llm_compose", _boom)++ result = await prompt_composer.compose(+ "make the wake path faster",+ session=workspace,+ terminal_name="Kai",+ brain=_Writer("pinned"),+ )++ assert result.composed_by == "fallback"+++async def test_the_rescue_shares_one_budget_with_the_first_attempt(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Three writers each burning a full timeout is not a rescue — it is the+ same fallback, minutes later. Once the budget is spent, no one else starts."""+ started: list[str] = []++ async def _hang(*, brain: object, **_kwargs: object) -> str:+ started.append(getattr(brain, "name", "?"))+ raise TimeoutError++ monkeypatch.setattr(prompt_composer, "COMPOSE_TIMEOUT_S", 0.0)+ _writers(monkeypatch, "slow", (_Writer("also-slow"), "api"))+ monkeypatch.setattr(prompt_composer, "_llm_compose", _hang)++ result = await prompt_composer.compose(+ "make the wake path faster", session=workspace, terminal_name="Kai"+ )++ assert started == []+ assert result.composed_by == "fallback"diff --git a/tests/unit/agentic_ide/test_fanout_route.py b/tests/unit/agentic_ide/test_fanout_route.pyindex b6dbdfe448..397edeea56 100644--- a/tests/unit/agentic_ide/test_fanout_route.py+++ b/tests/unit/agentic_ide/test_fanout_route.py@@ -44,7 +44,7 @@ def _offline_planner(monkeypatch: pytest.MonkeyPatch) -> None:That is the configuration an arbitrary downloader has, so pinning the routeagainst it is the point rather than a shortcut (§3)."""- monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: (None, ""))async def fake_compose(utterance: str, **kwargs: object) -> ComposedPrompt:name = kwargs["terminal_name"]diff --git a/tests/unit/agentic_ide/test_prompt_composer.py b/tests/unit/agentic_ide/test_prompt_composer.pyindex caadacef97..0de6790468 100644--- a/tests/unit/agentic_ide/test_prompt_composer.py+++ b/tests/unit/agentic_ide/test_prompt_composer.py@@ -49,7 +49,7 @@ def _writer_available(monkeypatch: pytest.MonkeyPatch) -> None:machine with no keys returns None and sends every test down thedeterministic path."""- monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: _Writer())+ monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: (_Writer(), "test"))@pytest.fixture()@@ -291,7 +291,7 @@ async def test_no_quality_writer_degrades_openly() -> None:"""Rather than silently demoting to whatever small model is left."""_prime(workspace)- monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: None)+ monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: (None, ""))result = await prompt_composer.compose("review the vosk wake provider", session=workspace, terminal_name="Kai"diff --git a/tests/unit/agentic_ide/test_work_split.py b/tests/unit/agentic_ide/test_work_split.pyindex 340c334d77..9ad91c6cae 100644--- a/tests/unit/agentic_ide/test_work_split.py+++ b/tests/unit/agentic_ide/test_work_split.py@@ -47,7 +47,7 @@ class _Splitter:@pytest.fixture(autouse=True)def _splitter_available(monkeypatch: pytest.MonkeyPatch) -> None:"""A quality-tier model is reachable unless a test says otherwise."""- monkeypatch.setattr(work_split, "_resolve_splitter", lambda: _Splitter())+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: (_Splitter(), "test"))@pytest.fixture()@@ -182,7 +182,7 @@ async def test_no_quality_provider_still_splits(workspace: _Session, monkeypatch: pytest.MonkeyPatch) -> None:"""A downloader with no API key must still be able to run a fleet (§3)."""- monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: (None, ""))result = await work_split.split("analyse it", session=workspace, count=3)assert result.split_by == "fallback"assert len(result.assignments) == 3@@ -192,7 +192,7 @@ async def test_no_quality_provider_still_splits(async def test_the_deterministic_split_uses_real_directories(workspace: _Session, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: (None, ""))result = await work_split.split("analyse it", session=workspace, count=3)areas = " ".join(a.area for a in result.assignments)# The fixture workspace has jarvis/, docs/ and tests/ — the split must name@@ -203,7 +203,7 @@ async def test_the_deterministic_split_uses_real_directories(async def test_the_deterministic_split_never_repeats_an_area(workspace: _Session, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: (None, ""))result = await work_split.split("analyse it", session=workspace, count=3)areas = [a.area for a in result.assignments]assert len(set(areas)) == len(areas)@@ -213,7 +213,7 @@ async def test_every_assignment_carries_the_original_order(workspace: _Session, monkeypatch: pytest.MonkeyPatch) -> None:"""A slice without the goal is an agent doing something else entirely."""- monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: (None, ""))result = await work_split.split("check cross-platform support", session=workspace, count=3)@@ -225,7 +225,7 @@ async def test_more_agents_than_directories_still_gets_everyone_a_slice(workspace: _Session, monkeypatch: pytest.MonkeyPatch) -> None:"""Eight agents on a four-directory repo: nobody may be left idle."""- monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: (None, ""))result = await work_split.split("analyse it", session=workspace, count=8)assert len(result.assignments) == 8assert all(a.task.strip() for a in result.assignments)@@ -236,7 +236,7 @@ async def test_an_empty_folder_still_produces_one_slice_per_agent(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:"""No readable structure is not a reason to brief nobody."""- monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: (None, ""))file_index.reset_cache()result = await work_split.split("analyse it", session=_Session(folder=str(tmp_path)), count=3@@ -250,3 +250,75 @@ async def test_zero_or_negative_counts_are_refused_not_guessed() -> None:result = await work_split.split("analyse it", session=workspace, count=0)assert result.assignments == ()+++async def test_a_dead_planner_hands_the_plan_to_the_next_provider(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The composer's failure mode applies here too: a depleted key answering+ 429 must cost the provider, not drop the fleet onto the crude by-directory+ split while a working provider sits idle (AP-22)."""+ calls: list[int] = []++ async def fake_llm_split(**_kwargs: object) -> str:+ calls.append(1)+ if len(calls) == 1:+ raise RuntimeError("429 RESOURCE_EXHAUSTED")+ return VALID_THREE++ monkeypatch.setattr(work_split, "_llm_split", fake_llm_split)+ monkeypatch.setattr(+ work_split, "_rescue_splitter", lambda tried: (_Splitter(), "tool_model:working")+ )++ result = await work_split.split("analyse it", session=workspace, count=3)++ assert result.split_by == "llm"+ assert len(result.assignments) == 3+ assert len(calls) == 2+++async def test_the_rung_that_died_is_named_for_the_rescue(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Re-probing the tier that just failed spends the same dead credential."""+ excluded: list[tuple[str, ...]] = []++ async def fake_llm_split(**_kwargs: object) -> str:+ raise RuntimeError("429 RESOURCE_EXHAUSTED")++ monkeypatch.setattr(work_split, "_llm_split", fake_llm_split)+ monkeypatch.setattr(+ work_split, "_resolve_splitter", lambda: (_Splitter(), "api")+ )+ monkeypatch.setattr(+ work_split,+ "_rescue_splitter",+ lambda tried: excluded.append(tuple(tried)) or (None, ""),+ )++ result = await work_split.split("analyse it", session=workspace, count=3)++ assert excluded == [("api",)]+ assert result.split_by == "fallback"+ assert len(result.assignments) == 3+++async def test_a_pinned_planner_is_never_substituted(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """``brain=`` is the caller deciding which model plans this fleet."""++ async def fake_llm_split(**_kwargs: object) -> str:+ raise RuntimeError("429 RESOURCE_EXHAUSTED")++ monkeypatch.setattr(work_split, "_llm_split", fake_llm_split)+ monkeypatch.setattr(+ work_split, "_rescue_splitter", lambda tried: pytest.fail("substituted a pin")+ )++ result = await work_split.split(+ "analyse it", session=workspace, count=3, brain=_Splitter()+ )++ assert result.split_by == "fallback"diff --git a/tests/unit/agentic_ide/test_writer_rescue.py b/tests/unit/agentic_ide/test_writer_rescue.pynew file mode 100644index 0000000000..04780debcf--- /dev/null+++ b/tests/unit/agentic_ide/test_writer_rescue.py@@ -0,0 +1,131 @@+"""Choosing a writer and surviving one are different questions.++``resolve_writer`` answers the first: a pin that cannot be honoured degrades+openly rather than billing a provider the user did not choose. It says nothing+about the case that actually broke the feature — the chosen writer ACCEPTS the+job and dies inside it. Measured on the dev box 2026-08-02: the resolved writer+was a key whose prepayment credits were gone, so every composition for days+ended on the raw spoken sentence while a signed-in subscription sat unused.+That is the single-provider brick AP-22 forbids.+"""+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.agentic_ide import writer+++def _cfg(choice: str = "auto") -> SimpleNamespace:+ return SimpleNamespace(agentic_ide=SimpleNamespace(prompt_writer=choice))+++def test_a_dead_api_tier_crosses_to_the_tool_model(monkeypatch: pytest.MonkeyPatch) -> None:+ """The exact live failure: the API rung answered 429, so the brief must be+ written by the model the user picked rather than not written at all."""+ monkeypatch.setattr(writer, "_load_config", lambda: _cfg("api"))+ monkeypatch.setattr(writer, "_tool_model", lambda cfg: "tool-brain")+ monkeypatch.setattr(writer, "_quality", lambda cfg: "api-brain")++ brain, source = writer.resolve_rescue_writer(exclude=("api",))++ assert brain == "tool-brain"+ assert source.startswith("tool_model")+++def test_the_rung_that_died_is_never_retried(monkeypatch: pytest.MonkeyPatch) -> None:+ """Re-probing the same tier spends the same dead credential twice."""+ monkeypatch.setattr(writer, "_load_config", lambda: _cfg())+ monkeypatch.setattr(writer, "_tool_model", lambda cfg: "tool-brain")+ monkeypatch.setattr(writer, "_subscription", lambda cfg, timeout: "sub-brain")+ monkeypatch.setattr(writer, "_quality", lambda cfg: "api-brain")++ brain, source = writer.resolve_rescue_writer(exclude=("tool_model:grok",))++ assert brain == "sub-brain"+ assert source.startswith("subscription")+++def test_a_named_source_is_compared_by_its_rung(monkeypatch: pytest.MonkeyPatch) -> None:+ """``subscription:antigravity`` and ``subscription:codex`` are one rung: the+ resolver hands back whichever CLI is connected, so trying again lands on the+ same one."""+ monkeypatch.setattr(writer, "_load_config", lambda: _cfg())+ monkeypatch.setattr(writer, "_tool_model", lambda cfg: None)+ monkeypatch.setattr(+ writer, "_subscription", lambda cfg, timeout: pytest.fail("re-probed a dead rung")+ )+ monkeypatch.setattr(writer, "_quality", lambda cfg: "api-brain")++ brain, source = writer.resolve_rescue_writer(exclude=("subscription:antigravity",))++ assert brain == "api-brain"+ assert source == "api"+++def test_nothing_left_degrades_instead_of_looping(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(writer, "_load_config", lambda: _cfg())+ monkeypatch.setattr(writer, "_tool_model", lambda cfg: None)+ monkeypatch.setattr(writer, "_subscription", lambda cfg, timeout: None)+ monkeypatch.setattr(writer, "_quality", lambda cfg: None)++ assert writer.resolve_rescue_writer() == (None, "")+++def test_a_raising_rung_does_not_stop_the_rescue(monkeypatch: pytest.MonkeyPatch) -> None:+ """A broken CLI probe must not cost the working rung behind it."""++ def _boom(_cfg: object, _timeout: object = None) -> object:+ raise RuntimeError("probe exploded")++ monkeypatch.setattr(writer, "_load_config", lambda: _cfg())+ monkeypatch.setattr(writer, "_tool_model", _boom)+ monkeypatch.setattr(writer, "_subscription", _boom)+ monkeypatch.setattr(writer, "_quality", lambda cfg: "api-brain")++ brain, source = writer.resolve_rescue_writer()++ assert brain == "api-brain"+ assert source == "api"+++def test_rescue_never_raises(monkeypatch: pytest.MonkeyPatch) -> None:+ def _boom() -> object:+ raise RuntimeError("config exploded")++ monkeypatch.setattr(writer, "_load_config", _boom)++ assert writer.resolve_rescue_writer() == (None, "")+++def test_the_cli_timeout_reaches_the_subscription_probe(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A CLI brain's own voice-tier cap must not kill a call the composer is+ still willing to wait for — same contract as the first resolution."""+ seen: list[float | None] = []+ monkeypatch.setattr(writer, "_load_config", lambda: _cfg())+ monkeypatch.setattr(writer, "_tool_model", lambda cfg: None)+ monkeypatch.setattr(+ writer, "_subscription", lambda cfg, timeout: seen.append(timeout) or "sub-brain"+ )++ writer.resolve_rescue_writer(cli_timeout_s=90.0)++ assert seen == [90.0]+++def test_both_call_sites_can_rescue() -> None:+ """The drift guard: a composer that crosses over while the splitter dies on+ the same dead key leaves the fleet on the crude by-directory plan."""+ import inspect++ from jarvis.agentic_ide import prompt_composer, work_split++ for module, function in (+ (prompt_composer, "_rescue_writer"),+ (work_split, "_rescue_splitter"),+ ):+ source = inspect.getsource(getattr(module, function))+ assert "resolve_rescue_writer" in source, f"{module.__name__} cannot cross over"