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.

perf(agentic-ide): cut prompt delivery latency without touching brief quality

rubenluetke10-beepebd24a0cbcb6
diff --git a/jarvis/agentic_ide/prompt_composer.py b/jarvis/agentic_ide/prompt_composer.py
index a26c568e55..b849839152 100644
--- a/jarvis/agentic_ide/prompt_composer.py
+++ b/jarvis/agentic_ide/prompt_composer.py
@@ -72,6 +72,16 @@ All of that now overlaps and none of it runs on the loop, so the model call
starts as soon as the slowest single piece of preparation is done instead of
after their sum.
+Measured again live 2026-08-12 (09:54, T1+T3): the writer call was 95%+ of a
+72 s delivery, and two things inside it were pure overhead. First, every
+subscription-CLI turn paid to start MCP servers, skills, and session
+persistence it can never use — the CLI brain now switches those off for
+structured turns (see ``claude_cli``), which cut the same real payload from
+27.5 s to 16.4 s with the brief unchanged. Second, a slow writer was waited
+out IN FULL before anyone else was allowed to start; attempts now overlap
+after ``HEDGE_AFTER_S`` and the first valid brief wins, which bounds the tail
+without demoting the model.
+
**On the silence.** The rest is perceived latency: for 10-27 s nothing at all
was said, so a working composer and a wedged one looked identical. The three
beats below (``start`` → ``thinking``/``drafting`` → ``ready``, and ``sent``
@@ -81,6 +91,7 @@ than none. They are terminal lines, so they follow the English-artifact rule
like every other log line; the SPOKEN readback the user hears is a separate
surface and stays in the turn's resolved output language.
"""
+
from __future__ import annotations
import asyncio
@@ -130,6 +141,20 @@ MAX_FILE_REFERENCES = 5
# shorter window buys the deterministic prompt AND the wait.
_MIN_ATTEMPT_S = 20.0
+# How long the chosen writer may stay silent before the next rung starts
+# WRITING ALONGSIDE it — not instead of it: the first valid brief wins and the
+# other attempt is cancelled. The serial shape this replaces is where the
+# minute-plus deliveries came from (live 2026-08-12 09:54: a healthy but slow
+# subscription call ran 71.4 s while the user waited; a hung one could burn 70 s
+# before the rescue was even ALLOWED to start). Hedging bounds that tail at
+# roughly this constant plus the second writer's own time.
+#
+# Above the healthy p90 on purpose: a brief on the lean CLI invocation measures
+# 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.
+HEDGE_AFTER_S = 30.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.
@@ -204,6 +229,7 @@ STAGE_START = "start"
STAGE_THINKING = "thinking"
STAGE_DRAFTING = "drafting"
STAGE_RETRY = "retry"
+STAGE_HEDGE = "hedge"
STAGE_READY = "ready"
STAGE_FALLBACK = "fallback"
STAGE_SENT = "sent"
@@ -342,9 +368,7 @@ _READY_PHRASES = (
def _start_message(kind: str, instruction: str, terminal_name: str) -> str:
"""The opening line, matched to what the user actually asked for."""
options = _START_PHRASES.get(kind) or _START_PHRASES[KIND_NEUTRAL]
- return _variant(options, instruction).format(
- name=terminal_name, subject=_subject(instruction)
- )
+ return _variant(options, instruction).format(name=terminal_name, subject=_subject(instruction))
def _thinking_message(
@@ -359,9 +383,7 @@ def _thinking_message(
context = "no matching files, so your words alone"
if writer_label:
context = f"{context}, via {writer_label}"
- return _variant(_THINKING_PHRASES, instruction).format(
- name=terminal_name, context=context
- )
+ return _variant(_THINKING_PHRASES, instruction).format(name=terminal_name, context=context)
def _ready_message(
@@ -396,6 +418,20 @@ def _retry_message(terminal_name: str, *, reason: str, writer: str) -> str:
return f"{terminal_name}'s writer dropped out ({reason}) - {taking_over}."
+def _hedge_message(terminal_name: str, *, writer: str) -> str:
+ """Said when a slow — not dead — writer gets a second one racing it.
+
+ Deliberately NOT the retry wording: "dropped out" would be a lie about a
+ writer that is still working, and the user should know two are now writing
+ so whichever brief arrives is not a surprise.
+ """
+ second = writer or "another writer"
+ return (
+ f"{terminal_name}'s brief is taking long - {second} is drafting in "
+ "parallel; the first good brief wins."
+ )
+
+
def _brief_defect(composed: str) -> str:
"""Why ``composed`` is unusable as a brief, or ``""`` when it is fine.
@@ -668,9 +704,7 @@ async def _compose_once(
),
on_first_delta=lambda: notify(
STAGE_DRAFTING,
- _variant(_DRAFTING_PHRASES, base_instruction or said).format(
- name=terminal_name
- ),
+ _variant(_DRAFTING_PHRASES, base_instruction or said).format(name=terminal_name),
),
)
@@ -769,9 +803,7 @@ async def compose(
def notify(stage: str, message: str) -> None:
_emit(
on_progress,
- ComposeNotice(
- stage=stage, message=message, terminal=terminal_name, kind=kind
- ),
+ ComposeNotice(stage=stage, message=message, terminal=terminal_name, kind=kind),
)
def _deterministic(
@@ -789,9 +821,7 @@ async def compose(
)
if not use_llm:
- found = await asyncio.to_thread(
- _file_candidates, session, subject, max_files * 2
- )
+ found = await asyncio.to_thread(_file_candidates, session, subject, max_files * 2)
return _deterministic("raw", candidates=found)
started = time.monotonic()
@@ -833,72 +863,142 @@ async def compose(
# every composition for days. That is the single-provider brick of AP-22,
# so a failed attempt crosses to the next rung.
#
+ # Attempts run CONCURRENTLY, in two situations. On a FAILURE the next rung
+ # starts at once, as before. On a STALL (``HEDGE_AFTER_S`` with no answer)
+ # the next rung starts WHILE the first is still writing — the serial shape
+ # this replaces made the user wait out a slow writer in full before anyone
+ # else was allowed to begin, which is where the minute-plus deliveries came
+ # from. The first valid brief wins and every other attempt is cancelled.
+ #
# 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 []
+ attempts: dict[asyncio.Task[str], str] = {}
+ # A pinned brain is the caller deciding — no hedge, no rescue, as before.
+ may_substitute = writer_task is not None
+ hedged = not may_substitute
composed = ""
reason = ""
- while True:
+ def _spawn_attempt(brn, source: str) -> bool: # noqa: ANN001 - Brain
+ """Start one writer on the brief, unless the budget says otherwise."""
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")
+ return False
+ task = asyncio.create_task(
+ asyncio.wait_for(
+ _compose_once(
+ brain=brn,
+ 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,
+ )
+ )
+ attempts[task] = source
+ return True
- 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,
- )
+ def _cancel_attempts() -> None:
+ for leftover in attempts:
+ _discard(leftover)
+ attempts.clear()
+
+ if not _spawn_attempt(writer, writer_source):
+ _discard(context_task)
+ return degrade(f"composer timed out after {COMPOSE_TIMEOUT_S:g}s")
+
+ try:
+ while attempts and not composed:
+ now = time.monotonic()
+ if now >= deadline:
+ break
+ wait_s = deadline - now
+ if not hedged:
+ 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
)
- 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:
+
+ 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.
+ hedged = True
+ if 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)),
+ )
+ continue
+
+ for task in done:
+ source = attempts.pop(task)
+ try:
+ candidate = _strip_wrapper(task.result())
+ except (TimeoutError, asyncio.CancelledError):
+ reason = f"composer timed out after {COMPOSE_TIMEOUT_S:g}s"
+ except Exception as exc: # noqa: BLE001 - any failure crosses over
+ logger.info(
+ "Agentic IDE prompt composer failed on {}: {}",
+ source or "the pinned writer",
+ exc,
+ )
+ reason = f"composer unavailable ({type(exc).__name__})"
+ else:
+ defect = _brief_defect(candidate)
+ if not defect:
+ composed = candidate
+ break
+ reason = defect
+ logger.info(
+ "Agentic IDE prompt composer: {} from {} ({} chars)",
+ defect,
+ source or "the pinned writer",
+ len(candidate),
+ )
+
+ if composed or attempts:
+ # Won, or a sibling attempt is still writing and may still win.
+ continue
+ if not may_substitute:
+ # The caller pinned this model explicitly. Substituting another
+ # one is not ours to decide.
+ break
+ if deadline - time.monotonic() < _MIN_ATTEMPT_S:
break
- logger.info(
- "Agentic IDE prompt composer: {} from {} ({} chars)",
- reason,
- writer_source or "the pinned writer",
- len(composed),
+ nxt, nxt_source = await asyncio.to_thread(_rescue_writer, tried)
+ if nxt is None or not _spawn_attempt(nxt, nxt_source):
+ break
+ tried.append(nxt_source)
+ notify(
+ STAGE_RETRY,
+ _retry_message(terminal_name, reason=reason, writer=_writer_label(nxt)),
)
+ except asyncio.CancelledError:
+ # The caller died mid-composition (voice hangup, dropped client). The
+ # attempt tasks are OURS — without this they would keep spending
+ # providers on a brief nobody can deliver.
+ _cancel_attempts()
+ _discard(context_task)
+ raise
- 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)),
- )
+ _cancel_attempts()
+ if not composed:
+ _discard(context_task)
+ return degrade(reason or f"composer timed out after {COMPOSE_TIMEOUT_S:g}s")
# 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
@@ -932,9 +1032,11 @@ async def compose(
__all__ = [
"COMPOSE_TIMEOUT_S",
+ "HEDGE_AFTER_S",
"MAX_FILE_REFERENCES",
"STAGE_DRAFTING",
"STAGE_FALLBACK",
+ "STAGE_HEDGE",
"STAGE_READY",
"STAGE_RETRY",
"STAGE_SENT",
diff --git a/jarvis/agentic_ide/writer.py b/jarvis/agentic_ide/writer.py
index d7738c048f..d09b2ec648 100644
--- a/jarvis/agentic_ide/writer.py
+++ b/jarvis/agentic_ide/writer.py
@@ -46,11 +46,51 @@ the user their instruction.
from __future__ import annotations
+import threading
+import time
from collections.abc import Sequence
from typing import Any
from loguru import logger
+#: How long one successful resolution answers for everybody. Resolving costs a
+#: config load plus a sign-in probe per candidate CLI (~0.5-1 s, run per PANE of
+#: a fan-out today), and the answer changes on human timescales: a sign-in, a
+#: sign-out, a settings change. Failures are never cached — a user who just
+#: fixed their key must not wait out a stale "nothing qualifies".
+_CACHE_TTL_S = 45.0
+
+_cache_lock = threading.Lock()
+#: ``(resolved_at, cli_timeout_s, brain, source)`` of the last success, or None.
+#: Deliberately NOT the resolver's shared ``(provider, model)`` cache: these are
+#: structured-prompt instances, and parking one where a voice tier could pick it
+#: up is the exact leak ``resolve_subscription_brain`` documents against.
+_cached: tuple[float, float | None, Any, str] | None = None
+
+
+def invalidate_writer_cache() -> None:
+ """Forget the cached writer (settings change, sign-out, failed call)."""
+ global _cached
+ with _cache_lock:
+ _cached = None
+
+
+def _cached_writer(cli_timeout_s: float | None) -> tuple[Any, str] | None:
+ """The still-fresh cached resolution for this budget, or None."""
+ with _cache_lock:
+ if _cached is None:
+ return None
+ resolved_at, budget, brain, source = _cached
+ if time.monotonic() - resolved_at > _CACHE_TTL_S or budget != cli_timeout_s:
+ return None
+ return brain, source
+
+
+def _remember_writer(cli_timeout_s: float | None, brain: Any, source: str) -> None:
+ global _cached
+ with _cache_lock:
+ _cached = (time.monotonic(), cli_timeout_s, brain, source)
+
def _load_config() -> Any:
from jarvis.core.config import load_config
@@ -89,7 +129,21 @@ def resolve_writer(*, cli_timeout_s: float | None = None) -> tuple[Any | None, s
Returns ``(None, "")`` whenever nothing qualifies — the caller then uses its
deterministic layer and reports that honestly.
+
+ A success is answered from a short-lived cache (``_CACHE_TTL_S``): a fleet
+ fan-out resolves once per pane within the same second, and each miss spends
+ a config load plus a sign-in probe per candidate CLI on the same answer.
"""
+ hit = _cached_writer(cli_timeout_s)
+ if hit is not None:
+ return hit
+ brain, source = _resolve_writer_uncached(cli_timeout_s=cli_timeout_s)
+ if brain is not None:
+ _remember_writer(cli_timeout_s, brain, source)
+ return brain, source
+
+
+def _resolve_writer_uncached(*, cli_timeout_s: float | None) -> tuple[Any | None, str]:
try:
config = _load_config()
choice = _configured_choice(config)
@@ -141,6 +195,9 @@ def resolve_rescue_writer(
pin still degrades at resolution time rather than quietly landing on a
provider the user did not choose.
"""
+ # A rescue means the resolved writer just failed in someone's hands, so a
+ # cached copy of that resolution must not answer the next composition.
+ invalidate_writer_cache()
tried = {str(source).split(":", 1)[0] for source in exclude if source}
try:
config = _load_config()
@@ -209,4 +266,4 @@ def _tool_model_writer(config: Any) -> tuple[Any | None, str]:
return brain, f"tool_model:{name}"
-__all__ = ["resolve_rescue_writer", "resolve_writer"]
+__all__ = ["invalidate_writer_cache", "resolve_rescue_writer", "resolve_writer"]
diff --git a/jarvis/plugins/brain/claude_cli.py b/jarvis/plugins/brain/claude_cli.py
index 56fb45b1f7..097710a2d9 100644
--- a/jarvis/plugins/brain/claude_cli.py
+++ b/jarvis/plugins/brain/claude_cli.py
@@ -30,13 +30,17 @@ Getting that choice wrong is the failure mode worth guarding: a structured
caller served conversationally gets three fluent sentences that read like a
valid result. Nobody inspects an answer that looks fine.
"""
+
from __future__ import annotations
import asyncio
import logging
+import re
import shutil
+import subprocess
import sys
import tempfile
+import threading
import time
from collections.abc import AsyncIterator
from contextlib import suppress
@@ -84,6 +88,87 @@ _CLI_SYSTEM = (
# slow here, so older history is dropped rather than paid for.
_CONVO_TURNS = 6
+# What a STRUCTURED print-mode turn switches off, and why it may. A structured
+# caller hands over the complete material in the payload and wants prose back;
+# the turn never legitimately uses a tool, an MCP server, a skill, or the saved
+# session. Yet a bare ``claude -p`` starts all of it: it connects every
+# user-configured MCP server, syncs plugins and skills, and persists the session
+# to disk — pure cold-start cost on a call whose whole output is one brief.
+# Measured on the maintainer's box 2026-08-12 with the composer's real payload:
+# 27.5 s bare against 16.4 s with this set, identical brief quality (the lean
+# run also stopped wrapping the brief in a code fence, which the composer
+# otherwise has to peel off).
+#
+# Each entry is gated on the probed flag set below, because a downloader's CLI
+# may be older than these flags — an unknown option makes the CLI exit with an
+# error instead of an answer, which would turn a speed-up into a broken writer
+# (§3: any CLI version keeps working).
+_FAST_STRUCTURED_ARGS: tuple[tuple[str, tuple[str, ...]], ...] = (
+ ("--tools", ("--tools", "")), # no built-in tools at all — writing only
+ ("--strict-mcp-config", ("--strict-mcp-config",)), # no MCP servers
+ ("--disable-slash-commands", ("--disable-slash-commands",)), # no skills
+ ("--no-session-persistence", ("--no-session-persistence",)), # no disk save
+)
+
+# ``BrainRequest.reasoning_effort`` values the CLI's ``--effort`` accepts
+# verbatim. "none" is deliberately absent: the CLI has no such level, and the
+# composer's documented floor is a modest effort, never zero.
+_EFFORT_LEVELS: frozenset[str] = frozenset({"low", "medium", "high"})
+
+# The probed set of long options this install's CLI understands, filled once
+# per process from ``claude --help``. ``None`` means "not probed yet"; an empty
+# set means the probe failed and every gated flag stays off — slower, but every
+# turn still works.
+_supported_flags: frozenset[str] | None = None
+_probe_lock = threading.Lock()
+
+_HELP_PROBE_TIMEOUT_S = 20.0
+_FLAG_RE = re.compile(r"--[a-z][a-z0-9-]*")
+
+
+def _probe_supported_flags() -> frozenset[str]:
+ """The long options ``claude --help`` advertises, probed once per process.
+
+ Ground truth over guesswork: gating on a version number means maintaining a
+ private map of which release introduced which flag, and getting one entry
+ wrong turns every composition into a CLI usage error. The help text is the
+ CLI's own statement of what it accepts.
+
+ Never raises. A missing binary, a hung probe, or unparseable output all
+ degrade to the empty set — the invocation then simply stays as lean as the
+ oldest supported CLI.
+ """
+ global _supported_flags
+ with _probe_lock:
+ if _supported_flags is not None:
+ return _supported_flags
+ flags: frozenset[str] = frozenset()
+ binary = _resolve_claude_binary()
+ if binary is not None:
+ try:
+ creationflags = NO_WINDOW_CREATIONFLAGS if sys.platform == "win32" else 0
+ result = subprocess.run( # noqa: S603 - fixed argv, no user input
+ [binary, "--help"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=_HELP_PROBE_TIMEOUT_S,
+ creationflags=creationflags,
+ )
+ flags = frozenset(_FLAG_RE.findall(result.stdout or ""))
+ except Exception: # noqa: BLE001 - a failed probe costs speed, not the turn
+ log.debug("claude-cli: --help probe failed", exc_info=True)
+ _supported_flags = flags
+ return flags
+
+
+def reset_flag_probe_cache() -> None:
+ """Forget the probed flag set (tests; a CLI upgrade mid-process)."""
+ global _supported_flags
+ with _probe_lock:
+ _supported_flags = None
+
def _resolve_claude_binary() -> str | None:
"""On-PATH ``claude`` binary (Windows shim variants included), or None."""
@@ -107,8 +192,7 @@ def _claude_subscription_connected() -> bool:
status = ClaudeAuthService().status()
return bool(
- getattr(status, "connected", False)
- and getattr(status, "mode", "") == "subscription"
+ getattr(status, "connected", False) and getattr(status, "mode", "") == "subscription"
)
except Exception: # noqa: BLE001 - a probe degrades, never raises
log.debug("claude-cli: subscription probe failed", exc_info=True)
@@ -175,12 +259,19 @@ class ClaudeCliBrain:
# ---- invocation ----------------------------------------------------
- def build_invocation(self, req: BrainRequest) -> tuple[list[str], str]:
+ def build_invocation(
+ self, req: BrainRequest, cli_flags: frozenset[str] | None = None
+ ) -> tuple[list[str], str]:
"""The argv and the stdin payload for one turn.
Pure and public because this pair — not the subprocess plumbing — is
what decides whether the answer comes back in the right shape, and that
is the property worth testing directly.
+
+ ``cli_flags`` is the probed set of long options this install's CLI
+ understands (see ``_probe_supported_flags``). Only flags present there
+ are added, so an older CLI never sees an option it would die on. ``None``
+ reads as "unknown" and keeps the invocation at its lowest common shape.
"""
binary = _resolve_claude_binary() or "claude"
argv: list[str] = [binary, "-p", "--output-format", "text"]
@@ -189,6 +280,17 @@ class ClaudeCliBrain:
argv += ["--disallowed-tools", *_DISALLOWED_TOOLS]
if self._structured_prompts:
+ known = cli_flags or frozenset()
+ for flag, args in _FAST_STRUCTURED_ARGS:
+ if flag in known:
+ argv += args
+ # The caller's reasoning_effort is a QUALITY decision it already
+ # made (the composer documents "medium" as its floor). The CLI's
+ # own default may think longer without writing a better brief, so
+ # the choice is forwarded rather than dropped.
+ effort = str(getattr(req, "reasoning_effort", "") or "").strip()
+ if "--effort" in known and effort in _EFFORT_LEVELS:
+ argv += ["--effort", effort]
system = str(getattr(req, "system", "") or "").strip()
if system:
argv += ["--system-prompt", system]
@@ -236,15 +338,21 @@ class ClaudeCliBrain:
"and run 'claude' once to sign in."
)
- argv, prompt = self.build_invocation(req)
+ # One help spawn per process lifetime: the first turn pays ~2-3 s for
+ # the probe, every later turn reads the cached set.
+ cli_flags = (
+ _supported_flags
+ if _supported_flags is not None
+ else await asyncio.to_thread(_probe_supported_flags)
+ )
+ argv, prompt = self.build_invocation(req, cli_flags=cli_flags)
# A throwaway working directory: this brain answers questions and has no
# business seeing, or being trusted in, the user's repository.
workdir = tempfile.mkdtemp(prefix="jarvis-claude-brain-")
creationflags = NO_WINDOW_CREATIONFLAGS if sys.platform == "win32" else 0
log.info(
- "claude-cli: spawning print-mode turn (model=%s, structured=%s, "
- "prompt=%d chars)",
+ "claude-cli: spawning print-mode turn (model=%s, structured=%s, prompt=%d chars)",
self._model or "<cli default>",
self._structured_prompts,
len(prompt),
@@ -324,9 +432,7 @@ class ClaudeCliBrain:
raise
except TimeoutError as exc:
await _kill()
- log.warning(
- "claude-cli: no answer within %.0fs (killed)", self.cli_timeout_s
- )
+ log.warning("claude-cli: no answer within %.0fs (killed)", self.cli_timeout_s)
raise RuntimeError(
f"Claude CLI did not answer within {self.cli_timeout_s:.0f}s."
) from exc
@@ -343,9 +449,7 @@ class ClaudeCliBrain:
proc.returncode,
detail[:200],
)
- raise RuntimeError(
- "Claude CLI returned no answer" + (f": {detail}" if detail else ".")
- )
+ raise RuntimeError("Claude CLI returned no answer" + (f": {detail}" if detail else "."))
log.info(
"claude-cli turn ok: %d chars in %.1fs on the subscription",
@@ -364,4 +468,4 @@ class ClaudeCliBrain:
return 0.0
-__all__ = ["ClaudeCliBrain"]
+__all__ = ["ClaudeCliBrain", "reset_flag_probe_cache"]
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index dedba66ba4..90328a4090 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -4108,6 +4108,12 @@ async def set_prompt_writer(payload: PromptWriterRequest) -> PromptWriterState:
)
raise HTTPException(status_code=409, detail=detail)
_persist_prompt_writer(requested)
+ # The composer answers "who writes" from a short-lived cache; a user who
+ # just changed the answer must not have the next brief written by the old
+ # one for the rest of the TTL.
+ from jarvis.agentic_ide.writer import invalidate_writer_cache
+
+ invalidate_writer_cache()
return PromptWriterState(prompt_writer=requested, options=_writer_options())
diff --git a/tests/unit/agentic_ide/conftest.py b/tests/unit/agentic_ide/conftest.py
index b080aa67d6..578363d3c4 100644
--- a/tests/unit/agentic_ide/conftest.py
+++ b/tests/unit/agentic_ide/conftest.py
@@ -100,6 +100,19 @@ def _never_touch_real_agent_configs(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(trust, "ensure_trusted", _skip)
[email protected](autouse=True)
+def _fresh_writer_cache() -> None:
+ """Start every test without a remembered brief writer.
+
+ ``writer.resolve_writer`` answers repeats from a short-lived cache in
+ production. Between tests that cache is a leak: the first test to resolve a
+ writer would hand its monkeypatched brain to every later test in the run.
+ """
+ from jarvis.agentic_ide import writer
+
+ writer.invalidate_writer_cache()
+
+
@pytest.fixture(autouse=True)
def _agent_history_in_tmp(
tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
diff --git a/tests/unit/agentic_ide/test_composer_hedge.py b/tests/unit/agentic_ide/test_composer_hedge.py
new file mode 100644
index 0000000000..e8cbd06de0
--- /dev/null
+++ b/tests/unit/agentic_ide/test_composer_hedge.py
@@ -0,0 +1,221 @@
+"""A slow writer no longer holds the brief hostage.
+
+The serial rescue in ``test_composer_writer_rescue.py`` covers writers that
+FAIL. This file covers the writer that merely stalls — the live 2026-08-12
+09:54 delivery waited 71.4 s on a healthy but slow subscription call, and the
+old loop was not allowed to start anyone else until that call ended or the
+whole budget was gone. After ``HEDGE_AFTER_S`` the next rung now writes
+ALONGSIDE the first, and the first valid brief wins.
+"""
+from __future__ import annotations
+
+import asyncio
+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."
+HEDGE_BRIEF = "## Task\nMake the wake path quick.\n\n## Done when\n- It is quick."
+
+
+@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:
+ 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))
+
+
+async def test_a_stalled_writer_gets_a_parallel_second_and_the_fast_one_wins(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The tail-latency case itself: first writer hangs, hedge delivers."""
+ stalled = asyncio.Event()
+ started: list[str] = []
+ excluded: 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
+ return HEDGE_BRIEF
+
+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_S", 0.05)
+ monkeypatch.setattr(
+ prompt_composer,
+ "_resolve_writer",
+ lambda: (_Writer("slow"), "subscription:slow"),
+ )
+ monkeypatch.setattr(
+ prompt_composer,
+ "_rescue_writer",
+ lambda tried: excluded.append(tuple(tried)) or (_Writer("fast"), "tool_model:fast"),
+ )
+ 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", "fast"]
+ # The stalled rung is named so the hedge cannot land on the same tier.
+ assert excluded == [("subscription:slow",)]
+ hedges = [n for n in notices if n.stage == prompt_composer.STAGE_HEDGE]
+ assert len(hedges) == 1
+ assert "fast" in hedges[0].message
+ assert hedges[0].terminal == "Kai"
+
+
+async def test_the_original_writer_still_wins_when_it_answers_first(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Hedging is insurance, not a substitution: a first writer that delivers
+ keeps the brief even though a second one was already drafting."""
+ parked = asyncio.Event()
+
+ async def _compose(*, brain: object, **_kwargs: object) -> str:
+ if getattr(brain, "name", "") == "laggard":
+ await parked.wait() # the hedge never finishes
+ await asyncio.sleep(0.15)
+ return BRIEF
+
+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_S", 0.01)
+ monkeypatch.setattr(
+ prompt_composer,
+ "_resolve_writer",
+ lambda: (_Writer("original"), "subscription:original"),
+ )
+ monkeypatch.setattr(
+ prompt_composer, "_rescue_writer", lambda tried: (_Writer("laggard"), "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 "faster" in result.text
+
+
+async def test_no_hedge_fires_while_the_writer_is_healthy(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A brief that arrives inside the window costs exactly one provider call."""
+
+ async def _compose(**_kwargs: object) -> str:
+ return BRIEF
+
+ monkeypatch.setattr(
+ prompt_composer, "_resolve_writer", lambda: (_Writer("prompt"), "api")
+ )
+ monkeypatch.setattr(
+ prompt_composer,
+ "_rescue_writer",
+ lambda tried: pytest.fail("hedged a healthy writer"),
+ )
+ 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 not [n for n in notices if n.stage == prompt_composer.STAGE_HEDGE]
+
+
+async def test_a_pinned_brain_is_never_hedged(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """``brain=`` is the caller deciding; a stall must not recruit a stranger."""
+ stalled = asyncio.Event()
+
+ async def _hang(**_kwargs: object) -> str:
+ await stalled.wait()
+ return BRIEF
+
+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_S", 0.01)
+ monkeypatch.setattr(prompt_composer, "COMPOSE_TIMEOUT_S", 0.2)
+ monkeypatch.setattr(prompt_composer, "_MIN_ATTEMPT_S", 0.0)
+ monkeypatch.setattr(
+ prompt_composer,
+ "_rescue_writer",
+ lambda tried: pytest.fail("substituted a pin"),
+ )
+ monkeypatch.setattr(prompt_composer, "_llm_compose", _hang)
+
+ 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_hedge_respects_the_shared_budget(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A second writer that cannot finish inside the budget never starts —
+ starting one would spend a provider on a brief that ships as the fallback."""
+ stalled = asyncio.Event()
+
+ async def _hang(**_kwargs: object) -> str:
+ await stalled.wait()
+ return BRIEF
+
+ monkeypatch.setattr(prompt_composer, "HEDGE_AFTER_S", 0.05)
+ monkeypatch.setattr(prompt_composer, "COMPOSE_TIMEOUT_S", 0.3)
+ monkeypatch.setattr(prompt_composer, "_MIN_ATTEMPT_S", 0.28)
+ monkeypatch.setattr(
+ prompt_composer,
+ "_resolve_writer",
+ lambda: (_Writer("slow"), "subscription:slow"),
+ )
+ monkeypatch.setattr(
+ prompt_composer,
+ "_rescue_writer",
+ lambda tried: pytest.fail("hedged past the budget"),
+ )
+ monkeypatch.setattr(prompt_composer, "_llm_compose", _hang)
+
+ result = await prompt_composer.compose(
+ "make the wake path faster", session=workspace, terminal_name="Kai"
+ )
+
+ assert result.composed_by == "fallback"
diff --git a/tests/unit/agentic_ide/test_writer_cache.py b/tests/unit/agentic_ide/test_writer_cache.py
new file mode 100644
index 0000000000..3f38f44e94
--- /dev/null
+++ b/tests/unit/agentic_ide/test_writer_cache.py
@@ -0,0 +1,101 @@
+"""The writer cache answers repeats; it must never answer a changed question.
+
+Resolving a writer costs a config load plus a sign-in probe per candidate CLI,
+and a fleet fan-out asks the identical question once per pane within the same
+second. The cache exists for that repeat. Everything else here is about the
+cases where remembering would be wrong: failures, spent budgets that differ,
+a writer that just died in someone's hands, and a user who changed the setting.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.agentic_ide import writer
+
+
+def _cfg(choice: str) -> SimpleNamespace:
+ return SimpleNamespace(agentic_ide=SimpleNamespace(prompt_writer=choice))
+
+
+def test_a_success_is_reused_within_the_ttl(monkeypatch: pytest.MonkeyPatch) -> None:
+ loads: list[int] = []
+ monkeypatch.setattr(
+ writer, "_load_config", lambda: loads.append(1) or _cfg("auto")
+ )
+ monkeypatch.setattr(writer, "_subscription", lambda cfg, timeout: "sub-brain")
+
+ first = writer.resolve_writer(cli_timeout_s=90.0)
+ second = writer.resolve_writer(cli_timeout_s=90.0)
+
+ assert first == second == ("sub-brain", "subscription:auto")
+ assert len(loads) == 1
+
+
+def test_a_failure_is_never_cached(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A user who just fixed their key must not wait out a stale 'nothing'."""
+ loads: list[int] = []
+ monkeypatch.setattr(
+ writer, "_load_config", lambda: loads.append(1) or _cfg("auto")
+ )
+ monkeypatch.setattr(writer, "_subscription", lambda cfg, timeout: None)
+ monkeypatch.setattr(writer, "_quality", lambda cfg: None)
+
+ assert writer.resolve_writer() == (None, "")
+ assert writer.resolve_writer() == (None, "")
+ assert len(loads) == 2
+
+
+def test_a_different_budget_misses_the_cache(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The budget is baked into a CLI brain at instantiation; handing a 30 s
+ caller a brain built for 90 s hands it the wrong internal deadline."""
+ budgets: list[float | None] = []
+ monkeypatch.setattr(writer, "_load_config", lambda: _cfg("auto"))
+ monkeypatch.setattr(
+ writer, "_subscription", lambda cfg, timeout: budgets.append(timeout) or "sub"
+ )
+
+ writer.resolve_writer(cli_timeout_s=90.0)
+ writer.resolve_writer(cli_timeout_s=30.0)
+
+ assert budgets == [90.0, 30.0]
+
+
+def test_a_rescue_resolution_invalidates_the_cache(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A rescue means the cached choice just failed in someone's hands; the
+ next composition must re-ask instead of getting the dead writer back."""
+ loads: list[int] = []
+ monkeypatch.setattr(
+ writer, "_load_config", lambda: loads.append(1) or _cfg("auto")
+ )
+ monkeypatch.setattr(writer, "_subscription", lambda cfg, timeout: "sub-brain")
+ monkeypatch.setattr(writer, "_quality", lambda cfg: "api-brain")
+ monkeypatch.setattr(writer, "_tool_model", lambda cfg: None)
+
+ writer.resolve_writer()
+ writer.resolve_rescue_writer(exclude=("subscription:auto",))
+ writer.resolve_writer()
+
+ # Three real resolutions: the second resolve_writer re-asked.
+ assert len(loads) == 3
+
+
+def test_the_cache_expires(monkeypatch: pytest.MonkeyPatch) -> None:
+ now = [1000.0]
+ monkeypatch.setattr(
+ writer, "time", SimpleNamespace(monotonic=lambda: now[0])
+ )
+ loads: list[int] = []
+ monkeypatch.setattr(
+ writer, "_load_config", lambda: loads.append(1) or _cfg("auto")
+ )
+ monkeypatch.setattr(writer, "_subscription", lambda cfg, timeout: "sub-brain")
+
+ writer.resolve_writer()
+ now[0] += writer._CACHE_TTL_S + 1.0 # noqa: SLF001
+ writer.resolve_writer()
+
+ assert len(loads) == 2
diff --git a/tests/unit/plugins/brain/test_claude_cli_brain.py b/tests/unit/plugins/brain/test_claude_cli_brain.py
index 0df4458db6..35b7872d9f 100644
--- a/tests/unit/plugins/brain/test_claude_cli_brain.py
+++ b/tests/unit/plugins/brain/test_claude_cli_brain.py
@@ -116,3 +116,109 @@ async def test_complete_raises_a_clear_error_when_the_cli_is_absent(
with pytest.raises(RuntimeError, match="Claude CLI"):
async for _delta in brain.complete(_req()):
pass
+
+
+_FAST_FLAGS = frozenset(
+ {
+ "--tools",
+ "--strict-mcp-config",
+ "--disable-slash-commands",
+ "--no-session-persistence",
+ "--effort",
+ }
+)
+
+
+def test_structured_turns_shed_startup_weight_the_cli_supports() -> None:
+ """A structured turn is pure writing: no tools, no MCP servers, no skills,
+ no saved session. Every one of those is cold-start cost on a call the user
+ is waiting through (27.5 s -> 16.4 s measured on the composer's payload)."""
+ brain = ClaudeCliBrain(structured_prompts=True)
+ argv, _prompt = brain.build_invocation(_req(), cli_flags=_FAST_FLAGS)
+ assert "--tools" in argv
+ assert argv[argv.index("--tools") + 1] == ""
+ for flag in ("--strict-mcp-config", "--disable-slash-commands",
+ "--no-session-persistence"):
+ assert flag in argv
+
+
+def test_an_older_cli_never_sees_a_flag_it_would_die_on() -> None:
+ """An unknown option makes the CLI exit with a usage error instead of an
+ answer — a speed-up that bricks the writer on an older install (§3)."""
+ brain = ClaudeCliBrain(structured_prompts=True)
+ for flags in (frozenset(), None):
+ argv, _prompt = brain.build_invocation(_req(), cli_flags=flags)
+ for flag in _FAST_FLAGS:
+ assert flag not in argv
+
+
+def test_the_callers_reasoning_effort_is_forwarded() -> None:
+ """The composer documents "medium" as its quality floor; the CLI's own
+ default may think longer without writing a better brief."""
+ from jarvis.core.protocols import BrainMessage, BrainRequest
+
+ req = BrainRequest(
+ messages=(BrainMessage(role="user", content="payload"),),
+ system="CONTRACT",
+ reasoning_effort="medium",
+ stream=True,
+ )
+ brain = ClaudeCliBrain(structured_prompts=True)
+ argv, _prompt = brain.build_invocation(req, cli_flags=_FAST_FLAGS)
+ assert argv[argv.index("--effort") + 1] == "medium"
+ # An unsupported CLI never sees it; "none" has no CLI level and stays home.
+ bare, _prompt = brain.build_invocation(req, cli_flags=frozenset())
+ assert "--effort" not in bare
+
+
+def test_conversational_turns_keep_their_shape() -> None:
+ """The lean set belongs to structured briefs; the voice path deliberately
+ keeps its read-only lookups and is not this change's to alter."""
+ brain = ClaudeCliBrain(structured_prompts=False)
+ argv, _prompt = brain.build_invocation(_req(), cli_flags=_FAST_FLAGS)
+ assert "--tools" not in argv
+ assert "--strict-mcp-config" not in argv
+
+
+def test_the_flag_probe_reads_the_clis_own_help(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Ground truth over version guesswork: the help text is the CLI's own
+ statement of what it accepts."""
+ from types import SimpleNamespace
+
+ from jarvis.plugins.brain import claude_cli
+
+ claude_cli.reset_flag_probe_cache()
+ monkeypatch.setattr(claude_cli, "_resolve_claude_binary", lambda: "claude")
+ monkeypatch.setattr(
+ claude_cli.subprocess,
+ "run",
+ lambda *a, **k: SimpleNamespace(
+ stdout="Options:\n --tools <tools...>\n --effort <level>\n"
+ ),
+ )
+ try:
+ flags = claude_cli._probe_supported_flags() # noqa: SLF001
+ assert {"--tools", "--effort"} <= flags
+ assert "--strict-mcp-config" not in flags
+ finally:
+ claude_cli.reset_flag_probe_cache()
+
+
+def test_a_failed_probe_degrades_to_the_minimal_invocation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """No probe answer means no gated flag — slower, never broken."""
+ from jarvis.plugins.brain import claude_cli
+
+ def _boom(*_args: object, **_kwargs: object) -> object:
+ raise OSError("no spawn on this host")
+
+ claude_cli.reset_flag_probe_cache()
+ monkeypatch.setattr(claude_cli, "_resolve_claude_binary", lambda: "claude")
+ monkeypatch.setattr(claude_cli.subprocess, "run", _boom)
+ try:
+ assert claude_cli._probe_supported_flags() == frozenset() # noqa: SLF001
+ finally:
+ claude_cli.reset_flag_probe_cache()