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
perf(agentic-ide): insurance on the writer's own clock, and a dead hedge is replaced at once
Harald7bca1527688b
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex c53235edce..51b782f850 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -9997,3 +9997,134 @@ hand-off is a no-op elsewhere); `tests/unit/ui/test_native_drop.py`;`tests/unit/web/test_agentic_ide_resolve_folder.py`; frontend`src/lib/nativeDrop.test.ts` and `FolderPicker.test.tsx` ("uses the real paththe desktop shell reports").++## BUG-145: a spoken "T2, do a deep dive on …" reaches the pane 26 s after the sentence ends — the brief writer's `auto` order put a coding CLI's cold process start on the voice turn's critical path, and its insurance was tuned for that CLI alone (HIGH, FIXED 2026-08-18)++**Symptom.** Realtime session `63617599` (2026-08-18 16:10, Vertex Live,+delegate tool mode). The user said "Kannst du bitte Terminal T2 … einen Deep+Dive machen …" and then watched T2 for 26 s before the brief landed+(`Agentic IDE prompt -> T2` at 16:10:50.288; the transcript closed at+16:10:24.15). First audio came at 27.3 s (`first_final_to_first_audio_ms+27338`). The session recorder holds the whole call as 53.3 s with one+sentence in and "Ist bei T2." out. The user's own reading was "my computer is <!-- i18n-allow: quoted voice output -->+lagging".++**Reconstruction (flight recorder + desktop log).**++1. +0.0 s transcript final; +0.5 s the routing decision blocked the event+ loop for 541 ms (`realtime event loop stalled 541 ms` — a stall of+ 500–880 ms is logged at this point of every session, separate issue).+2. +1.1 s → +3.7 s: `AgenticIdeComposeProgress start → thinking`. The writer+ probe (`claude status` + `resolve_subscription_brain: writing on+ claude-cli`) took 2.6 s.+3. +3.7 s → +22.7 s: `claude-cli: spawning print-mode turn (prompt=693+ chars)` … `claude-cli turn ok: 1248 chars in 18.9s`. Nearly all of it was+ the SPAWN, not the writing: an EMPTY answer from the same CLI (the fact+ extractor's `2 chars` turns) took 17.2 s and 18.9 s in the same minute,+ against 5.2–6.2 s at 15:36 and 9–13 s at 16:00. The cold start had+ tripled within an hour, under a load the log shows plainly: two Claude+ Code TUIs had just been spawned in T1/T2 (16:09:38), Gemini Live and the+ wake detectors were running, 117 microphone frames were dropped in the+ session, and right after it three more CLIs (claude, gemini, codex) were+ spawned concurrently for fact extraction.+4. +22.7 s → +26.1 s: the paste was typed; `_await_arrival` polled 3.0 s for+ the text to show on T2's input line and never saw it (`never saw the+ prompt reach T2 — reporting it as unconfirmed`); Enter; delivered.+5. +26.1 s "Ist bei T2." — twice (BUG-143, fixed the same day). No instant <!-- i18n-allow: quoted voice output -->+ ack was spoken at all: unlike the 15:35 and 15:57 sessions there is no+ `delegate bridge: … line requested` line for this call, and in those two+ sessions the composed line was `dropped non-conforming` — the ack shipped+ 2026-08-17 (ADR-0033) has still not produced audio in a live call. Open.++**Root.** Two decisions that were each right for the writer they were+measured against and wrong together on the voice path.+(1) `jarvis/agentic_ide/writer.py`: `auto` preferred a connected coding+subscription because it is work the user has already paid for, and only+then crossed to the API tier. A subscription CLI pays a cold process start+per brief — 10–12 s in the 2026-07-26 measurement that raised the compose+budget to 90 s, 16–25 s end to end for a lean brief on 2026-08-12, 19 s+today — and that start-up cost scales with machine load exactly when the+user is doing the most (spawning agents). The user's pinned Tool Model on+the same box writes the same brief in ~5 s warm (measured 2026-08-18: 5.0 s+and 4.8 s for the identical instruction; the deep tier 7–8 s for a plain+rewrite per the composer's own notes).+(2) `jarvis/agentic_ide/prompt_composer.py`: the hedge — a second writer+started alongside a stalled first — waited a fixed 30 s for a subscription+writer and 20 s for an API writer, each figure the healthy p90 of ONE writer+on ONE day. Neither knows that a Tool Model normally answers in 5 s, so a+hung fast writer got 20 s of silence before insurance was allowed to start.+And when the hedge itself died (on the dev box the `api` rung resolves to a+keyless OpenRouter — `JARVIS__BRAIN__PRIMARY=openrouter` sits in the shell+environment and overrides `jarvis.toml`'s `vertex`; measured: "No OpenRouter+API key found" 5 ms after the hedge started), no third writer was allowed —+"at most once per brief" — and the brief sat out the remaining budget behind+the stalled primary although a signed-in CLI was idle: measured 90.05 s to+the deterministic fallback.++**Fix.**+* `writer.py`: ONE order for `auto` and for the rescue, `_AUTO_ORDER =+ ("tool_model", "api", "subscription")` — the writer that answers soonest+ without a quality demotion. The Tool Model leads because it is, in the+ Tool Model tab's own words, the model that "routes spoken commands and+ starts background agents"; direct API calls have no process to cold-start;+ the subscription writes under `auto` only when nothing API-side qualifies,+ so a downloader whose ONLY credential is a coding CLI still gets a brief,+ and a user who wants the plan spent on purpose pins `subscription`. Pins+ are untouched. Under `auto` an unset Tool Model is the ordinary case and no+ longer logs as a broken pin. Config description and the settings card's+ "Automatic" label say the new order.+* `prompt_composer.py`: `HEDGE_AFTER_S` / `HEDGE_AFTER_API_S` are CEILINGS+ now. `_hedge_after_s(source)` derives the threshold from the writer's own+ recent valid briefs in this process (2.5 × their median, never below a 6 s+ floor, never above the family ceiling, keyed by full source so no model+ inherits another's clock, in-memory only because a CLI's spawn cost+ tripled within an hour). Without history the ceilings apply unchanged. A+ hedge that dies or writes a defect while the primary still stalls is+ replaced by the next rung at once — still one extra writer at a time,+ every rung tried at most once.++**Class.** A cost-first default on a latency-critical path, and a fixed+"suspiciously slow" number measured against one writer and applied to+every writer. Same family as BUG-140 (a per-call cold cost paid on the+critical path) and the 2026-08-12 hedge (a serial wait that had to be+measured to be seen). The general rule: on the voice path the first+question is "who answers soonest", cost and quality are constraints on that+answer, not the other way round; and any threshold that says "slow" must be+relative to what THIS writer normally does.++**Verification.** Live on the dev box, same instruction as 16:10, through+`prompt_composer.compose` with the real config: `tool_model:vertex`+resolves in 0.00 s warm; the brief lands in 5.0 s and 4.8 s (runs 2 and 3 of+one process). Honest caveats: run 1 of a fresh process took 56 s — the raw+google-genai SDK against Vertex `global` answered a bare "Say OK." in 49 s,+22 s, 9.9 s and 5.7 s in the same minute (17:25), so the provider had a slow+spell during the measurement; that is the provider, not the writer order,+and the router (same model) suffers it equally. The hedge history recorded+`[52.8, 5.0, 4.8]` and would insure the next brief at 12.5 s instead of 20 s.+Not yet observed in a live voice call — needs the app restarted.++**Tests.** `tests/unit/agentic_ide/test_writer_resolution.py` (auto prefers+the Tool Model, then the API tier, reaches the subscription last, never+probes a CLI while a faster writer qualifies, an unset Tool Model logs no+broken pin, a raising CLI probe degrades); `test_writer_rescue.py` (a dead+Tool Model crosses to the API tier before the CLI, the subscription is the+last rescue, first choice and rescue share ONE order); `test_writer_cache.py`+(cache tests pinned to the subscription rung explicitly);+`test_composer_hedge.py` (ceilings without history, a fast writer's history+pulls insurance forward, the floor, never above the ceiling, per-source+clocks, only valid briefs recorded, bounded history, the loop teaches the+threshold, a defective brief teaches nothing, history tightens the live+hedge end to end, a dead hedge is replaced by the next rung, a healthy hedge+recruits nobody else); `conftest.py` starts every test with an empty writer+clock.++**Open, seen while looking.** (a) The instant ack (ADR-0033) has produced no+audio in any of the three sessions this afternoon — needs one live call at+debug level. (b) The 500–880 ms event-loop stall at every routing decision.+(c) `JARVIS__BRAIN__PRIMARY=openrouter` / `JARVIS__TTS__PROVIDER=+openrouter-tts` in the maintainer's shell environment override `jarvis.toml`+and point the quality tier, the fact extractor ("Verdichter brain-call+failed: No OpenRouter API key") and the TTS default at a provider without a+key. (d) The paste's 3 s arrival check did not see the text on T2 — one+sample, cause unknown (slow render under load vs. a placeholder shape the+detector does not know).diff --git a/jarvis/agentic_ide/prompt_composer.py b/jarvis/agentic_ide/prompt_composer.pyindex 286bf845c2..1ff58dea3c 100644--- a/jarvis/agentic_ide/prompt_composer.py+++ b/jarvis/agentic_ide/prompt_composer.py@@ -96,8 +96,10 @@ from __future__ import annotationsimport asyncioimport re+import statisticsimport sysimport time+from collections import dequefrom collections.abc import Callable, Sequencefrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -153,6 +155,9 @@ _MIN_ATTEMPT_S = 20.0# 16-25 s end to end, so a hedge at 30 s fires only on genuinely slow calls and# the double spend stays rare. The hedge crosses to the SAME rungs the rescue# already uses on failure — quality-tier by construction, never a demotion.+#+# Since 2026-08-18 this is the CEILING for a subscription writer, not the+# threshold itself — see ``_hedge_after_s``.HEDGE_AFTER_S = 30.0# When the writer is a direct API call (the ``api`` and ``tool_model`` rungs),@@ -161,8 +166,60 @@ HEDGE_AFTER_S = 30.0# above would let an already-fast path sit through half a minute of silence# before a second writer was allowed to begin. Still above the API path's# healthy band, so the double spend stays as rare as it is for the CLI.+#+# Since 2026-08-18 the CEILING for an API writer — see ``_hedge_after_s``.HEDGE_AFTER_API_S = 20.0+# The insurance threshold calibrates itself to the writer actually in use.+#+# The two ceilings above were each measured against ONE writer on ONE day, and+# each has already been revised (45 → 90 s budget, 30 s, then a separate 20 s+# for the API rungs) as the writers changed. They still cannot tell a Tool+# Model that writes a brief in ~5 s (measured 2026-08-18) from a deep+# reasoning tier that needs 13-21 s: with a fixed 20 s, a hung fast writer+# costs the user twenty seconds of silence before insurance is even allowed+# to start — four times what that writer normally takes. So the threshold is+# derived from the writer's OWN+# recent, valid briefs in this process: ``_HEDGE_MULTIPLIER`` × their median,+# never below ``_HEDGE_FLOOR_S`` (a single quick brief must not arm a+# hair-trigger on the next one, and a bigger brief with five outlines+# legitimately takes longer than a plain rewrite), never above the ceiling+# for that writer's family. With no history yet — the first brief after+# boot — the ceilings apply unchanged, which is exactly the behaviour every+# hedge test pins.+#+# Keyed by the writer's full source (``tool_model:vertex``, ``api``,+# ``subscription:claude-cli``), so a different model never inherits another's+# clock. In-memory only: what a writer costs changes with the machine's load+# (a subscription CLI's spawn tripled within an hour on 2026-08-18), so a+# figure carried across restarts would more often mislead than help.+_HEDGE_HISTORY_DEPTH = 5+_HEDGE_MULTIPLIER = 2.5+_HEDGE_FLOOR_S = 6.0+_recent_writer_seconds: dict[str, deque[float]] = {}+++def _hedge_after_s(source: str) -> float:+ """Seconds the writer ``source`` may stay silent before insurance starts."""+ ceiling = HEDGE_AFTER_S if source.startswith("subscription") else HEDGE_AFTER_API_S+ history = _recent_writer_seconds.get(source)+ if not history:+ return ceiling+ return min(ceiling, max(_HEDGE_FLOOR_S, statistics.median(history) * _HEDGE_MULTIPLIER))+++def _remember_writer_seconds(source: str, seconds: float) -> None:+ """Record one VALID brief's wall-clock for ``source``'s future threshold."""+ if not source or seconds <= 0:+ return+ _recent_writer_seconds.setdefault(source, deque(maxlen=_HEDGE_HISTORY_DEPTH)).append(seconds)+++def _forget_writer_seconds() -> None:+ """Drop every recorded duration (tests; a process starts empty anyway)."""+ _recent_writer_seconds.clear()++# Speech artefacts the deterministic layer removes. Matching *input vocabulary*# in the supported locales — these are the words people actually say while# thinking, not prose.@@ -900,6 +957,7 @@ async def compose(deadline = started + COMPOSE_TIMEOUT_Stried: list[str] = [writer_source] if writer_source else []attempts: dict[asyncio.Task[str], str] = {}+ spawned_at: dict[asyncio.Task[str], float] = {}# A pinned brain is the caller deciding — no hedge, no rescue, as before.may_substitute = writer_task is not Nonehedged = not may_substitute@@ -931,6 +989,7 @@ async def compose())attempts[task] = source+ spawned_at[task] = time.monotonic()return Truedef _cancel_attempts() -> None:@@ -949,15 +1008,12 @@ async def compose(breakwait_s = deadline - nowif not hedged:- # The threshold follows the PRIMARY writer's family: a- # subscription CLI pays a cold process start a direct API call- # never does, so "suspiciously slow" starts earlier there.- # Read at loop time, not hoisted — tests pin these constants.- hedge_after_s = (- HEDGE_AFTER_S- if writer_source.startswith("subscription")- else HEDGE_AFTER_API_S- )+ # The threshold follows the PRIMARY writer: its family's+ # ceiling (a subscription CLI pays a cold process start a+ # direct API call never does), tightened by its own recent+ # briefs. Read at loop time, not hoisted — tests pin the+ # ceilings.+ hedge_after_s = _hedge_after_s(writer_source)wait_s = min(wait_s, max(started + hedge_after_s - now, 0.0))done, _pending = await asyncio.wait(set(attempts), timeout=wait_s, return_when=asyncio.FIRST_COMPLETED@@ -965,7 +1021,8 @@ async def compose(if not done and not hedged:# Nobody failed — the writer is just slow. The next rung starts- # alongside it rather than after it; at most once per brief.+ # alongside it rather than after it; at most ONE extra writer+ # at a time (see ``hedge_ended`` below for the one exception).hedged = Trueif deadline - time.monotonic() >= _MIN_ATTEMPT_S:nxt, nxt_source = await asyncio.to_thread(_rescue_writer, tried)@@ -977,8 +1034,10 @@ async def compose()continue+ hedge_ended = Falsefor task in done:source = attempts.pop(task)+ hedge_ended = hedge_ended or (hedged and source != writer_source)try:candidate = _strip_wrapper(task.result())except (TimeoutError, asyncio.CancelledError):@@ -994,6 +1053,9 @@ async def compose(defect = _brief_defect(candidate)if not defect:composed = candidate+ _remember_writer_seconds(+ source, time.monotonic() - spawned_at.get(task, now)+ )breakreason = defectlogger.info(@@ -1003,8 +1065,28 @@ async def compose(len(candidate),)- if composed or attempts:- # Won, or a sibling attempt is still writing and may still win.+ if composed:+ break+ if attempts:+ # A sibling attempt is still writing and may still win. When+ # the one that just ended was the HEDGE — a rescue rung that+ # died or wrote a defect while the primary is still stalling —+ # the next rung takes its place at once: a hedge that never+ # got to write is no insurance, and the user is still waiting.+ # Live 2026-08-18: the API rung on the dev box died in 5 ms+ # (a keyless provider), and the brief then sat out the whole+ # 90 s budget behind a stalled primary although a signed-in+ # CLI was idle. Still one extra writer at a time — the dead+ # hedge is gone — and every rung is tried at most once, so+ # this cannot spend more than the rescue ladder holds.+ if hedge_ended and may_substitute and deadline - time.monotonic() >= _MIN_ATTEMPT_S:+ nxt, nxt_source = await asyncio.to_thread(_rescue_writer, tried)+ if nxt is not None and _spawn_attempt(nxt, nxt_source):+ tried.append(nxt_source)+ notify(+ STAGE_HEDGE,+ _hedge_message(terminal_name, writer=_writer_label(nxt)),+ )continueif not may_substitute:# The caller pinned this model explicitly. Substituting anotherdiff --git a/tests/unit/agentic_ide/conftest.py b/tests/unit/agentic_ide/conftest.pyindex 578363d3c4..d685f8d1d0 100644--- a/tests/unit/agentic_ide/conftest.py+++ b/tests/unit/agentic_ide/conftest.py@@ -113,6 +113,20 @@ def _fresh_writer_cache() -> None:writer.invalidate_writer_cache()[email protected](autouse=True)+def _fresh_hedge_history() -> None:+ """Start every test without a remembered writer clock.++ ``prompt_composer`` calibrates its hedge threshold from the durations of+ the briefs it delivered in this process. Between tests that memory is a+ leak: an instant fake writer in one test would tighten the insurance for a+ later test that expects the documented ceiling.+ """+ from jarvis.agentic_ide import prompt_composer++ prompt_composer._forget_writer_seconds() # noqa: SLF001++@pytest.fixture(autouse=True)def _agent_history_in_tmp(tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatchdiff --git a/tests/unit/agentic_ide/test_composer_hedge.py b/tests/unit/agentic_ide/test_composer_hedge.pyindex e93edbcf28..71fcf5ecfb 100644--- a/tests/unit/agentic_ide/test_composer_hedge.py+++ b/tests/unit/agentic_ide/test_composer_hedge.py@@ -350,3 +350,261 @@ async def test_the_hedge_respects_the_shared_budget()assert result.composed_by == "fallback"+++# ---------------------------------------------------------------------------+# The threshold follows the writer actually in use (2026-08-18).+#+# ``HEDGE_AFTER_S`` / ``HEDGE_AFTER_API_S`` are ceilings: a writer with recent+# valid briefs in this process is insured at a multiple of ITS OWN median, never+# below the floor and never above its family's ceiling. Without history the+# ceilings apply unchanged — which is what every test above relies on.+# ---------------------------------------------------------------------------+++def test_without_history_the_ceilings_apply(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_S", 30.0)+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_API_S", 20.0)++ assert prompt_composer._hedge_after_s("subscription:claude-cli") == 30.0 # noqa: SLF001+ assert prompt_composer._hedge_after_s("tool_model:vertex") == 20.0 # noqa: SLF001+ assert prompt_composer._hedge_after_s("api") == 20.0 # noqa: SLF001+++def test_a_fast_writers_history_pulls_insurance_forward(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A Tool Model that writes a brief in 3 s is insured at 7.5 s, not 20 s —+ the fixed API ceiling would let a hung fast writer sit through seven times+ its normal wait before a second writer was allowed to start."""+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_API_S", 20.0)+ for _ in range(3):+ prompt_composer._remember_writer_seconds("tool_model:vertex", 3.0) # noqa: SLF001++ assert prompt_composer._hedge_after_s("tool_model:vertex") == pytest.approx(7.5) # noqa: SLF001+++def test_the_floor_keeps_one_quick_brief_from_arming_a_hair_trigger(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """One 0.8 s rewrite must not insure the next, bigger brief at 2 s: a brief+ that reads five outlines legitimately takes longer than a plain rewrite."""+ monkeypatch.setattr(prompt_composer, "_HEDGE_FLOOR_S", 6.0)+ prompt_composer._remember_writer_seconds("api", 0.8) # noqa: SLF001++ assert prompt_composer._hedge_after_s("api") == 6.0 # noqa: SLF001+++def test_history_never_lifts_the_threshold_above_the_family_ceiling(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A slow writer keeps its measured ceiling; the calibration only ever+ tightens insurance, it never loosens it past what the constants promise."""+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_S", 30.0)+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_API_S", 20.0)+ for _ in range(3):+ prompt_composer._remember_writer_seconds("subscription:claude-cli", 25.0) # noqa: SLF001+ prompt_composer._remember_writer_seconds("api", 25.0) # noqa: SLF001++ assert prompt_composer._hedge_after_s("subscription:claude-cli") == 30.0 # noqa: SLF001+ assert prompt_composer._hedge_after_s("api") == 20.0 # noqa: SLF001+++def test_each_writer_keeps_its_own_clock() -> None:+ """A different model never inherits another's history — the CLI's 18 s+ must not slow the Tool Model's insurance, nor the reverse."""+ for _ in range(3):+ prompt_composer._remember_writer_seconds("subscription:claude-cli", 18.0) # noqa: SLF001++ assert (+ prompt_composer._hedge_after_s("tool_model:vertex") # noqa: SLF001+ == prompt_composer.HEDGE_AFTER_API_S+ )+++def test_only_a_valid_brief_is_recorded() -> None:+ prompt_composer._remember_writer_seconds("", 3.0) # noqa: SLF001+ prompt_composer._remember_writer_seconds("api", 0.0) # noqa: SLF001+ prompt_composer._remember_writer_seconds("api", -1.0) # noqa: SLF001++ assert not prompt_composer._recent_writer_seconds # noqa: SLF001+++def test_the_history_holds_the_last_few_briefs_only() -> None:+ """A writer that got faster is not held hostage by an old slow spell."""+ for seconds in (30.0, 30.0, 30.0, 30.0, 30.0, 2.0, 2.0, 2.0, 2.0, 2.0):+ prompt_composer._remember_writer_seconds("api", seconds) # noqa: SLF001++ assert list(prompt_composer._recent_writer_seconds["api"]) == [2.0] * 5 # noqa: SLF001+++async def test_a_delivered_brief_teaches_the_writers_threshold(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The loop feeds the calibration: a valid brief from ``tool_model:fast``+ leaves one measured duration behind under exactly that source."""++ async def _compose(**_kwargs: object) -> str:+ return BRIEF++ monkeypatch.setattr(+ prompt_composer, "_resolve_writer", lambda: (_Writer("fast"), "tool_model:fast")+ )+ 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"+ history = prompt_composer._recent_writer_seconds # noqa: SLF001+ assert list(history) == ["tool_model:fast"]+ assert len(history["tool_model:fast"]) == 1+ assert history["tool_model:fast"][0] > 0+++async def test_a_defective_brief_teaches_nothing(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A writer whose answer was thrown away must not look fast for it: only+ the rescue that actually delivered is measured."""++ async def _compose(*, brain: object, **_kwargs: object) -> str:+ if getattr(brain, "name", "") == "broken":+ return "ok" # far too short to be a brief — a defect, not a brief+ return BRIEF++ monkeypatch.setattr(+ prompt_composer, "_resolve_writer", lambda: (_Writer("broken"), "tool_model:broken")+ )+ monkeypatch.setattr(prompt_composer, "_rescue_writer", lambda tried: (_Writer("fine"), "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 list(prompt_composer._recent_writer_seconds) == ["api"] # noqa: SLF001+++async def test_history_tightens_the_live_hedge(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """End to end: with the API ceiling far away, a writer whose recent briefs+ were quick is insured on its own clock, and the second writer wins."""+ stalled = asyncio.Event()+ started: list[str] = []++ async def _compose(*, brain: object, **_kwargs: object) -> str:+ name = getattr(brain, "name", "?")+ started.append(name)+ if name == "hung":+ await stalled.wait() # never set — cancelled by the winner+ return HEDGE_BRIEF++ # The ceiling would never fire inside this test; only the calibrated+ # threshold can. The floor is lowered to make that threshold reachable.+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_API_S", 60.0)+ monkeypatch.setattr(prompt_composer, "_HEDGE_FLOOR_S", 0.02)+ for _ in range(3):+ prompt_composer._remember_writer_seconds("tool_model:hung", 0.02) # noqa: SLF001+ monkeypatch.setattr(+ prompt_composer, "_resolve_writer", lambda: (_Writer("hung"), "tool_model:hung")+ )+ monkeypatch.setattr(prompt_composer, "_rescue_writer", lambda tried: (_Writer("fast"), "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 "quick" in result.text+ assert started == ["hung", "fast"]+++async def test_a_hedge_that_dies_is_replaced_by_the_next_rung(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Live 2026-08-18: the primary stalled, the hedge (a keyless API rung)+ died in milliseconds, and the brief then sat out the whole budget behind+ the stall although a signed-in CLI was idle. A dead hedge is no insurance:+ the next rung takes its place at once, still one extra writer at a time."""+ stalled = asyncio.Event()+ started: list[str] = []+ asked: list[tuple[str, ...]] = []++ async def _compose(*, brain: object, **_kwargs: object) -> str:+ name = getattr(brain, "name", "?")+ started.append(name)+ if name == "slow":+ await stalled.wait() # never set — cancelled by the winner+ if name == "dead":+ raise RuntimeError("No API key found")+ return HEDGE_BRIEF++ def _rescue(tried: list[str]) -> tuple[_Writer, str]:+ asked.append(tuple(tried))+ if len(asked) == 1:+ return _Writer("dead"), "api"+ return _Writer("fast"), "subscription:fast"++ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_API_S", 0.05)+ monkeypatch.setattr(+ prompt_composer, "_resolve_writer", lambda: (_Writer("slow"), "tool_model:slow")+ )+ monkeypatch.setattr(prompt_composer, "_rescue_writer", _rescue)+ monkeypatch.setattr(prompt_composer, "_llm_compose", _compose)++ notices: list[prompt_composer.ComposeNotice] = []+ result = await prompt_composer.compose(+ "make the wake path faster",+ session=workspace,+ terminal_name="Kai",+ on_progress=notices.append,+ )++ assert result.composed_by == "llm"+ assert "quick" in result.text+ assert started == ["slow", "dead", "fast"]+ # Every rung is asked for once, and the dead one is named as tried.+ assert asked == [("tool_model:slow",), ("tool_model:slow", "api")]+ assert len([n for n in notices if n.stage == prompt_composer.STAGE_HEDGE]) == 2+++async def test_a_healthy_hedge_recruits_nobody_else(+ workspace: _Session, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The bound still holds: while the hedge is alive and writing, no third+ writer is started, however long the primary stalls."""+ stalled = asyncio.Event()+ started: list[str] = []++ async def _compose(*, brain: object, **_kwargs: object) -> str:+ name = getattr(brain, "name", "?")+ started.append(name)+ if name == "slow":+ await stalled.wait()+ await asyncio.sleep(0.2) # the hedge takes its time — but it is alive+ return HEDGE_BRIEF++ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_API_S", 0.05)+ monkeypatch.setattr(+ prompt_composer, "_resolve_writer", lambda: (_Writer("slow"), "tool_model:slow")+ )+ monkeypatch.setattr(+ prompt_composer,+ "_rescue_writer",+ lambda tried: (_Writer("hedge"), "api")+ if len(tried) == 1+ else pytest.fail("recruited a third writer while the hedge was alive"),+ )+ 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 started == ["slow", "hedge"]