Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): resolve who a spoken instruction is for, and say so honestly
Ruben Lütke9ea46a279184
diff --git a/jarvis/agentic_ide/clarify.py b/jarvis/agentic_ide/clarify.pynew file mode 100644index 0000000000..640d6912ec--- /dev/null+++ b/jarvis/agentic_ide/clarify.py@@ -0,0 +1,742 @@+"""Ask which terminal was meant, instead of guessing or going silent.++A call-sign arrives through speech recognition, and the resolver has to draw a+line somewhere: above it a word IS a pane's name, below it the word is ordinary+speech. Both sides of that line have now failed in production, on the same day,+in opposite directions:++* **Silent miss** (2026-07-27 16:18) — a pane called "Ellis" came back as+ "Ilies", scoring 0.667 against a 0.72 floor. The addressed-terminal path stood+ down without a word, no prompt ever reached the pane, and the live model —+ which never learns any of this — told the user an agent was working on it.+* **Silent false hit** — ordinary words of the spoken language reach the pool+ from below: "allen" scores 0.750 against "Alex", i.e. ABOVE the same floor.+ A sentence about the outside world ("what is Elon Musk up to?") must never+ become an instruction typed into somebody's coding agent.++No threshold fixes both, because the two failures overlap on the score axis —+the maintainer's directive (2026-07-27) is therefore to decide by CONTEXT and,+when context says "this is about the panes" but the name is uncertain, to ASK:++ "Did you mean Ellis?"++That is what this module decides. It answers one question — "is this turn+addressing the workspace, and if so, which pane did the user probably mean?" —+and, like ``intent``, it is a detector, not a policy: the caller decides what to+do with the answer.++The asymmetry that shapes every rule below: a needless question costs the user+one word ("yes"), while a wrong guess types a stranger's task into an agent that+then works for minutes on it. So the gate is deliberately hard to pass, and+whatever it is unsure about becomes a question rather than an action.++Cost: pure regex over the utterance, no IO and no LLM (AP-9 / AP-11), so it is+safe on the voice hot path.+"""+from __future__ import annotations++import re+import time+from dataclasses import dataclass, field++from .names import near_miss, resolve++# How long a pending question stays answerable. Voice turns arrive within+# seconds; two minutes covers a slow "uh... yes, Ellis" without letting a+# forgotten question deliver work much later in the session. Same bound as the+# delegation offer window, for the same reason.+_WINDOW_TTL_S = 120.0++# A short answer is an ANSWER to the question ("yes", "Ellis", "the second+# one"); a long sentence is the user moving on and must never deliver the old+# task. Same bound the spawn gate uses for its confirmation.+_ANSWER_MAX_WORDS = 6+++# --------------------------------------------------------------------------- #+# Is this turn about the workspace at all? #+# --------------------------------------------------------------------------- #+# The gate that separates "prompt Max" from "what is Elon Musk doing". Evidence+# has to be POSITIVE and explicit: the default answer is no, because that is the+# answer that cannot type a stranger's sentence into a running coding agent.++#: Words that only ever mean the coding workspace. Naming a pane, or the act of+#: handing one work, is the strongest evidence there is.+_WORKSPACE_NOUN_RE = re.compile(+ r"\b(?:terminals?|terminales|panes?|workspaces?|"+ r"arbeitsbereich\w*|instanz\w*|instances?|" # i18n-allow: input vocab+ r"prompte?\w*|prompting|anprompt\w*|" # i18n-allow: input vocab+ r"beauftrag\w*|briefe?\w*|briefing)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)++#: The work coding agents actually do. A sentence carrying this vocabulary is+#: about the user's own codebase, which is what the panes are for — as opposed+#: to a question about the world, which never contains it.+_CODING_WORK_RE = re.compile(+ r"\b(?:"+ # investigation / analysis+ r"deep[\s-]?dive|root[\s-]?cause|debug\w*|analysier\w*|analyz\w*|analis\w*|"+ r"untersuch\w*|investigate\w*|diagnos\w*|" # i18n-allow: input vocab+ # change+ # i18n-allow: input vocab+ r"fix\w*|behebe?\w*|repariere?\w*|refactor\w*|implementier\w*|implement\w*|"+ r"commit\w*|merge\w*|rebase\w*|deploy\w*|"+ # artifacts+ r"bugs?|fehler\w*|tests?|teste\w*|repo\w*|branch\w*|" # i18n-allow: input vocab+ r"code\w*|datei\w*|files?|funktion\w*|functions?|" # i18n-allow: input vocab+ r"pull[\s-]?request|pr\b|"+ # Spanish work vocabulary, kept level with the other two locales+ r"arregl\w*|revis\w*|prueba\w*|archivo\w*|rama\w*"+ r")\b",+ re.IGNORECASE,+)++#: Handing work to somebody — "sag X …", "lass X …", "tell X to …". Reused from+#: the same vocabulary ``intent`` addresses panes with, kept here as a flat verb+#: scan because at this point the NAME is exactly what we are unsure about, so a+#: name-anchored template cannot be built yet.+_HANDOVER_VERB_RE = re.compile(+ # Stems, not fixed forms: the maintainer's own phrasing is "… machen+ # LASSEN", and a `lass\b` alternative silently misses every separable and+ # infinitive form German actually hands work over in.+ r"\b(?:sag\w*|schick\w*|gib|geb\w*|frag\w*|lass\w*|l[aä]sst|" # i18n-allow: input vocab+ r"beauftrag\w*|[uü]bergib|[uü]bergeb\w*|weiterleit\w*|" # i18n-allow: input vocab+ r"tell|send|give|ask|hand|forward|assign|let|have|"+ r"dile|d[ií]gale|env[ií]a|manda|preg[uú]nta|pasa|asigna|encarga)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+++#: "X SOLL das fixen" — an order aimed at a third party, carried by the modal+#: rather than by a handover verb. This is the other half of how work is+#: assigned in speech, and ``intent`` matches it name-anchored; here the name is+#: precisely what is uncertain, so the modal is scanned on its own and paired+#: with coding work to keep it honest.+_DIRECTIVE_MODAL_RE = re.compile(+ r"\b(?:soll|sollen|sollte|sollten|m[uü]ssen|muss|" # i18n-allow: input vocab+ r"should|must|shall|"+ r"deber[ií]an?|debe|deben)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+++#: "What has X done?" / "How far is X?" — asking a NAMED worker for a status+#: report. The shape carries no coding vocabulary at all, which is why it+#: needed its own rule: "was hat Dana gemacht" names no repo, no test, no bug+#: and no branch, so the coding-work pairings below never saw it.+#:+#: Each locale gets both word orders, and the German alternation carries the+#: optional perfect prefix ("gemacht", "getan", "gearbeitet") — the tense+#: spoken German actually uses to ask about work that has already happened, and+#: the exact form the live 2026-07-27 turn was lost on.+_REPORT_QUESTION_RE = re.compile(+ # A progress opener is a status question on its own — "wie weit ist Ellis?"+ # carries no verb of doing at all, and nothing else is ever asked with it.+ r"\b(?:wie\s+weit|wie\s+l[aä]uft|wie\s+steht|how\s+far|" # i18n-allow: input vocab+ r"c[oó]mo\s+va)\b|"+ r"\bwas\b[^.!?]{0,40}?" # i18n-allow: input vocab+ r"\b(?:ge)?(?:macht|machen|tut|tun|tan|treibt|treiben|arbeitet|" # i18n-allow: input vocab+ r"arbeiten|schafft|geschafft|erledigt|rausgefunden|" # i18n-allow: input vocab+ r"herausgefunden|gebaut|geschrieben|ge[aä]ndert)\b|" # i18n-allow: input vocab+ r"\b(?:ist|sind)\b[^.!?]{0,30}?\b(?:fertig|durch|soweit)\b|" # i18n-allow: input vocab+ r"\b(?:what|how)\b[^.!?]{0,40}?"+ r"\b(?:doing|done|do|did|up\s+to|going|built|found|changed|"+ r"working\s+on|progress\w*)\b|"+ r"\b(?:is|are)\b[^.!?]{0,30}?\b(?:done|finished|ready|stuck)\b|"+ r"\b(?:qu[eé]|c[oó]mo)\b[^.!?]{0,40}?"+ r"\b(?:hacen?|haciendo|hecho|hizo|hicieron|va|van|"+ r"encontr\w*|cambi\w*)\b|"+ r"\b(?:est[aá]|est[aá]n)\b[^.!?]{0,30}?\b(?:listo\w*|terminad\w*)\b|"+ r"\b(?:status|fortschritt|estado|progreso)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+++def addresses_workspace(text: str) -> bool:+ """Whether this turn is plausibly about the open coding workspace.++ Four independent kinds of evidence, any one of which is enough:++ 1. the utterance NAMES the workspace or the act of prompting a pane+ ("prompt Max", "beauftrage Max") — unambiguous on its own;+ 2. it hands work over AND that work is coding work ("tell Max to fix the+ tests");+ 3. it gives a third-party order AND that order is coding work ("Ellis soll+ einen Deep Dive machen") — the shape that carries no handover verb;+ 4. it asks a named worker for a STATUS REPORT ("was hat Ellis gemacht?").++ In 2 and 3 the pairing is what does the work. A handover verb alone+ deliberately does NOT qualify: "tell me what Elon Musk is doing" is a+ handover verb plus a name and nothing else, and that sentence must never+ reach a coding agent.++ 4 stands alone without a coding-work pairing, and it may, because of what+ it can and cannot cause. This module only ever produces a QUESTION — "did+ you mean Ellis?" — and only for a turn where no pane was certainly named+ and exactly one word came close. A status question about somebody the user+ really did mean as a person therefore costs one "no"; without the rule, a+ call-sign that speech recognition garbled inside the single most common+ workspace question there is went silently nowhere, which is the failure+ this whole module exists to end.+ """+ body = str(text or "")+ if _WORKSPACE_NOUN_RE.search(body):+ return True+ # A status question about a FULL personal name is about that person: "sag+ # mir was Elon Musk gerade macht" has the identical shape to "sag mir was+ # Ellis gerade macht" and the opposite meaning, and the surname is the only+ # thing that tells them apart. Same rule the collective address uses, so+ # the two cannot drift into disagreeing about one sentence.+ if _REPORT_QUESTION_RE.search(body) and not is_outside_world_talk(body):+ return True+ if not _CODING_WORK_RE.search(body):+ return False+ return bool(+ _HANDOVER_VERB_RE.search(body) or _DIRECTIVE_MODAL_RE.search(body)+ )+++# --------------------------------------------------------------------------- #+# Is this word a call-sign at all? #+# --------------------------------------------------------------------------- #++#: Word characters only — the unit the resolver scores. Mirrors ``intent``.+_WORD_RE = re.compile(r"[^\W\d_]+", re.UNICODE)++_SENTENCE_START_RE = re.compile(r"(?:^|[.!?:;]\s*|\n\s*)$")++#: Function words that are never a call-sign, however close they score. This is+#: matching *input vocabulary*, not prose.+#:+#: Needed because similarity alone cannot tell them apart from a garbled name —+#: measured against the shipping pool, "kannst" reaches "Casey" at 0.600,+#: "macht" reaches "Max" at 0.571, and "allen" reaches "Alex" at 0.750, which is+#: ABOVE the acting threshold. That last one is the maintainer's own+#: counter-example (2026-07-27): a sentence about the outside world must never+#: become a prompt typed into every open pane.+#:+#: Deliberately only the closed class (pronouns, articles, modals, question+#: words, common auxiliaries). Content words are left out: they are what a+#: person's name competes with legitimately, and the capitalization signal plus+#: the workspace gate already cover them.+#: Kept as one tuple per language rather than one merged literal: the locales+#: overlap ("no", "me", "es", "a" are each two languages' function words), and a+#: single set literal would both hide that and read as a mistake.+_STOPWORDS_DE: tuple[str, ...] = ( # i18n-allow: input vocabulary+ "alle", "allen", "aller", "alles", "als", "am", "an", "auch", "auf",+ "aus", "bei", "bin", "bis", "bist", "bitte", "da", "dann", "das",+ "dass", "dein", "deine", "dem", "den", "denn", "der", "des", "die",+ "dir", "doch", "du", "ein", "eine", "einen", "einer", "eines", "er",+ "es", "etwas", "euch", "für", "gerade", "gib", "hab", "habe", "haben",+ "hast", "hat", "hier", "ich", "ihm", "ihn", "ihr", "im", "in", "ist",+ "ja", "kann", "kannst", "können", "könnte", "lass", "lassen", "mach",+ "machen", "macht", "mal", "man", "mein", "meine", "mir", "mit", "muss",+ "müssen", "nach", "nein", "nicht", "noch", "nur", "ob", "oder", "sag",+ "sage", "schon", "sein", "seine", "sich", "sie", "sind", "so", "soll",+ "sollen", "über", "um", "und", "uns", "unser", "von", "vor", "war",+ "was", "wenn", "wer", "werde", "werden", "wie", "wieso", "will",+ "wir", "wird", "wo", "zu", "zum", "zur",+)+_STOPWORDS_EN: tuple[str, ...] = (+ "a", "all", "am", "an", "and", "are", "as", "ask", "at", "be", "been",+ "but", "by", "can", "could", "did", "do", "does", "for", "from", "get",+ "give", "had", "has", "have", "he", "her", "him", "his", "how", "i",+ "if", "in", "into", "is", "it", "its", "just", "let", "make", "makes",+ "me", "my", "no", "not", "now", "of", "on", "one", "or", "our", "out",+ "please", "put", "say", "she", "should", "so", "some", "tell", "that",+ "the", "their", "them", "then", "there", "these", "they", "this",+ "to", "up", "us", "was", "we", "were", "what", "when", "where",+ "which", "who", "why", "will", "with", "would", "yes", "you", "your",+)+_STOPWORDS_ES: tuple[str, ...] = ( # i18n-allow: input vocabulary+ "a", "al", "algo", "aqui", "así", "como", "con", "cual", "cuando",+ "de", "del", "dile", "donde", "el", "ella", "ellos", "en", "era",+ "es", "esa", "ese", "eso", "esta", "este", "esto", "está", "están",+ "haz", "la", "las", "le", "les", "lo", "los", "mas", "me", "mi",+ "no", "nos", "o", "para", "pero", "por", "que", "qué", "quien",+ "se", "ser", "si", "sí", "sobre", "solo", "son", "su", "sus", "te",+ "tu", "un", "una", "uno", "y", "ya", "yo",+)+_STOPWORDS: frozenset[str] = frozenset(+ _STOPWORDS_DE + _STOPWORDS_EN + _STOPWORDS_ES+)+++def _capitalization_is_informative(text: str) -> bool:+ """Whether this transcript capitalizes at all, i.e. whether case can rule.++ An all-lowercase transcript is a provider quirk, not evidence that the+ utterance contains no names.+ """+ body = str(text or "")+ return any(ch.isupper() for ch in body)+++def _is_proper_name_position(text: str, start: int, end: int) -> bool:+ """Whether the word at ``[start:end)`` reads as a proper name.++ Two filters, in this order, because they fail differently:++ 1. **a function word is never a name** — decisive in every transcript,+ including one with no capitals at all;+ 2. **otherwise capitalization decides**, when the transcript capitalizes at+ all. Position is deliberately NOT considered: a call-sign opening the+ sentence is the most natural way to address a pane ("Ellis, schau dir+ das an"), and excluding sentence-initial words would blind the check to+ exactly that shape.+ """+ word = text[start:end]+ if word.casefold() in _STOPWORDS:+ return False+ if _is_vocabulary_word(word):+ return False+ if not _capitalization_is_informative(text):+ return True+ return word[:1].isupper()+++#: What somebody ASKS FOR about a pane, as a noun: "Alex Status?", "Dana+#: Fortschritt", "Casey progress". German capitalizes every noun, so without+#: this these read as surnames and the pane is disowned as a person out in the+#: world — which is how "Alex Status?", a textbook status question, matched+#: nothing at all.+_STATUS_NOUN_RE = re.compile(+ r"\b(?:status|fortschritt\w*|stand|update\w*|progress|" # i18n-allow: input vocab+ r"bericht\w*|report\w*|estado|progreso|informe\w*)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+++def _is_vocabulary_word(word: str) -> bool:+ """Whether the word is one this module already reads as something else.++ A word that names the WORK cannot also name the worker. Without this, an+ all-lowercase transcript — where capitalization cannot rule anything out —+ let "fixen" stand in for the pane "Finn" (0.667) and ask about a sentence+ that names no pane at all.++ Anchored so only a WHOLE word counts: the vocabulary patterns are written+ to find their stems anywhere in a sentence, and reused unanchored they+ would reject any call-sign that merely contains one.+ """+ for pattern in (+ _WORKSPACE_NOUN_RE,+ _CODING_WORK_RE,+ _HANDOVER_VERB_RE,+ _DIRECTIVE_MODAL_RE,+ _STATUS_NOUN_RE,+ ):+ match = pattern.match(word)+ if match is not None and match.end() == len(word):+ return True+ return False+++#: A second capitalized word directly after the candidate — "Elon MUSK", "Max+#: MUSTERMANN". Panes carry exactly one given name (see ``names.NAME_POOL``), so+#: a surname is positive evidence that a PERSON is meant, not a terminal. This+#: is the maintainer's own criterion (2026-07-27): "when I only say a first+#: name" is the case that should ask.+_SURNAME_FOLLOWS_RE = re.compile(r"^[\s,]*[A-ZÄÖÜ][^\W\d_]+")+_SURNAME_PRECEDES_RE = re.compile(r"[A-ZÄÖÜ][^\W\d_]+[\s,]*$")+++def is_part_of_full_name(text: str, start: int, end: int) -> bool:+ """Whether the candidate is part of a longer proper name ("Elon Musk").++ Public because ``intent`` needs exactly this answer too: a call-sign is a+ single given name, so a first name carrying a surname is a PERSON out in+ the world and never the pane. Two copies of that rule would be two chances+ to disagree about one sentence, which is how "what has Dana Schmidt done"+ ends up read as a question about a terminal.+ """+ if not _capitalization_is_informative(text):+ return False+ following = _SURNAME_FOLLOWS_RE.match(text[end:])+ if following is not None:+ # German capitalizes every noun, so the word after a call-sign is+ # capitalized whether it is a surname or the thing being asked about.+ # A word this module already reads as work, a workspace or a status is+ # therefore never the surname: "Alex Status?" is a question about the+ # pane, and reading "Status" as a family name struck the pane out of+ # its own status question. Same reasoning for "sag Dana Bescheid".+ if not _is_vocabulary_word(following.group(0).strip(" ,")):+ return True+ preceding = text[:start]+ leading = _SURNAME_PRECEDES_RE.search(preceding)+ if leading is None:+ return False+ if _is_vocabulary_word(leading.group(0).strip(" ,")):+ return False+ # A capitalized word in FRONT only makes this a surname when that word is+ # not itself the one opening the sentence. The sentence-start test has to+ # be aimed at THAT word, not at the candidate: aimed at the candidate it+ # read "Ist Blake fertig?" as a person called Ist Blake, because "Ist" is+ # capitalized for grammar and stands at the very beginning — which silently+ # withdrew the pane from every question opening with a verb.+ return not _SENTENCE_START_RE.search(preceding[: leading.start()])+++#: Two capitalized words in a row, the second not opening a sentence — a person+#: or organisation out in the world ("Elon Musk", "Barack Obama"). Panes carry a+#: single given name, so this shape never describes one.+_MULTIWORD_NAME_RE = re.compile(+ r"(?<![.!?:;\n])\s[A-ZÄÖÜ][^\W\d_]+\s+[A-ZÄÖÜ][^\W\d_]+"+)+++def is_outside_world_talk(text: str) -> bool:+ """Whether this turn is about the world rather than the user's codebase.++ Guards the COLLECTIVE address ("sag allen …"), which reaches every open+ pane at once and is therefore the most expensive thing a misheard word can+ trigger. The maintainer's counter-example (2026-07-27): a question about a+ public figure that speech recognition turns into "sag allen …" must not+ become an instruction typed into every running coding agent.++ Deliberately narrow — it answers yes only for a full personal name with no+ coding work anywhere in the sentence. "Tell everyone to stop" carries no+ such name and stays a perfectly good collective instruction.+ """+ body = str(text or "")+ if not _capitalization_is_informative(body):+ return False+ return bool(+ _MULTIWORD_NAME_RE.search(body) and not _CODING_WORK_RE.search(body)+ )+++# --------------------------------------------------------------------------- #+# The detector #+# --------------------------------------------------------------------------- #+++@dataclass(frozen=True, slots=True)+class UncertainName:+ """One word that came close to a call-sign, and the panes it might be."""++ spoken: str+ """The word as the transcript spelled it ("Ilies")."""++ candidates: tuple[str, ...]+ """Panes it could mean, best first. Never empty."""+++@dataclass(frozen=True, slots=True)+class ClarificationNeeded:+ """Everything one turn addressed that could not simply be acted on.++ A turn addresses a FLEET, not a pane — "Alex und Blaike, macht beide einen+ Deep Dive" is one instruction for two agents — so this carries a list on+ both axes. The single-name shape it started as could not represent that+ turn at all, and the resulting behaviour was the worst of the three+ possible ones: Alex was briefed, Blaike was dropped without a word, and the+ user watched one agent work believing two were (live 2026-07-27 19:07).+ """++ uncertain: tuple[UncertainName, ...]+ """The words that need a question. Never empty."""++ utterance: str+ """The original turn, kept verbatim so the confirmed pane gets the REAL+ task and not a paraphrase assembled from fragments."""++ certain: tuple[str, ...] = ()+ """Panes the SAME turn named beyond doubt. They are not in question and+ must be briefed whatever the answer is; they travel with the question only+ so the caller can tell "one pane is uncertain" from "everything is"."""++ @property+ def spoken(self) -> str:+ """The first uncertain word — the one a single-name question names."""+ return self.uncertain[0].spoken++ @property+ def candidates(self) -> tuple[str, ...]:+ """Panes the first uncertain word could mean."""+ return self.uncertain[0].candidates++ @property+ def offered(self) -> tuple[str, ...]:+ """Every pane any of the uncertain words could mean, in order."""+ seen: list[str] = []+ for item in self.uncertain:+ for name in item.candidates:+ if name not in seen:+ seen.append(name)+ return tuple(seen)+++#: What may stand between two names that are being listed together. Only+#: enumeration punctuation and the supported languages' "and" — anything else+#: means the two words are in different clauses and say nothing about each+#: other. Matching *input vocabulary*, not prose.+_ENUMERATION_GAP_RE = re.compile(+ r"^[\s,;&]*"+ # i18n-allow: input vocabulary — the supported languages' "and"+ r"(?:und|and|y|e|sowie|plus|as\s+well\s+as|together\s+with|junto\s+con)?"+ r"[\s,;&]*$",+ re.IGNORECASE,+)+++def _is_listed_beside(text: str, span: tuple[int, int], others: list[tuple[int, int]]) -> bool:+ """Whether the word at ``span`` is enumerated next to one of ``others``.++ "Alex und Blaike" lists two call-signs; "Alex, look at what Blaike wrote"+ does not, and the difference is exactly what sits between them. Used only+ where a word would otherwise be too weak to ask about on its own, so it+ buys reach without widening what a lone stray capital can trigger.+ """+ start, end = span+ for other_start, other_end in others:+ if other_end <= start and _ENUMERATION_GAP_RE.match(text[other_end:start]):+ return True+ if end <= other_start and _ENUMERATION_GAP_RE.match(text[end:other_start]):+ return True+ return False+++def detect_clarification(+ user_text: str, *, names: list[str]+) -> ClarificationNeeded | None:+ """What this turn addressed but did not clearly name, or ``None``.++ Every condition below removes one way of being wrong:++ 1. **the turn addresses the workspace** — otherwise a question about the+ world could put words into a coding agent;+ 2. **the word reads as a proper name** — capitalized, not just first in+ its sentence;+ 3. **it is not part of a longer proper name** — "Elon Musk" is a person;+ 4. **a word that stands alone in its uncertainty** may only ask when it is+ the turn's ONLY unclear name and no pane was certainly named. Beyond+ that single case the word has to be ENUMERATED beside another name+ ("Alex und Blaike") — that is what separates a garbled member of a list+ from a stray capital in a sentence that already works.++ A certainly-named pane no longer ENDS the search, which is the change that+ matters. It used to: any certain name returned ``None``, so "Alex und+ Blaike" produced a question about nothing, Alex was briefed alone, and the+ second agent the user had just addressed was dropped in silence. The+ certain panes now travel with the answer instead (``certain``) — the caller+ briefs them immediately and asks only about the rest.+ """+ text = str(user_text or "").strip()+ if len(text) < 3 or not names:+ return None+ if not addresses_workspace(text):+ return None++ certain: list[str] = []+ certain_spans: list[tuple[int, int]] = []+ uncertain: list[tuple[tuple[int, int], UncertainName]] = []+ for match in _WORD_RE.finditer(text):+ word = match.group(0)+ span = (match.start(), match.end())+ # Certain means the exact name or the same sound — deliberately the+ # same bar ``near_miss`` uses, so no utterance can fall between the two+ # paths and produce neither an action nor a question.+ sure = resolve(word, names, fuzzy=False)+ if sure is not None:+ if sure not in certain:+ certain.append(sure)+ certain_spans.append(span)+ continue+ candidates = near_miss(word, names)+ if not candidates:+ continue+ if not _is_proper_name_position(text, *span):+ continue+ if is_part_of_full_name(text, *span):+ continue+ uncertain.append(+ (span, UncertainName(spoken=word, candidates=tuple(n for n, _ in candidates)))+ )++ if not uncertain:+ return None++ if len(uncertain) > 1 or certain:+ # More than one unclear word, or one standing beside a certain name:+ # only the ones being LISTED with another name survive. A single stray+ # near miss elsewhere in the sentence is noise, and asking about it+ # would tax every turn that already works.+ neighbours = certain_spans + [span for span, _ in uncertain]+ kept = [+ (span, item)+ for span, item in uncertain+ if _is_listed_beside(text, span, [s for s in neighbours if s != span])+ ]+ if not kept:+ return None+ uncertain = kept++ return ClarificationNeeded(+ uncertain=tuple(item for _, item in uncertain),+ utterance=text,+ certain=tuple(certain),+ )+++# --------------------------------------------------------------------------- #+# The answer window #+# --------------------------------------------------------------------------- #+++@dataclass(slots=True)+class _Pending:+ uncertain: tuple[UncertainName, ...]+ utterance: str+ asked_at: float+ question: str = ""++ @property+ def candidates(self) -> tuple[str, ...]:+ """Every pane on offer, in the order they were spoken."""+ seen: list[str] = []+ for item in self.uncertain:+ for name in item.candidates:+ if name not in seen:+ seen.append(name)+ return tuple(seen)+++@dataclass(slots=True)+class ClarificationWindow:+ """A question waiting for its answer.++ Without this the question would be theatre: "did you mean Ellis?" followed+ by "yes" has to actually deliver the ORIGINAL task, or the user has simply+ been made to repeat themselves — which is worse than the silent miss it+ replaces, because it also cost them a turn.+ """++ _pending: _Pending | None = field(default=None)++ def arm(+ self, need: ClarificationNeeded, *, question: str = "", now: float | None = None+ ) -> None:+ self._pending = _Pending(+ uncertain=need.uncertain,+ utterance=need.utterance,+ asked_at=time.monotonic() if now is None else now,+ question=question,+ )++ def disarm(self) -> None:+ self._pending = None++ @property+ def armed(self) -> bool:+ return self._pending is not None++ def resolve_answer(+ self, answer: str, *, language: str = "de", now: float | None = None+ ) -> tuple[tuple[str, ...], str] | None:+ """``(panes, original_utterance)`` for a clear answer, else ``None``.++ A tuple of panes rather than one, because the question can be about a+ fleet: "did you mean Alex and Blake?" is answered by one "yes" and both+ agents have to be briefed by it. Answering it with one pane was how the+ second agent of an addressed pair got lost.++ Consumed exactly once either way — a question that has been answered,+ declined or ignored must never deliver work on a later turn.++ Three shapes count as an answer, in falling directness:++ 1. the user NAMES offered panes ("Ellis", "Alex and Blake") — decisive+ even when several were offered;+ 2. a short affirmative — it confirms every uncertain word that has only+ ONE candidate, because "yes" cannot choose between two;+ 3. anything else: the window closes and the turn proceeds normally.+ """+ pending = self._pending+ if pending is None:+ return None+ current = time.monotonic() if now is None else now+ if (current - pending.asked_at) > _WINDOW_TTL_S:+ self._pending = None+ return None++ text = str(answer or "").strip()+ if not text:+ return None++ offered = list(pending.candidates)+ named = [+ hit+ for hit in (+ resolve(match.group(0), offered, fuzzy=False)+ for match in _WORD_RE.finditer(text)+ )+ if hit is not None+ ]+ if not named:+ # The whole answer as one token, which is how a one-word reply and+ # a two-word call-sign both arrive.+ single = resolve(text, offered)+ if single is not None:+ named = [single]+ if named:+ self._pending = None+ return tuple(dict.fromkeys(named)), pending.utterance++ # Only a SHORT turn is an answer at all; a full sentence is the user+ # moving on, and delivering the old task then would be a surprise. The+ # bound grows with the number of names on offer: confirming a fleet+ # costs more words than confirming one pane.+ if len(text.split()) > _ANSWER_MAX_WORDS + len(pending.uncertain) - 1:+ self._pending = None+ return None++ verdict = _classify(text, language)+ self._pending = None+ if verdict != "confirm":+ return None+ decided = tuple(+ dict.fromkeys(+ item.candidates[0] for item in pending.uncertain if len(item.candidates) == 1+ )+ )+ return (decided, pending.utterance) if decided else None+++def _classify(text: str, language: str) -> str:+ """Yes/no verdict for a short answer, across every supported language.++ The per-turn language tag cannot be trusted (STT mislabels are a known+ class), so the answer is classified under all supported languages and a+ veto keeps its safety priority — exactly what ``spawn_gate`` does.+ """+ try:+ from jarvis.voice.echo_confirmation import classify_response # noqa: PLC0415+ except Exception: # noqa: BLE001 — a classifier fault is simply "no answer"+ return "unknown"+ verdicts = {+ classify_response(text, language=lang)+ for lang in {"de", "en", "es", str(language or "de")}+ }+ if "veto" in verdicts:+ return "veto"+ return "confirm" if "confirm" in verdicts else "unknown"+++#: ONE conversation per process (desktop app / headless session), so ONE shared+#: window — the same reasoning as ``spawn_gate.OFFER_WINDOW``. Tests reset it+#: via ``disarm()``.+WINDOW = ClarificationWindow()+++__all__ = [+ "WINDOW",+ "ClarificationNeeded",+ "ClarificationWindow",+ "UncertainName",+ "addresses_workspace",+ "detect_clarification",+ "is_outside_world_talk",+ "is_part_of_full_name",+]diff --git a/jarvis/agentic_ide/context.py b/jarvis/agentic_ide/context.pyindex b99da70e9d..c567e657ec 100644--- a/jarvis/agentic_ide/context.py+++ b/jarvis/agentic_ide/context.py@@ -45,7 +45,7 @@ _HEADER = ("\n""How to behave while this mode is on:\n""- When the user tells a named terminal to do something (\"tell Kai to …\", "- "\"Mika soll …\", \"let Nova refactor …\"), send it to THAT terminal with "+ "\"Mika soll …\", \"let Nova refactor …\"), send it to THAT terminal with " # i18n-allow: quoted addressing examples the router must match"the agentic-ide-prompt function. That is the whole point of this mode. ""NEVER spawn a background agent for work aimed at a terminal, and never ""answer with what you WOULD have sent — send it.\n"diff --git a/jarvis/agentic_ide/drop_analysis.py b/jarvis/agentic_ide/drop_analysis.pynew file mode 100644index 0000000000..74a4c4823e--- /dev/null+++ b/jarvis/agentic_ide/drop_analysis.py@@ -0,0 +1,452 @@+"""What a dropped file actually CONTAINS, worked out before an agent is briefed.++Dropping a screenshot on the prompt bar and dropping it on a pane are two+different products. The pane types a path and stops there, which is right for+"look at this file": the coding agent opens it itself. But a *screenshot* handed+to a coding agent is frequently a dead end — several of the CLIs this app drives+are text-only, and the ones that can see an image still have to be told to look+at it. The user meanwhile has dropped a picture of a broken layout and typed+"fix this", and what reaches the agent is a path and a pronoun.++So this module reads the drop first. An image gets described by a model that can+actually see it; a document gets its text pulled out; and the result is folded+into the prompt as context the agent can work from *whether or not* it can open+the file itself. The file reference still ships alongside — a vision-capable+agent should look at the original, and the description is the floor, not a+replacement.++Three rules this module is built around:++* **Capability, never a provider name** (AP-21). The describing model is chosen+ by ``supports_vision`` alone. A text-only provider is skipped rather than+ handed a picture, because it does not refuse one: it answers about the+ filename and the sentence around it, confidently, and that description is+ worse than none at all.+* **Degrade out loud** (§3). A downloader with one text-only key gets the+ extracted documents, the file references, and an honest line saying the image+ was not described. Nothing here is load-bearing enough to break a drop.+* **Never raise.** Every failure path returns an analysis carrying a note. The+ user dropped a file and typed an instruction; losing that to a provider+ timeout would be the worst outcome available.+"""+from __future__ import annotations++import asyncio+import base64+from collections.abc import Sequence+from dataclasses import dataclass++from loguru import logger++from jarvis.brain.drop_context import (+ DroppedItem,+ extract_pdf_text,+ is_image,+ is_pdf,+ is_textual,+)++#: Whole-analysis budget. Generous, because it runs while the user is still+#: typing their instruction — the drop is analysed the moment it lands, not at+#: send time, so this rarely sits on anybody's critical path. On expiry the+#: analyses collected so far ship and the rest carry a note.+ANALYSIS_TIMEOUT_S = 60.0++#: How many images one drop may spend model calls on. Dropping a folder of+#: twenty screenshots is a real thing to do by accident; the rest are still+#: attached and referenced, just not described.+MAX_IMAGES_ANALYZED = 4++#: Per-file extracted text. Enough for a spec or a stack trace, far short of+#: pasting a whole book into the brief.+MAX_TEXT_CHARS = 6_000++#: Everything this module contributes to one prompt, across all files.+MAX_TOTAL_CHARS = 20_000++#: Per-image payload before it ships to the model. Mirrors the drop intake's+#: budget; ``cap_image_b64`` downscales over-budget images and never raises.+MAX_IMAGE_BYTES = 4 * 1024 * 1024++#: How a described image is labelled, and how an extracted document is. Used by+#: the UI and by the prompt blueprint, so the two cannot disagree about what+#: kind of thing an attachment is.+KIND_IMAGE = "image"+KIND_TEXT = "text"+KIND_PDF = "pdf"+KIND_OTHER = "other"++#: ``described_by`` values — which layer produced ``detail``.+BY_VISION = "vision"+BY_EXTRACTION = "extraction"+BY_NONE = "none"++# What the describing model is asked for. Written for the reader it actually+# has: a coding agent that will act on this description and cannot see the+# picture. Hence "quote text verbatim" — a paraphrased error message cannot be+# grepped for, and grepping for it is the first thing the agent will want to do.+_VISION_SYSTEM = """\+You describe an image for a coding agent that cannot see it. The user dropped \+this image into a coding session, so the description IS the agent's only view \+of it. Be specific and complete; a vague description wastes the agent's turn.++Cover, in whatever order suits the image:+- What the image is: a UI screenshot, a terminal, an error dialog, a diagram, \+a photo, a design mockup.+- Every piece of readable text, QUOTED VERBATIM — error messages, stack \+traces, file paths, line numbers, labels, button text, code. Exact wording \+matters more than anything else here, because the agent will search the \+repository for these strings.+- The layout, when the image shows an interface: what sits where, how elements \+are arranged and aligned, spacing, sizing, colours, and anything visibly \+broken — overlapping, cut off, misaligned, overflowing, or unreadable.+- The state it shows: what appears selected, focused, disabled, loading, \+errored, or empty.++Write plain prose and short lists. Describe only what is visible: do not guess \+at the cause, do not propose a fix, and do not describe anything the image \+does not show.\+"""+++@dataclass(frozen=True, slots=True)+class DropAnalysis:+ """One dropped file, and what was learned from its contents."""++ name: str+ """The file's display name."""++ reference: str+ """How the agent should refer to the file (``@path`` or a quoted path)."""++ kind: str+ """One of ``image`` / ``text`` / ``pdf`` / ``other``."""++ detail: str = ""+ """The vision description or the extracted text. Empty when neither ran."""++ described_by: str = BY_NONE+ """``vision``, ``extraction``, or ``none`` — which layer produced ``detail``."""++ note: str = ""+ """Why ``detail`` is empty or partial. Empty on the happy path."""++ def to_dict(self) -> dict[str, str]:+ """Wire shape — the same keys the frontend and the CLI receive."""+ return {+ "name": self.name,+ "reference": self.reference,+ "kind": self.kind,+ "detail": self.detail,+ "described_by": self.described_by,+ "note": self.note,+ }++ @classmethod+ def from_dict(cls, raw: dict) -> DropAnalysis:+ """Rebuild from the wire, tolerating anything missing or mistyped.++ The caller is a JSON request body, so nothing here may assume a shape.+ A malformed attachment becomes an empty-detail one rather than a 500 on+ a prompt the user is waiting to send.+ """++ def _text(key: str) -> str:+ value = raw.get(key) if isinstance(raw, dict) else None+ return value.strip() if isinstance(value, str) else ""++ kind = _text("kind") or KIND_OTHER+ return cls(+ name=_text("name") or "file",+ reference=_text("reference"),+ kind=kind if kind in {KIND_IMAGE, KIND_TEXT, KIND_PDF, KIND_OTHER} else KIND_OTHER,+ detail=_text("detail")[:MAX_TEXT_CHARS],+ described_by=_text("described_by") or BY_NONE,+ note=_text("note"),+ )+++def _kind_of(item: DroppedItem) -> str:+ """Which of the four buckets this drop falls in. One register, shared."""+ if is_image(item):+ return KIND_IMAGE+ if is_textual(item):+ return KIND_TEXT+ if is_pdf(item):+ return KIND_PDF+ return KIND_OTHER+++def _resolve_vision_brain(): # noqa: ANN202 - Brain | None, avoid an import cycle+ """The model that describes pictures, or None when nothing can see.++ Resolution lives in ``jarvis.brain.resolver`` so this module never grows its+ own idea of which provider to use. Any failure is None, not an exception.+ """+ try:+ from jarvis.brain.resolver import resolve_vision_brain+ from jarvis.core.config import load_config++ return resolve_vision_brain(load_config())+ except Exception as exc: # noqa: BLE001 - a blind analysis is still an analysis+ logger.info("Agentic IDE drop analysis: no vision brain ({})", exc)+ return None+++async def _describe_image(brain, item: DroppedItem) -> str: # noqa: ANN001 - Brain+ """One bounded call that turns a picture into words. Raises on failure."""+ from jarvis.core.protocols import BrainMessage, BrainRequest, ImageBlock+ from jarvis.vision.image_budget import cap_image_b64++ mime, data_b64 = cap_image_b64(+ item.mime or "image/png",+ base64.b64encode(item.data).decode("ascii"),+ MAX_IMAGE_BYTES,+ )+ request = BrainRequest(+ messages=(+ BrainMessage(+ role="user",+ content=(+ f"Describe this image ({item.name}) for the coding agent, "+ "following your instructions."+ ),+ images=(ImageBlock(mime=mime, data_b64=data_b64),),+ ),+ ),+ system=_VISION_SYSTEM,+ # Description, not interpretation: the same picture should not produce a+ # different account on the second drop.+ temperature=0.2,+ max_tokens=2000,+ stream=True,+ )+ chunks: list[str] = []+ async for delta in brain.complete(request):+ if delta.content:+ chunks.append(delta.content)+ return "".join(chunks).strip()[:MAX_TEXT_CHARS]+++async def _analyze_image(brain, item: DroppedItem, reference: str) -> DropAnalysis: # noqa: ANN001+ """Describe one image, degrading to an honest note on any failure."""+ if brain is None:+ return DropAnalysis(+ name=item.name,+ reference=reference,+ kind=KIND_IMAGE,+ note=(+ "No provider that can see images is reachable, so this one was "+ "attached but not described."+ ),+ )+ try:+ text = await _describe_image(brain, item)+ except Exception as exc: # noqa: BLE001 - a failed description is not a failed drop+ logger.info("Agentic IDE drop analysis: {} not described ({})", item.name, exc)+ return DropAnalysis(+ name=item.name,+ reference=reference,+ kind=KIND_IMAGE,+ note=f"Could not be described ({type(exc).__name__}); it is attached as a file.",+ )+ if not text:+ return DropAnalysis(+ name=item.name,+ reference=reference,+ kind=KIND_IMAGE,+ note="The description came back empty; it is attached as a file.",+ )+ return DropAnalysis(+ name=item.name,+ reference=reference,+ kind=KIND_IMAGE,+ detail=text,+ described_by=BY_VISION,+ )+++def _analyze_document(item: DroppedItem, reference: str) -> DropAnalysis:+ """Pull the text out of a document. Pure CPU/decode work — no model."""+ kind = _kind_of(item)+ if kind == KIND_TEXT:+ body = item.data.decode("utf-8", errors="replace").strip()[:MAX_TEXT_CHARS]+ if body:+ return DropAnalysis(+ name=item.name,+ reference=reference,+ kind=KIND_TEXT,+ detail=body,+ described_by=BY_EXTRACTION,+ )+ return DropAnalysis(+ name=item.name, reference=reference, kind=KIND_TEXT, note="The file is empty."+ )+ if kind == KIND_PDF:+ body = extract_pdf_text(item.data, max_chars=MAX_TEXT_CHARS).strip()+ if body:+ return DropAnalysis(+ name=item.name,+ reference=reference,+ kind=KIND_PDF,+ detail=body,+ described_by=BY_EXTRACTION,+ )+ return DropAnalysis(+ name=item.name,+ reference=reference,+ kind=KIND_PDF,+ note=(+ "No text could be extracted (it may be a scan, or encrypted); "+ "it is attached as a file."+ ),+ )+ return DropAnalysis(+ name=item.name,+ reference=reference,+ kind=KIND_OTHER,+ note=(+ f"Binary file ({item.mime or 'unknown type'}, {len(item.data)} bytes) — "+ "attached for the agent to open."+ ),+ )+++def _trim_to_budget(results: list[DropAnalysis]) -> list[DropAnalysis]:+ """Keep the whole analysis under ``MAX_TOTAL_CHARS``.++ Trimming is per-file and says so in the note, rather than dropping files+ off the end: an attachment that silently vanished between the chip the user+ saw and the prompt the agent got is the kind of quiet loss this codebase+ keeps paying for.+ """+ budget = MAX_TOTAL_CHARS+ trimmed: list[DropAnalysis] = []+ for item in results:+ if not item.detail:+ trimmed.append(item)+ continue+ if len(item.detail) <= budget:+ budget -= len(item.detail)+ trimmed.append(item)+ continue+ keep = max(0, budget)+ budget = 0+ trimmed.append(+ DropAnalysis(+ name=item.name,+ reference=item.reference,+ kind=item.kind,+ detail=item.detail[:keep].rstrip(),+ described_by=item.described_by if keep else BY_NONE,+ note=(+ "Shortened to fit the prompt — the whole file is attached."+ if keep+ else "Too long to include here — the whole file is attached."+ ),+ )+ )+ return trimmed+++async def analyze(+ items: Sequence[tuple[DroppedItem, str]],+ *,+ timeout_s: float = ANALYSIS_TIMEOUT_S,+ brain=None, # noqa: ANN001 - Brain, avoid an import cycle+) -> list[DropAnalysis]:+ """Work out what each dropped file contains.++ ``items`` pairs each dropped file with the reference string the agent will+ use for it, so the analysis and the path the agent opens can never drift+ apart.++ Images are described concurrently by one vision-capable model; documents are+ extracted on worker threads. ``brain`` pins the describing model (tests, and+ a caller that already resolved one); leaving it None resolves one and returns+ honest notes when none can see.++ Never raises.+ """+ if not items:+ return []++ image_indexes = [i for i, pair in enumerate(items) if _kind_of(pair[0]) == KIND_IMAGE]+ describable = set(image_indexes[:MAX_IMAGES_ANALYZED])+ overflow = set(image_indexes[MAX_IMAGES_ANALYZED:])++ # Resolving a brain touches config and the provider registry; skip it+ # entirely for a drop of nothing but documents.+ writer = brain if brain is not None else (_resolve_vision_brain() if describable else None)++ results: list[DropAnalysis | None] = [None] * len(items)++ for index, (item, reference) in enumerate(items):+ if index in overflow:+ results[index] = DropAnalysis(+ name=item.name,+ reference=reference,+ kind=KIND_IMAGE,+ note=(+ f"Not described — only the first {MAX_IMAGES_ANALYZED} images of a "+ "drop are; it is attached as a file."+ ),+ )++ async def _run_image(index: int, item: DroppedItem, reference: str) -> None:+ results[index] = await _analyze_image(writer, item, reference)++ async def _run_document(index: int, item: DroppedItem, reference: str) -> None:+ # Decoding a 25 MB file (and pypdf on a big PDF) is real CPU work; it+ # does not belong on the event loop that is also serving the UI.+ results[index] = await asyncio.to_thread(_analyze_document, item, reference)++ tasks = [+ _run_image(index, item, reference)+ if index in describable+ else _run_document(index, item, reference)+ for index, (item, reference) in enumerate(items)+ if index not in overflow+ ]++ try:+ await asyncio.wait_for(+ asyncio.gather(*tasks, return_exceptions=True), timeout=timeout_s+ )+ except TimeoutError:+ logger.info(+ "Agentic IDE drop analysis: timed out after {:g}s — shipping what finished",+ timeout_s,+ )+ except Exception as exc: # noqa: BLE001 - analysis must never break a drop+ logger.info("Agentic IDE drop analysis failed: {}", exc)++ # Anything still unfilled either timed out or raised inside gather. It gets+ # the same honest treatment as any other undescribed file.+ for index, (item, reference) in enumerate(items):+ if results[index] is None:+ results[index] = DropAnalysis(+ name=item.name,+ reference=reference,+ kind=_kind_of(item),+ note="Analysis did not finish in time; it is attached as a file.",+ )++ return _trim_to_budget([r for r in results if r is not None])+++__all__ = [+ "ANALYSIS_TIMEOUT_S",+ "BY_EXTRACTION",+ "BY_NONE",+ "BY_VISION",+ "KIND_IMAGE",+ "KIND_OTHER",+ "KIND_PDF",+ "KIND_TEXT",+ "MAX_IMAGES_ANALYZED",+ "MAX_TEXT_CHARS",+ "MAX_TOTAL_CHARS",+ "DropAnalysis",+ "analyze",+]diff --git a/jarvis/agentic_ide/fanout.py b/jarvis/agentic_ide/fanout.pyindex c4432f912b..cfe7dc0b36 100644--- a/jarvis/agentic_ide/fanout.py+++ b/jarvis/agentic_ide/fanout.py@@ -177,6 +177,27 @@ async def deliver(gate = asyncio.Semaphore(max(1, int(limit)))async def one(name: str) -> Delivery:+ """One pane's verdict, announced the moment it is known.++ Announced here rather than after the gather: with a fleet composing at+ once, collecting every line until the slowest pane finishes turns+ per-pane progress back into the silence it exists to remove.+ """+ delivery = await _one(name)+ try:+ from .prompt_composer import announce_delivery++ announce_delivery(+ delivery.terminal,+ delivered=delivery.delivered,+ submitted=delivery.submitted,+ reason=delivery.reason,+ )+ except Exception: # noqa: BLE001 - a progress line never costs a delivery+ log.debug("Agentic IDE fan-out: could not announce %s", name, exc_info=True)+ return delivery++ async def _one(name: str) -> Delivery:term = session.find(name) if session is not None else Noneif term is None:return Delivery(@@ -185,6 +206,19 @@ async def deliver(reason_code="unknown_pane",reason="there is no terminal by that name in this workspace",)+ # A plain terminal is a shell, not an agent — Jarvis does not type into+ # one (see session.accepts_prompts). Checked here as well as in the+ # sender so naming one in a fleet order costs neither a composition nor+ # an exception, and comes back as a plain sentence the readback can say.+ from .session import accepts_prompts++ if not accepts_prompts(str(getattr(term, "agent", "") or "")):+ return Delivery(+ terminal=term.name,+ delivered=False,+ reason_code="not_an_agent",+ reason="it is a plain terminal, so Jarvis does not type into it",+ )# Status and PTY are checked BEFORE composing: a prompt for a dead pane# costs a full quality-tier call and can never be typed anywhere.status = str(getattr(term, "status", "") or "unknown")diff --git a/jarvis/agentic_ide/fleet_actions.py b/jarvis/agentic_ide/fleet_actions.pynew file mode 100644index 0000000000..13e7ad7d16--- /dev/null+++ b/jarvis/agentic_ide/fleet_actions.py@@ -0,0 +1,97 @@+"""Codex-fleet actions shared by voice and REST entry points."""+from __future__ import annotations++import asyncio+import logging+import time+from collections.abc import Sequence+from typing import Any++READY_TIMEOUT_S = 45.0+READY_POLL_S = 0.25+_INPUT_MARKERS = ("›", "❯", ">")+log = logging.getLogger(__name__)+++def _ready_for_prompt(term: Any) -> bool:+ if getattr(term, "status", "") != "live" or not getattr(term, "pty_id", None):+ return False+ # Claude Code already has a stable launch-and-prompt path. Restrict the new+ # startup gate to Codex so that working behaviour stays byte-for-byte fast.+ if getattr(term, "agent", "") != "codex":+ return True+ transcript = getattr(term, "transcript", None)+ if transcript is None:+ return True+ try:+ lines = transcript.tail(30)+ except Exception: # noqa: BLE001 - a test double may expose no real buffer+ return True+ return any(line.strip().startswith(_INPUT_MARKERS) for line in lines)+++async def wait_for_prompt_ready(+ session: Any,+ names: Sequence[str],+ *,+ timeout_s: float = READY_TIMEOUT_S,+) -> tuple[str, ...]:+ """Wait for newly mounted Codex panes to display their real input line."""+ wanted = tuple(dict.fromkeys(name for name in names if name))+ deadline = time.monotonic() + max(0.0, timeout_s)+ while True:+ ready = tuple(+ name+ for name in wanted+ if (term := session.find(name)) is not None and _ready_for_prompt(term)+ )+ if len(ready) == len(wanted) or time.monotonic() >= deadline:+ return ready+ await asyncio.sleep(READY_POLL_S)+++async def close_agent_terminals(registry: Any, agent: str | None) -> list[Any]:+ """Close every matching terminal in the front workspace."""+ session = registry.session+ if session is None:+ return []+ names = [+ term.name+ for term in session.terminals+ if agent is None or term.agent == agent+ ]+ closed: list[Any] = []+ # Use the long-standing one-pane operation so this remains compatible with+ # registries that do not yet expose the newer batch convenience method.+ for name in names:+ try:+ closed.append(await registry.close_terminal(name))+ except Exception: # noqa: BLE001 - continue closing the remaining fleet+ log.warning("Agentic IDE: could not close terminal %s", name, exc_info=True)+ return closed+++def terminals_closed_event(+ session: Any,+ closed: Sequence[Any],+ *,+ source_layer: str,+) -> Any:+ """Build the typed bus event that refreshes workspace clients."""+ from jarvis.core.events import AgenticIdeTerminalsClosed++ return AgenticIdeTerminalsClosed(+ session_id=session.id,+ names=tuple(term.name for term in closed),+ folder=session.folder,+ source_layer=source_layer,+ )+++__all__ = [+ "READY_POLL_S",+ "READY_TIMEOUT_S",+ "close_agent_terminals",+ "terminals_closed_event",+ "wait_for_prompt_ready",+]diff --git a/jarvis/agentic_ide/intent.py b/jarvis/agentic_ide/intent.pyindex 5eaf5faf9f..0058a7b561 100644--- a/jarvis/agentic_ide/intent.py+++ b/jarvis/agentic_ide/intent.py@@ -58,11 +58,29 @@ _DIRECTIVE_TEMPLATES: tuple[str, ...] = (# user says "Iris und Bruno sollen …", and a singular-only verb list made# the second addressee depend on the weaker last-resort path.r"\b{name}\b[^.!?]{{0,20}}?\b(?:soll|sollen|sollte|sollten|kann|" # i18n-allow: input vocab- r"k[oö]nnen|k[oö]nnte|k[oö]nnten|m[uü]ssen|muss)\b", # i18n-allow: input vocab+ r"k[oö]e?nnen|k[oö]e?nnte|k[oö]e?nnten|m[uü]e?ssen|muss|" # i18n-allow: input vocab+ r"m[uü]e?sste|m[uü]e?ssten|darf|" # i18n-allow: input vocab+ r"d[uü]e?rfen|d[uü]e?rfte|d[uü]e?rften)\b", # i18n-allow: input vocabr"\b{name}\b[^.!?]{{0,20}}?\b(?:should|can|could|please|must)\b",r"\b{name}\b[^.!?]{{0,20}}?\b(?:deber[ií]an?|pueden?|podr[ií]an?)\b",r"\b(?:lass|l[aä]sst)\b[^.!?]{{0,20}}?\b{name}\b",r"\blet\b[^.!?]{{0,20}}?\b{name}\b",+ # "prompt this terminal Kai …" / "prompte Mika …" / "instruct Nova to …".+ # The verb that literally MEANS handing a pane its work, and the one the+ # live 2026-07-27 failure was phrased with: "could you please prompt this+ # terminal Alex, do a deep dive …". It matched no shape here, so the+ # question mark at the end carried the turn into the read-only branch below,+ # nothing was typed into Alex, and the live model filled the silence by+ # claiming the agent had been briefed. Every neighbouring module already+ # knew this vocabulary (``clarify._WORKSPACE_NOUN_RE``,+ # ``_FLEET_BRIEF_RE``, ``_CLOSE_BRIEFING_RE``); only the list that decides+ # who gets the work did not.+ #+ # Stems, so "prompting" / "prompte" / "anprompten" / "promptea" all land.+ # Deliberately narrow: these verbs have no status-question reading, which is+ # what makes them safe to let outrank the question branch.+ r"\b(?:prompt\w*|anprompt\w*|instruct\w*|instruy\w*|anweis\w*)\b"+ r"[^.!?]{{0,40}}?\b{name}\b",# "schick(e) das an Kai" / "gib Mika …" / "frag Nova …" / "beauftrage Kai …"r"\b(?:schick|schicke|gib|gibt|frag|frage|beauftrag|beauftrage|"r"[uü]bergib|[uü]bergebe|weiterleit\w*)\b[^.!?]{{0,40}}?\b{name}\b",@@ -71,23 +89,81 @@ _DIRECTIVE_TEMPLATES: tuple[str, ...] = (# "an Kai:" / "in Mika:" / "bei Nova" / "über Kai" — a routing preposition# immediately in front of the call-sign.r"\b(?:an|in|bei|[uü]ber|via|to|into|en|a)\s+{name}\b",+ # "setz Kai auf den Wake-Bug an" / "put Nova on the audit" / "point Aria at+ # the failing test". The PREPOSITION is what makes these unambiguous — bare+ # "setz"/"put" is ordinary work talk ("put the file back"), but putting a+ # NAME on something is only ever an assignment.+ r"\b(?:setz|setze|ansetz\w*)\b[^.!?]{{0,20}}?\b{name}\b" # i18n-allow: input vocab+ r"[^.!?]{{0,25}}?\bauf\b", # i18n-allow: input vocab+ r"\b(?:put|point|set)\b\s+{name}\s+(?:on|at|onto|to)\b",+ r"\b(?:pon|p[oó]n|asigna|encarga\w*)\b[^.!?]{{0,25}}?\b{name}\b",# Vocative: the name opens the utterance ("Kai, mach mal …").r"^{name}\b\s*[,:]",)+# Shapes that address a pane but are one step less certain than the ones above,+# so they only count when the utterance ALSO describes work (see+# ``_looks_like_instruction``). That second, independent piece of evidence is+# the whole safety argument: each template here has a reading that is not an+# assignment, and the work verb is what tells the two apart.+#+# They exist because the anchored shapes above share two blind spots that+# ordinary speech walks into constantly:+#+# 1. **The modal in front of the name.** "Kann Alex mal die Tests fixen?" is how+# people actually hand over work out loud, and every template above expects+# the modal AFTER the call-sign. Without this the sentence carried no+# addressing shape at all, and its question mark then sent it to the+# read-only branch — the same failure shape as the 2026-07-27 live miss.+# 2. **The German sentence bracket.** German puts the handing-over verb at the+# END: "kannst du Alex bitte SAGEN, dass …", "würdest du Alex BITTEN, …".+# Every handover template above looks for the verb in front of the name, so+# the most natural polite German assignment matched nothing.+#+# "fragen"/"ask" is deliberately absent from the bracket list: "kannst du Alex+# fragen, was er macht" is a genuine status question, and the read branch has+# to keep it.+_WEAK_DIRECTIVE_TEMPLATES: tuple[str, ...] = (+ # Modal directly in front of the call-sign, all three locales.+ r"\b(?:kann|k[oö]e?nnte|soll|sollte|m[uü]e?sste|darf|d[uü]e?rfte|" # i18n-allow: input vocab+ r"w[uü]e?rde|m[oö]e?ge|mag)\s+{name}\b", # i18n-allow: input vocab+ r"\b(?:can|could|should|would|will|shall|must|may)\s+{name}\b",+ r"\b(?:puede|podr[ií]a|deber[ií]a|debe)\s+{name}\b",+ # "que Alex revise el área" — the Spanish way to order a third party about.+ # Anchored to the START of the utterance on purpose: mid-sentence "que" is+ # the ordinary relative pronoun ("quiero saber que Alex revisó"), and+ # matching it there would turn asking ABOUT a pane into typing at it.+ r"^(?:[¿¡]\s*)?que\s+{name}\b",+ # The German sentence bracket: name first, handing-over verb last.+ r"\b{name}\b[^.!?]{{0,30}}?\b(?:sagen|bitten|beauftragen|anweisen|" # i18n-allow: input vocab+ r"[uü]bergeben|weiterleiten|zuweisen|prompten|briefen)\b", # i18n-allow: input vocab+ # "have Alex review …" / "get Alex to fix …" / "I want Alex to …". The call+ # sign follows IMMEDIATELY: at any distance these verbs are ordinary speech+ # about a pane rather than an order to it ("I have a question about Alex").+ r"\b(?:have|get|need|want)\s+{name}\b",+)+# "what is Mika doing?" — a read, never a spawn either. Both word orders are# covered per language: German and Spanish put the verb before the name ("was# macht Mika"), English after it ("what is Mika doing").+#+# The optional ``ge`` prefix carries the German PERFECT, which is how spoken+# German asks about finished work at least as often as the present tense asks+# about running work: "was hat Dana gemacht" is the live 2026-07-27 miss, and+# `\bmacht` cannot match inside "gemacht" — there is no word boundary after+# "ge". One prefix covers "gemacht", "getan" and "gearbeitet" at once._REPORT_TEMPLATES: tuple[str, ...] = (r"\bwas\b[^.!?]{{0,30}}?\b{name}\b[^.!?]{{0,30}}?"- r"\b(?:macht|machen|tut|tun|treibt|treiben|arbeitet|arbeiten)\b",+ r"\b(?:ge)?(?:macht|machen|tut|tun|tan|treibt|treiben|arbeitet|arbeiten)\b",r"\bwas\b[^.!?]{{0,20}}?"- r"\b(?:macht|machen|tut|tun|treibt|treiben|arbeitet|arbeiten)\b"+ r"\b(?:ge)?(?:macht|machen|tut|tun|tan|treibt|treiben|arbeitet|arbeiten)\b"r"[^.!?]{{0,20}}?\b{name}\b",- r"\b(?:what|how)\b[^.!?]{{0,30}}?\b{name}\b[^.!?]{{0,30}}?\b(?:doing|up\s+to|going|at)\b",+ r"\b(?:what|how)\b[^.!?]{{0,30}}?\b{name}\b[^.!?]{{0,30}}?"+ r"\b(?:doing|done|do|did|up\s+to|going|at|been|built|found|changed)\b",r"\b(?:qu[eé]|c[oó]mo)\b[^.!?]{{0,30}}?\b{name}\b[^.!?]{{0,30}}?"- r"\b(?:hacen?|haciendo|van?)\b",- r"\b(?:qu[eé]|c[oó]mo)\b[^.!?]{{0,20}}?\b(?:hacen?|haciendo|van?)\b"+ r"\b(?:hacen?|haciendo|hecho|hizo|hicieron|van?)\b",+ r"\b(?:qu[eé]|c[oó]mo)\b[^.!?]{{0,20}}?"+ r"\b(?:hacen?|haciendo|hecho|hizo|hicieron|van?)\b"r"[^.!?]{{0,20}}?\b{name}\b",r"\b{name}\b[^.!?]{{0,20}}?\b(?:status|fortschritt|progress|estado)\b",r"\b(?:status|fortschritt|progress|estado)\b[^.!?]{{0,20}}?\b{name}\b",@@ -140,14 +216,11 @@ class TerminalIntent:def _running_names() -> list[str]:"""Call-signs of the open workspace, or ``[]`` when none is open."""try:- from .session import get_registry+ from .session import running_call_signs- session = get_registry().session+ return running_call_signs()except Exception: # noqa: BLE001 - the detector must never break a turnreturn []- if session is None:- return []- return [term.name for term in session.terminals]def _name_alternatives(name: str) -> str:@@ -157,11 +230,73 @@ def _name_alternatives(name: str) -> str:"Kay" and "Mika" as "Micah". The phonetic folding in ``names.resolve`` coversthat for *word* matching; here we only need a pattern loose enough to locatethe name inside a sentence, and ``resolve`` re-checks the hit afterwards.++ The templates themselves stay anchored on the exact spelling — the garbled+ spellings are handled once, up front, by ``_canonical_text``, so every+ template inherits the tolerance instead of each one re-implementing it."""escaped = re.escape(name)return escaped+def _is_person_of_the_world(text: str, start: int, end: int) -> bool:+ """Whether the word at ``[start:end)`` carries a surname, i.e. is a person.++ Delegated to ``clarify`` so ONE rule decides it, and failure-tolerant on+ purpose: this guard may only ever WITHHOLD a pane reading, so a fault has+ to degrade to "not a person" rather than break detection.+ """+ try:+ from .clarify import is_part_of_full_name++ return is_part_of_full_name(text, start, end)+ except Exception: # noqa: BLE001 - a guard fault must never break a turn+ return False+++def _is_outside_world_talk(text: str) -> bool:+ """Whether the turn is about the world rather than the workspace.++ Imported lazily and failure-tolerant on purpose: the guard may only ever+ WITHHOLD a collective address, so a fault here has to degrade to the+ historical behaviour rather than break detection.+ """+ try:+ from .clarify import is_outside_world_talk++ return is_outside_world_talk(text)+ except Exception: # noqa: BLE001 - a guard fault must never break a turn+ return False+++def _canonical_text(text: str, candidates: list[str]) -> str:+ """The utterance with every same-sounding spelling replaced by the call-sign.++ Closes a gap that made the phonetic tolerance half-real: ``resolve`` maps+ "Elis" and "Ellys" onto "Ellis" without hesitating, but the addressing+ templates are built from ``re.escape(name)`` and therefore only ever matched+ the EXACT spelling. So "sag Elis, sie soll die Tests fixen" carried a+ textbook addressing shape, named a pane the resolver recognised — and was+ detected as nothing at all, because the one template that could have caught+ it was looking for a second "l".++ Only spellings that fold to the SAME SOUND are substituted (``fuzzy=False``).+ A merely similar word must not be rewritten into a call-sign: that is the+ branch where ordinary speech collides with the pool ("allen" scores 0.750+ against "Alex"), and rewriting it here would hand every template a name the+ user never said.+ """+ if not candidates:+ return text++ def _replace(match: re.Match[str]) -> str:+ word = match.group(0)+ hit = resolve(word, candidates, fuzzy=False)+ return hit if hit is not None else word++ return _WORD_RE.sub(_replace, text)++def _compile(templates: tuple[str, ...], names: list[str]) -> list[tuple[str, re.Pattern[str]]]:out: list[tuple[str, re.Pattern[str]]] = []for name in names:@@ -178,6 +313,20 @@ def _compile(templates: tuple[str, ...], names: list[str]) -> list[tuple[str, re#: part of the addressing, not of the work ("schick das AN Kai")._ADDRESS_PREPOSITION = r"(?:an|to|a|bei|in|[uü]ber|via)" # i18n-allow: input vocab+#: How people point AT a pane before naming it: "prompt THIS TERMINAL Alex …".+#: Part of the address, never part of the work — leaving it in briefed an agent+#: with "this terminal do a deep dive", which reads like an instruction to open+#: one.+#: Wrapped as ONE optional group on purpose: a trailing ``?`` at the use site+#: would bind to this pattern's last token instead of the whole phrase, making+#: the pane noun mandatory and stripping nothing at all.+_ADDRESS_PANE_NOUN = (+ r"(?:"+ r"(?:(?:this|that|the|dieses?|diesem|das|dem|el|la|ese|este)\s+)?" # i18n-allow: input vocab+ r"(?:terminals?|terminales|panes?|tabs?)\s+"+ r")?"+)+def _strip_addressing(text: str, *names: str) -> str:"""The utterance with the addressing preamble and the call-signs removed.@@ -188,14 +337,16 @@ def _strip_addressing(text: str, *names: str) -> str:"""cleaned = re.sub(r"\b(?:sag|sage|sagst|tell|dile|d[ií]gale|schick|schicke|send|gib|give|"- r"frag|frage|ask|lass|let|beauftrage?|assign|env[ií]a|manda)\b\s*",+ r"frag|frage|ask|lass|let|beauftrage?|assign|env[ií]a|manda|"+ r"prompt\w*|anprompt\w*|instruct\w*|instruy\w*|anweis\w*)\b\s*"," ",text,flags=re.IGNORECASE,)for name in names:cleaned = re.sub(- rf"\b{_ADDRESS_PREPOSITION}?\s*{re.escape(name)}\b\s*[,:]?\s*",+ rf"\b{_ADDRESS_PANE_NOUN}{_ADDRESS_PREPOSITION}?\s*"+ rf"{re.escape(name)}\b\s*[,:]?\s*"," ",cleaned,flags=re.IGNORECASE,@@ -234,6 +385,14 @@ _EVERYONE_TEMPLATES: tuple[re.Pattern[str], ...] = tuple(r"[\s,]*\b(?:allen|alle)\b",r"\b(?:tell|ask|give|assign|send)\b[\s,]*"r"\b(?:everyone|everybody|them\s+all|all\s+of\s+them)\b",+ r"\b(?:jede[nr]?\s+(?:davon|dieser)|alle\s+davon)\b[^.!?]{0,50}?"+ r"\b(?:prompt\w*|anweis\w*|beauftrag\w*)\b", # i18n-allow: input vocab+ r"\b(?:prompt\w*|anweis\w*|beauftrag\w*)\b[^.!?]{0,30}?"+ r"\b(?:jede[nr]?\s+(?:davon|dieser)|alle\s+davon)\b", # i18n-allow: input vocab+ r"\b(?:each\s+(?:one|of\s+them)|all\s+of\s+them)\b[^.!?]{0,50}?"+ r"\b(?:prompt|brief|instruct|assign)\w*\b",+ r"\b(?:prompt|brief|instruct|assign)\w*\b[^.!?]{0,30}?"+ r"\b(?:each\s+(?:one|of\s+them)|all\s+of\s+them)\b",r"^(?:und\s+)?\b(?:alle|allen)\b[^.!?]{0,20}?" # i18n-allow: input vocabr"\b(?:soll|sollen|m[uü]ssen|k[oö]nnen)\b", # i18n-allow: input vocabr"^(?:and\s+)?\b(?:everyone|everybody|all\s+of\s+them)\b[^.!?]{0,20}?"@@ -247,6 +406,19 @@ _EVERYONE_TEMPLATES: tuple[re.Pattern[str], ...] = tuple(# against. Digits and underscores can never be part of a spoken name._WORD_RE = re.compile(r"[^\W\d_]+", re.UNICODE)+#: Verbs that can ONLY mean "hand this pane its work". The templates above are+#: anchored on the call-sign and therefore bounded by distance, so a longer way+#: of saying the same thing ("could you prompt the terminal that is called Alex+#: to …") slips past every one of them. This is the un-anchored backstop for+#: that, and its whole safety argument is the word list: unlike "frag" or "ask",+#: none of these has a status-question reading, so "kannst du Alex fragen, was+#: er macht" — a genuine read — is untouched by it.+_BRIEFING_VERB_RE = re.compile(+ r"\b(?:prompt\w*|anprompt\w*|instruct\w*|instruy\w*|anweis\w*|" # i18n-allow: input vocab+ r"beauftrag\w*|briefing|briefe\w*|assign\w*|encarga\w*)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+def _mentions(text: str, candidates: list[str], *, fuzzy: bool = True@@ -272,6 +444,72 @@ def _mentions(return out+def _people_of_the_world(text: str, candidates: list[str]) -> set[str]:+ """Call-signs this utterance uses as a PERSON's first name, not as a pane.++ A call-sign is a single given name, so "Dana Schmidt" is a human being and+ "Dana" is the terminal. Only names whose EVERY occurrence carries a surname+ count: a sentence that says both ("ask Dana whether Dana Schmidt replied")+ still addresses the pane.++ Applied to the REPORT side alone. The acting shapes keep their existing+ evidence untouched, because German capitalizes nouns and "sag Dana+ Bescheid" would read as a surname — withholding a report costs a sentence,+ withholding a prompt costs the user's work.+ """+ as_person: set[str] = set()+ as_pane: set[str] = set()+ for match in _WORD_RE.finditer(text):+ hit = resolve(match.group(0), candidates, fuzzy=False)+ if hit is None:+ continue+ if _is_person_of_the_world(text, match.start(), match.end()):+ as_person.add(hit)+ else:+ as_pane.add(hit)+ return as_person - as_pane+++def _questioned_panes(text: str, candidates: list[str]) -> set[str]:+ """Panes a QUESTION asks about purely by naming them, or ``set()``.++ The general form of the report templates, and the reason they no longer+ have to enumerate tenses: what makes "was hat Dana gemacht" a question+ about a terminal is not the verb, it is that a running pane is called Dana+ and the sentence is a question.++ Three conditions, each removing a way of being wrong:++ 1. **it is a question** — a trailing "?" or an interrogative opening it.+ A statement that merely mentions a pane is not a request for a status+ report, and the acting branches already own the ones that are;+ 2. **the name is CERTAIN** — the exact call-sign or a spelling that folds+ to the same sound. Here the name is the whole case, so the fuzzy band+ is not admissible: measured against the shipping pool, ordinary speech+ reaches it ("unten" scores into "Hunter"), and an uncertain name is the+ clarify path's question to ask, not this path's answer to give;+ 3. **it is not a person's full name** — "was hat Dana Schmidt gemacht" is+ about a human being, and a surname is the signal that says so.++ A question that HANDS WORK OVER is none of this branch's business, however+ it is worded. Politeness is the ordinary way to give an order out loud —+ "could you please prompt this terminal Alex, do a deep dive …?" is an+ instruction with a question mark on it — and reading it as a status request+ is how the live 2026-07-27 turn ended with an idle terminal and a spoken+ claim that the agent had been briefed. The anchored templates catch these+ when the verb sits near the name; ``_BRIEFING_VERB_RE`` catches the rest.+ """+ if not candidates:+ return set()+ if not (text.rstrip().endswith("?") or _QUESTION_OPENER_RE.search(text.lstrip())):+ return set()+ if _BRIEFING_VERB_RE.search(text):+ return set()+ return {+ name for _, _, name in _mentions(text, candidates, fuzzy=False)+ } - _people_of_the_world(text, candidates)++def _coordinated_group(mentions: list[tuple[int, int, str]], text: str, anchors: set[str]) -> set[str]:@@ -332,29 +570,62 @@ def detect_all(if not candidates:return []+ # Everything below reads the CANONICAL utterance — same words, but every+ # same-sounding spelling of a call-sign replaced by the call-sign itself, so+ # a transcript that wrote "Elis" is matched by the templates built for+ # "Ellis". Only ``utterance`` keeps the user's original wording, because+ # that is what the prompt composer must read back.+ working = _canonical_text(text, candidates)+# A report question is checked first: "what is Kai doing?" also matches the# looser "ist Kai …" directive shape, and answering it as a prompt would type# the question into the agent.+ # A first name carrying a surname is a human being, so it is struck from+ # the READ side before anything else looks at it. Without this, widening+ # the report shapes to the German perfect turned "was hat Dana Schmidt+ # gemacht" — a question about a person — into a status request for the+ # pane called Dana.+ people = _people_of_the_world(working, candidates)report_anchors = {namefor name, pattern in _compile(_REPORT_TEMPLATES, candidates)- if pattern.search(text)- }+ if pattern.search(working)+ } - peopleprompt_anchors = {namefor name, pattern in _compile(_DIRECTIVE_TEMPLATES, candidates)- if pattern.search(text)+ if pattern.search(working)}- mentions = _mentions(text, candidates)-- if any(pattern.search(text) for pattern in _EVERYONE_TEMPLATES):- kind = KIND_REPORT if report_anchors and not prompt_anchors else KIND_PROMPT+ # The weaker shapes need the utterance to describe work as well; see+ # ``_WEAK_DIRECTIVE_TEMPLATES`` for why each of them cannot stand alone.+ weak_prompt_anchors: set[str] = set()+ if _looks_like_instruction(working) or _BRIEFING_VERB_RE.search(working):+ weak_prompt_anchors = {+ name+ for name, pattern in _compile(_WEAK_DIRECTIVE_TEMPLATES, candidates)+ if pattern.search(working)+ }+ mentions = _mentions(working, candidates)++ # The collective address reaches EVERY open pane, so it is the costliest+ # thing a misheard word can trigger — a question about a public figure that+ # speech recognition turned into "sag allen …" would brief the whole+ # workspace with it. Checked here rather than inside the templates because+ # it is a property of the sentence, not of any one addressing shape.+ if any(pattern.search(working) for pattern in _EVERYONE_TEMPLATES) and not (+ _is_outside_world_talk(working)+ ):+ kind = (+ KIND_REPORT+ if report_anchors and not (prompt_anchors or weak_prompt_anchors)+ else KIND_PROMPT+ )return [TerminalIntent(terminal=name,kind=kind,instruction="" if kind == KIND_REPORT- else _useful_instruction(text, name),+ else _useful_instruction(working, name),utterance=text,)for name in candidates@@ -366,10 +637,44 @@ def detect_all(elif prompt_anchors:kind = KIND_PROMPTanchors = prompt_anchors- elif mentions and _looks_like_instruction(text):+ elif weak_prompt_anchors:+ # Above the question branch on purpose: politeness and the German+ # sentence bracket both produce sentences that END in a question mark+ # while HANDING WORK OVER, and reading those as status requests is the+ # exact failure this whole area keeps coming back to. Below the report+ # shapes, so "ist Alex fertig?" is untouched.+ kind = KIND_PROMPT+ anchors = weak_prompt_anchors+ elif (asked_about := _questioned_panes(working, candidates)):+ # A QUESTION that names a running pane is about that pane. This is the+ # maintainer's own rule (2026-07-27): while a coding workspace is open,+ # a call-sign belongs to the terminal carrying it, even though somebody+ # out in the world shares the name.+ #+ # It exists because the template lists above can only ever cover the+ # verbs somebody thought of, and the live miss proved how thin that+ # cover is: "was hat Dana gemacht" — ordinary spoken German, perfect+ # tense — matched no report shape, so the turn was not the workspace's+ # at all and the live model answered that it did not know any Dana.+ # Every tense, every phrasing and every locale would each have needed+ # its own template; the NAME is the evidence that generalises.+ #+ # Safe to be this generous only because a report is READ-ONLY: the+ # caller answers from what the pane printed and never types into it.+ # The acting branches keep their stricter evidence, which is why this+ # sits BELOW them — an utterance carrying a real addressing shape is+ # still that shape, question mark or not.+ kind = KIND_REPORT+ anchors = asked_about+ mentions = [item for item in mentions if item[2] in asked_about]+ elif mentions and (+ _looks_like_instruction(working) or _BRIEFING_VERB_RE.search(working)+ ):# Last resort: the utterance names terminals and reads as an# instruction. Requiring a verb keeps a passing mention ("Alex is a- # nice name") from being addressed.+ # nice name") from being addressed. A briefing verb counts as that verb+ # in its own right — "prompt Alex" is a complete order even though the+ # work itself is described with nouns.## This is the ONLY branch where the call-sign is the whole case: no# "tell X to …", no "X should …" — just a name and a verb. That makes@@ -381,7 +686,7 @@ def detect_all(# to be exact (or fold to the same sound, which is what carries a# garbled transcript). An addressing shape, being independent evidence,# still admits a fuzzy call-sign in the branches above.- certain = _mentions(text, candidates, fuzzy=False)+ certain = _mentions(working, candidates, fuzzy=False)if not certain:return []mentions = certain@@ -390,13 +695,13 @@ def detect_all(else:return []- addressed = _coordinated_group(mentions, text, anchors)+ addressed = _coordinated_group(mentions, working, anchors)ordered = [name for _, _, name in mentions if name in addressed]# An anchor matched by a template but never located as a word (a garbled# transcript the templates still caught) keeps its place at the end.ordered += [name for name in anchors if name not in ordered]- shared = "" if kind == KIND_REPORT else _useful_instruction(text, *ordered)+ shared = "" if kind == KIND_REPORT else _useful_instruction(working, *ordered)return [TerminalIntent(terminal=name, kind=kind, instruction=shared, utterance=text@@ -433,13 +738,44 @@ def _useful_instruction(text: str, *names: str) -> str:return stripped if len(stripped) >= _MIN_INSTRUCTION_CHARS else text+# Umlauts are written ``[uü]e?`` throughout this module rather than ``[uü]``:+# voice transcripts carry the real character, but the same detectors serve+# TYPED turns, and a keyboard without a German layout produces "pruefen" /+# "uebernimmt". The bare class covered the dropped-umlaut spelling ("prufen")+# and missed the transliterated one, which is the spelling people actually+# type._INSTRUCTION_VERB_RE = re.compile(- r"\b(?:mach|machen|bau|baue|schreib|schreibe|fix|fixe|behebe|pr[uü]f|pr[uü]fe|"- r"check|checke|analysier\w*|review\w*|refactor\w*|teste?|starte?|implementier\w*|"- r"[aä]nder\w*|erstell\w*|f[uü]g\w*|entfern\w*|l[oö]sch\w*|untersuch\w*|"- r"build|write|make|run|test|start|implement|change|create|add|remove|delete|"+ # Stems, not fixed forms. German hands work over in the INFINITIVE at least+ # as often as in the imperative — "sag Ellis, sie soll die Tests fixen" —+ # and a `fix|fixe` alternative matches neither "fixen" nor "Tests". The+ # effect was invisible and total: such a turn produced no addressed pane at+ # all, which is the same silent nothing this module was written to end.+ # ``analy[sz]`` rather than ``analysier``: the German stem alone missed the+ # plain English "analyze the codebase", which is how the live 2026-07-27+ # utterance described its work.+ r"\b(?:mach\w*|bau\w*|schreib\w*|fix\w*|beheb\w*|pr[uü]e?f\w*|"+ r"check\w*|analy[sz]\w*|review\w*|refactor\w*|test\w*|start\w*|implementier\w*|"+ r"[aä]e?nder\w*|erstell\w*|f[uü]e?g\w*|entfern\w*|l[oö]e?sch\w*|untersuch\w*|"+ r"repariere?\w*|debugg?\w*|commit\w*|"+ # Taking a job on is describing work just as much as doing it is: "Alex+ # übernimmt den Wake-Bug" is an assignment, and without the verb the+ # sentence carried a call-sign and nothing else.+ r"[uü]e?bernimm\w*|[uü]e?bernehm\w*|aktualisier\w*|schau\w*|guck\w*|" # i18n-allow: input vocab+ r"k[uü]e?mmer\w*|" # i18n-allow: input vocab+ r"audit\w*|inspect\w*|verify|update|handle|cover|take\s+over|"+ r"build|write|make|run|implement\w*|change|create|add|remove|delete|"r"investigate|look|read|find|search|explain|document|"- r"haz|escribe|crea|revisa|arregla|ejecuta|implementa|analiza)\b",+ # "do a deep dive on X" describes the work with a noun phrase, and it is+ # the single most common way this workspace is asked for anything — yet+ # every verb in this list missed it, so "would you have Alex do a deep+ # dive?" carried no work at all and stayed a status question.+ r"deep[\s-]?dive|root[\s-]?cause|"+ # Spanish carries an order to a third party in the subjunctive — "que Lee+ # REVISE el área" is the ordinary way to say "have Lee review the area" —+ # so the stems have to reach past the 2nd-person imperative. Fixed forms+ # only made the Spanish half of every detector that consults this quietly+ # weaker than the German and English halves.+ r"haz|hag[ao]\w*|escrib\w*|crea|revis\w*|arregl\w*|ejecut\w*|analic\w*|analiz\w*)\b",re.IGNORECASE,)@@ -509,9 +845,13 @@ _NUMBER_WORDS: dict[str, int] = {# German — "ein/eine/einen" doubles as the article, which is exactly right # i18n-allow: names the German number words below# here ("mach noch ein Terminal auf" = one). # i18n-allow: quoted spoken input"ein": 1, "eine": 1, "einen": 1, "eins": 1, # i18n-allow: German number words (input vocabulary)- "zwei": 2, "drei": 3, "vier": 4, "fünf": 5, "funf": 5, "sechs": 6, # i18n-allow: German number words (input vocabulary)- "sieben": 7, "acht": 8, "neun": 9, "zehn": 10, "elf": 11, "zwölf": 12, # i18n-allow: German number words (input vocabulary)- "zwolf": 12,+ # Both ASCII spellings of every umlaut word: a transcript may drop the+ # umlaut ("funf") or transliterate it ("fuenf"), and only the first was+ # covered — so "starte fünf Agenten" fell back to a count of one whenever+ # the provider wrote it the common way.+ "zwei": 2, "drei": 3, "vier": 4, "fünf": 5, "funf": 5, "fuenf": 5, # i18n-allow: number words+ "sechs": 6, "sieben": 7, "acht": 8, "neun": 9, "zehn": 10, "elf": 11, # i18n-allow: numbers+ "zwölf": 12, "zwolf": 12, "zwoelf": 12, # i18n-allow: number words# English"a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5,"six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11,@@ -628,6 +968,16 @@ class SpawnTerminalsRequest:anyone (maintainer report 2026-07-26)."""+@dataclass(frozen=True, slots=True)+class CloseTerminalsRequest:+ """A spoken request to close a whole kind of workspace terminal."""++ agent: str | None+ """``"claude"`` / ``"codex"``, or ``None`` for every coding CLI."""++ utterance: str++def _spoken_count(text: str) -> int:"""The requested number of panes: digits, a number word, or 1.@@ -636,11 +986,14 @@ def _spoken_count(text: str) -> int:"""from .session import MAX_TERMINALS- digits = re.search(r"\b(\d{1,3})\b", text)- if digits is not None:- return max(1, min(int(digits.group(1)), MAX_TERMINALS))- for word in text.lower().split():- cleaned = "".join(ch for ch in word if ch.isalpha())+ # Read the FIRST number in speech order. Searching all digits before number+ # words contradicted this function's contract and turned "five terminals;+ # each may start 50 workers" into a request for 50 terminals.+ for match in re.finditer(r"\b(?:\d{1,3}|[^\W\d_]+)\b", text, re.UNICODE):+ raw = match.group(0).casefold()+ if raw.isdigit():+ return max(1, min(int(raw), MAX_TERMINALS))+ cleaned = "".join(ch for ch in raw if ch.isalpha())if cleaned in _NUMBER_WORDS:return max(1, min(_NUMBER_WORDS[cleaned], MAX_TERMINALS))return 1@@ -729,6 +1082,338 @@ _BACKGROUND_RE = re.compile(re.IGNORECASE,)+# Keep terminal opening grammar inside the clause that actually contains the+# pane noun. The live 2026-07-27 failure contained "ten new terminals" as a+# reference to work already done and "start 50 sub-agents" much later. Global+# noun/verb/number searches joined those unrelated fragments into a fresh+# 50-terminal request.+_CLAUSE_RE = re.compile(r"[^.!?;\n]+")+_SPAWN_PAIR_MAX_GAP = 80+++@dataclass(frozen=True, slots=True)+class _SpawnSpan:+ start: int+ end: int+ parse_text: str+++def _span_gap(left: re.Match[str], right: re.Match[str]) -> int:+ if left.end() < right.start():+ return right.start() - left.end()+ if right.end() < left.start():+ return left.start() - right.end()+ return 0+++_FLEET_BRIEF_RE = re.compile(+ r"\b(?:jede\w*\s+(?:davon|dieser)|each\s+(?:one|of\s+them)|"+ r"prompt\w*|brief\w*|instruct\w*|assign\w*|tell\w*|"+ r"anweis\w*|beauftrag\w*|gib\w*\s+.*\baufgabe\w*)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+++def _spawn_span(text: str) -> _SpawnSpan | None:+ """The bounded clause that genuinely asks for panes to be opened."""+ for clause_match in _CLAUSE_RE.finditer(text):+ clause = clause_match.group(0)+ panes = list(_PANE_NOUN_RE.finditer(clause))+ actors = list(_OPEN_VERB_RE.finditer(clause)) + list(_ADDITIVE_RE.finditer(clause))+ if not panes or not actors:+ continue+ pairs = [+ (pane, actor)+ for pane in panes+ for actor in actors+ if _span_gap(pane, actor) <= _SPAWN_PAIR_MAX_GAP+ and _FLEET_BRIEF_RE.search(+ clause,+ min(pane.end(), actor.end()),+ max(pane.start(), actor.start()),+ )+ is None+ ]+ if not pairs:+ continue+ pane, actor = min(pairs, key=lambda pair: _span_gap(*pair))+ anchor_end = max(pane.end(), actor.end())++ # Mixed fleets may continue after the first pane noun ("three terminals+ # of Codex and two of Claude"). Parse the rest of this one clause, but+ # stop when it begins telling the fleet what to do; repeated counts in+ # that task are not additional pane groups.+ parse_end = len(clause)+ briefing = _FLEET_BRIEF_RE.search(clause, anchor_end)+ if briefing is not None:+ parse_end = briefing.start()+ return _SpawnSpan(+ start=clause_match.start(),+ end=clause_match.start() + anchor_end,+ parse_text=clause[:parse_end],+ )+ return None+++#: A spawn clause that is a CONDITION attached to work described earlier in the+#: sentence, rather than the request itself: "let Lee do a deep dive on this and+#: fix it — if there is no terminal by that name, spawn a new one and prompt it+#: right in there". The work is then in FRONT of the spawn clause, and reading+#: only what FOLLOWS it (which is just the fallback wording) opened a blank pane+#: and announced it as ready while the task was silently dropped — the live+#: failure of 2026-07-27, where the user's answer was "you did nothing".+#:+#: The conditional marker is what separates that shape from ordinary talk in+#: front of a plain request ("the tests are green. Open two more terminals"),+#: where the leading sentence is emphatically NOT a brief for the new panes.+_SPAWN_CONDITION_RE = re.compile(+ r"\b(?:wenn|falls|sofern|ansonsten|sonst|" # i18n-allow: input vocab+ r"if|in\s+case|unless|otherwise|"+ r"si|en\s+caso|sino)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+++def _leading_task(text: str, span: _SpawnSpan) -> str:+ """Work described BEFORE a conditional spawn clause, or ``""``.++ Two conditions, and each one removes a way of being wrong:++ 1. the spawn clause has to be CONDITIONAL — "spawn one *if* none is called+ that" is a fallback for work stated elsewhere, while a bare "open two+ terminals" is the whole request and anything before it is conversation;+ 2. the leading text has to read as an instruction, or there is no task to+ hand over in the first place.++ A pane the user ADDRESSED never reaches here: ``detect_spawn`` stands down+ for an addressed call-sign before this is consulted, so the leading text+ belongs to nobody but the panes about to be opened.+ """+ if _SPAWN_CONDITION_RE.search(text[span.start : span.end]) is None:+ return ""+ lead = text[: span.start].strip(" ,:-")+ if not lead or not _looks_like_instruction(lead):+ return ""+ cleaned = _FILLER_PREFIX_RE.sub("", lead).strip()+ return cleaned if len(cleaned) >= _MIN_INSTRUCTION_CHARS else lead+++def spawn_includes_task(user_text: str) -> bool:+ """Whether a pane-spawn request also tells the new fleet to do work."""+ text = (user_text or "").strip()+ span = _spawn_span(text)+ if span is None:+ # The terminal-noun-free agent-fleet form can still carry a task.+ request = detect_spawn(text)+ return request is not None and bool(_INSTRUCTION_VERB_RE.search(text))+ remainder = text[span.end :]+ if _FLEET_BRIEF_RE.search(remainder) or _INSTRUCTION_VERB_RE.search(remainder):+ return True+ return bool(_leading_task(text, span))+++_TASK_AFTER_BRIEF_RE = re.compile(+ r"\b(?:prompt\w*|brief\w*|instruct\w*|assign\w*|tell\w*|"+ r"anweis\w*|beauftrag\w*)\b\s*"+ r"(?:,?\s*(?:dass|damit|that|to|que)\s*)?"+ r"(?:(?:sie|er|es|they|it|each(?:\s+one)?|cada\s+uno)\s+)?",+ re.IGNORECASE,+)+++def spawn_instruction(user_text: str) -> str:+ """Return the work for new panes without the instruction to open them."""+ text = (user_text or "").strip()+ span = _spawn_span(text)+ if span is None:+ nouns = list(_AGENT_NOUN_RE.finditer(text))+ actors = list(_OPEN_VERB_RE.finditer(text))+ if nouns and actors:+ noun, actor = min(+ ((noun, actor) for noun in nouns for actor in actors),+ key=lambda pair: _span_gap(*pair),+ )+ remainder = text[max(noun.end(), actor.end()) :].strip(" ,:-")+ remainder = re.sub(+ r"^(?:which|that|who|die|der|das|welche\w*|que)\s+", # i18n-allow: input vocab+ "",+ remainder,+ flags=re.IGNORECASE,+ )+ if remainder:+ return remainder+ return text+ remainder = text[span.end :].strip(" ,:-")+ briefing = _TASK_AFTER_BRIEF_RE.search(remainder)+ if briefing is not None:+ task = remainder[briefing.end() :].strip(" ,:-")+ task = re.sub(+ r"^(?:to|that|dass|damit|que)\s+", # i18n-allow: input vocab+ "",+ task,+ flags=re.IGNORECASE,+ )+ # "…open a new one and prompt it THERE" — the briefing verb is about+ # WHERE the work goes, and what follows it is a fragment, not the work.+ # Handing that fragment to a fresh agent as its task is how a pane got+ # briefed with the single word "there".+ if len(task) >= _MIN_INSTRUCTION_CHARS:+ return task+ if _INSTRUCTION_VERB_RE.search(remainder) is None:+ # Nothing to do AFTER the spawn clause: the work may be in front of it,+ # with the spawn as its fallback ("… let it do X; if no pane is called+ # that, open one"). Handing the new pane the fallback wording instead+ # is how a pane came up blank and was reported ready.+ lead = _leading_task(text, span)+ if lead:+ return lead+ return remainder or text+++_RECENT_FLEET_RE = re.compile(+ r"\b(?:jede[nr]?\s+(?:davon|dieser)|alle\s+davon|diese\w*|"+ r"each\s+(?:one|of\s+them)|all\s+of\s+them|those\s+(?:agents|terminals)|"+ r"cada\s+uno\s+de\s+ellos|todos\s+ellos)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+++def references_recent_fleet(user_text: str) -> bool:+ """Whether a follow-up points back to the panes opened in the prior turn."""+ return bool(_RECENT_FLEET_RE.search(user_text or ""))+++_CLOSE_VERB_RE = re.compile(+ # ``c(?:e|ie)rr`` carries the Spanish stem change: the imperative people+ # actually say is "CIERRA todos los terminales", and a ``cerr``-only stem+ # matched the infinitive while missing every spoken command.+ r"\b(?:schlie(?:ß|ss)\w*|beend\w*|stopp?\w*|zumach\w*|close\w*|" # i18n-allow: input vocab+ r"quit\w*|"+ r"kill\w*|c(?:e|ie)rr\w*|det[eé]n\w*)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)++#: German closes things with a separable verb, so the particle lands at the end+#: of the clause: "mach alle Terminals ZU". Both halves are needed — the bare+#: "mach" is the OPEN verb, which is why this exact sentence used to open panes+#: instead of closing them, the worst kind of miss because the user watches the+#: opposite of what they asked for happen.+_CLOSE_PARTICLE_RE = re.compile(+ r"\b(?:mach|macht|mache|machen)\b[^.!?]{0,60}?\b(?:zu|dicht)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+_ALL_PANES_RE = re.compile(+ r"\b(?:alle[nr]?|s[aä]mtliche[nr]?|jede[nr]?|all|every|each|todos?|todas?)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+_CLOSE_STATE_QUESTION_RE = re.compile(+ r"^(?:are|is|sind|ist|est[aá]n?)\b[^?]*\b(?:closed|geschlossen|cerrad\w*)\b",+ re.IGNORECASE,+)++# How far the quantifier and the pane noun may sit apart and still be ONE noun+# phrase ("all the open terminals"), rather than two things the sentence merely+# mentions on its way past ("all the failing tests in the terminals"). Roomy+# enough for an adjective and a CLI name, far below the reach of an unrelated+# object.+_CLOSE_QUANTIFIER_MAX_GAP = 20+# How far the closing verb may sit from the panes it closes. Both word orders+# are a character or two in practice — "close all terminals" and "alle+# Terminals schließen" — so the allowance covers an interposed adverb, never a+# second clause.+_CLOSE_VERB_MAX_GAP = 30++# The utterance is HANDING WORK to the panes rather than closing them.+#+# This is the entire difference between "close all terminals" and "tell all the+# terminals to stop the dev server", and without the distinction the second one+# killed every agent in the workspace: the detector asked only whether a pane+# noun, an "all" word and a stop-verb appeared ANYWHERE in the sentence, which+# every fleet instruction carrying the word "stop" satisfies. Measured on real+# phrasings, eight of nine ordinary fleet instructions were read as a request to+# destroy the workspace.+#+# A briefing verb only counts in FRONT of the pane noun, because that is where+# it governs: "tell all terminals to stop" briefs them, while "close all+# terminals and tell me when you are done" really does close them.+_CLOSE_BRIEFING_RE = re.compile(+ r"\b(?:tell\w*|ask\w*|have|let|instruct\w*|assign\w*|prompt\w*|brief\w*|"+ r"sag\w*|frag\w*|lass\w*|l[aä]sst|anweis\w*|beauftrag\w*|schick\w*|" # i18n-allow: input vocab+ r"dile|d[ií]gale|pregunt\w*|pide|pida|manda|env[ií]a|encarga\w*)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+++def _closes_the_fleet(clause: str) -> bool:+ """Does this clause ask for the PANES THEMSELVES to be closed?++ Three things have to line up, and each one removes a way of being wrong:++ 1. the quantifier belongs to the panes ("all the terminals") rather than to+ something running inside them ("all the node processes in the+ terminals"),+ 2. the closing verb sits close enough to govern that phrase instead of+ merely sharing a sentence with it,+ 3. nothing in front of the pane noun turns the sentence into an instruction+ FOR the panes.++ The asymmetry is deliberate. A missed close costs one click on a button+ that is right there; a false one kills every coding agent in the workspace+ with no confirmation and no undo — so every ambiguous shape stands down.+ """+ for pane in _PANE_NOUN_RE.finditer(clause):+ if _CLOSE_BRIEFING_RE.search(clause, 0, pane.start()) is not None:+ continue+ # The German separable verb wraps AROUND the panes it closes ("mach+ # alle Terminals zu"), so containment is the test, not distance.+ for bracket in _CLOSE_PARTICLE_RE.finditer(clause):+ if bracket.start() <= pane.start() and pane.end() <= bracket.end():+ if _ALL_PANES_RE.search(clause, bracket.start(), pane.start()):+ return True+ for quantifier in _ALL_PANES_RE.finditer(clause, 0, pane.start()):+ if pane.start() - quantifier.end() > _CLOSE_QUANTIFIER_MAX_GAP:+ continue+ for verb in _CLOSE_VERB_RE.finditer(clause):+ # Either word order: the verb ahead of the phrase ("close all+ # terminals") or behind it ("alle Terminals schließen").+ ahead = quantifier.start() - verb.end()+ behind = verb.start() - pane.end()+ if (+ 0 <= ahead <= _CLOSE_VERB_MAX_GAP+ or 0 <= behind <= _CLOSE_VERB_MAX_GAP+ ):+ return True+ return False+++def detect_close_fleet(user_text: str) -> CloseTerminalsRequest | None:+ """A request to close all matching panes in the open workspace.++ Deliberately hard to trigger, and read one CLAUSE at a time for the same+ reason ``_spawn_span`` is: a sentence that mentions terminals early and+ stopping something late is two thoughts, not a close request. What the+ clause has to actually contain lives in ``_closes_the_fleet``.+ """+ text = (user_text or "").strip()+ if (+ len(text) < 6+ or _QUESTION_OPENER_RE.search(text)+ or _CLOSE_STATE_QUESTION_RE.search(text)+ ):+ return None+ for clause_match in _CLAUSE_RE.finditer(text):+ clause = clause_match.group(0)+ if not _closes_the_fleet(clause):+ continue+ # Read from the clause that actually closes, so a CLI named elsewhere in+ # the sentence cannot narrow (or widen) which panes are stopped.+ agent_match = _AGENT_RE.search(clause)+ agent = None+ if agent_match is not None:+ agent = _canonical_agent(agent_match.group("agent"))+ return CloseTerminalsRequest(agent=agent, utterance=text)+ return None+def _is_agent_fleet(text: str, names: list[str] | None) -> bool:"""True for a fleet request that says "agents" instead of "terminals".@@ -777,16 +1462,24 @@ def detect_spawn(text = (user_text or "").strip()if len(text) < 6:return None- if _PANE_NOUN_RE.search(text) is None and not _is_agent_fleet(text, names):+ span = _spawn_span(text)+ agent_fleet = span is None and _is_agent_fleet(text, names)+ if span is None and not agent_fleet:return Noneif _QUESTION_OPENER_RE.search(text) is not None:return None- if _OPEN_VERB_RE.search(text) is None and _ADDITIVE_RE.search(text) is None:- return None- if detect(text, names=names) is not None:+ addressed_text = span.parse_text if span is not None else text+ addressed_before_spawn = (+ span is not None+ and span.start > 0+ and detect(text[: span.start], names=names) is not None+ )+ if addressed_before_spawn or detect(addressed_text, names=names) is not None:return None- groups = _spoken_groups(text)+ parse_text = addressed_text++ groups = _spoken_groups(parse_text)if groups:return SpawnTerminalsRequest(count=sum(g.count for g in groups),@@ -795,11 +1488,11 @@ def detect_spawn(groups=groups,)- agent_match = _AGENT_RE.search(text)+ agent_match = _AGENT_RE.search(parse_text)agent: str | None = Noneif agent_match is not None:agent = _canonical_agent(agent_match.group("agent"))- count = _spoken_count(text)+ count = _spoken_count(parse_text)return SpawnTerminalsRequest(count=count,agent=agent,@@ -874,6 +1567,45 @@ def wants_split(user_text: str) -> bool:)+#: "both of you", "you two", "all three of them", "die zwei Terminals". What+#: these have in common is a COUNT the utterance states out loud, which is the+#: only evidence that survives a call-sign speech recognition mangled beyond+#: recognition. Matching *input vocabulary*, not prose.+_PLURAL_ADDRESS_RE = re.compile(+ r"\b(?:"+ # explicit "both" / "all of you", in every supported language+ r"beide[nsr]?|alle\s+beide|ihr\s+(?:beide[nr]?|zwei|drei|vier)|euch\s+beide[nr]?|"+ r"both(?:\s+of\s+(?:you|them))?|all\s+(?:of\s+)?(?:you|them)|you\s+(?:two|three|four)|"+ r"ambos|ambas|los\s+dos|las\s+dos|ustedes\s+dos|"+ # a spoken count next to what is being counted+ r"(?:zwei|drei|vier|f[üu]nf|two|three|four|five|dos|tres|cuatro|cinco|[2-9])\s+"+ r"(?:der\s+|die\s+|von\s+den\s+|of\s+the\s+|de\s+los\s+)?"+ r"(?:terminals?|terminales|panes?|agent(?:s|en)?|instanz\w*|instances?)"+ r")\b",+ re.IGNORECASE,+)+++def expects_several(user_text: str) -> bool:+ """True when the utterance says out loud that MORE THAN ONE pane is meant.++ The one signal that outlives a garbled call-sign. Live 2026-07-27 19:07:+ "Alexa and Dave should both do a deep dive" — "Alexa" was recoverable as+ Alex, "Dave" matched no pane at any threshold, and the turn quietly briefed+ one agent while the user watched for two. Nothing in the name resolver can+ fix that; the word "both" can, because it says the count independently of+ whether either name survived transcription.++ Deliberately narrow: an explicit "both/all of you/you two", or a spoken+ number standing next to the thing being counted. A bare plural noun does+ NOT qualify — "look at the terminals" states no count.+ """+ text = (user_text or "").strip()+ if len(text) < 6:+ return False+ return bool(_PLURAL_ADDRESS_RE.search(text))++def owns_turn(user_text: str, *, names: list[str] | None = None) -> bool:"""True when the open workspace should handle this turn instead of a spawn.@@ -897,6 +1629,8 @@ def owns_turn(user_text: str, *, names: list[str] | None = None) -> bool:text = (user_text or "").strip()if not text:return False+ if detect_close_fleet(text) is not None:+ return Trueif detect_spawn(text, names=names) is not None:return Trueif names_spawn_vehicle(text):@@ -907,12 +1641,18 @@ def owns_turn(user_text: str, *, names: list[str] | None = None) -> bool:__all__ = ["KIND_PROMPT","KIND_REPORT",+ "CloseTerminalsRequest","SpawnGroup","SpawnTerminalsRequest","TerminalIntent","detect","detect_all",+ "detect_close_fleet","detect_spawn",+ "expects_several","owns_turn",+ "references_recent_fleet",+ "spawn_instruction",+ "spawn_includes_task","wants_split",]diff --git a/jarvis/agentic_ide/names.py b/jarvis/agentic_ide/names.pyindex 91139ca6b9..808a028094 100644--- a/jarvis/agentic_ide/names.py+++ b/jarvis/agentic_ide/names.py@@ -66,6 +66,24 @@ RESERVED_NAMES: frozenset[str] = frozenset(# unrelated word ("Wiki", "Marker") does not._MATCH_FLOOR = 0.72+# The NEAR-MISS band: close enough that a human would ask "did you mean Ellis?",+# too far to act on. Its whole reason to exist is the live 2026-07-27 failure —+# a pane called "Ellis" came back from speech recognition as "Ilies" (0.667,+# just under the floor), so the addressed-terminal path stood down in silence+# and the user was told an agent was working when none was.+#+# The floor of the band is NOT what makes acting on it safe: ordinary words of+# the spoken language reach well into it ("wieso" scores 0.500 against "Finn",+# "kannst" 0.600 against "Casey"), and no threshold separates those from a+# garbled call-sign. Safety comes from the CONTEXT gate in ``clarify.py`` — a+# near miss may only ever produce a QUESTION, and only in a turn that is+# addressing the workspace at all. The band merely keeps that question rare.+#+# Set low enough to reach the maintainer's own example (2026-07-27): a pane+# called "Maggie" heard as "Max" scores 0.571, and asking is exactly what+# should happen there.+_NEAR_MISS_FLOOR = 0.55+def default_names(count: int) -> list[str]:"""First ``count`` call-signs, extended with numbered fallbacks if needed."""@@ -183,11 +201,66 @@ def resolve(return best[1] if best else None+def similarity(spoken: str, name: str) -> float:+ """How close ONE spoken word is to ONE call-sign, on the resolver's scale.++ The exact score ``resolve`` ranks by, exposed so the near-miss path cannot+ drift into scoring differently from the path that acts.+ """+ word = normalize(spoken)+ key = normalize(name)+ if not word or not key:+ return 0.0+ return max(+ SequenceMatcher(None, word, key).ratio(),+ SequenceMatcher(None, phonetic_key(word), phonetic_key(key)).ratio(),+ )+++def near_miss(+ spoken: str, candidates: list[str], *, limit: int = 3+) -> tuple[tuple[str, float], ...]:+ """Call-signs ``spoken`` ALMOST names, best first, or ``()``.++ The line is drawn at CERTAINTY, not at a score: a word that is the name or+ folds to the same sound ("Elis" → "Ellis") is certain and returns ``()`` —+ the acting path owns it. Everything else that still scores close is+ uncertain and belongs in a question, however high it scores.++ That boundary matters more than it looks. A merely-similar word used to sit+ in a blind spot between the two paths: "Dena" scores 0.75 against "Dana", so+ the resolver called it a match and the near-miss check stood down — while+ the addressing templates, which need the exact spelling, found nothing at+ all. The turn produced neither an action nor a question. Anchoring both+ sides on the same notion of certainty is what closes that gap.++ Several candidates are returned on purpose. A transcript that sits between+ two panes ("Mags" between "Max" and "Maggie") is exactly the case where+ picking the best score silently is how the wrong agent gets the work; the+ caller asks instead, and it can only ask if it knows both.+ """+ if not spoken or not candidates:+ return ()+ if resolve(spoken, candidates, fuzzy=False) is not None:+ return ()+ scored = sorted(+ (+ (name, score)+ for name in candidates+ if (score := similarity(spoken, name)) >= _NEAR_MISS_FLOOR+ ),+ key=lambda item: (-item[1], item[0]),+ )+ return tuple(scored[:limit])++__all__ = ["NAME_POOL","RESERVED_NAMES","default_names",+ "near_miss","normalize","phonetic_key","resolve",+ "similarity",]diff --git a/jarvis/agentic_ide/prompt_blueprint.py b/jarvis/agentic_ide/prompt_blueprint.pyindex 30989ffa16..c9ad81e73e 100644--- a/jarvis/agentic_ide/prompt_blueprint.py+++ b/jarvis/agentic_ide/prompt_blueprint.py@@ -298,6 +298,7 @@ def user_block(candidates: list[str],skeletons: dict[str, str],house_rules: str,+ attachments: list | None = None,) -> str:"""Everything the composer knows, laid out for one model call.@@ -312,6 +313,14 @@ def user_block(if house_rules:parts.append("HOUSE RULES OF THIS REPOSITORY\n" + house_rules)+ dropped = attachment_block(attachments or [])+ if dropped:+ parts.append(+ "FILES THE USER DROPPED (already saved where the agent can open "+ "them; an image was described by a model that could see it)\n" + dropped+ )+ parts.append(_ATTACHMENT_RULES)+if skeletons:outlines = "\n\n".join(f'<file path="{path}">\n{text}\n</file>' for path, text in skeletons.items()@@ -343,16 +352,45 @@ def user_block(return "\n\n".join(parts)-def render_fallback(instruction: str, files: list[str]) -> str:+def render_fallback(+ instruction: str,+ files: list[str],+ attachments: list | None = None,+) -> str:"""The deterministic prompt: same skeleton, no model involved.Used whenever no writer model is reachable. It is always better than theraw transcript, so the feature never depends on a provider being up.++ Dropped files are carried here as well, and that is the load-bearing half+ for a downloader with no writing model: the screenshot was still described+ (vision and prompt-writing are separate providers, and having one without+ the other is ordinary), so the description belongs in the prompt whether or+ not a model wrote the prose around it."""task = " ".join((instruction or "").split())- if not task:+ usable = [a for a in attachments or [] if getattr(a, "name", "")]+ if not task and not usable:return ""- out = [f"## Task\n{task}"]+ out = [f"## Task\n{task}"] if task else []++ if usable:+ blocks: list[str] = []+ for item in usable:+ head = f"### {item.name}"+ if item.reference:+ # Plain hyphen, like the rest of the agent-facing text here: this+ # string is TYPED into a terminal, and a pane's encoding is not+ # ours to assume.+ head += f" - {item.reference}"+ if item.detail and getattr(item, "described_by", "") == "vision":+ blocks.append(f"{head}\nWhat this image shows:\n\n{item.detail}")+ elif item.detail:+ blocks.append(f"{head}\nContents:\n\n```\n{item.detail}\n```")+ else:+ blocks.append(f"{head}\n{item.note or 'No content could be read.'}")+ out.append("## Dropped files\n" + "\n\n".join(blocks))+if files:listed = "\n".join(f"- `@{f}`" for f in files)out.append(f"## Key files\n{listed}")@@ -429,6 +467,7 @@ __all__ = ["MAX_BODY_CHARS","TARGET_MAX_CHARS","TARGET_MIN_CHARS",+ "attachment_block","ends_on_reference","looks_like_brief","looks_truncated",diff --git a/jarvis/agentic_ide/prompt_composer.py b/jarvis/agentic_ide/prompt_composer.pyindex c413337106..04a389e20d 100644--- a/jarvis/agentic_ide/prompt_composer.py+++ b/jarvis/agentic_ide/prompt_composer.py@@ -56,11 +56,33 @@ slower, better prompt explicitly. Reading file outlines costs more still. Sothe composer takes its time and the bound below is generous — what must neverhappen is a silent demotion to a weaker model, because nobody inspects a promptthat looks fine.++**What was made faster, and what deliberately was not.** The model's own+writing is the wait, and shortening it means a shorter brief — the one thing+this module exists not to do. What WAS serial and did not need to be is the+preparation around it: resolving the writer (a config load plus a subscription+probe per candidate CLI) ran on the event loop and finished before the first+file was opened, and the file outlines were read before the house rules were.+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.++**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``+once the pane took it) are printed as they happen, and each one names the pane+it belongs to — with a fleet composing at once, an unattributed line is worse+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 annotationsimport asyncioimport re+import sys+import time+from collections.abc import Callable, Sequencefrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -68,6 +90,13 @@ from loguru import loggerfrom .file_index import cached_indexfrom .session import MAX_PROMPT_CHARS, sanitize_prompt+from .task_kind import (+ KIND_IMPLEMENT,+ KIND_INVESTIGATE,+ KIND_NEUTRAL,+ KIND_QUESTION,+ KIND_REVIEW,+)# The composer is not on the voice hot path the way an ack is, but the user is# waiting to hear "sent to Kai". On timeout the deterministic prompt ships, so@@ -133,6 +162,221 @@ class ComposedPrompt:"""Why the fallback was used, when it was. Empty on the happy path."""+# --------------------------------------------------------------- progress+# The stages of one composition, in the order they happen. Named constants+# because a sink may want to filter or style them, and a caller matching on a+# literal string is how a stage gets renamed and silently stops arriving.+STAGE_START = "start"+STAGE_THINKING = "thinking"+STAGE_DRAFTING = "drafting"+STAGE_READY = "ready"+STAGE_FALLBACK = "fallback"+STAGE_SENT = "sent"+++@dataclass(frozen=True, slots=True)+class ComposeNotice:+ """One progress line about the prompt being written for one terminal."""++ stage: str+ """One of the ``STAGE_*`` constants above."""++ message: str+ """The finished English line, ready to print. Always names the terminal."""++ terminal: str = ""+ kind: str = ""+ """The detected task kind, so a sink can style a review differently from a+ build. Empty for notices that happen outside a composition (``sent``)."""+++ProgressSink = Callable[[ComposeNotice], None]+"""Where notices go. Sync on purpose: a sink is called from inside a voice turn+and must not be able to await anything, let alone the pane it describes."""+++def print_notice(notice: ComposeNotice) -> None:+ """Put one notice where the user is actually looking. Never raises.++ Standard output when there is one — that is the terminal a headless install+ and a ``--dev`` run are both watched from. Under the tray build there is no+ console at all (``pythonw.exe`` gives the process no stdout), so the line+ goes to the log file instead of being lost. Exactly one copy either way:+ the same sentence twice reads as a bug in the thing reporting progress.+ """+ logger.debug("Agentic IDE composer [{}] {}", notice.stage, notice.message)+ stream = getattr(sys, "stdout", None)+ if stream is None:+ logger.info("Agentic IDE composer: {}", notice.message)+ return+ try:+ stream.write(f"Jarvis: {notice.message}\n")+ stream.flush()+ except (OSError, ValueError, AttributeError, UnicodeError):+ # A closed, detached or non-decodable stream is not a failure of the+ # composition — the notice just goes somewhere that survives.+ logger.info("Agentic IDE composer: {}", notice.message)+++def _emit(sink: ProgressSink | None, notice: ComposeNotice) -> None:+ """Deliver one notice. A broken sink costs the line, never the prompt."""+ try:+ (sink or print_notice)(notice)+ except Exception: # noqa: BLE001 - progress is decoration, the brief is not+ logger.debug("Agentic IDE composer: a progress sink raised", exc_info=True)+++# How much of the instruction a notice quotes back. Long enough to recognise+# the request, short enough that the line stays one line in a narrow terminal.+_MAX_SUBJECT_CHARS = 72+++def _subject(instruction: str) -> str:+ """A short stand-in for what the user asked for, in their own words.++ Quoted rather than paraphrased: paraphrasing costs a model call, and this+ line has to appear BEFORE any of the work starts to be worth printing.+ """+ words = " ".join((instruction or "").split())+ if len(words) <= _MAX_SUBJECT_CHARS:+ return words+ return words[:_MAX_SUBJECT_CHARS].rsplit(" ", 1)[0].rstrip(",;:-") + "..."+++def _variant(options: tuple[str, ...], seed: str) -> str:+ """One of ``options``, chosen by the instruction rather than at random.++ Two properties at once. Varied, because the same sentence on every turn+ stops being read after the second time and the user is then back to+ watching silence. Deterministic, because a test cannot pin a line that+ changes per run — and ``hash()`` is salted per process, so it is unusable+ here even though it looks like the obvious choice.+ """+ if not options:+ return ""+ return options[sum(map(ord, seed or "")) % len(options)]+++_START_PHRASES: dict[str, tuple[str, ...]] = {+ KIND_IMPLEMENT: (+ 'All right - writing {name} the build brief for "{subject}".',+ 'On it: {name} gets the full spec for "{subject}".',+ 'Right, briefing {name} to build "{subject}".',+ ),+ KIND_REVIEW: (+ 'All right - writing {name} a review brief for "{subject}".',+ 'On it: {name} gets asked to review "{subject}".',+ 'Right, briefing {name} to go through "{subject}".',+ ),+ KIND_INVESTIGATE: (+ 'All right - briefing {name} to dig into "{subject}".',+ 'On it: {name} gets the investigation brief for "{subject}".',+ 'Right, pointing {name} at "{subject}" to find the cause.',+ ),+ KIND_QUESTION: (+ 'All right - writing {name} the question about "{subject}".',+ 'On it: asking {name} about "{subject}".',+ 'Right, putting {name}\'s question about "{subject}" together.',+ ),+ KIND_NEUTRAL: (+ 'All right, writing the prompt for {name} - "{subject}".',+ 'On it: putting {name}\'s prompt together - "{subject}".',+ 'Right, {name}\'s prompt is being written - "{subject}".',+ ),+}++_THINKING_PHRASES = (+ "Thinking {name}'s brief through - {context}.",+ "Reading the code before {name} is briefed - {context}.",+ "Working out what {name} needs to know - {context}.",+)++_DRAFTING_PHRASES = (+ "{name}'s brief is coming in now.",+ "Writing {name}'s brief out.",+ "The brief for {name} is being written.",+)++_READY_PHRASES = (+ "{name} is briefed - {size} characters{files} in {secs}s. Sending it now.",+ "Brief written for {name}: {size} characters{files}, {secs}s. Handing it over.",+ "Done - {size} characters{files} for {name} in {secs}s. Sending.",+)+++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)+ )+++def _thinking_message(+ instruction: str, terminal_name: str, *, outlines: int, writer_label: str+) -> str:+ """The line that stands while the model works — with what it was handed."""+ if outlines == 1:+ context = "one file outline to go on"+ elif outlines:+ context = f"{outlines} file outlines to go on"+ else:+ 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+ )+++def _ready_message(+ instruction: str, terminal_name: str, *, size: int, files: int, seconds: float+) -> str:+ """What was written, before it is typed anywhere."""+ if files == 1:+ files_clause = ", one file attached"+ elif files:+ files_clause = f", {files} files attached"+ else:+ files_clause = ""+ return _variant(_READY_PHRASES, instruction).format(+ name=terminal_name, size=size, files=files_clause, secs=f"{seconds:.1f}"+ )+++def _writer_label(brain: object) -> str:+ """The writing model's own name, when it has one worth printing."""+ name = str(getattr(brain, "name", "") or "").strip()+ return name[:40]+++def announce_delivery(+ terminal_name: str,+ *,+ delivered: bool,+ submitted: bool | None = None,+ reason: str = "",+ sink: ProgressSink | None = None,+) -> None:+ """The closing line, once the pane has been handed the prompt — or has not.++ Lives here rather than at the send site so the whole sequence the user+ reads is worded in one place, and so it can never claim more than happened:+ "typed" and "started" are different states (a prompt ending on an ``@path``+ sits in the input box looking exactly like a running task), and the+ unconfirmed third state says so instead of picking the flattering reading.+ """+ if not delivered:+ message = f"{terminal_name} did not get it: {reason or 'it refused the prompt'}."+ elif submitted is True:+ message = f"Sent - {terminal_name} has the brief and is working on it."+ elif submitted is False:+ message = f"{terminal_name} is holding the brief in its input box - it never started."+ else:+ message = f"Sent to {terminal_name} - I could not confirm it started."+ _emit(sink, ComposeNotice(stage=STAGE_SENT, message=message, terminal=terminal_name))++def _clean_speech(text: str) -> str:"""The instruction with speech artefacts and politeness scaffolding gone."""cleaned = _FILLER_RE.sub(" ", text or "")@@ -236,8 +480,15 @@ async def _llm_compose(brain, # noqa: ANN001 - Brain, avoid an import cyclesystem_prompt: str,user_block: str,+ on_first_delta: Callable[[], None] | None = None,) -> str:- """One bounded call that writes the prompt."""+ """One bounded call that writes the prompt.++ ``on_first_delta`` fires the moment the model's answer starts arriving. It+ is the only signal that separates "still waiting" from "it is writing", and+ the gap between them is the whole wait on a subscription CLI, which pays a+ 10-12 s cold process start before it thinks at all.+ """from jarvis.core.protocols import BrainMessage, BrainRequestrequest = BrainRequest(@@ -262,10 +513,31 @@ async def _llm_compose(chunks: list[str] = []async for delta in brain.complete(request):if delta.content:+ if not chunks and on_first_delta is not None:+ on_first_delta()chunks.append(delta.content)return "".join(chunks).strip()+async def _read_context(+ session, # noqa: ANN001 - Session, avoid an import cycle+ candidates: list[str],+) -> tuple[dict[str, str], str]:+ """The file outlines and the repository's house rules, read at once.++ Both are disk IO on a path a voice turn is waiting on, and neither needs+ the other's result. They used to be awaited one after the other for no+ reason beyond the order they were written in.+ """+ from .code_skeleton import skeletons as read_skeletons++ outlines, house_rules = await asyncio.gather(+ asyncio.to_thread(read_skeletons, session.folder, candidates),+ asyncio.to_thread(_house_rules, session),+ )+ return outlines, house_rules++async def _compose_once(*,brain, # noqa: ANN001 - Brain, avoid an import cycle@@ -276,17 +548,30 @@ async def _compose_once(agent_display: str,candidates: list[str],kind: str,+ context, # noqa: ANN001 - Awaitable[tuple[dict[str, str], str]]+ notify: Callable[[str, str], None],+ attachments: list,) -> str:- """Read the candidate files, then make the one writing call.+ """Wait for the file material, then make the one writing call.- File reading runs in a worker thread: it is disk IO on a path a voice turn- is waiting on, and the whole call already sits under ``COMPOSE_TIMEOUT_S``.+ ``context`` arrives as an awaitable rather than as finished data so the+ reading can already be running while the caller resolves the writer — and+ so the wait for it still sits inside ``COMPOSE_TIMEOUT_S``, which a value+ computed before the timeout was armed would not."""from . import prompt_blueprint as blueprint- from .code_skeleton import skeletons as read_skeletons- outlines = await asyncio.to_thread(read_skeletons, session.folder, candidates)- house_rules = await asyncio.to_thread(_house_rules, session)+ outlines, house_rules = await context++ notify(+ STAGE_THINKING,+ _thinking_message(+ base_instruction or said,+ terminal_name,+ outlines=len(outlines),+ writer_label=_writer_label(brain),+ ),+ )return await _llm_compose(brain=brain,@@ -300,6 +585,13 @@ async def _compose_once(candidates=candidates,skeletons=outlines,house_rules=house_rules,+ attachments=attachments,+ ),+ on_first_delta=lambda: notify(+ STAGE_DRAFTING,+ _variant(_DRAFTING_PHRASES, base_instruction or said).format(+ name=terminal_name+ ),),)@@ -315,6 +607,26 @@ 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.++ The probe loads the config and asks every subscription candidate whether it+ is signed in; a broken one there must cost the deterministic prompt, not+ the turn.+ """+ try:+ return await task+ except Exception: # noqa: BLE001 - resolution never breaks a composition+ logger.info("Agentic IDE writer resolution failed", exc_info=True)+ return None+++def _discard(task: asyncio.Task) -> None:+ """Drop a preparation task whose result is no longer wanted, quietly."""+ task.cancel()+ task.add_done_callback(lambda done: done.cancelled() or done.exception())++async def compose(utterance: str,*,@@ -325,6 +637,8 @@ async def compose(use_llm: bool = True,max_files: int = MAX_FILE_REFERENCES,brain=None, # noqa: ANN001 - Brain, avoid an import cycle+ on_progress: ProgressSink | None = None,+ attachments: Sequence | None = None,) -> ComposedPrompt:"""Build the prompt for ``terminal_name`` out of what the user said.@@ -333,6 +647,19 @@ async def compose(Passing a fast model here trades prompt accuracy for a few seconds, whichis the trade the maintainer decided against on 2026-07-25.+ ``attachments`` are ``drop_analysis.DropAnalysis`` entries for files the+ user dropped alongside the instruction — a described screenshot, an+ extracted document. They reach BOTH layers: the writer folds them into the+ brief, and the deterministic prompt lists them, because the model that+ described the picture and the model that writes prose are separate+ providers and having one without the other is ordinary.++ ``on_progress`` receives a ``ComposeNotice`` at each beat of the+ composition; left None they are printed (see ``print_notice``). The typed+ prompt bar passes ``use_llm=False`` and gets no notices at all — nothing is+ being written there, and a progress line about an instant operation is+ noise.+Never raises: every failure path lands on the deterministic prompt, because"the agent got a rougher prompt" is a far better outcome than "yourinstruction vanished".@@ -342,16 +669,29 @@ async def compose(said = (utterance or "").strip()base_instruction = _clean_speech(instruction or said) or (instruction or said).strip()+ attached = list(attachments or [])if not said:return ComposedPrompt(text="", composed_by="raw", note="empty instruction")- candidates = _file_candidates(session, base_instruction or said, max_files * 2)+ subject = base_instruction or said+ kind = classify(base_instruction)++ def notify(stage: str, message: str) -> None:+ _emit(+ on_progress,+ ComposeNotice(+ stage=stage, message=message, terminal=terminal_name, kind=kind+ ),+ )- def _deterministic(composed_by: str, note: str = "") -> ComposedPrompt:- chosen = candidates[:max_files]+ def _deterministic(+ composed_by: str, note: str = "", candidates: list[str] | None = None+ ) -> ComposedPrompt:+ chosen = (candidates or [])[:max_files]return ComposedPrompt(text=sanitize_prompt(- blueprint.render_fallback(base_instruction, chosen), keep_newlines=True+ blueprint.render_fallback(base_instruction, chosen, attached),+ keep_newlines=True,)[:MAX_PROMPT_CHARS],files=chosen,composed_by=composed_by,@@ -359,13 +699,38 @@ async def compose()if not use_llm:- return _deterministic("raw")+ found = await asyncio.to_thread(+ _file_candidates, session, subject, max_files * 2+ )+ return _deterministic("raw", candidates=found)++ started = time.monotonic()+ notify(STAGE_START, _start_message(kind, subject, terminal_name))++ # The writer probe goes first and runs on its own: it is the one piece of+ # preparation that can take seconds (a config load plus a sign-in probe per+ # subscription CLI), it needs nothing from the disk work below, and running+ # it on the event loop stalled every other pane of a fan-out with it.+ writer_task: asyncio.Task | None = (+ asyncio.create_task(asyncio.to_thread(_resolve_writer)) if brain is None else None+ )++ candidates = await asyncio.to_thread(_file_candidates, session, subject, max_files * 2)- writer = brain if brain is not None else _resolve_writer()+ def degrade(note: str) -> ComposedPrompt:+ notify(STAGE_FALLBACK, f"{terminal_name} gets the plain brief instead: {note}.")+ return _deterministic("fallback", note, candidates=candidates)++ # Reading the outlines starts NOW, not once the writer is known — on a cold+ # 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)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.- return _deterministic("fallback", "no quality-tier provider reachable")+ _discard(context_task)+ return degrade("no quality-tier provider reachable")try:composed = await asyncio.wait_for(@@ -377,21 +742,24 @@ async def compose(terminal_name=terminal_name,agent_display=agent_display,candidates=candidates,- kind=classify(base_instruction),+ kind=kind,+ context=context_task,+ notify=notify,+ attachments=attached,),timeout=COMPOSE_TIMEOUT_S,)composed = _strip_wrapper(composed)except TimeoutError:- return _deterministic(- "fallback", f"composer timed out after {COMPOSE_TIMEOUT_S:g}s"- )+ _discard(context_task)+ return degrade(f"composer timed out after {COMPOSE_TIMEOUT_S:g}s")except Exception as exc: # noqa: BLE001 - any provider failure degradeslogger.info("Agentic IDE prompt composer fell back: {}", exc)- return _deterministic("fallback", f"composer unavailable ({type(exc).__name__})")+ _discard(context_task)+ return degrade(f"composer unavailable ({type(exc).__name__})")if not composed:- return _deterministic("fallback", "composer returned nothing usable")+ 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@@ -403,7 +771,7 @@ async def compose("({} chars) — falling back",len(composed),)- return _deterministic("fallback", "composer output was not a brief")+ return degrade("composer output was not a brief")if blueprint.looks_truncated(composed):# Half a brief reads as a whole one, which is exactly what makes it@@ -414,13 +782,14 @@ async def compose("— falling back",len(composed),)- return _deterministic("fallback", "composer output was cut off")+ 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# costs the agent a turn; the bare path costs it nothing.- referenced = _existing(session.folder, _extract_referenced(composed))- for bad in (r for r in _extract_referenced(composed) if r not in referenced):+ written = _extract_referenced(composed)+ referenced = _existing(session.folder, written)+ for bad in (r for r in written if r not in referenced):composed = composed.replace(f"@{bad}", bad)if blueprint.ends_on_reference(composed):@@ -430,13 +799,34 @@ async def compose(final = sanitize_prompt(composed, keep_newlines=True)[:MAX_PROMPT_CHARS]if not final:- return _deterministic("fallback", "composer returned nothing usable")+ return degrade("composer returned nothing usable")++ notify(+ STAGE_READY,+ _ready_message(+ subject,+ terminal_name,+ size=len(final),+ files=len(referenced),+ seconds=time.monotonic() - started,+ ),+ )return ComposedPrompt(text=final, files=referenced, composed_by="llm")__all__ = ["COMPOSE_TIMEOUT_S","MAX_FILE_REFERENCES",+ "STAGE_DRAFTING",+ "STAGE_FALLBACK",+ "STAGE_READY",+ "STAGE_SENT",+ "STAGE_START",+ "STAGE_THINKING",+ "ComposeNotice","ComposedPrompt",+ "ProgressSink",+ "announce_delivery","compose",+ "print_notice",]diff --git a/jarvis/brain/drop_context.py b/jarvis/brain/drop_context.pyindex 055ba52343..5cfe7617cb 100644--- a/jarvis/brain/drop_context.py+++ b/jarvis/brain/drop_context.py@@ -121,22 +121,44 @@ def _suffix(name: str) -> str:return PurePosixPath(name.replace("\\", "/")).suffix.lower()-def _is_image(item: DroppedItem) -> bool:+# The three classifiers below are PUBLIC on purpose. The Agentic IDE analyses+# the same dropped files a second time (to describe a screenshot and extract a+# document before a coding agent is briefed), and a second copy of the+# extension/MIME register there would drift the moment either side learns a new+# file type — the classic multi-layer drift this repo keeps getting bitten by.+# One register, two callers.+++def is_image(item: DroppedItem) -> bool:+ """True when this drop is a picture — something a model has to SEE."""return item.mime.lower().startswith("image/")-def _is_textual(item: DroppedItem) -> bool:+def is_textual(item: DroppedItem) -> bool:+ """True when this drop can be inlined as UTF-8 text.++ Extension and MIME both count, because drag-drop MIME is unreliable: an OS+ happily hands over ``application/octet-stream`` for a ``.py`` file.+ """mime = item.mime.lower()if mime.startswith(_TEXTUAL_MIME_PREFIXES) or mime in _TEXTUAL_MIMES:return Truereturn _suffix(item.name) in _TEXT_EXTS-def _is_pdf(item: DroppedItem) -> bool:+def is_pdf(item: DroppedItem) -> bool:+ """True when this drop is a PDF, whichever of MIME or name says so."""return item.mime.lower() == "application/pdf" or _suffix(item.name) == ".pdf"-def _extract_pdf_text(data: bytes, *, max_chars: int) -> str:+# Kept as private aliases: this module's own call sites read better unprefixed,+# and the names appear in existing tests.+_is_image = is_image+_is_textual = is_textual+_is_pdf = is_pdf+++def extract_pdf_text(data: bytes, *, max_chars: int) -> str:"""Best-effort PDF text extraction; empty string when unavailable.``pypdf`` is optional — never a hard dependency. Any failure (missing lib,@@ -158,6 +180,9 @@ def _extract_pdf_text(data: bytes, *, max_chars: int) -> str:return ""+_extract_pdf_text = extract_pdf_text++def classify_and_compose(items: Sequence[DroppedItem],dragged_text: str | None = None,diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 4c0febf532..94e7d217fe 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -5773,6 +5773,7 @@ class BrainManager:normal path runs untouched."""try:+ from jarvis.agentic_ide import clarify as ide_clarifyfrom jarvis.agentic_ide import fanout as ide_fanoutfrom jarvis.agentic_ide import intent as ide_intentexcept Exception: # noqa: BLE001 - optional surface@@ -5785,14 +5786,33 @@ class BrainManager:session = registry.sessionif session is None:return None+ candidates = [t.name for t in session.terminals]+ # An answer to a pending "did you mean Ellis?" is claimed before+ # anything else. It names no pane on its own ("ja") and carries no+ # instruction, so every detector below would read it as ordinary+ # conversation and the task the user already spoke would be lost a+ # second time — which is worse than the silent miss the question+ # replaced, because it also cost them a turn.+ #+ # The window classifies the answer under every supported language+ # itself, so no per-turn language has to be resolved before it.+ answered = ide_clarify.WINDOW.resolve_answer(user_text)+ recent = getattr(self, "_last_ide_spawn", None)+ if (+ ide_intent.references_recent_fleet(user_text)+ and recent is not None+ and recent[0] == session.id+ and time.monotonic() - recent[2] <= 300.0+ ):+ recent_names = [name for name in recent[1] if session.find(name)]+ if recent_names:+ candidates = recent_namesaddressed = ide_intent.detect_all(- user_text, names=[t.name for t in session.terminals]+ user_text, names=candidates)except Exception: # noqa: BLE001 - detection must never break a turnreturn None- if not addressed:- return None- found = addressed[0]+# Naming the spawn vehicle outranks the workspace: "spawn an agent that# helps Kai" is a genuine background-worker request even with a# workspace open. Same test the spawn gate and ``intent.owns_turn`` use,@@ -5810,6 +5830,48 @@ class BrainManager:conversation_language=self._conversation_language,)+ # A clarified pane is briefed with the ORIGINAL utterance — the sentence+ # that actually carried the work — not with the "yes" that confirmed it.+ if answered is not None:+ panes, original = answered+ # Every pane the answer confirmed, not the first one: "Alex und+ # Blaike, macht beide …" is ONE instruction for two agents, and a+ # single "yes" has to brief both of them. Answering it with one+ # pane is how the second agent of an addressed pair was lost (live+ # 2026-07-27 19:07).+ live = [name for name in panes if session.find(name) is not None]+ if live:+ log.info(+ "Agentic IDE: clarified call-sign(s) resolved to %s",+ ", ".join(live),+ )+ return await self._deliver_agentic_ide_prompt(+ session=session,+ names=live,+ utterance=original,+ instruction="",+ language=out_lang,+ )++ if not addressed:+ # No pane was named with certainty — but the turn may still have+ # MEANT one. A call-sign arrives through speech recognition, and the+ # live 2026-07-27 failure was exactly this: "Ellis" came back as+ # "Ilies", scored just under the acting threshold, and this path+ # returned None without a word. Nothing reached the pane, nothing+ # was said, and the live model — which never learns any of this —+ # filled the silence by claiming an agent was working.+ #+ # Asking costs the user one word and cannot type a stranger's+ # sentence into a coding agent, so uncertainty resolves to a+ # question. ``detect_clarification`` decides when there is one to+ # ask; it stands down for anything that is not addressing the+ # workspace.+ return self._ask_which_agentic_ide_terminal(+ user_text, candidates=candidates, language=out_lang+ )+ found = addressed[0]+# A question about a pane is read-only: answer it from what that pane# printed, and let the normal brain path phrase the answer with the# focus-context block (which already carries the transcript tail).@@ -5818,6 +5880,17 @@ class BrainManager:names = [item.terminal for item in addressed]+ # A turn addresses a FLEET, and speech recognition may have carried+ # only part of it across. "Alex und Blaike, macht beide einen Deep+ # Dive" resolves Alex and mangles Blake, and this path used to brief+ # Alex and say nothing at all about the rest — so the user heard one+ # agent confirmed and believed two were working (live 2026-07-27+ # 19:07). The pane that WAS understood still gets its brief; the one+ # that was not becomes a question appended to the same answer.+ leftover = self._agentic_ide_leftover_question(+ user_text, candidates=candidates, claimed=names, language=out_lang+ )+# NOTHING is spoken between here and the delivery verdict below, and that# silence is the feature. A bridge line lived here for a few hours on# 2026-07-27 to fill the prompt writer's 10-21 s, and it produced the@@ -5860,28 +5933,334 @@ class BrainManager:log.warning("Agentic IDE work split failed", exc_info=True)assignments = None- # No brain is pinned for the composer on purpose. An earlier version- # handed it this turn's FAST router model to save 4-5 s, but that- # optimised the wrong axis: the prompt is what the coding agent then- # works from for minutes, and the maintainer's decision on 2026-07-25- # was explicitly for the better prompt over the quicker handoff. The- # composer resolves a quality-tier model itself and degrades to its- # deterministic prompt when none is reachable.+ verdict = await self._deliver_agentic_ide_prompt(+ session=session,+ names=names,+ utterance=user_text,+ instruction=found.instruction,+ language=out_lang,+ assignments=assignments,+ )+ if leftover is not None:+ # Armed only now: a question about the rest of the fleet is worth+ # asking once the panes that WERE understood are actually briefed,+ # and a delivery that failed on the way there should not leave a+ # question standing about work nobody received.+ need, question = leftover+ ide_clarify.WINDOW.arm(need, question=question)+ log.info(+ "Agentic IDE: briefed %s, asking about %s",+ ", ".join(names),+ " / ".join(need.offered),+ )+ return f"{verdict} {question}" if verdict else question+ return verdict++ async def _deliver_agentic_ide_prompt(+ self,+ *,+ session: Any,+ names: list[str],+ utterance: str,+ instruction: str,+ language: str,+ assignments: dict[str, str] | None = None,+ ) -> str | None:+ """Compose and type one instruction into the addressed panes.++ Shared by the addressed-terminal path and by the answer to a "did you+ mean …?" question, so a clarified pane is briefed through exactly the+ same composer and reported by exactly the same verdict line. A second+ delivery site would be free to drift into announcing something it did+ not do, which is the failure class this whole area exists to prevent.++ No brain is pinned for the composer on purpose. An earlier version+ handed it this turn's FAST router model to save 4-5 s, but that+ optimised the wrong axis: the prompt is what the coding agent then+ works from for minutes, and the maintainer's decision on 2026-07-25+ was explicitly for the better prompt over the quicker handoff. The+ composer resolves a quality-tier model itself and degrades to its+ deterministic prompt when none is reachable.+ """+ from jarvis.agentic_ide import fanout as ide_fanout++ # Returning None here would hand the turn to the model with nothing to+ # go on, and a model asked about a pane it cannot see answers from the+ # user's own question — which is precisely how "I have let Alex know"+ # was spoken over a terminal that had received nothing (2026-07-27).+ # A delivery that did not happen is a fact worth saying out loud, so+ # every exit below carries one; ``deliver`` itself never raises for a+ # single pane, so reaching these means the whole fan-out fell over.try:result = await ide_fanout.deliver(session=session,terminals=names,- utterance=user_text,- instruction=found.instruction,+ utterance=utterance,+ instruction=instruction,assignments=assignments,)except Exception: # noqa: BLE001 - never crash the turn over a panelog.warning("Agentic IDE fast-path failed", exc_info=True)- return None+ return action_phrase(+ "ide_prompt_sent_nobody", language, failed=_join_names(names, language)+ )if not result.deliveries:+ log.warning(+ "Agentic IDE fast-path: fan-out returned no verdicts for %s",+ ", ".join(names),+ )+ return action_phrase(+ "ide_prompt_sent_nobody", language, failed=_join_names(names, language)+ )+ return _fanout_reply_line(result, language)++ def _ask_which_agentic_ide_terminal(+ self,+ user_text: str,+ *,+ candidates: list[str],+ language: str,+ ) -> str | None:+ """Ask which pane was meant, or ``None`` when there is nothing to ask.++ The question is armed as a one-shot window: the user's next turn ("ja",+ "Ellis") delivers the ORIGINAL instruction to the confirmed pane, so+ clarifying costs one word rather than a repeated sentence.+ """+ try:+ from jarvis.agentic_ide import clarify as ide_clarify+ except Exception: # noqa: BLE001 - optional surface+ return None+ try:+ need = ide_clarify.detect_clarification(user_text, names=candidates)+ except Exception: # noqa: BLE001 - a detector fault stays silent+ return None+ if need is None:+ return None++ question = self._agentic_ide_clarify_question(need, language)+ ide_clarify.WINDOW.arm(need, question=question)+ log.info(+ "Agentic IDE: heard %r, asking whether %s was meant",+ " / ".join(item.spoken for item in need.uncertain),+ " / ".join(need.offered),+ )+ return question++ @staticmethod+ def _agentic_ide_clarify_question(+ need: Any, language: str, *, also: bool = False+ ) -> str:+ """The spoken question for one uncertain call-sign, or for a list.++ Three shapes, because they mean three different things and a user has+ to be able to answer each with one word: one pane offered ("did you+ mean Blake?"), one word that could be several panes ("Max OR+ Maggie?"), and several garbled names in one list ("Alex AND Blake?").+ Joining the last one with "or" would ask the user to pick between two+ agents they had just addressed together.+ """+ spoken = need.spoken+ if len(need.uncertain) > 1:+ heard = [item.spoken for item in need.uncertain]+ spoken = action_phrase("join_and", language).join(+ (", ".join(heard[:-1]), heard[-1])+ )++ offered = need.offered+ if len(need.uncertain) == 1 and len(offered) == 1:+ if also:+ return action_phrase(+ "ide_terminal_clarify_also",+ language,+ spoken=spoken,+ names=offered[0],+ )+ return action_phrase(+ "ide_terminal_clarify_one", language, spoken=spoken, name=offered[0]+ )+ # Alternatives for ONE word are offered with "or"; a list of separate+ # names is joined with "and", because both were meant.+ joiner = "join_and" if len(need.uncertain) > 1 else "join_or"+ joined = action_phrase(joiner, language).join(+ (", ".join(offered[:-1]), offered[-1])+ )+ return action_phrase(+ "ide_terminal_clarify_also" if also else "ide_terminal_clarify_many",+ language,+ spoken=spoken,+ names=joined,+ )++ def _agentic_ide_leftover_question(+ self,+ user_text: str,+ *,+ candidates: list[str],+ claimed: list[str],+ language: str,+ ) -> tuple[Any, str] | None:+ """A question about the addressees this turn named but did not resolve.++ Returns ``(need, question)`` when the utterance addressed panes BEYOND+ the ones about to be briefed, else ``None``. The caller arms it after+ the delivery, so the user hears which agents really got the work before+ being asked about the rest.++ Nothing is asked when every uncertain word points at a pane that is+ already being briefed — that is the same addressee reached twice, not a+ second one.+ """+ try:+ from jarvis.agentic_ide import clarify as ide_clarify+ from jarvis.agentic_ide import intent as ide_intent++ need = ide_clarify.detect_clarification(user_text, names=candidates)+ except Exception: # noqa: BLE001 - a detector fault stays silent+ return None++ already = {name.casefold() for name in claimed}+ if need is not None and not all(+ all(name.casefold() in already for name in item.candidates)+ for item in need.uncertain+ ):+ return need, self._agentic_ide_clarify_question(need, language, also=True)++ # No word came close enough to name a pane — and a call-sign can be+ # mangled past every threshold there is ("Dave" for a pool that holds+ # none). What survives that is the COUNT the user stated out loud:+ # "both of you" says two agents were addressed however badly the names+ # travelled. Briefing one and saying nothing is the failure this+ # catches — the user hears one name confirmed and believes two are+ # working (live 2026-07-27 19:07).+ try:+ if not ide_intent.expects_several(user_text):+ return None+ except Exception: # noqa: BLE001 - a detector fault stays silent+ return None+ if len(claimed) > 1:+ return None+ rest = tuple(name for name in candidates if name.casefold() not in already)+ if not rest:+ return None+ # Armed over every OTHER pane, so the next word ("Blake") delivers the+ # original task. A bare "yes" decides nothing here and must not: there+ # is no candidate to confirm, only panes to choose between.+ unresolved = ide_clarify.ClarificationNeeded(+ uncertain=(ide_clarify.UncertainName(spoken="", candidates=rest),),+ utterance=user_text,+ certain=tuple(claimed),+ )+ return unresolved, action_phrase(+ "ide_terminal_who_else", language, names=", ".join(claimed)+ )++ async def _brief_spawned_agentic_ide_fleet(+ self,+ session: Any,+ names: list[str],+ user_text: str,+ ) -> None:+ """Brief newly mounted Codex panes once their real input lines exist."""+ from jarvis.agentic_ide import fanout as ide_fanout+ from jarvis.agentic_ide import intent as ide_intent+ from jarvis.agentic_ide.fleet_actions import wait_for_prompt_ready++ instruction = ide_intent.spawn_instruction(user_text)+ assignments: dict[str, str] | None = None+ if len(names) > 1 and ide_intent.wants_split(user_text):+ try:+ from jarvis.agentic_ide import work_split as ide_split++ plan = await ide_split.split(+ instruction,+ session=session,+ count=len(names),+ )+ assignments = {+ name: item.task+ for name, item in zip(names, plan.assignments, strict=False)+ }+ except Exception: # noqa: BLE001 - the common brief is still usable+ log.warning("Agentic IDE spawned-fleet split failed", exc_info=True)++ ready = await wait_for_prompt_ready(session, names)+ missing = [name for name in names if name not in ready]+ if missing:+ log.warning(+ "Agentic IDE spawned-fleet briefing: panes never became ready: %s",+ ", ".join(missing),+ )+ if not ready:+ return++ result = await ide_fanout.deliver(+ session=session,+ terminals=ready,+ utterance=user_text,+ instruction=instruction,+ assignments=assignments,+ )+ log.info(+ "Agentic IDE spawned-fleet briefing: %d of %d prompts delivered",+ len(result.delivered),+ len(names),+ )++ async def _run_agentic_ide_close_fast_path(+ self,+ user_text: str,+ *,+ trace_id: UUID | None = None,+ ) -> str | None:+ """Close an explicitly requested terminal fleet without model routing."""+ try:+ from jarvis.agentic_ide import intent as ide_intent+ from jarvis.agentic_ide.fleet_actions import (+ close_agent_terminals,+ terminals_closed_event,+ )+ from jarvis.agentic_ide.session import get_registry++ request = ide_intent.detect_close_fleet(user_text)+ except Exception: # noqa: BLE001 - optional surfacereturn None- return _fanout_reply_line(result, out_lang)+ if request is None:+ return None++ out_lang = resolve_output_language(+ self._reply_language,+ "unknown",+ user_text,+ default=DEFAULT_LOCALE,+ conversation_language=self._conversation_language,+ )+ registry = get_registry()+ session = registry.session+ if session is None:+ return action_phrase("ide_terminals_none_to_close", out_lang)+ closed = await close_agent_terminals(registry, request.agent)+ if not closed:+ return action_phrase("ide_terminals_none_to_close", out_lang)+ if self._bus is not None:+ try:+ await self._bus.publish(+ terminals_closed_event(+ session,+ closed,+ source_layer="brain.agentic_ide_close",+ )+ )+ except Exception: # noqa: BLE001 - the terminals are already closed+ log.warning("Agentic IDE close: UI notification failed", exc_info=True)+ names = [term.name for term in closed]+ return action_phrase(+ "ide_terminals_closed",+ out_lang,+ count=len(names),+ names=_join_names(names, out_lang),+ )async def _run_agentic_ide_spawn_fast_path(self,@@ -6020,15 +6399,48 @@ class BrainManager:log.warning("Agentic IDE spawn: UI notification failed", exc_info=True)names = [t.name for t in created]+ if session is not None:+ self._last_ide_spawn = (session.id, tuple(names), time.monotonic())++ briefing_queued = bool(+ session is not None and ide_intent.spawn_includes_task(user_text)+ )+ if briefing_queued and session is not None:+ tasks = getattr(self, "_ide_background_tasks", None)+ if tasks is None:+ tasks = set()+ self._ide_background_tasks = tasks+ task = asyncio.create_task(+ self._brief_spawned_agentic_ide_fleet(session, names, user_text),+ name="agentic-ide-spawned-fleet-briefing",+ )+ tasks.add(task)++ def _briefing_done(done: asyncio.Task[Any]) -> None:+ tasks.discard(done)+ if done.cancelled():+ return+ try:+ done.result()+ except Exception: # noqa: BLE001 - background failure is logged+ log.warning(+ "Agentic IDE spawned-fleet briefing failed",+ exc_info=True,+ )++ task.add_done_callback(_briefing_done)log.info("Agentic IDE spawn fast-path: opened %d pane(s) %s%s",len(names),names,f" in {folder_label}" if folder_label else "",)- return _terminals_spawned_line(+ line = _terminals_spawned_line(names, requested=request.count, folder=folder_label, lang=out_lang)+ if briefing_queued:+ line = f"{line} {action_phrase('ide_terminals_briefing_queued', out_lang)}"+ return linedef _is_explicit_heavy_request(self, user_text: str) -> bool:"""Return whether the user semantically requested a heavy worker."""@@ -8491,6 +8903,22 @@ class BrainManager:)return nav_reply+ # Agentic-IDE fleet close: "close all Codex terminals" is a concrete+ # workspace action, not a question for the router to interpret. It runs+ # before addressed delivery so the word "all" cannot become a prompt+ # sent into the very panes the user asked to stop.+ ide_close_reply = await self._run_agentic_ide_close_fast_path(+ user_text, trace_id=turn_trace_id,+ )+ if ide_close_reply is not None:+ await self._record_response_side_effects(+ user_text=user_text,+ response_text=ide_close_reply,+ use_history=use_history,+ trace_id=turn_trace_id,+ )+ return ide_close_reply+# Agentic-IDE fast-path: an instruction aimed at a named terminal of the# open coding workspace is DELIVERED to that terminal, deterministically.# Placed before force-spawn — whose depth-marker hoist used to swallowdiff --git a/jarvis/brain/resolver.py b/jarvis/brain/resolver.pyindex 98d165c570..f2a452dce8 100644--- a/jarvis/brain/resolver.py+++ b/jarvis/brain/resolver.py@@ -232,6 +232,62 @@ def resolve_quality_brain(return None+def resolve_vision_brain(+ config: JarvisConfig,+ *,+ bus: EventBus | None = None,+) -> Brain | None:+ """A Brain that can actually LOOK at an image, or None.++ Gated purely on the ``supports_vision`` capability (AP-21) — never on a+ provider name or a model id. Several providers in a normal chain are+ text-only (a subscription CLI, a local model), and handing one an image+ does not fail loudly: it answers about the words around the picture as if+ it had seen it. That is the failure mode this resolver exists to prevent,+ so a provider is skipped unless it declares the capability.++ ``supports_vision`` is read defensively rather than assumed True: a+ provider that does not declare it at all is treated as blind, because the+ caller's whole job here is to describe a picture and a confident+ description of an image nobody looked at is worse than no description.++ Never raises. None means "nothing here can see", and the caller says so+ instead of pretending otherwise.+ """+ _ensure_bus_subscription(bus)+ try:+ chain = list(_resolve_chain(config))+ except Exception: # noqa: BLE001 - a config problem must not kill the caller+ log.info("resolve_vision_brain: chain could not be built", exc_info=True)+ return None++ for provider, model in chain:+ cache_key = (provider, model or "")+ brain = _cache.get(cache_key)+ if brain is None:+ try:+ brain = _get_registry().instantiate(+ provider, **({"model": model} if model else {}),+ )+ except Exception as exc: # noqa: BLE001+ log.info(+ "resolve_vision_brain: %s/%s not instantiable (%s)",+ provider, model or "<default>", type(exc).__name__,+ )+ continue+ _cache[cache_key] = brain+ if not getattr(brain, "supports_vision", False):+ log.debug(+ "resolve_vision_brain: skipping %s/%s (supports_vision is not set)",+ provider, model or "<default>",+ )+ continue+ return brain++ log.info("resolve_vision_brain: no vision-capable provider reachable")+ return None++def _subscription_connected(provider: str) -> bool:"""Whether ``provider``'s subscription login is usable right now.diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.pyindex 7fa386ce6a..1123280da9 100644--- a/jarvis/brain/turn_planner.py+++ b/jarvis/brain/turn_planner.py@@ -35,6 +35,7 @@ class TurnReason(StrEnum):PRIVATE_DATA = "private_data"SKILL = "skill"UNCERTAIN = "uncertain"+ WORKSPACE = "workspace"@dataclass(frozen=True)@@ -379,6 +380,50 @@ def _matched_capabilities(return tuple(sorted(item for item in matched if item))+def _is_workspace_turn(text: str, workspace_names: Sequence[str]) -> bool:+ """Whether this turn is about a terminal of the open coding workspace.++ The realtime half of the 2026-07-27 miss. Asked "was hat Dana gemacht", the+ live model answered that it did not know any person called Dana — correctly,+ from its own knowledge, because nothing had ever told it that a coding agent+ named Dana was running two feet away. No vocabulary rule could have caught+ that turn: it carries no lookup verb, no action, no possessive and no+ connected domain, so the planner routed it natively and the pane was never+ consulted. The CALL-SIGN is the evidence, and it is evidence the static+ vocabularies below structurally cannot hold, because the names are chosen+ per workspace at runtime.++ The verdict is delegated to the workspace's OWN detectors rather than+ re-derived here — the same rule that decides which pane gets the work has to+ decide whether the orchestrator is needed for it, or the planner would+ delegate turns the workspace then declines (and worse, the reverse). Both+ are pure regex over the utterance, no IO and no LLM, so this keeps the+ module's promise on the voice hot path.++ Two shapes qualify:++ 1. a pane is named — addressed, or asked about ("was hat Dana gemacht");+ 2. a pane is ALMOST named — the clarify path has a question to ask, and it+ can only ask it from the orchestrator.+ """+ names = [str(name) for name in workspace_names if str(name or "").strip()]+ if not names or not str(text or "").strip():+ return False+ try:+ from jarvis.agentic_ide.intent import detect++ if detect(text, names=names) is not None:+ return True+ except Exception: # noqa: BLE001 - optional surface, never breaks planning+ return False+ try:+ from jarvis.agentic_ide.clarify import detect_clarification++ return detect_clarification(text, names=names) is not None+ except Exception: # noqa: BLE001 - optional surface, never breaks planning+ return False++def is_contextual_follow_up(text: str, context: Sequence[str]) -> bool:"""Return whether ``text`` explicitly refers to the bounded prior context."""normalized = _normalize(text).strip()@@ -400,18 +445,49 @@ def plan_turn(tool_names: Iterable[str] = (),evidence_domains: Mapping[str, Sequence[str]] | None = None,context: Sequence[str] = (),+ skill_index: Any | None = None,+ workspace_names: Sequence[str] = (),) -> TurnPlan:"""Return the conservative shared execution plan for ``text``.Uncertainty is resolved toward the orchestrator because it can stillanswer conversationally, while a native realtime model cannot recoverprivate or connected evidence it never received.- """++ ``skill_index`` is an optional ``jarvis.skills.relevance.SkillMatchIndex``+ — a frozen bag of dicts and frozensets exposing ``.rank()``, holding+ no registry reference, no paths and no file handles. Passing it in (rather+ than importing the skill package here) is what keeps this module's promise+ of no model call, no disk access and no network structurally true, and+ avoids dragging ``jarvis.skills``' eager package init into every early+ import of the planner (AP-26).++ Without it the planner falls back to its static vocabulary, which for skills+ means the three literal trigger words in _SKILL_RE above — i.e. it has no idea+ what is actually installed, so "starte die Morgenroutine" produced no skill+ reason at all.++ ``workspace_names`` is the live Agentic-IDE call-signs+ (``agentic_ide.session.running_call_signs``). Like the skill index it is+ passed IN rather than looked up, so this module keeps holding no registry+ reference; see ``_is_workspace_turn`` for why a runtime-chosen name can+ never be covered by the static vocabularies.+ """ # i18n-allow: names the German trigger words the static branch matchesnormalized = _normalize(text).strip()if not normalized:return TurnPlan(path=TurnPath.NATIVE_REALTIME)reasons: set[TurnReason] = set()+ # Checked before the suppressors and never dampened by them: a named pane+ # is as strong as evidence gets, and the reason it must not be weakened is+ # that its most ordinary phrasings are exactly the shapes the suppressors+ # target: a question about what a pane has done reads as third-party+ # smalltalk, and a modal asking whether a pane should do something reads as+ # first-person deliberation. Both would be talked back down into a native+ # answer the model cannot give.+ workspace_turn = _is_workspace_turn(text, workspace_names)+ if workspace_turn:+ reasons.add(TurnReason.WORKSPACE)definition = bool(_DEFINITION_RE.search(normalized))instructional = bool(_INSTRUCTIONAL_RE.search(normalized))# An instructional form asks for an explanation, even when the sentence@@ -420,7 +496,10 @@ def plan_turn(# not execute the referenced action or fetch private/current evidence.# Return early so none of the conservative evidence heuristics below can# turn an advice question into an orchestrator-owned action.- if instructional:+ #+ # A named pane is the exception: "how do I get Dana to run the tests" asks+ # about THIS workspace, and only the orchestrator can see what Dana is.+ if instructional and not workspace_turn:return TurnPlan(path=TurnPath.NATIVE_REALTIME)required = () if definition or instructional else _matched_capabilities(text,@@ -502,6 +581,31 @@ def plan_turn(reasons.add(TurnReason.MISSION)if _SKILL_RE.search(normalized) and not definition:reasons.add(TurnReason.SKILL)+ elif skill_index is not None and not definition:+ # Content-aware skill detection: ask the deterministic index whether an+ # INSTALLED skill actually owns this utterance. Pure CPU, no IO. Only a+ # FIRE-band hit counts — a NARROW candidate is a suggestion for the+ # orchestrator's prompt, not a reason to pay a delegation.+ #+ # The band is derived here from the index's own corpus-relative+ # threshold rather than asked of the index, because the band vocabulary+ # lives in jarvis.skills.match_eval and having the scorer know about it+ # would close an import cycle. The scorer ranks; callers decide.+ try:+ ranking = skill_index.rank(text, limit=1)+ winner = ranking.top+ if (+ winner is not None+ and winner.score >= ranking.fire_threshold+ and ranking.clear_winner+ ):+ reasons.add(TurnReason.SKILL)+ required = tuple(sorted({*required, f"skill:{winner.name}"}))+ except Exception: # noqa: BLE001+ # Silent by design: this module has no logger and must stay free of+ # side effects, and a scorer fault simply means the static+ # vocabulary decides, exactly as before the index existed.+ reasons.discard(TurnReason.SKILL)# Realtime follow-ups routinely omit the evidence domain and ASR may garble# the possessive itself. Inherit only when the current lookup contains an@@ -601,6 +705,10 @@ def plan_turn(TurnReason.CURRENT_DATA,TurnReason.LOCAL_STATE,TurnReason.PRIVATE_DATA,+ # What the pane actually printed is evidence the live model+ # never holds; answering "what has Dana done" without it is+ # exactly the guess this whole path exists to prevent.+ TurnReason.WORKSPACE,}),)diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txtindex ea849dab91..e80eb570a4 100644--- a/scripts/ci/german-allowlist.txt+++ b/scripts/ci/german-allowlist.txt@@ -401,11 +401,15 @@ jarvis/agentic_ide/prompt_composer.py# --- Their tests: every German string is a simulated user utterance fed to the# classifiers above — the speech input the matcher is scored on, i.e. the-# content under test (reason 4, same shape as tts_eval/corpus.py). ----tests/unit/agentic_ide/test_clarify.py-tests/unit/agentic_ide/test_intent.py-tests/unit/agentic_ide/test_file_index.py-tests/unit/agentic_ide/test_prompt_submit.py+# content under test (reason 4, same shape as tts_eval/corpus.py). The whole+# directory is listed rather than each file: it exists to score the+# addressing classifiers, so a future test there is by construction another+# batch of utterances. The two brain-side fast-path tests below hold the+# same fixtures and are listed individually — tests/unit/brain/ at large+# stays English-checked. ---+tests/unit/agentic_ide/*+tests/unit/brain/test_agentic_ide_spawn_fast_path.py+tests/unit/brain/test_agentic_ide_clarify_fast_path.py# --- Generated command reference: every German fragment in it is a quoted# SPOKEN EXAMPLE copied out of a Command-Registry description ("'Mika solldiff --git a/tests/unit/agentic_ide/test_attach_analysis_route.py b/tests/unit/agentic_ide/test_attach_analysis_route.pynew file mode 100644index 0000000000..45f106cc2b--- /dev/null+++ b/tests/unit/agentic_ide/test_attach_analysis_route.py@@ -0,0 +1,366 @@+"""Dropping a file on the prompt bar: stored, read, and folded into the prompt.++The route has to serve two different gestures without them interfering:++* **A drop on a PANE** — types a path and stops. Cheap, no model, unchanged.+* **A drop on the PROMPT BAR** — reads the file (describes an image, extracts a+ document), types nothing, and hands the contents back so the composed prompt+ can carry them. That is what makes dropping a screenshot work against a coding+ agent that cannot open one.++The failure this guards is quiet, which is why it is pinned end to end: an+analysis that is produced and then dropped on the floor looks exactly like one+that was never asked for, and the user only finds out when the agent asks what+the screenshot showed.+"""+from __future__ import annotations++import io+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agentic_ide import drop_analysis, drops, prompt_composer+from jarvis.agentic_ide import session as session_mod+from jarvis.agentic_ide.drop_analysis import DropAnalysis+from jarvis.agentic_ide.session import Registry+from tests.fakes.fake_pty_manager import FakePtyManager++PNG = (+ b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"+ b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00"+ b"\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82"+)++[email protected](autouse=True)+def _isolated_recents(+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch+) -> None:+ from jarvis.agentic_ide import recents++ store = tmp_path_factory.mktemp("recents") / "recents.json"+ monkeypatch.setattr(recents, "_store_path", lambda: store)++[email protected](autouse=True)+def _staged_vision(monkeypatch: pytest.MonkeyPatch) -> None:+ """A provider that can see, so the description is deterministic.++ Staged at the resolver rather than the call: that is the seam a real install+ varies at, and it lets one test remove vision entirely to check the honest+ degradation (§3).+ """++ class _Delta:+ content = "A login dialog; the submit button overflows and reads 'Sign inn'."++ class _Seeing:+ supports_vision = True++ async def complete(self, request): # noqa: ANN001, ANN202+ yield _Delta()++ monkeypatch.setattr(drop_analysis, "_resolve_vision_brain", _Seeing)+++def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ reg = Registry(pty_manager=FakePtyManager())+ monkeypatch.setattr(session_mod, "get_registry", lambda: reg)+ from jarvis.ui.web import agentic_ide_routes++ monkeypatch.setattr(agentic_ide_routes, "get_registry", lambda: reg)+ return reg+++def client(registry: Registry) -> TestClient:+ from jarvis.ui.web.agentic_ide_routes import router++ app = FastAPI()+ app.include_router(router)+ return TestClient(app)+++async def _noop(_text: str) -> None:+ return None+++async def _noop_exit(_code: int) -> None:+ return None+++async def _workspace(registry: Registry, folder: Path) -> str:+ await registry.start(str(folder), [{"agent": "claude"}])+ assert registry.session is not None+ term = registry.session.terminals[0]+ await registry.attach(term.name, 100, 30, _noop, _noop_exit)+ return term.name+++def _upload(name: str = "shot.png", data: bytes = PNG) -> dict:+ return {"files": (name, io.BytesIO(data), "image/png")}+++# ------------------------------------------------------------------- analysis+async def test_a_dropped_screenshot_comes_back_described(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ name = await _workspace(registry, tmp_path)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/attach",+ files=_upload(),+ data={"analyze": "true", "deliver": "false"},+ )++ assert response.status_code == 200+ body = response.json()+ assert len(body["analysis"]) == 1+ entry = body["analysis"][0]+ assert entry["kind"] == "image"+ assert entry["described_by"] == "vision"+ assert "submit button overflows" in entry["detail"]+ # The reference has to point at the file that was actually written, so an+ # agent that CAN open it is not sent to a path that does not exist.+ assert drops.DROP_DIRNAME.split("/")[0] in entry["reference"]+++async def test_deliver_false_types_nothing_into_the_pane(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ name = await _workspace(registry, tmp_path)+ written: list[str] = []+ term = registry.session.terminals[0]+ registry.write = lambda key, text: written.append(text) or True # type: ignore[assignment]++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/attach",+ files=_upload(),+ data={"analyze": "true", "deliver": "false"},+ )++ assert response.status_code == 200+ assert response.json()["delivered"] is False+ assert written == []+ # Held, not lost: the file is on disk where the prompt will point at it.+ assert (tmp_path / drops.DROP_DIRNAME).is_dir()+ assert list((tmp_path / drops.DROP_DIRNAME).iterdir())+ assert term is not None+++async def test_a_pane_drop_still_types_and_does_no_analysis(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ """The cheap path is unchanged — a pane drop must not start paying for a model."""+ name = await _workspace(registry, tmp_path)+ written: list[str] = []+ registry.write = lambda key, text: written.append(text) or True # type: ignore[assignment]++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/attach", files=_upload()+ )++ assert response.status_code == 200+ body = response.json()+ assert body["delivered"] is True+ assert body["analysis"] == []+ assert written and "shot.png" in written[0]+++async def test_a_document_drop_returns_its_text(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ name = await _workspace(registry, tmp_path)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/attach",+ files={"files": ("spec.md", io.BytesIO(b"# Spec\nReturn 202."), "text/markdown")},+ data={"analyze": "true", "deliver": "false"},+ )++ entry = response.json()["analysis"][0]+ assert entry["kind"] == "text"+ assert entry["described_by"] == "extraction"+ assert "Return 202." in entry["detail"]+++async def test_without_a_vision_provider_the_drop_still_works_and_says_why(+ client: TestClient, registry: Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The install of a downloader whose only key reaches a text-only model."""+ monkeypatch.setattr(drop_analysis, "_resolve_vision_brain", lambda: None)+ name = await _workspace(registry, tmp_path)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/attach",+ files=_upload(),+ data={"analyze": "true", "deliver": "false"},+ )++ assert response.status_code == 200+ entry = response.json()["analysis"][0]+ assert entry["detail"] == ""+ assert entry["note"]+ # The file itself still landed and is still referenced.+ assert entry["reference"]+ assert response.json()["copied"] == 1+++async def test_two_files_that_sanitize_to_one_name_stay_two(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ """Each dropped file gets its OWN reference, matched to its own bytes.++ ``safe_name`` maps different names onto the same one ("a b.txt" and+ "a-b.txt" both become "a_b.txt"), and they are stored as two distinct files.+ Pairing them up by name would reference one of them twice and lose the+ other — a file the user watched land, gone.+ """+ name = await _workspace(registry, tmp_path)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/attach",+ files=[+ ("files", ("a b.txt", io.BytesIO(b"first file"), "text/plain")),+ ("files", ("a-b.txt", io.BytesIO(b"second file"), "text/plain")),+ ],+ data={"analyze": "true", "deliver": "false"},+ )++ assert response.status_code == 200+ body = response.json()+ assert body["copied"] == 2+ assert len(body["references"]) == 2+ assert len(set(body["references"])) == 2+ # And each analysis carries the bytes of ITS file, not the other's.+ details = sorted(a["detail"] for a in body["analysis"])+ assert details == ["first file", "second file"]+++async def test_an_empty_file_does_not_desynchronise_the_rest(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ """An empty entry is skipped on both sides, so nothing shifts by one."""+ name = await _workspace(registry, tmp_path)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/attach",+ files=[+ ("files", ("empty.txt", io.BytesIO(b""), "text/plain")),+ ("files", ("real.txt", io.BytesIO(b"the real contents"), "text/plain")),+ ],+ data={"analyze": "true", "deliver": "false"},+ )++ assert response.status_code == 200+ body = response.json()+ assert body["files"] == ["real.txt"]+ assert body["analysis"][0]["detail"] == "the real contents"+++async def test_an_empty_drop_is_still_refused(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ name = await _workspace(registry, tmp_path)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/attach",+ data={"analyze": "true", "deliver": "false"},+ )++ assert response.status_code == 422+++# -------------------------------------------------------------------- prompt+async def test_the_analysis_reaches_the_composed_prompt(+ client: TestClient, registry: Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The whole point: what was read out of the file is in what the agent gets."""+ name = await _workspace(registry, tmp_path)+ seen: dict = {}++ async def fake_compose(utterance: str, **kwargs: object): # noqa: ANN202+ seen["attachments"] = list(kwargs.get("attachments") or [])+ return prompt_composer.ComposedPrompt(+ text=f"## Task\n{utterance}", composed_by="llm"+ )++ monkeypatch.setattr(prompt_composer, "compose", fake_compose)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/prompt",+ json={+ "prompt": "fix this",+ "compose": True,+ "dry_run": True,+ "attachments": [+ {+ "name": "shot.png",+ "reference": "@.jarvis/drops/shot.png",+ "kind": "image",+ "detail": "The submit button overflows its container.",+ "described_by": "vision",+ "note": "",+ }+ ],+ },+ )++ assert response.status_code == 200+ assert len(seen["attachments"]) == 1+ assert isinstance(seen["attachments"][0], DropAnalysis)+ assert "submit button overflows" in seen["attachments"][0].detail+++async def test_attachments_without_composition_are_not_silently_dropped(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ """A caller that says "here is what the user dropped" is owed delivery of it.++ Without this branch the picture would be described, paid for, shown to the+ user as attached, and then never reach the agent at all.+ """+ name = await _workspace(registry, tmp_path)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/prompt",+ json={+ "prompt": "fix this",+ "compose": False,+ "dry_run": True,+ "attachments": [+ {+ "name": "shot.png",+ "reference": "@shot.png",+ "kind": "image",+ "detail": "The submit button overflows its container.",+ "described_by": "vision",+ "note": "",+ }+ ],+ },+ )++ body = response.json()+ assert "submit button overflows" in body["composed"]+ assert "fix this" in body["composed"]+++async def test_a_plain_prompt_is_untouched_by_the_attachment_path(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ name = await _workspace(registry, tmp_path)++ response = client.post(+ f"/api/agentic-ide/terminals/{name}/prompt",+ json={"prompt": "run the tests", "compose": False, "dry_run": True},+ )++ body = response.json()+ assert body["composed"] == "run the tests"+ assert body["composed_by"] == "raw"diff --git a/tests/unit/agentic_ide/test_clarify.py b/tests/unit/agentic_ide/test_clarify.pynew file mode 100644index 0000000000..884f12ca46--- /dev/null+++ b/tests/unit/agentic_ide/test_clarify.py@@ -0,0 +1,351 @@+"""A misheard call-sign must ask, and only ever ask about the workspace.++Two live failures of 2026-07-27 meet in this module, and they pull in opposite+directions — which is why the cases below are written as two lists that must+BOTH hold, rather than as one threshold:++* the pane "Ellis" came back from speech recognition as "Ilies" and the+ addressed-terminal path stood down in silence, so nothing was typed anywhere+ and the live model claimed an agent was working;+* ordinary speech reaches the same pool from the other side ("allen" scores+ 0.750 against "Alex", above the acting threshold), so a sentence about the+ outside world must never be typed into somebody's coding agent.++The maintainer's own examples are pinned verbatim, including the counter-example+("what is Elon Musk up to?") — they are the specification.+"""++from __future__ import annotations++import pytest++from jarvis.agentic_ide import intent+from jarvis.agentic_ide.clarify import (+ ClarificationWindow,+ addresses_workspace,+ detect_clarification,+ is_outside_world_talk,+)++PANES = ["Alex", "Blake", "Casey", "Dana", "Ellis", "Finn"]+++def _outcome(text: str, names: list[str] | None = None) -> str:+ """What the workspace does with this turn: act, ask, or stay out of it.++ Deliberately routed through BOTH detectors in the order the brain calls+ them. A case that acts must not also ask, and a case that neither acts nor+ asks must be silent for a reason — the three outcomes are only meaningful+ together.+ """+ panes = names or PANES+ if intent.detect_all(text, names=panes):+ return "act"+ return "ask" if detect_clarification(text, names=panes) else "silent"+++# --------------------------------------------------------------------------- #+# A turn addresses a FLEET (live 2026-07-27 19:07) #+# --------------------------------------------------------------------------- #+++def test_a_garbled_name_beside_a_certain_one_is_still_asked_about() -> None:+ """The 19:07 failure: two panes addressed, one briefed, one dropped silent.++ A certainly-named pane used to end the search, so the second addressee —+ whose call-sign speech recognition had mangled — produced no action and no+ question. The user heard that Alex was working and believed both were.+ """+ need = detect_clarification(+ "Alex und Blaike sollen beide einen Deep Dive machen", names=PANES+ )+ assert need is not None, "the second addressee must not vanish"+ assert need.certain == ("Alex",), "the pane that WAS understood is carried"+ assert need.candidates == ("Blake",)+ assert need.spoken == "Blaike"+++def test_two_garbled_names_in_one_list_both_get_asked_about() -> None:+ """"Alexa und Blaike" is one instruction for two agents, not noise."""+ need = detect_clarification(+ "Alexa und Blaike sollen beide einen Deep Dive machen", names=PANES+ )+ assert need is not None+ assert [item.spoken for item in need.uncertain] == ["Alexa", "Blaike"]+ assert need.offered == ("Alex", "Blake")++ window = ClarificationWindow()+ window.arm(need)+ # ONE "yes" confirms the whole list — that is the point of asking once.+ assert window.resolve_answer("ja") == (("Alex", "Blake"), need.utterance)+++def test_naming_both_panes_answers_for_both() -> None:+ need = detect_clarification(+ "Alexa und Blaike sollen beide einen Deep Dive machen", names=PANES+ )+ assert need is not None+ window = ClarificationWindow()+ window.arm(need)+ resolved = window.resolve_answer("Alex and Blake")+ assert resolved is not None+ assert resolved[0] == ("Alex", "Blake")+++def test_a_stray_near_miss_beside_a_working_turn_stays_silent() -> None:+ """The cost of the change must not be a question on every good turn.++ "Alex" is certain and the sentence works; "Kannst" scores against "Casey"+ without being listed beside anything, so it is noise and must not produce+ a question the user then has to say "no" to.+ """+ need = detect_clarification(+ "Alex soll bitte die Tests reparieren, Kannst das laufen", names=PANES+ )+ assert need is None+++# --------------------------------------------------------------------------- #+# The live failure #+# --------------------------------------------------------------------------- #+++def test_the_live_transcript_asks_instead_of_going_silent() -> None:+ """The 2026-07-27 16:18 turn, verbatim from the session transcript."""+ spoken = (+ "kannst du bitte Ilies ein Deep Dive machen lassen und sie soll "+ "gucken, wieso wenn man aus dem Agentic IDE Mode rausgeht"+ )+ need = detect_clarification(spoken, names=PANES)+ assert need is not None, "the turn that started this must not be silent"+ assert need.candidates == ("Ellis",)+ assert need.spoken == "Ilies"+ # The ORIGINAL wording is carried, because it holds the actual task.+ assert need.utterance == spoken+++def test_the_answer_delivers_the_original_task() -> None:+ """A question is only worth asking if "yes" still does the work."""+ window = ClarificationWindow()+ spoken = "kannst du bitte Ilies das Deep Dive machen lassen"+ need = detect_clarification(spoken, names=PANES)+ assert need is not None+ window.arm(need)++ assert window.resolve_answer("ja") == (("Ellis",), spoken)+ # One question, one answer: the window is spent.+ assert not window.armed+ assert window.resolve_answer("ja") is None+++def test_naming_the_pane_answers_even_with_several_offered() -> None:+ """"Maggie" decides what a bare "yes" cannot."""+ window = ClarificationWindow()+ panes = ["Alex", "Max", "Maggie"]+ need = detect_clarification("Kannst du bitte Mags prompten?", names=panes)+ assert need is not None+ assert set(need.candidates) == {"Max", "Maggie"}+ window.arm(need)++ resolved = window.resolve_answer("Maggie")+ assert resolved is not None+ assert resolved[0] == ("Maggie",)+++def test_a_bare_yes_cannot_choose_between_two_panes() -> None:+ window = ClarificationWindow()+ need = detect_clarification(+ "Kannst du bitte Mags prompten?", names=["Alex", "Max", "Maggie"]+ )+ assert need is not None+ window.arm(need)+ assert window.resolve_answer("ja") is None+++def test_a_declined_question_delivers_nothing() -> None:+ window = ClarificationWindow()+ need = detect_clarification("Kannst du bitte Ilies prompten?", names=PANES)+ assert need is not None+ window.arm(need)+ assert window.resolve_answer("nein") is None+ assert not window.armed+++def test_moving_on_closes_the_question_instead_of_answering_it() -> None:+ """A full sentence is the user moving on, not an answer."""+ window = ClarificationWindow()+ need = detect_clarification("Kannst du bitte Ilies prompten?", names=PANES)+ assert need is not None+ window.arm(need)+ assert (+ window.resolve_answer(+ "ach lass mal, erzähl mir lieber wie das Wetter morgen wird"+ )+ is None+ )+ assert not window.armed+++def test_a_stale_question_never_delivers_work() -> None:+ window = ClarificationWindow()+ need = detect_clarification("Kannst du bitte Ilies prompten?", names=PANES)+ assert need is not None+ window.arm(need, now=0.0)+ assert window.resolve_answer("ja", now=10_000.0) is None+++# --------------------------------------------------------------------------- #+# The maintainer's specification (2026-07-27) #+# --------------------------------------------------------------------------- #++# "If I only say a first name that could be roughly the same, it should check+# that I mean the right one."+ASKS = [+ ("kannst du bitte Ilies ein Deep Dive machen lassen", None),+ ("Ilies soll mal einen Deep Dive machen", None),+ ("Kannst du bitte Mags prompten?", ["Alex", "Max", "Maggie"]),+ ("Dena soll die Tests fixen", None),+ ("Kannst du Ellice beauftragen, den Bug zu fixen", None),+]++# "But not, for example: 'can you tell me what Elon Musk is doing right now?'+# … and then it prompts everyone. That must of course not happen."+STAYS_OUT = [+ "Kannst du bitte mir sagen, was Elon Musk gerade macht?",+ "Sag mir was Elon Musk gerade macht",+ "Was macht Elon gerade?",+ "Wer ist Elon Musk?",+ "kannst du mir sagen was Barack Obama gerade macht",+ "Erzähl mir was über Elias Canetti",+ "wie ist das Wetter heute",+ "kannst du bitte den Bug fixen",+ "mach mal einen Deep Dive in den Code",+ "Ilies ist ein schöner Name",+ "schick das an Alexander Müller weiter",+ "lass die Tests laufen und fixe die Fehler",+ "Das soll man mal fixen",+]++[email protected](("spoken", "panes"), ASKS)+def test_an_uncertain_call_sign_asks(spoken: str, panes: list[str] | None) -> None:+ assert _outcome(spoken, panes) == "ask", spoken++[email protected]("spoken", STAYS_OUT)+def test_the_outside_world_never_reaches_a_pane(spoken: str) -> None:+ assert _outcome(spoken) == "silent", spoken+++# --------------------------------------------------------------------------- #+# Certainty still acts — asking must not become the new normal #+# --------------------------------------------------------------------------- #++ACTS = [+ "sag Ellis, sie soll die Tests fixen",+ # Same sound, different spelling: certain, and therefore acted on. This is+ # the gap the canonicalization in ``intent`` closed — the templates are+ # built from the exact spelling and used to match none of these.+ "Sag Elis, sie soll die Tests fixen",+ "beauftrage Ellys mit dem Bug",+ "Kannst du Elliss beauftragen, den Bug zu fixen",+ "Was macht Ellis gerade?",+ "sag allen, sie sollen die Tests fixen",+]++[email protected]("spoken", ACTS)+def test_a_certain_call_sign_is_still_acted_on(spoken: str) -> None:+ assert _outcome(spoken) == "act", spoken+++def test_a_misheard_collective_address_cannot_brief_the_whole_workspace() -> None:+ """The costliest thing a garbled word can do is reach EVERY pane at once."""+ assert is_outside_world_talk("sag allen was Elon Musk gerade macht")+ assert intent.detect_all(+ "sag allen was Elon Musk gerade macht", names=PANES+ ) == []+ # A genuine collective instruction still reaches everyone.+ assert len(intent.detect_all("sag allen, sie sollen aufhören", names=PANES)) == len(+ PANES+ )+++# --------------------------------------------------------------------------- #+# The gate itself #+# --------------------------------------------------------------------------- #+++ ("spoken", "expected"),+ [+ ("Kannst du bitte Max prompten?", True),+ ("beauftrage Max mit dem Bug", True),+ ("sag Max, er soll die Tests fixen", True),+ ("Max soll die Tests fixen", True),+ # A handover verb and a name and nothing else is NOT workspace evidence.+ ("Sag mir was Elon Musk gerade macht", False),+ ("wie ist das Wetter", False),+ ],+)+def test_workspace_gate(spoken: str, expected: bool) -> None:+ assert addresses_workspace(spoken) is expected+++def test_an_all_lowercase_transcript_still_refuses_function_words() -> None:+ """Case cannot rule when the provider capitalizes nothing; stopwords still do."""+ need = detect_clarification(+ "kannst du bitte den bug fixen lassen", names=PANES+ )+ assert need is None+++# --------------------------------------------------------------------------- #+# Asking a pane for a status report #+# --------------------------------------------------------------------------- #+# The 16:53 half of the same day: "Was hat Dana gemacht?" carries no repo, no+# test, no bug and no branch, so the coding-work pairings never saw it — a+# garbled call-sign inside the single most common workspace question there is+# went silently nowhere.+++ "spoken",+ [+ "Was hat Ellis gemacht?",+ "Was macht Ellis gerade?", # i18n-allow: German speech input under test+ "Wie weit ist Ellis?", # i18n-allow: German speech input under test+ "What has Ellis done?",+ "How far is Ellis?",+ "Que ha hecho Ellis?",+ ],+)+def test_a_status_question_addresses_the_workspace(spoken: str) -> None:+ assert addresses_workspace(spoken) is True+++def test_a_garbled_call_sign_in_a_status_question_asks() -> None:+ """The live 16:53 shape, with the name mangled the way 16:18 mangled it."""+ need = detect_clarification("Was hat Ilies gemacht?", names=PANES)+ assert need is not None+ assert need.candidates == ("Ellis",)+ # And the confirmed pane is briefed with the ORIGINAL question, not "yes".+ window = ClarificationWindow()+ window.arm(need)+ assert window.resolve_answer("ja") == (("Ellis",), "Was hat Ilies gemacht?")+++ "spoken",+ [+ # A full personal name turns the identical shape into a question about+ # a human being — the surname is the only thing that tells them apart.+ "Sag mir was Elon Musk gerade macht",+ "Was hat Angela Merkel gemacht?",+ ],+)+def test_a_status_question_about_a_person_stays_out_of_the_workspace(+ spoken: str,+) -> None:+ assert addresses_workspace(spoken) is False+ assert _outcome(spoken) == "silent"diff --git a/tests/unit/agentic_ide/test_composer_progress.py b/tests/unit/agentic_ide/test_composer_progress.pynew file mode 100644index 0000000000..0cae1c0feb--- /dev/null+++ b/tests/unit/agentic_ide/test_composer_progress.py@@ -0,0 +1,248 @@+"""The composer says what it is doing while it does it.++Writing a brief takes 10-27 s — a quality-tier model reading file outlines,+and on a subscription CLI a cold process start before it thinks at all. For all+of that the terminal used to show nothing, which makes a working composer and a+wedged one look identical, and makes the wait feel longer than it is.++So the beats are part of the contract now, and these guards pin the three+properties that make them worth printing rather than noise: they arrive in+order, every line names the pane it belongs to (a fleet composes at once, and+an unattributed line is worse than none), and none of them can ever cost the+prompt itself.+"""+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.agentic_ide import prompt_composer+++class _Writer:+ """Stands in for a resolved quality-tier Brain."""++ name = "test-writer"+++class _StreamingBrain:+ """Brain double that answers in two deltas, like a real stream."""++ name = "streaming-writer"++ async def complete(self, _req: object): # noqa: ANN202 - test double+ from jarvis.core.protocols import BrainDelta++ yield BrainDelta(content="## Task\nLook at the wake word path.")+ yield BrainDelta(content="\n\n## Done when\nThe cause is named.")++[email protected](autouse=True)+def _writer_available(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: _Writer())+++def _session(tmp_path) -> object: # noqa: ANN001 - pytest tmp_path+ profile = SimpleNamespace(+ instruction_files=[], summary_lines=lambda: ["Test workspace"]+ )+ return SimpleNamespace(folder=str(tmp_path), profile=profile)+++def _brief(**_kwargs: object) -> object:+ async def _answer() -> str:+ return "## Task\nLook at the wake word path."++ return _answer()+++async def test_the_beats_arrive_in_order_and_name_the_pane(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None: # noqa: ANN001+ seen: list[prompt_composer.ComposeNotice] = []+ monkeypatch.setattr(prompt_composer, "_llm_compose", _brief)++ result = await prompt_composer.compose(+ "schau dir mal den wake word pfad an", # i18n-allow: German speech input under test+ session=_session(tmp_path),+ terminal_name="Kate",+ on_progress=seen.append,+ )++ assert result.composed_by == "llm"+ assert [n.stage for n in seen] == [+ prompt_composer.STAGE_START,+ prompt_composer.STAGE_THINKING,+ prompt_composer.STAGE_READY,+ ]+ assert all("Kate" in n.message for n in seen)+ assert all(n.terminal == "Kate" for n in seen)+ # The closing line reports what was actually written, not that something was.+ assert "characters" in seen[-1].message+++async def test_the_first_token_says_the_model_started_writing(+ tmp_path,+) -> None: # noqa: ANN001+ """The gap before the first token IS the wait on a cold subscription CLI."""+ seen: list[prompt_composer.ComposeNotice] = []++ await prompt_composer.compose(+ "why does the wake word not fire",+ session=_session(tmp_path),+ terminal_name="Kate",+ brain=_StreamingBrain(),+ on_progress=seen.append,+ )++ stages = [n.stage for n in seen]+ assert prompt_composer.STAGE_DRAFTING in stages+ # It lands between "thinking" and "ready", and only once however many+ # deltas arrive.+ assert stages.count(prompt_composer.STAGE_DRAFTING) == 1+ assert stages.index(prompt_composer.STAGE_THINKING) < stages.index(+ prompt_composer.STAGE_DRAFTING+ ) < stages.index(prompt_composer.STAGE_READY)+++async def test_the_opening_line_follows_the_instruction(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None: # noqa: ANN001+ """Context-aware, not one canned sentence read past after the second time."""+ monkeypatch.setattr(prompt_composer, "_llm_compose", _brief)+ session = _session(tmp_path)++ lines: list[str] = []+ for spoken in (+ "review the wake word detection",+ "build a retry into the uploader",+ "why does the bar freeze when I hang up",+ ):+ seen: list[prompt_composer.ComposeNotice] = []+ await prompt_composer.compose(+ spoken, session=session, terminal_name="Kate", on_progress=seen.append+ )+ opening = next(+ n.message for n in seen if n.stage == prompt_composer.STAGE_START+ )+ lines.append(opening)+ # The user's own words come back, so a misheard instruction is visible+ # before the model has spent 20 s on it.+ assert spoken.split()[-1] in opening++ assert len(set(lines)) == len(lines), "three instructions, three openings"+++async def test_the_same_instruction_always_reads_the_same(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None: # noqa: ANN001+ """Varied per instruction, never per run — a random line cannot be pinned."""+ monkeypatch.setattr(prompt_composer, "_llm_compose", _brief)+ session = _session(tmp_path)++ async def opening() -> str:+ seen: list[prompt_composer.ComposeNotice] = []+ await prompt_composer.compose(+ "review the wake word detection",+ session=session,+ terminal_name="Kate",+ on_progress=seen.append,+ )+ return next(n.message for n in seen if n.stage == prompt_composer.STAGE_START)++ assert await opening() == await opening()+++async def test_a_broken_sink_never_costs_the_prompt(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None: # noqa: ANN001+ monkeypatch.setattr(prompt_composer, "_llm_compose", _brief)++ def _explode(_notice: prompt_composer.ComposeNotice) -> None:+ raise RuntimeError("the progress view is gone")++ result = await prompt_composer.compose(+ "review the wake word detection",+ session=_session(tmp_path),+ terminal_name="Kate",+ on_progress=_explode,+ )++ assert result.composed_by == "llm"+ assert result.text.startswith("## Task")+++async def test_the_typed_prompt_bar_stays_silent(tmp_path) -> None: # noqa: ANN001+ """Nothing is being written there — a progress line would be noise."""+ seen: list[prompt_composer.ComposeNotice] = []++ result = await prompt_composer.compose(+ "run the tests",+ session=_session(tmp_path),+ terminal_name="Kate",+ use_llm=False,+ on_progress=seen.append,+ )++ assert result.composed_by == "raw"+ assert seen == []+++async def test_degrading_is_announced_rather_than_hidden(+ tmp_path, monkeypatch: pytest.MonkeyPatch+) -> None: # noqa: ANN001+ """A plain brief is a fine outcome; a plain brief passed off as a written+ one is not — the readback afterwards would claim more than happened."""+ seen: list[prompt_composer.ComposeNotice] = []+ monkeypatch.setattr(prompt_composer, "_resolve_writer", lambda: None)++ result = await prompt_composer.compose(+ "review the wake word detection",+ session=_session(tmp_path),+ terminal_name="Kate",+ on_progress=seen.append,+ )++ assert result.composed_by == "fallback"+ closing = seen[-1]+ assert closing.stage == prompt_composer.STAGE_FALLBACK+ assert "Kate" in closing.message+ assert "quality-tier" in closing.message+ assert prompt_composer.STAGE_READY not in [n.stage for n in seen]+++ ("submitted", "expected"),+ [+ (True, "working on it"),+ (False, "never started"),+ (None, "could not confirm"),+ ],+)+async def test_the_closing_line_keeps_typed_and_started_apart(+ submitted: bool | None, expected: str+) -> None:+ """A prompt sitting in an input box looks exactly like a running task."""+ seen: list[prompt_composer.ComposeNotice] = []++ prompt_composer.announce_delivery(+ "Kate", delivered=True, submitted=submitted, sink=seen.append+ )++ assert len(seen) == 1+ assert seen[0].stage == prompt_composer.STAGE_SENT+ assert "Kate" in seen[0].message+ assert expected in seen[0].message+++async def test_an_undelivered_pane_says_why() -> None:+ seen: list[prompt_composer.ComposeNotice] = []++ prompt_composer.announce_delivery(+ "Kate", delivered=False, reason="its agent is exited, not running",+ sink=seen.append,+ )++ assert "Kate did not get it" in seen[0].message+ assert "exited" in seen[0].messagediff --git a/tests/unit/agentic_ide/test_drop_analysis.py b/tests/unit/agentic_ide/test_drop_analysis.pynew file mode 100644index 0000000000..b8fe54da64--- /dev/null+++ b/tests/unit/agentic_ide/test_drop_analysis.py@@ -0,0 +1,219 @@+"""``drop_analysis`` — reading what a dropped file actually contains.++The point of this module is that a coding agent gets the CONTENT of a dropped+screenshot, not just a path to it. So the tests care about two things above all:+that the content really travels, and that when it cannot (no vision-capable+provider, a failing one, a scanned PDF) the result says so out loud instead of+returning something that reads like a description.+"""+from __future__ import annotations++import pytest++from jarvis.agentic_ide import drop_analysis+from jarvis.agentic_ide.drop_analysis import DropAnalysis, analyze+from jarvis.brain.drop_context import DroppedItem+++class _Delta:+ def __init__(self, content: str) -> None:+ self.content = content+++class _SeeingBrain:+ """A vision-capable brain that reports what it was handed."""++ supports_vision = True++ def __init__(self, answer: str = "A login form with the submit button cut off.") -> None:+ self.answer = answer+ self.calls: list[object] = []++ async def complete(self, request): # noqa: ANN001, ANN201+ self.calls.append(request)+ yield _Delta(self.answer)+++class _BrokenBrain:+ supports_vision = True++ async def complete(self, request): # noqa: ANN001, ANN201+ raise RuntimeError("provider is down")+ yield # pragma: no cover - makes this an async generator+++def _image(name: str = "shot.png") -> DroppedItem:+ # A one-pixel PNG: real bytes, so nothing has to special-case a fake.+ data = (+ b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"+ b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00"+ b"\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82"+ )+ return DroppedItem(name=name, mime="image/png", data=data)+++async def test_image_is_described_and_the_description_travels() -> None:+ brain = _SeeingBrain()++ result = await analyze([(_image(), "@.jarvis/drops/shot.png")], brain=brain)++ assert len(result) == 1+ assert result[0].kind == "image"+ assert result[0].described_by == "vision"+ assert "submit button cut off" in result[0].detail+ # The reference has to survive alongside the description: an agent that CAN+ # open the picture should still be pointed at it.+ assert result[0].reference == "@.jarvis/drops/shot.png"+ assert len(brain.calls) == 1+ # The picture must actually reach the model — a text-only call would produce+ # a confident description of nothing.+ assert brain.calls[0].messages[0].images+++async def test_no_vision_provider_says_so_rather_than_inventing(monkeypatch) -> None:+ # The install every open-source downloader might have: keys that reach a+ # text-only provider and nothing that can see. ``brain=None`` means "resolve+ # one", so the absence has to be staged at the resolver.+ monkeypatch.setattr(drop_analysis, "_resolve_vision_brain", lambda: None)++ result = await analyze([(_image(), "@shot.png")], brain=None)++ assert len(result) == 1+ assert result[0].detail == ""+ assert result[0].described_by == "none"+ assert "not described" in result[0].note.lower()+++async def test_a_document_only_drop_never_resolves_a_vision_brain(monkeypatch) -> None:+ # Resolving one loads config and walks the provider registry; a drop with no+ # picture in it has no reason to pay for that.+ def _boom() -> None:+ raise AssertionError("a document-only drop must not resolve a vision brain")++ monkeypatch.setattr(drop_analysis, "_resolve_vision_brain", _boom)+ item = DroppedItem(name="notes.txt", mime="text/plain", data=b"hello")++ result = await analyze([(item, '"notes.txt"')], brain=None)++ assert result[0].described_by == "extraction"+++async def test_a_failing_provider_costs_the_description_and_nothing_else() -> None:+ result = await analyze([(_image(), "@shot.png")], brain=_BrokenBrain())++ assert len(result) == 1+ assert result[0].described_by == "none"+ assert result[0].note # honest, and names nothing it did not do+ assert "cut off" not in result[0].detail+++async def test_text_documents_are_extracted_without_a_model() -> None:+ item = DroppedItem(name="spec.md", mime="text/markdown", data=b"# Spec\nDo the thing.")++ result = await analyze([(item, '"spec.md"')], brain=None)++ assert result[0].kind == "text"+ assert result[0].described_by == "extraction"+ assert "Do the thing." in result[0].detail+++async def test_a_binary_file_is_reported_as_attached_not_as_read() -> None:+ item = DroppedItem(name="archive.zip", mime="application/zip", data=b"PK\x03\x04rest")++ result = await analyze([(item, '"archive.zip"')], brain=None)++ assert result[0].kind == "other"+ assert result[0].detail == ""+ assert "attached" in result[0].note.lower()+++async def test_images_beyond_the_cap_are_named_not_silently_dropped() -> None:+ brain = _SeeingBrain()+ pairs = [+ (_image(f"shot{i}.png"), f"@shot{i}.png")+ for i in range(drop_analysis.MAX_IMAGES_ANALYZED + 2)+ ]++ result = await analyze(pairs, brain=brain)++ # Every dropped file still comes back — the user saw a chip for each one.+ assert len(result) == len(pairs)+ described = [r for r in result if r.described_by == "vision"]+ assert len(described) == drop_analysis.MAX_IMAGES_ANALYZED+ skipped = [r for r in result if r.described_by == "none"]+ assert all(str(drop_analysis.MAX_IMAGES_ANALYZED) in r.note for r in skipped)+++async def test_a_mixed_drop_describes_the_image_and_extracts_the_document() -> None:+ brain = _SeeingBrain()+ pairs = [+ (_image(), "@shot.png"),+ (DroppedItem(name="notes.txt", mime="text/plain", data=b"line one"), '"notes.txt"'),+ ]++ result = await analyze(pairs, brain=brain)++ assert [r.kind for r in result] == ["image", "text"]+ assert result[0].described_by == "vision"+ assert result[1].described_by == "extraction"+++async def test_an_empty_drop_is_not_an_error() -> None:+ assert await analyze([]) == []+++async def test_a_long_extraction_is_shortened_and_says_that_it_was() -> None:+ body = b"x" * (drop_analysis.MAX_TOTAL_CHARS + 5_000)+ pairs = [+ (DroppedItem(name=f"big{i}.txt", mime="text/plain", data=body), f'"big{i}.txt"')+ for i in range(6)+ ]++ result = await analyze(pairs, brain=None)++ assert len(result) == len(pairs) # nothing falls off the end+ assert sum(len(r.detail) for r in result) <= drop_analysis.MAX_TOTAL_CHARS+ # Whatever the TOTAL budget cut has to admit it — a shortened file that+ # reads complete is exactly the quiet loss this bound must not cause. (A+ # file at the per-file cap is not "cut" in that sense; it is the normal+ # bounded extraction.)+ trimmed = [r for r in result if len(r.detail) < drop_analysis.MAX_TEXT_CHARS]+ assert trimmed+ assert all(r.note for r in trimmed)+++def test_from_dict_survives_a_malformed_payload() -> None:+ # The wire is a JSON body; a bad one must not 500 a prompt the user is+ # waiting on.+ item = DropAnalysis.from_dict({"name": "a.png", "kind": "nonsense", "detail": 5})++ assert item.name == "a.png"+ assert item.kind == "other"+ assert item.detail == ""+++def test_to_dict_and_back_is_lossless() -> None:+ original = DropAnalysis(+ name="shot.png",+ reference="@shot.png",+ kind="image",+ detail="what it shows",+ described_by="vision",+ )++ assert DropAnalysis.from_dict(original.to_dict()) == original+++ ("name", "mime", "expected"),+ [+ ("a.png", "image/png", "image"),+ # Drag-drop MIME is unreliable — a .py handed over as octet-stream is+ # still text, and the extension is what says so.+ ("a.py", "application/octet-stream", "text"),+ ("a.pdf", "application/octet-stream", "pdf"),+ ("a.bin", "application/octet-stream", "other"),+ ],+)+def test_kind_matches_the_shared_register(name: str, mime: str, expected: str) -> None:+ assert drop_analysis._kind_of(DroppedItem(name=name, mime=mime, data=b"x")) == expecteddiff --git a/tests/unit/agentic_ide/test_fanout_route.py b/tests/unit/agentic_ide/test_fanout_route.pyindex 940f1541e1..b6dbdfe448 100644--- a/tests/unit/agentic_ide/test_fanout_route.py+++ b/tests/unit/agentic_ide/test_fanout_route.py@@ -191,17 +191,15 @@ async def test_the_route_opens_the_fleet_it_needs(async def test_a_freshly_opened_pane_is_reported_as_not_yet_running(client: TestClient, registry: Registry, tmp_path: Path) -> None:- """KNOWN LIMIT, pinned so it cannot be mistaken for success.+ """With nothing able to MOUNT the panes, the route says so instead of lying.- A pane's agent process starts when the workspace VIEW mounts it, not when- the registry entry is created — so panes opened by this call are still- ``pending`` microseconds later and nothing can be typed into them yet.+ A pane's agent process starts when the workspace view mounts it, not when+ the registry entry is created. This client has no bus, so no view is ever+ told the panes exist and none of them can come up — waiting would only turn+ an honest "not_running" into a slow one.- The route reports that truthfully rather than claiming a briefed fleet, and- that honesty is what this test pins. What it does NOT yet do is wait for- the panes to come up and brief them once they have; until it does,- spawn+brief in one call opens the fleet and briefs nobody. Delivering after- the panes go live is the remaining piece of this feature.+ When there IS a bus, the route waits for the panes and briefs them; that is+ ``test_fanout_opens_and_briefs_a_pane_in_one_call`` below."""await _live_workspace(registry, tmp_path, 1)@@ -274,3 +272,131 @@ async def test_dry_run_plans_without_typing_anything(assert len(body["split"]["assignments"]) == 2assert registry.session is not Noneassert all(t.prompts_sent == 0 for t in registry.session.terminals)+++# ------------------------------------------------- prompting a pane that is not there+# A live voice session on 2026-07-27 asked for a pane called "Lee", which was+# not running. The prompt 404'd with a bare "no terminal called that", the caller+# read it as "then open one", and call-signs come from a fixed pool — so the pane+# it opened was called something else and the very same prompt failed again. Four+# rounds later the workspace had four blank panes and nobody had been briefed.+# The error now names the move that actually recovers, and it says the same thing+# whether or not composition was asked for.+++async def test_prompting_an_unknown_pane_says_how_to_recover(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ names = await _live_workspace(registry, tmp_path, 2)++ response = client.post(+ "/api/agentic-ide/terminals/Lee/prompt",+ json={"prompt": "do a deep dive", "compose": False},+ )++ assert response.status_code == 404+ detail = response.json()["detail"]+ assert "No terminal called 'Lee'" in detail+ assert all(name in detail for name in names), "the running panes are named"+ assert "cannot be requested" in detail, "opening a pane will not create this name"+ assert "/api/agentic-ide/fanout" in detail, "the one call that does recover"+++async def test_the_unknown_pane_error_does_not_depend_on_composition(+ client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ """One cause, one answer.++ Composition used to decide the shape of this failure: 404 with it on, 409+ with it off. Two different-looking dead ends for one cause is how a caller+ learns to retry instead of to recover.+ """+ await _live_workspace(registry, tmp_path, 1)++ composed = client.post(+ "/api/agentic-ide/terminals/Lee/prompt",+ json={"prompt": "do a deep dive", "compose": True},+ )+ verbatim = client.post(+ "/api/agentic-ide/terminals/Lee/prompt",+ json={"prompt": "do a deep dive", "compose": False},+ )++ assert composed.status_code == verbatim.status_code == 404+ assert composed.json()["detail"] == verbatim.json()["detail"]+++class _MountingBus:+ """A bus whose subscriber behaves like the workspace view: it MOUNTS panes.++ That is the whole mechanism the route depends on — the view hears about new+ panes, mounts them, and their agents start. Simulating it here is what makes+ "open one and brief it" testable end to end instead of only up to the point+ where the old code gave up.+ """++ def __init__(self, registry: Registry) -> None:+ self._registry = registry+ self.sections: list[str] = []++ async def publish(self, event: object) -> None:+ section = getattr(event, "section", None)+ if section is not None:+ self.sections.append(section)+ return+ for name in getattr(event, "names", ()):+ await self._registry.attach(name, 100, 30, _noop, _noop_exit)+++def mounting_client(registry: Registry) -> TestClient:+ from jarvis.ui.web.agentic_ide_routes import router++ app = FastAPI()+ app.include_router(router)+ app.state.bus = _MountingBus(registry)+ return TestClient(app)+++async def test_fanout_opens_and_briefs_a_pane_in_one_call(+ mounting_client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ """The recovery the 404 points at has to actually work in one step.++ This is the whole answer to "if no terminal is called that, open one and+ prompt it": the reply carries the call-sign the new pane was really given,+ so the caller never has to guess a name that was never available to it —+ and the pane is actually briefed, which is what "in one call" has to mean.+ """+ await _live_workspace(registry, tmp_path, 1)++ response = mounting_client.post(+ "/api/agentic-ide/fanout",+ json={"instruction": "investigate the empty area", "spawn": [{"count": 1}]},+ )++ assert response.status_code == 200+ body = response.json()+ opened = [t["name"] for t in body["opened"]]+ assert len(opened) == 1+ assert body["ok"] is True+ assert [d["terminal"] for d in body["delivered"]] == opened+ assert body["undelivered"] == []+++async def test_opening_panes_brings_the_workspace_forward(+ mounting_client: TestClient, registry: Registry, tmp_path: Path+) -> None:+ """A workspace behind another section never starts the panes it just got.++ The mount is what starts a pane's agent, so a fan-out that opens panes+ without bringing the view forward can be relied on to brief nobody.+ """+ await _live_workspace(registry, tmp_path, 1)++ mounting_client.post(+ "/api/agentic-ide/fanout",+ json={"instruction": "investigate the empty area", "spawn": [{"count": 1}]},+ )++ assert mounting_client.app.state.bus.sections == ["agentic-ide"]diff --git a/tests/unit/agentic_ide/test_fleet_actions.py b/tests/unit/agentic_ide/test_fleet_actions.pynew file mode 100644index 0000000000..e7ca043663--- /dev/null+++ b/tests/unit/agentic_ide/test_fleet_actions.py@@ -0,0 +1,74 @@+from __future__ import annotations++from dataclasses import dataclass, field++import pytest++from jarvis.agentic_ide.fleet_actions import (+ close_agent_terminals,+ wait_for_prompt_ready,+)+++class _Transcript:+ def __init__(self, lines: list[str]) -> None:+ self._lines = lines++ def tail(self, _count: int) -> list[str]:+ return self._lines+++@dataclass+class _Term:+ name: str+ agent: str+ status: str = "live"+ pty_id: str | None = "pty"+ transcript: _Transcript = field(default_factory=lambda: _Transcript([]))+++class _Session:+ def __init__(self, terms: list[_Term]) -> None:+ self.terminals = terms++ def find(self, name: str) -> _Term | None:+ return next((term for term in self.terminals if term.name == name), None)+++async def test_codex_waits_for_its_input_line_but_claude_does_not() -> None:+ codex = _Term("Cody", "codex")+ claude = _Term("Clara", "claude")+ session = _Session([codex, claude])++ assert await wait_for_prompt_ready(session, ["Cody", "Clara"], timeout_s=0) == (+ "Clara",+ )++ codex.transcript = _Transcript(["OpenAI Codex", "› "])+ assert await wait_for_prompt_ready(session, ["Cody", "Clara"], timeout_s=0) == (+ "Cody",+ "Clara",+ )+++async def test_close_agent_terminals_only_closes_the_requested_cli() -> None:+ class _Registry:+ def __init__(self) -> None:+ self.session = _Session(+ [_Term("Cody", "codex"), _Term("Clara", "claude"), _Term("Cole", "codex")]+ )++ async def close_terminal(self, name: str) -> _Term:+ term = self.session.find(name)+ assert term is not None+ self.session.terminals.remove(term)+ return term++ registry = _Registry()++ closed = await close_agent_terminals(registry, "codex")++ assert [term.name for term in closed] == ["Cody", "Cole"]+ assert [term.name for term in registry.session.terminals] == ["Clara"]diff --git a/tests/unit/agentic_ide/test_intent.py b/tests/unit/agentic_ide/test_intent.pyindex 277dafa58a..4415eb0ae7 100644--- a/tests/unit/agentic_ide/test_intent.py+++ b/tests/unit/agentic_ide/test_intent.py@@ -270,3 +270,148 @@ def test_a_request_to_divide_the_work_is_recognised(utterance: str) -> None:)def test_ordinary_orders_are_not_split_requests(utterance: str) -> None:assert intent.wants_split(utterance) is False+++# --------------------------------------------------------------------------- #+# A name that belongs to a running pane IS that pane #+# --------------------------------------------------------------------------- #+# Live failure 2026-07-27 (voice session 16:53): asked "Was hat Dana gemacht?"+# with a terminal called Dana running, Jarvis answered that it did not know+# which person Dana was. The utterance is ordinary spoken German in the perfect+# tense, and every report template was written in the present — `\bmacht` finds+# nothing inside "gemacht", because there is no word boundary after "ge".+#+# The lesson pinned here is bigger than one tense: enumerating verbs is what+# failed, so the general rule is that a QUESTION naming a running pane is about+# that pane, whatever verb it happens to carry.+++ ("utterance", "terminal"),+ [+ # The verbatim live failure.+ ("Was hat Dana gemacht?", "Dana"),+ # The same question in the other tenses and locales.+ ("Was hat Dana gestern gemacht?", "Dana"),+ ("Was hat Alex gebaut?", "Alex"),+ ("What did Dana do?", "Dana"),+ ("What has Blake been up to?", "Blake"),+ ("Que hizo Dana?", "Dana"),+ # No verb of doing at all — the name and the question mark are enough.+ ("Was ist mit Casey?", "Casey"), # i18n-allow: German speech input under test+ ("Wie weit ist Alex?", "Alex"), # i18n-allow: German speech input under test+ ("Dana?", "Dana"),+ ],+)+def test_a_question_naming_a_pane_is_a_report_about_it(+ utterance: str, terminal: str+) -> None:+ found = intent.detect(utterance, names=NAMES)+ assert found is not None, utterance+ assert found.terminal == terminal+ # READ, never write: the question must never be typed into the agent.+ assert found.kind == intent.KIND_REPORT+++ "utterance",+ [+ # A surname makes it a person, even though a pane shares the first name.+ "Was hat Dana Schmidt gemacht?",+ # Somebody out in the world who shares no name with any pane.+ "Was hat Elon Musk gemacht?",+ "Was hat der Bundeskanzler gemacht?", # i18n-allow: German speech input under test+ # A question with no call-sign in it at all.+ "Was hast du heute gemacht?", # i18n-allow: German speech input under test+ "Wie ist das Wetter?", # i18n-allow: German speech input under test+ ],+)+def test_a_question_about_the_world_is_not_a_pane_report(utterance: str) -> None:+ assert intent.detect(utterance, names=NAMES) is None+ assert intent.owns_turn(utterance, names=NAMES) is False+++def test_addressing_still_outranks_the_question_reading() -> None:+ """A question that HANDS WORK over stays a prompt, not a status read."""+ found = intent.detect("Kannst du das an Dana schicken?", names=NAMES)+ assert found is not None+ assert found.terminal == "Dana"+ assert found.kind == intent.KIND_PROMPT+++# --------------------------------------------------------------------------- #+# A polite order is still an order #+# --------------------------------------------------------------------------- #+# Live failure (voice session 2026-07-27 18:01): "Could you please prompt this+# terminal Alex, do a deep dive ...?" reached nobody. "prompt" — the verb that+# literally names this feature — carried no addressing shape, so the trailing+# question mark sent the turn into the read-only branch, the fast path stood+# down, and the live model answered "I have let Alex know" while Alex's pane+# still showed its startup banner. Politeness is how people give orders out+# loud, and a question mark must never be the thing that swallows one.++LIVE_FAILURE_POLITE_PROMPT = (+ "Could you please prompt this terminal Alex, do a deep dive and analyze "+ "all our whole code base and look for security vulnerabilities which can "+ "come up when using personal Jarvis?"+)+++def test_a_polite_prompt_request_reaches_the_pane_it_names() -> None:+ """The exact 2026-07-27 utterance must be typed into Alex, not read back."""+ found = intent.detect(LIVE_FAILURE_POLITE_PROMPT, names=NAMES)+ assert found is not None+ assert found.terminal == "Alex"+ assert found.kind == intent.KIND_PROMPT+ assert intent.owns_turn(LIVE_FAILURE_POLITE_PROMPT, names=NAMES) is True+ # The pane noun is part of the address, not of the work: an agent briefed+ # with "this terminal do a deep dive" reads it as an order to open one.+ assert "terminal" not in found.instruction.lower()+ assert "deep dive" in found.instruction.lower()+++def test_a_polite_prompt_request_is_not_a_terminal_spawn() -> None:+ """Naming a pane outranks the terminal noun the sentence also carries."""+ assert intent.detect_spawn(LIVE_FAILURE_POLITE_PROMPT, names=NAMES) is None+++ ("utterance", "terminal"),+ [+ # The briefing verb sits too far from the name for any anchored+ # template — the un-anchored backstop is what carries these.+ ("Could you prompt the terminal that is called Blake to fix the tests?", "Blake"),+ ("Kannst du Alex bitte anweisen, den Wake-Pfad zu pruefen?", "Alex"), # i18n-allow: input+ ("Instruct Casey to refactor the vosk provider", "Casey"),+ ("Prompte Dana mal bitte, sie soll die Tests fixen", "Dana"), # i18n-allow: input+ ],+)+def test_briefing_verbs_hand_work_over_across_locales(+ utterance: str, terminal: str+) -> None:+ found = intent.detect(utterance, names=NAMES)+ assert found is not None, utterance+ assert found.terminal == terminal+ assert found.kind == intent.KIND_PROMPT+++def test_a_polite_question_about_a_pane_is_still_a_read() -> None:+ """The backstop must not swallow reads phrased as a request.++ "ask" has a status-question reading and is deliberately NOT a briefing+ verb; without that distinction, wanting to know what an agent is doing+ would type the question into it.+ """+ utterance = "Kannst du Alex fragen, was er macht?" # i18n-allow: German input+ found = intent.detect(utterance, names=NAMES)+ assert found is not None+ assert found.terminal == "Alex"+ assert found.kind == intent.KIND_REPORT+++def test_a_pane_named_in_a_sentence_about_a_person_still_reaches_the_pane() -> None:+ """One occurrence carrying a surname must not disown the other."""+ # i18n-allow: German speech input under test+ found = intent.detect("Frag Dana, ob Dana Schmidt geantwortet hat", names=NAMES)+ assert found is not None+ assert found.terminal == "Dana"diff --git a/tests/unit/agentic_ide/test_intent_phrasebook.py b/tests/unit/agentic_ide/test_intent_phrasebook.pynew file mode 100644index 0000000000..9cfe0808a6--- /dev/null+++ b/tests/unit/agentic_ide/test_intent_phrasebook.py@@ -0,0 +1,239 @@+"""A phrasebook guard: does the workspace understand how people actually talk?++The other intent tests each pin ONE shape that once broke. This file asks the+broader question that keeps producing those breaks — given the many ways a+person can hand work to a coding agent, ask what it is doing, or ask for more+panes, does every one of them reach the right path?++It exists because the failures in this area all look the same from the outside+and all have the same cause: a phrasing nobody had written a template for+produces NO match, the deterministic fast path stands down without a word, and+the live model fills the silence by claiming something happened. The user hears+a confident sentence and finds an idle terminal. A miss here is never visible+as a miss, which is exactly why it needs a broad, boring guard rather than+another single-case regression test.++Two properties make this a phrasebook rather than a wishlist:++* every case is routed through ``_classify``, which mirrors the ORDER the brain+ actually applies (close, then spawn, then addressed delivery) — a detector+ that answers correctly in isolation but loses the turn to an earlier gate is+ still a bug, and only the ordered view can see it;+* the negative cases carry the same weight as the positive ones. Widening a+ detector until every phrasing lands is easy and wrong: a false positive types+ a stranger's sentence into a running coding agent, which is worse than any+ miss. The unrelated block is what keeps the widening honest.++German and Spanish utterances here are speech-recognition input vocabulary —+the words a person literally says — not prose (CLAUDE.md §1, closed list item+3). They are the content under test.+"""+from __future__ import annotations++import pytest++from jarvis.agentic_ide import intent++NAMES = ["Alex", "Blake", "Casey", "Dana"]+++def _classify(text: str) -> str:+ """The path this utterance takes, in the order the brain applies them.++ Mirrors ``BrainManager``: the close fast path runs first (so "all" cannot+ become a prompt typed into the very panes being stopped), then the spawn+ fast path, then addressed delivery. Returns ``"none"`` when the workspace+ declines the turn.+ """+ if intent.detect_close_fleet(text) is not None:+ return "close"+ if intent.detect_spawn(text, names=NAMES) is not None:+ return "spawn"+ found = intent.detect_all(text, names=NAMES)+ return found[0].kind if found else "none"+++# --------------------------------------------------------------------------- #+# Handing work to a named pane #+# --------------------------------------------------------------------------- #++PROMPTS_DE = [+ "Sag Alex, er soll die Tests laufen lassen",+ "Alex soll mal schauen warum der Wake-Pfad nicht geht",+ "Gib Alex die Aufgabe den Bug zu fixen",+ "Alex, mach mal einen Review vom Audio-Code",+ "Lass Alex das übernehmen und die Tests fixen",+ "Beauftrage Alex mit dem Refactoring",+ "Setz Alex mal auf den Wake-Bug an",+ "Alex übernimmt den Wake-Bug",+ "Alex müsste mal die Doku aktualisieren",+ "Alex darf gerne den Wake-Bug untersuchen",+ "Ich möchte dass Alex den Wake-Pfad prüft",+ # The modal in FRONT of the call-sign — the ordinary spoken order, and the+ # one every name-anchored template used to miss.+ "Kann Alex mal die Tests fixen?",+ "Könnte Alex bitte den Code prüfen?",+ # The German sentence bracket: the handing-over verb lands at the end.+ "Kannst du Alex bitte sagen, dass er einen Deep Dive machen soll?",+ "Würdest du Alex bitten die Tests zu fixen?",+]++PROMPTS_EN = [+ "Tell Alex to run the tests",+ "Alex should look into the wake path",+ "Have Alex review the audio code",+ "Get Alex to fix the failing test",+ "Ask Alex to check the config",+ "Can Alex look at the wake bug?",+ "Could Alex please check the vosk provider?",+ "I want Alex to analyze the codebase",+ "I need Alex to fix the wake path",+ "Put Alex on the security audit",+ "Point Alex at the security audit",+ "Alex, take a look at the vosk provider",+ "Would you have Alex do a deep dive on the audio code?",+ "Alex needs to fix the failing tests",+ "Let's have Alex take the wake path",+]++PROMPTS_ES = [+ "Dile a Alex que revise el codigo",+ "Alex deberia revisar el codigo de audio",+ "Pidele a Alex que arregle los tests",+ "Que Alex analice el area de audio",+ "Encargale a Alex la auditoria de seguridad",+ "Puede Alex revisar el wake path?",+]+++ "utterance", PROMPTS_DE + PROMPTS_EN + PROMPTS_ES # i18n-allow: input vocab+)+def test_work_handed_to_a_named_pane_is_delivered(utterance: str) -> None:+ """Every way of assigning work must reach the pane, not a status read."""+ assert _classify(utterance) == intent.KIND_PROMPT, utterance+ found = intent.detect(utterance, names=NAMES)+ assert found is not None and found.terminal == "Alex", utterance+ # The router's precedence gate has to agree, or force-spawn takes the turn+ # and the work becomes an invisible background mission.+ assert intent.owns_turn(utterance, names=NAMES) is True, utterance+++# --------------------------------------------------------------------------- #+# Asking what a pane is up to #+# --------------------------------------------------------------------------- #++REPORTS = [+ "Was macht Alex gerade?", # i18n-allow: input vocab+ "Ist Alex fertig?", # i18n-allow: input vocab+ "Wie weit ist Alex?", # i18n-allow: input vocab+ "Was hat Alex rausgefunden?", # i18n-allow: input vocab+ "Läuft Alex noch?", # i18n-allow: input vocab+ "Hat Alex schon was gefunden?", # i18n-allow: input vocab+ "Alex Status?",+ "What is Alex doing?",+ "Is Alex done yet?",+ "Any progress from Alex?",+ "Que hizo Alex?",+ # Politeness does not make a question an order — "ask" is deliberately not+ # a briefing verb, because this is a read and typing it into Alex would+ # both lose the answer and waste the agent's turn.+ "Kannst du Alex fragen, was er macht?", # i18n-allow: input vocab+]++[email protected]("utterance", REPORTS)+def test_questions_about_a_pane_stay_read_only(utterance: str) -> None:+ """A status question must never be typed into the agent it asks about."""+ assert _classify(utterance) == intent.KIND_REPORT, utterance+++# --------------------------------------------------------------------------- #+# Asking for more panes, and for fewer #+# --------------------------------------------------------------------------- #++SPAWNS = [+ "Mach mal drei neue Terminals auf", # i18n-allow: input vocab+ "Spawne fünf Claude Code Terminals", # i18n-allow: input vocab+ "Öffne noch zwei Terminals", # i18n-allow: input vocab+ "Ich brauche noch ein Terminal", # i18n-allow: input vocab+ "Gib mir drei Codex Terminals", # i18n-allow: input vocab+ "Ich hätte gern noch zwei Claude Terminals", # i18n-allow: input vocab+ "Open three more terminals",+ "Can you open five terminals?",+ "Add two more panes",+ "Abre tres terminales mas",+ "Starte fünf Agenten die den Code analysieren und teilt euch auf", # i18n-allow: input vocab+]++[email protected]("utterance", SPAWNS)+def test_asking_for_more_panes_opens_them(utterance: str) -> None:+ assert _classify(utterance) == "spawn", utterance+++CLOSES = [+ "Schließ alle Terminals", # i18n-allow: input vocab+ # German closes with a separable verb, so the particle lands at the end and+ # the stem is the OPEN verb. This exact sentence used to open panes.+ "Mach alle Terminals zu", # i18n-allow: input vocab+ "Close all the terminals",+ "Cierra todos los terminales",+]++[email protected]("utterance", CLOSES)+def test_closing_the_fleet_never_opens_more(utterance: str) -> None:+ """Watching the opposite of your request happen is the worst kind of miss."""+ assert _classify(utterance) == "close", utterance+++def test_a_spoken_count_survives_every_umlaut_spelling() -> None:+ """The same request must open the same number of panes however it is typed.++ Voice transcripts carry the real character; typed turns reach the very same+ detectors from a keyboard without a German layout.+ """+ for spelling in ("fünf", "funf", "fuenf"): # i18n-allow: input vocab+ request = intent.detect_spawn(+ f"Mach mal {spelling} neue Terminals auf", names=NAMES # i18n-allow: input vocab+ )+ assert request is not None, spelling+ assert request.count == 5, spelling+++# --------------------------------------------------------------------------- #+# What the workspace must keep its hands off #+# --------------------------------------------------------------------------- #+# The counterweight to everything above. Each widening of a detector is only+# safe while these still answer "none": a false positive types a stranger's+# sentence into a running coding agent, which no user can undo.++UNRELATED = [+ "Wie ist das Wetter heute?", # i18n-allow: input vocab+ "Was hat Elon Musk gemacht?", # i18n-allow: input vocab+ "Erklär mir bitte wie Vosk funktioniert", # i18n-allow: input vocab+ "Alex ist ein schöner Name für ein Kind", # i18n-allow: input vocab+ "Mach einen Deep Dive in meine Google Cloud Kosten", # i18n-allow: input vocab+ "Was hat Alex Schmidt gestern gesagt?", # i18n-allow: input vocab+ "Kannst du prüfen ob der Server läuft?", # i18n-allow: input vocab+]++[email protected]("utterance", UNRELATED)+def test_turns_that_are_not_the_workspaces_are_left_alone(utterance: str) -> None:+ assert _classify(utterance) == "none", utterance+ assert intent.owns_turn(utterance, names=NAMES) is False, utterance+++SPAWN_VEHICLE = [+ "Spawne einen Subagenten der Alex hilft", # i18n-allow: input vocab+ "Start a background agent to review this",+ "Delegiere das an einen Worker", # i18n-allow: input vocab+]++[email protected]("utterance", SPAWN_VEHICLE)+def test_an_explicit_background_request_still_gets_a_worker(utterance: str) -> None:+ """Widening the workspace must not swallow a genuine mission request."""+ assert intent.owns_turn(utterance, names=NAMES) is False, utterancediff --git a/tests/unit/agentic_ide/test_names.py b/tests/unit/agentic_ide/test_names.pyindex e5b0ef7c1d..b250b66065 100644--- a/tests/unit/agentic_ide/test_names.py+++ b/tests/unit/agentic_ide/test_names.py@@ -114,9 +114,8 @@ def test_name_embedded_in_a_sentence_is_found() -> None:# A German utterance is the point of this case: the resolver has to find a# call-sign inside whatever language the user speaks, so the sentence around# the name is speech-recognition input vocabulary, not prose.- assert resolve( # i18n-allow: spoken input vocabulary under test- "sag nova sie soll die tests laufen lassen", ["Mika", "Nova"]- ) == "Nova"+ utterance = "sag nova sie soll die tests laufen lassen" # i18n-allow: input vocab+ assert resolve(utterance, ["Mika", "Nova"]) == "Nova"def test_unrelated_words_resolve_to_nothing() -> None:diff --git a/tests/unit/agentic_ide/test_plain_terminal.py b/tests/unit/agentic_ide/test_plain_terminal.pynew file mode 100644index 0000000000..6a058df991--- /dev/null+++ b/tests/unit/agentic_ide/test_plain_terminal.py@@ -0,0 +1,171 @@+"""A pane that runs this machine's shell instead of a coding agent.++Three things have to hold, and each one has bitten a terminal product before:++1. A plain terminal launches the SHELL, not a shell wrapped around an agent.+2. It is a first-class pane — its own process, its own call-sign, closable and+ countable like any other.+3. Jarvis never types into it. A plain terminal is a live shell prompt, so an+ injected line would not be read, it would RUN — which would turn the one+ keystroke channel voice can reach into arbitrary command execution.+"""+from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.agentic_ide import session as session_mod+from jarvis.agentic_ide.session import PLAIN_TERMINAL, Registry, SessionError+from tests.fakes.fake_pty_manager import FakePtyManager+++def fake_pty() -> FakePtyManager:+ return FakePtyManager()+++def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Registry:+ # Both coding CLIs "installed", so these tests do not depend on the machine+ # running them. The plain terminal keeps its real argv resolution — that is+ # part of what is under test.+ real_argv = session_mod.agent_argv++ def _argv(name: str):+ return (f"/usr/bin/{name}",) if name in session_mod.AGENT_BINARIES else real_argv(name)++ monkeypatch.setattr(session_mod, "agent_argv", _argv)+ return Registry(pty_manager=fake_pty)+++# --------------------------------------------------------------- what it runs+def test_it_is_offered_as_a_runnable_that_takes_no_prompts() -> None:+ assert session_mod.is_runnable(PLAIN_TERMINAL)+ assert session_mod.agent_display(PLAIN_TERMINAL) == "Plain Terminal"+ assert session_mod.accepts_prompts(PLAIN_TERMINAL) is False+ assert session_mod.accepts_prompts("claude") is True+++def test_argv_is_the_host_shell_with_no_agent_wrapped_around_it() -> None:+ from jarvis.terminal.shells import default_shell++ shell = default_shell()+ assert shell is not None, "the test host has no shell"+ assert session_mod.agent_argv(PLAIN_TERMINAL) == tuple(shell.argv)+++# ------------------------------------------------------------- as a real pane+async def test_a_split_can_open_one_beside_an_agent(+ registry: Registry, tmp_path: Path, fake_pty: FakePtyManager+) -> None:+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])+ term = await registry.add_terminal(anchor="Alex", direction="right", agent=PLAIN_TERMINAL)++ assert term.agent == PLAIN_TERMINAL+ assert term.display_name == "Plain Terminal"+ # A pane of its own, not a view of the agent's: its own call-sign, its own+ # column, and no account to bill.+ assert term.name != "Alex"+ assert term.column == 1+ assert term.account is None+ assert len(registry.session.terminals) == 2+++async def test_it_spawns_its_own_process(+ registry: Registry, tmp_path: Path, fake_pty: FakePtyManager+) -> None:+ """Every terminal is a separate child — the shell pane included."""+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])+ plain = await registry.add_terminal(anchor="Alex", direction="right", agent=PLAIN_TERMINAL)++ async def _out(_text: str) -> None: ...++ async def _exit(_code: int) -> None: ...++ agent_pane = await registry.attach("alex", 80, 24, _out, _exit)+ shell_pane = await registry.attach(plain.key, 80, 24, _out, _exit)++ assert agent_pane.pty_id and shell_pane.pty_id+ assert agent_pane.pty_id != shell_pane.pty_id+ assert shell_pane.status == "live"+ # ...and it is the shell that was started, not a coding CLI.+ argv = " ".join(fake_pty.spawns[-1]["argv"])+ assert "claude" not in argv+ assert "codex" not in argv+++async def test_a_workspace_can_be_opened_with_one_from_the_start(+ registry: Registry, tmp_path: Path+) -> None:+ session = await registry.start(+ str(tmp_path), [{"agent": "claude"}, {"agent": PLAIN_TERMINAL}]+ )+ assert [t.agent for t in session.terminals] == ["claude", PLAIN_TERMINAL]+++# -------------------------------------------------------- the injection guard+async def test_jarvis_refuses_to_type_into_a_shell(+ registry: Registry, tmp_path: Path+) -> None:+ await registry.start(str(tmp_path), [{"agent": "claude", "name": "Alex"}])+ plain = await registry.add_terminal(anchor="Alex", direction="right", agent=PLAIN_TERMINAL)++ async def _out(_text: str) -> None: ...++ async def _exit(_code: int) -> None: ...++ await registry.attach(plain.key, 80, 24, _out, _exit)+ assert plain.status == "live" # refused because of WHAT it is, not its state++ with pytest.raises(SessionError) as excinfo:+ await registry.send_prompt(plain.name, "rm -rf /")+ assert "shell" in str(excinfo.value).lower()+ assert plain.prompts_sent == 0+++async def test_the_pane_payload_says_it_takes_no_prompts(+ registry: Registry, tmp_path: Path+) -> None:+ """The UI needs this to keep such a pane out of the prompt bar's targets."""+ session = await registry.start(+ str(tmp_path), [{"agent": "claude"}, {"agent": PLAIN_TERMINAL}]+ )+ payload = {t["agent"]: t for t in session.to_dict()["terminals"]}+ assert payload["claude"]["accepts_prompts"] is True+ assert payload[PLAIN_TERMINAL]["accepts_prompts"] is False+++async def test_a_fleet_order_skips_it_with_an_honest_reason(+ registry: Registry, tmp_path: Path+) -> None:+ """Naming one in "everyone, do X" costs neither a composition nor a crash."""+ from jarvis.agentic_ide import fanout++ session = await registry.start(+ str(tmp_path),+ [{"agent": "claude", "name": "Alex"}, {"agent": PLAIN_TERMINAL, "name": "Nova"}],+ )++ composed: list[str] = []++ async def _compose(utterance: str, **kwargs): # noqa: ANN001, ANN202+ composed.append(kwargs.get("terminal_name", ""))+ raise AssertionError("a plain terminal must never reach composition")++ result = await fanout.deliver(+ session=session,+ terminals=["Nova"],+ utterance="run the tests",+ compose=_compose,+ send=lambda name, text: None, # type: ignore[arg-type]+ )+ assert composed == []+ assert result.undelivered+ assert result.undelivered[0].reason_code == "not_an_agent"diff --git a/tests/unit/agentic_ide/test_prompt_attachments.py b/tests/unit/agentic_ide/test_prompt_attachments.pynew file mode 100644index 0000000000..94ad737af7--- /dev/null+++ b/tests/unit/agentic_ide/test_prompt_attachments.py@@ -0,0 +1,151 @@+"""Dropped files reaching the composed prompt.++A described screenshot that does not make it into the brief has cost the user+the drop AND the model call that described it, while looking like it worked. So+these pin the one thing that matters: the contents travel on BOTH layers — the+model-written brief and the deterministic one — because the model that describes+a picture and the model that writes prose are separate providers, and having one+without the other is an ordinary install, not an edge case.+"""+from __future__ import annotations++from jarvis.agentic_ide import prompt_blueprint as blueprint+from jarvis.agentic_ide.drop_analysis import DropAnalysis+++def _described(name: str = "shot.png") -> DropAnalysis:+ return DropAnalysis(+ name=name,+ reference=f"@.jarvis/drops/{name}",+ kind="image",+ detail="The submit button overflows its container and the label reads 'Sign inn'.",+ described_by="vision",+ )+++def _extracted(name: str = "spec.md") -> DropAnalysis:+ return DropAnalysis(+ name=name,+ reference=f'"{name}"',+ kind="text",+ detail="The endpoint must return 202 on success.",+ described_by="extraction",+ )+++def _undescribed(name: str = "photo.png") -> DropAnalysis:+ return DropAnalysis(+ name=name,+ reference=f"@{name}",+ kind="image",+ note="No provider that can see images is reachable, so this one was attached.",+ )+++class TestWriterBlock:+ """What the writing model is shown."""++ def test_the_description_and_the_reference_both_reach_the_writer(self) -> None:+ block = blueprint.attachment_block([_described()])++ assert "submit button overflows" in block+ assert "@.jarvis/drops/shot.png" in block++ def test_an_undescribed_file_shows_its_reason_not_a_blank(self) -> None:+ block = blueprint.attachment_block([_undescribed()])++ assert "attached" in block+ assert "None" not in block++ def test_no_attachments_produces_no_block(self) -> None:+ assert blueprint.attachment_block([]) == ""++ def test_the_user_block_carries_the_attachment_and_its_rules(self) -> None:+ text = blueprint.user_block(+ utterance="fix this",+ instruction="fix this",+ terminal_name="Mika",+ agent_display="Claude Code",+ profile_lines=[],+ candidates=[],+ skeletons={},+ house_rules="",+ attachments=[_described()],+ )++ assert "submit button overflows" in text+ # The rules are what stop the writer from producing "the screenshot the+ # user dropped" and calling it a brief.+ assert "VERBATIM" in text++ def test_the_attachment_rules_stay_out_of_a_prompt_with_no_attachment(self) -> None:+ text = blueprint.user_block(+ utterance="run the tests",+ instruction="run the tests",+ terminal_name="Mika",+ agent_display="Claude Code",+ profile_lines=[],+ candidates=[],+ skeletons={},+ house_rules="",+ )++ assert "DROPPED" not in text+ assert "attachment" not in text.lower()+++class TestDeterministicLayer:+ """The layer a downloader with no writing model actually gets."""++ def test_the_description_survives_with_no_writing_model(self) -> None:+ text = blueprint.render_fallback("fix the layout", [], [_described()])++ assert "submit button overflows" in text+ assert "shot.png" in text++ def test_extracted_document_text_survives_too(self) -> None:+ text = blueprint.render_fallback("implement it", [], [_extracted()])++ assert "must return 202" in text++ def test_an_undescribed_file_is_still_named(self) -> None:+ text = blueprint.render_fallback("fix the layout", [], [_undescribed()])++ assert "photo.png" in text+ assert "attached" in text++ def test_attachments_and_file_references_coexist(self) -> None:+ text = blueprint.render_fallback("fix it", ["src/Login.tsx"], [_described()])++ assert "submit button overflows" in text+ assert "@src/Login.tsx" in text++ def test_the_prompt_never_ends_on_a_reference(self) -> None:+ # A trailing @path holds the agent's completion popup open and eats the+ # Enter that follows.+ text = blueprint.render_fallback("fix it", ["src/Login.tsx"], [_described()])++ assert not blueprint.ends_on_reference(text)++ def test_no_instruction_but_a_dropped_file_still_produces_a_prompt(self) -> None:+ # Dropping a file and sending without typing is a real gesture; it must+ # not silently produce an empty prompt.+ text = blueprint.render_fallback("", [], [_described()])++ assert "submit button overflows" in text++ def test_nothing_at_all_stays_empty(self) -> None:+ assert blueprint.render_fallback("", [], []) == ""++ def test_the_body_cap_is_respected(self) -> None:+ huge = DropAnalysis(+ name="big.txt",+ reference='"big.txt"',+ kind="text",+ detail="x" * 50_000,+ described_by="extraction",+ )++ text = blueprint.render_fallback("read it", [], [huge])++ assert len(text) <= blueprint.MAX_BODY_CHARSdiff --git a/tests/unit/agentic_ide/test_prompt_composer.py b/tests/unit/agentic_ide/test_prompt_composer.pyindex 9ebba79815..38326b8cf6 100644--- a/tests/unit/agentic_ide/test_prompt_composer.py+++ b/tests/unit/agentic_ide/test_prompt_composer.py@@ -160,15 +160,22 @@ async def test_a_fenced_or_quoted_answer_is_unwrapped() -> None:_prime(workspace)+ # A BRIEF inside the fence, not a bare sentence: the composer rejects output+ # with no heading as debris (``looks_like_brief``), so a one-line payload+ # would take the fallback and this would be testing that instead of the+ # unwrapping it is named for.+ brief = "## Task\nReview the wake word detection."+async def _fenced(**_kwargs: object) -> str:- return "```\nReview the wake word detection.\n```"+ return f"```\n{brief}\n```"monkeypatch.setattr(prompt_composer, "_llm_compose", _fenced)result = await prompt_composer.compose("review the wake word detection", session=workspace, terminal_name="Kai")- assert result.text == "Review the wake word detection."+ assert result.text == brief+ assert result.composed_by == "llm"async def test_use_llm_false_keeps_the_users_own_wording(workspace: _Session) -> None:diff --git a/tests/unit/agentic_ide/test_spawn_intent.py b/tests/unit/agentic_ide/test_spawn_intent.pyindex aa26c20b62..636356507f 100644--- a/tests/unit/agentic_ide/test_spawn_intent.py+++ b/tests/unit/agentic_ide/test_spawn_intent.py@@ -229,6 +229,9 @@ def test_an_agent_fleet_with_a_split_belongs_to_the_open_workspace() -> None:assert found is not Noneassert found.count == 5assert intent.owns_turn(FLEET_REQUEST, names=NAMES) is True+ instruction = intent.spawn_instruction(FLEET_REQUEST)+ assert "spawnen" not in instruction # i18n-allow: fixture assertion+ assert "Codebase" in instructiondef test_an_agent_fleet_naming_a_coding_cli_also_counts() -> None:@@ -284,3 +287,195 @@ def test_an_addressed_terminal_still_wins_over_the_spawn_grammar() -> None:assert found is not Noneassert found.terminal == "Alex"assert intent.detect_spawn(utterance, names=NAMES) is None+++# --------------------------------------------------------------------------- #+# Live voice regressions from 2026-07-27 #+# --------------------------------------------------------------------------- #+++def test_repeated_fleet_count_inside_the_task_does_not_double_the_spawn() -> None:+ utterance = (+ "Kannst du bitte fünf neue Codex Terminals spawnen und ich möchte, "+ "dass du jeden dieser fünf Codex Agents promptest, dass sie einen "+ "Deep Dive machen"+ ) # i18n-allow: production transcript under test++ found = intent.detect_spawn(utterance, names=NAMES)++ assert found is not None+ assert found.count == 5+ assert found.agent == "codex"+ assert intent.spawn_includes_task(utterance) is True+ assert intent.spawn_instruction(utterance) == "einen Deep Dive machen"+++def test_worker_count_later_in_the_task_is_not_a_terminal_count() -> None:+ utterance = (+ "Spawn five Codex terminals and prompt each one to start 50 subagents "+ "for a read-only review"+ )++ found = intent.detect_spawn(utterance, names=NAMES)++ assert found is not None+ assert found.count == 5+ assert found.groups == (intent.SpawnGroup(count=5, agent="codex"),)+ assert intent.spawn_includes_task(utterance) is True+++def test_polite_commas_do_not_separate_the_spawn_verb_from_the_count() -> None:+ found = intent.detect_spawn(+ "Spawn, please, five Codex terminals for me",+ names=NAMES,+ )++ assert found is not None+ assert found.count == 5+ assert found.agent == "codex"+++def test_follow_up_about_existing_terminals_does_not_spawn_worker_count() -> None:+ utterance = (+ "Aber du hast hier zehn neue Terminals und du sollst jeden davon "+ "prompten, dass die selber noch mal 50 Subagenten starten"+ ) # i18n-allow: production transcript under test++ assert intent.detect_spawn(utterance, names=NAMES) is None+ assert intent.references_recent_fleet(utterance) is True+ assert [item.terminal for item in intent.detect_all(utterance, names=NAMES)] == NAMES+++def test_close_all_codex_terminals_is_a_workspace_intent() -> None:+ utterance = "Kannst du bitte alle Codex Terminals schließen?" # i18n-allow: production transcript under test++ found = intent.detect_close_fleet(utterance)++ assert found == intent.CloseTerminalsRequest(agent="codex", utterance=utterance)+ assert intent.owns_turn(utterance, names=NAMES) is True+++ "utterance",+ [+ "Are all Codex terminals closed?",+ "Close the Codex terminal named Alex",+ "What closes every terminal?",+ ],+)+def test_close_all_detector_rejects_questions_and_single_panes(utterance: str) -> None:+ assert intent.detect_close_fleet(utterance) is None+++ "utterance",+ [+ # Briefing the fleet — the verb belongs to the WORK, not to the panes.+ "tell all the terminals to stop what they are doing",+ "tell every terminal to stop the dev server",+ "ask all terminals to stop after this task",+ "have each terminal close the files it opened",+ "sag allen Terminals, sie sollen die Tests stoppen", # i18n-allow: spoken input under test+ # The quantifier belongs to something running INSIDE the panes.+ "kill all the node processes in the terminals",+ "stop all the failing tests in the terminals",+ "beende alle laufenden Testläufe in den Terminals", # i18n-allow: spoken input under test+ ],+)+def test_fleet_instructions_are_never_read_as_closing_the_workspace(+ utterance: str,+) -> None:+ """A prompt for the fleet must not destroy the fleet.++ Every one of these closed EVERY pane in the workspace — no confirmation, no+ undo, ten coding agents gone — because the detector only asked whether a+ pane noun, an "all" word and a stop-verb appeared anywhere in the sentence.+ They are the ordinary way a user talks to a workspace full of terminals, so+ each one has to stay a prompt.+ """+ assert intent.detect_close_fleet(utterance) is None+++ ("utterance", "agent"),+ [+ ("close all terminals", None),+ ("Please close all Codex terminals", "codex"),+ ("schliess alle Terminals", None), # i18n-allow: spoken input under test+ # i18n-allow: spoken input under test+ ("Kannst du bitte alle Claude Code Terminals beenden?", "claude"),+ ("close all the open terminals", None),+ ("stop every pane", None),+ ],+)+def test_a_real_close_request_still_closes(utterance: str, agent: str | None) -> None:+ """The narrowing must not cost the feature itself."""+ found = intent.detect_close_fleet(utterance)++ assert found is not None+ assert found.agent == agent+++# --------------------------------------------------------------------------- #+# Live voice regression from 2026-07-27: the task stated BEFORE the spawn #+# --------------------------------------------------------------------------- #+# The user described the work first, named a pane that was not running, and put+# the spawn in a conditional afterthought: "let Lee do a deep dive on this and+# fix it — if there is no terminal by that name, open one and prompt it right in+# there". Only the text AFTER the spawn clause was read for a task, and that+# text is nothing but the fallback wording. So one blank pane opened, was+# announced as ready, and the deep dive was never handed to anyone. The user's+# next sentence was "you did nothing".++CONDITIONAL_SPAWN = (+ "Kannst du bitte dazu Lee einen Deep Dive machen lassen? Und das fixen. "+ "Wenn es kein Terminal gibt, welches so heißt, spawn ein neues und lass "+ "es dann direkt da rein"+) # i18n-allow: production transcript under test+++def test_a_task_stated_before_a_conditional_spawn_still_reaches_the_new_pane() -> None:+ found = intent.detect_spawn(CONDITIONAL_SPAWN, names=NAMES)++ assert found is not None+ assert found.count == 1, "one pane was asked for, not one per clause"+ assert intent.spawn_includes_task(CONDITIONAL_SPAWN) is True+ instruction = intent.spawn_instruction(CONDITIONAL_SPAWN)+ assert "Deep Dive" in instruction+ assert "spawn" not in instruction.casefold(), "the fallback wording is not the work"+++def test_the_english_and_spanish_conditional_forms_carry_the_task_too() -> None:+ english = (+ "Have Lee investigate the empty area in the layout and fix it. "+ "If there is no terminal called that, open a new one and prompt it there"+ )+ spanish = (+ "Que Lee revise el área vacía del diseño y lo arregle. "+ "Si no hay una terminal con ese nombre, abre una nueva"+ ) # i18n-allow: spoken input under test++ for utterance in (english, spanish):+ assert intent.spawn_includes_task(utterance) is True+ assert "Lee" in intent.spawn_instruction(utterance)+++ "utterance",+ [+ # No condition: the sentence in front is conversation, not a brief.+ # i18n-allow: spoken input under test+ "Die Tests sind gerade grün geworden. Spawne zwei neue Terminals",+ "I fixed the layout myself. Open two more Codex terminals",+ # A condition but nothing that reads as work in front of it.+ "Wenn noch Platz ist, spawn bitte ein Terminal", # i18n-allow: spoken input under test+ ],+)+def test_talk_in_front_of_a_plain_spawn_is_not_a_brief(utterance: str) -> None:+ """The panes open blank, which is exactly what was asked for.++ Reading any leading sentence as a task would type yesterday's news into a+ fresh agent — the mirror image of the bug above, and just as wrong.+ """+ assert intent.detect_spawn(utterance, names=NAMES) is not None+ assert intent.spawn_includes_task(utterance) is Falsediff --git a/tests/unit/brain/test_agentic_ide_clarify_fast_path.py b/tests/unit/brain/test_agentic_ide_clarify_fast_path.pynew file mode 100644index 0000000000..d705c0f995--- /dev/null+++ b/tests/unit/brain/test_agentic_ide_clarify_fast_path.py@@ -0,0 +1,312 @@+"""A call-sign the transcript garbled is asked about, then delivered on.++The live failure of 2026-07-27 16:18, end to end: the pane "Ellis" came back+from speech recognition as "Ilies", scoring just under the acting threshold. The+addressed-terminal path returned ``None`` without a word — no prompt was typed,+nothing was said, and the realtime model, which is never told any of this, filled+the silence by announcing that an agent was on it. The maintainer spent the next+two turns being told a lie.++What this file pins is the whole repaired loop, because each half is worthless+alone:++* an uncertain call-sign produces a QUESTION rather than silence, and types+ nothing into any pane while it is unanswered;+* the answer delivers the ORIGINAL sentence — the one that carried the task — so+ clarifying costs the user one word instead of repeating themselves;+* a sentence about the outside world still reaches no pane at all, which is the+ failure the question must not buy at the price of.+"""+from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.agentic_ide import clarify as ide_clarify+from jarvis.agentic_ide import prompt_composer+from jarvis.agentic_ide import session as session_mod+from jarvis.agentic_ide.prompt_composer import ComposedPrompt+from jarvis.agentic_ide.session import Registry+from jarvis.brain.manager import BrainManager+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from tests.fakes.fake_pty_manager import FakePtyManager++[email protected](autouse=True)+def _isolated_recents(+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Never rewrite the developer's real recent-workspace list from a test."""+ from jarvis.agentic_ide import recents++ store = tmp_path_factory.mktemp("recents") / "recents.json"+ monkeypatch.setattr(recents, "_store_path", lambda: store)++[email protected](autouse=True)+def _clean_window() -> None:+ """The clarification window is process-wide; no test may inherit one."""+ ide_clarify.WINDOW.disarm()+ yield+ ide_clarify.WINDOW.disarm()+++def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ reg = Registry(pty_manager=FakePtyManager())+ monkeypatch.setattr(session_mod, "get_registry", lambda: reg)+ return reg+++def manager() -> BrainManager:+ cfg = JarvisConfig()+ cfg.brain.primary = "fake"+ mgr = BrainManager(config=cfg, bus=EventBus(), tools={})+ # Pinned so the wording assertions never depend on the host's own locale+ # (AP-23: never test against the maintainer's configuration).+ mgr._reply_language = "en"+ return mgr++[email protected](autouse=True)+def _fake_composer(monkeypatch: pytest.MonkeyPatch) -> list[str]:+ """A deterministic stand-in for the quality-tier prompt writer."""+ seen: list[str] = []++ async def fake_compose(utterance: str, **kwargs: object) -> ComposedPrompt:+ seen.append(str(kwargs.get("instruction") or utterance))+ return ComposedPrompt(+ text=f"## Task\n{utterance}", files=[], composed_by="llm"+ )++ monkeypatch.setattr(prompt_composer, "compose", fake_compose)+ return seen+++async def _noop(_text: str) -> None:+ return None+++async def _noop_exit(_code: int) -> None:+ return None+++async def _open(registry: Registry, folder: Path, count: int) -> list[str]:+ """Open ``count`` panes AND bring their agents live; return their call-signs."""+ await registry.start(str(folder), [{"agent": "claude"} for _ in range(count)])+ assert registry.session is not None+ for term in list(registry.session.terminals):+ await registry.attach(term.name, 100, 30, _noop, _noop_exit)+ return [t.name for t in registry.session.terminals]+++def _typed(registry: Registry) -> list[str]:+ """Everything the panes were actually sent this test."""+ return list(registry._pty.typed) # noqa: SLF001 - the fake's recording surface+++def _briefs(registry: Registry) -> list[str]:+ """Just the prompts, without the Enter that submits each one."""+ return [text for text in _typed(registry) if text.strip()]+++# --------------------------------------------------------------------------- #+++async def test_a_garbled_call_sign_asks_instead_of_silently_doing_nothing(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ """The regression: 'Ilies' must not vanish into a silent ``None``."""+ names = await _open(registry, tmp_path, 5)+ assert "Ellis" in names, "the fifth pane of the pool is the one that was misheard"++ reply = await manager._run_agentic_ide_fast_path(+ "can you have Ilies do a deep dive and find out why the tests fail"+ )++ assert reply is not None, "the turn that started all of this must not be silent"+ assert "Ellis" in reply+ assert "Ilies" in reply, "the user hears what was understood, not just a guess"+ assert ide_clarify.WINDOW.armed+++async def test_nothing_is_typed_into_a_pane_while_the_question_is_open(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ """Asking must not also act — that would be guessing with extra steps."""+ await _open(registry, tmp_path, 5)++ await manager._run_agentic_ide_fast_path(+ "can you have Ilies do a deep dive and find out why the tests fail"+ )++ assert _typed(registry) == []+++async def test_the_answer_delivers_the_original_task(+ manager: BrainManager,+ registry: Registry,+ tmp_path: Path,+ _fake_composer: list[str],+) -> None:+ """"Yes" must do the work the FIRST sentence described, not repeat itself."""+ await _open(registry, tmp_path, 5)+ task = "can you have Ilies do a deep dive and find out why the tests fail"++ question = await manager._run_agentic_ide_fast_path(task)+ assert question is not None++ verdict = await manager._run_agentic_ide_fast_path("yes")++ assert verdict is not None+ assert "Ellis" in verdict+ # The composer saw the original sentence, never the bare confirmation.+ assert any("deep dive" in seen for seen in _fake_composer)+ assert not any(seen.strip().casefold() == "yes" for seen in _fake_composer)+ assert not ide_clarify.WINDOW.armed+++async def test_declining_delivers_nothing(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ await _open(registry, tmp_path, 5)+ await manager._run_agentic_ide_fast_path(+ "can you have Ilies do a deep dive and find out why the tests fail"+ )++ assert await manager._run_agentic_ide_fast_path("no") is None+ assert _typed(registry) == []+ assert not ide_clarify.WINDOW.armed+++async def test_a_question_about_the_outside_world_neither_asks_nor_types(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ """The maintainer's counter-example, pinned as a hard negative."""+ await _open(registry, tmp_path, 5)++ reply = await manager._run_agentic_ide_fast_path(+ "can you tell me what Elon Musk is doing right now?"+ )++ assert reply is None+ assert _typed(registry) == []+ assert not ide_clarify.WINDOW.armed+++async def test_a_certain_call_sign_still_acts_without_asking(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ """Clarifying must not become the new normal for names that ARE clear."""+ names = await _open(registry, tmp_path, 5)++ reply = await manager._run_agentic_ide_fast_path(+ f"tell {names[0]} to fix the failing tests"+ )++ assert reply is not None+ assert not ide_clarify.WINDOW.armed+ assert _typed(registry), "a certain call-sign is delivered, not questioned"+++# --------------------------------------------------------------------------- #+# A turn addresses a FLEET (live 2026-07-27 19:07) #+# --------------------------------------------------------------------------- #+++async def test_two_garbled_call_signs_are_asked_about_together(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ """Two mangled names in one list used to produce nothing at all.++ The detector stood down above one uncertain word, so "Alexa und Blaike,+ macht beide ..." reached neither pane and asked nothing — the silent miss+ this whole area exists to end, only for a pair instead of a single pane.+ """+ await _open(registry, tmp_path, 5)++ reply = await manager._run_agentic_ide_fast_path(+ "Alexa and Blaike should both do a deep dive on the failing tests"+ )++ assert reply is not None+ assert "Alex" in reply and "Blake" in reply+ assert _typed(registry) == [], "nothing is typed while the question is open"+ assert ide_clarify.WINDOW.armed+++async def test_one_yes_briefs_the_whole_addressed_pair(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ """One question, one word, both agents working."""+ await _open(registry, tmp_path, 5)+ task = "Alexa and Blaike should both do a deep dive on the failing tests"+ assert await manager._run_agentic_ide_fast_path(task) is not None++ verdict = await manager._run_agentic_ide_fast_path("yes")++ assert verdict is not None+ assert "Alex" in verdict and "Blake" in verdict+ assert len(_briefs(registry)) == 2, "both addressees are briefed, not the first"+ assert all("deep dive" in text for text in _briefs(registry))+++async def test_a_pane_that_was_understood_is_briefed_before_the_question(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ """A name past every threshold ("Dave") must not cost the one that worked.++ The live shape: Alex resolves, "Dave" matches no pane at any threshold, and+ the turn said "Alex is on it" while the user was waiting for two agents.+ The count the user stated out loud is what survives that, so the work goes+ out AND the gap is named in the same breath.+ """+ await _open(registry, tmp_path, 5)++ reply = await manager._run_agentic_ide_fast_path(+ "Alex and Dave should both do a deep dive on the failing tests"+ )++ assert reply is not None+ assert "Alex" in reply+ assert len(_briefs(registry)) == 1, "the pane that WAS understood is briefed"+ assert ide_clarify.WINDOW.armed, "and the second addressee is asked about"+++async def test_naming_the_missing_pane_delivers_the_original_task(+ manager: BrainManager,+ registry: Registry,+ tmp_path: Path,+ _fake_composer: list[str],+) -> None:+ """"Blake" answers "who else?" with the work the first sentence carried."""+ await _open(registry, tmp_path, 5)+ await manager._run_agentic_ide_fast_path(+ "Alex and Dave should both do a deep dive on the failing tests"+ )++ verdict = await manager._run_agentic_ide_fast_path("Blake")++ assert verdict is not None+ assert "Blake" in verdict+ assert len(_briefs(registry)) == 2+ assert all("deep dive" in text for text in _briefs(registry))+++async def test_a_single_addressee_is_never_asked_who_else(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ """The plural check must not tax the ordinary one-pane turn."""+ names = await _open(registry, tmp_path, 5)++ reply = await manager._run_agentic_ide_fast_path(+ f"tell {names[0]} to do a deep dive on the failing tests"+ )++ assert reply is not None+ assert not ide_clarify.WINDOW.armed+ assert len(_briefs(registry)) == 1diff --git a/tests/unit/brain/test_agentic_ide_close_fast_path.py b/tests/unit/brain/test_agentic_ide_close_fast_path.pynew file mode 100644index 0000000000..5969db74fc--- /dev/null+++ b/tests/unit/brain/test_agentic_ide_close_fast_path.py@@ -0,0 +1,72 @@+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.agentic_ide import session as session_mod+from jarvis.brain.manager import BrainManager+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+++class _Bus:+ def __init__(self) -> None:+ self.events: list[object] = []++ async def publish(self, event: object) -> None:+ self.events.append(event)+++class _Registry:+ def __init__(self) -> None:+ self.session = SimpleNamespace(+ id="workspace",+ folder="/project",+ terminals=[+ SimpleNamespace(name="Cody", agent="codex"),+ SimpleNamespace(name="Clara", agent="claude"),+ SimpleNamespace(name="Cole", agent="codex"),+ ],+ )++ async def close_terminal(self, name: str) -> object:+ term = next(term for term in self.session.terminals if term.name == name)+ self.session.terminals.remove(term)+ return term+++async def test_close_all_codex_is_exact_and_not_model_dependent(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ registry = _Registry()+ monkeypatch.setattr(session_mod, "get_registry", lambda: registry)+ cfg = JarvisConfig()+ cfg.brain.primary = "fake"+ manager = BrainManager(config=cfg, bus=EventBus(), tools={})+ bus = _Bus()+ manager._bus = bus # type: ignore[assignment]+ manager._reply_language = "en"++ reply = await manager._run_agentic_ide_close_fast_path(+ "Please close all Codex terminals"+ )++ assert reply == "Closed 2 terminals: Cody and Cole."+ assert [term.name for term in registry.session.terminals] == ["Clara"]+ assert len(bus.events) == 1+ assert type(bus.events[0]).__name__ == "AgenticIdeTerminalsClosed"+ assert bus.events[0].names == ("Cody", "Cole")+++async def test_non_close_turn_stands_aside(monkeypatch: pytest.MonkeyPatch) -> None:+ registry = _Registry()+ monkeypatch.setattr(session_mod, "get_registry", lambda: registry)+ cfg = JarvisConfig()+ cfg.brain.primary = "fake"+ manager = BrainManager(config=cfg, bus=EventBus(), tools={})++ assert await manager._run_agentic_ide_close_fast_path("Review Codex output") is None+ assert len(registry.session.terminals) == 3diff --git a/tests/unit/brain/test_agentic_ide_fanout_fast_path.py b/tests/unit/brain/test_agentic_ide_fanout_fast_path.pyindex 591d678779..a0eaacb472 100644--- a/tests/unit/brain/test_agentic_ide_fanout_fast_path.py+++ b/tests/unit/brain/test_agentic_ide_fanout_fast_path.py@@ -17,6 +17,7 @@ The composer is faked throughout. It is a quality-tier provider call by design"""from __future__ import annotations+import timefrom pathlib import Pathimport pytest@@ -183,6 +184,28 @@ async def test_a_single_addressed_pane_keeps_the_singular_reply(assert not _sent_to(registry, second)+async def test_pronoun_follow_up_only_targets_the_newly_spawned_fleet(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ await _open(registry, tmp_path, 4)+ first, _second, third, fourth = _names(registry)+ assert registry.session is not None+ manager._last_ide_spawn = (+ registry.session.id,+ (third, fourth),+ time.monotonic(),+ )++ reply = await manager._run_agentic_ide_fast_path(+ "Prompt each of them to run a read-only review"+ )++ assert reply is not None+ assert not _sent_to(registry, first)+ assert _sent_to(registry, third)+ assert _sent_to(registry, fourth)++def _prompt_of(registry: Registry, name: str) -> str:assert registry.session is not Noneterm = registry.session.find(name)@@ -283,3 +306,63 @@ async def test_nobody_reachable_is_never_reported_as_sent(assert reply is not Nonelowered = reply.lower()assert any(word in lowered for word in ("not", "could not", "n't"))+++async def test_a_polite_prompt_request_reaches_the_pane_end_to_end(+ manager: BrainManager, registry: Registry, tmp_path: Path+) -> None:+ """The live 2026-07-27 18:01 turn, through the whole brain path.++ "Could you please prompt this terminal X, do a deep dive ...?" produced no+ reply and no keystroke: the verb "prompt" carried no addressing shape, so+ the trailing question mark routed the turn to the read-only branch and this+ fast path stood down in silence. The live model then answered "I have let X+ know" over a terminal still showing its startup banner. Pinned here rather+ than only in the detector tests, because it was the SILENCE that made the+ lie possible — the reply is as load-bearing as the keystroke.+ """+ await _open(registry, tmp_path, 2)+ first, second = _names(registry)++ reply = await manager._run_agentic_ide_fast_path(+ f"Could you please prompt this terminal {first}, do a deep dive and "+ "analyze all our whole code base and look for security vulnerabilities?"+ )++ assert reply is not None+ assert first in reply+ assert _sent_to(registry, first)+ assert not _sent_to(registry, second)+ # The pane noun belongs to the address, not to the work: an agent briefed+ # with "this terminal do a deep dive" reads it as an order to open one.+ assert "deep dive" in _prompt_of(registry, first).lower()+++async def test_a_fan_out_that_falls_over_still_says_so(+ manager: BrainManager,+ registry: Registry,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A delivery that did not happen must never be answered with silence.++ Returning None hands the turn to the model with nothing to go on, and a+ model asked about a pane it cannot see answers from the user's own question+ — which is how a briefing that never left the building was spoken as done.+ """+ from jarvis.agentic_ide import fanout as ide_fanout++ async def exploding_deliver(**_kwargs: object) -> object:+ raise RuntimeError("pty layer is gone")++ monkeypatch.setattr(ide_fanout, "deliver", exploding_deliver)++ await _open(registry, tmp_path, 1)+ (only,) = _names(registry)++ reply = await manager._run_agentic_ide_fast_path(f"Tell {only} to run the tests")++ assert reply is not None, "a failed delivery must be spoken, not swallowed"+ assert only in reply+ lowered = reply.lower()+ assert any(word in lowered for word in ("not", "could not", "n't"))diff --git a/tests/unit/brain/test_agentic_ide_spawn_fast_path.py b/tests/unit/brain/test_agentic_ide_spawn_fast_path.pyindex d43b3d258c..a5fee73f42 100644--- a/tests/unit/brain/test_agentic_ide_spawn_fast_path.py+++ b/tests/unit/brain/test_agentic_ide_spawn_fast_path.py@@ -13,11 +13,14 @@ class, one layer up. These tests pin the three things that make the feature real"""from __future__ import annotations+import asynciofrom pathlib import Path+from types import SimpleNamespaceimport pytest-from jarvis.agentic_ide import recents, session as session_mod+from jarvis.agentic_ide import recents+from jarvis.agentic_ide import session as session_modfrom jarvis.agentic_ide.session import MAX_TERMINALS, Registryfrom jarvis.brain.manager import BrainManagerfrom jarvis.core.bus import EventBus@@ -44,7 +47,10 @@ def _event_names(bus: FakeBus) -> list[str]:@pytest.fixture(autouse=True)-def _isolated_recents(tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch) -> None:+def _isolated_recents(+ tmp_path_factory: pytest.TempPathFactory,+ monkeypatch: pytest.MonkeyPatch,+) -> None:"""Keep the recents file out of the developer's real data directory.Opening a workspace records it as "most recently used", and that file lives@@ -150,6 +156,73 @@ async def test_a_named_agent_is_honoured_over_the_inherited_one(assert [t.agent for t in registry.session.terminals] == ["codex", "claude", "claude"]+async def test_spawn_and_prompt_queues_exactly_the_new_codex_fleet(+ manager: tuple[BrainManager, FakeBus],+ registry: Registry,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ mgr, _bus = manager+ await _open(registry, tmp_path, 1, agent="claude")+ received: list[tuple[list[str], str]] = []+ called = asyncio.Event()++ async def _brief(_session: object, names: list[str], utterance: str) -> None:+ received.append((names, utterance))+ called.set()++ monkeypatch.setattr(mgr, "_brief_spawned_agentic_ide_fleet", _brief)+ utterance = (+ "Spawn five Codex terminals and prompt each one to start 50 subagents "+ "for a read-only platform review"+ )++ reply = await mgr._run_agentic_ide_spawn_fast_path(utterance)+ await asyncio.wait_for(called.wait(), timeout=1)++ assert registry.session is not None+ new_terms = registry.session.terminals[1:]+ assert len(new_terms) == 5+ assert {term.agent for term in new_terms} == {"codex"}+ assert received == [([term.name for term in new_terms], utterance)]+ assert reply is not None+ assert "as soon as the terminals are ready" in reply+++async def test_queued_fleet_receives_the_task_not_the_spawn_scaffolding(+ manager: tuple[BrainManager, FakeBus],+ registry: Registry,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis.agentic_ide import fanout, fleet_actions++ mgr, _bus = manager+ session = await _open(registry, tmp_path, 2, agent="codex")+ names = [term.name for term in session.terminals]+ captured: dict[str, object] = {}++ async def _ready(_session: object, wanted: list[str]) -> tuple[str, ...]:+ return tuple(wanted)++ async def _deliver(**kwargs: object) -> object:+ captured.update(kwargs)+ return SimpleNamespace(delivered=(object(), object()))++ monkeypatch.setattr(fleet_actions, "wait_for_prompt_ready", _ready)+ monkeypatch.setattr(fanout, "deliver", _deliver)+ utterance = (+ "Spawn two Codex terminals and prompt each one to perform a read-only "+ "platform compatibility review"+ )++ await mgr._brief_spawned_agentic_ide_fleet(session, names, utterance)++ assert captured["terminals"] == tuple(names)+ assert captured["instruction"] == "perform a read-only platform compatibility review"+ assert "Spawn two Codex terminals" not in str(captured["instruction"])++async def test_without_a_named_agent_the_new_panes_inherit(manager: tuple[BrainManager, FakeBus], registry: Registry, tmp_path: Path) -> None:@@ -318,3 +391,86 @@ async def test_a_clearly_german_turn_is_answered_in_german_without_a_pin()assert reply is not Noneassert "neue Terminals" in reply # i18n-allow: asserted German reply+++# --------------------------------------------------------------------------- #+# Live voice regression 2026-07-27: one pane, and it gets the work #+# --------------------------------------------------------------------------- #+++async def test_a_conditional_spawn_opens_one_pane_and_briefs_it(+ manager: tuple[BrainManager, FakeBus],+ registry: Registry,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The whole reported failure, pinned at the layer that produced it.++ The user described the work, named a pane that was not running, and made+ the spawn a fallback: "let Lee do a deep dive on this and fix it — if there+ is no terminal by that name, open one and prompt it right there". The task+ sits in FRONT of the spawn clause, and only what followed it was read, so a+ blank pane opened, "ready" was spoken, and nobody was briefed. What the user+ said next was "you did nothing" — followed by four more panes as the router+ tried to reach a call-sign that could never exist.+ """+ mgr, _bus = manager+ await _open(registry, tmp_path, 2)+ received: list[tuple[list[str], str]] = []+ called = asyncio.Event()++ async def _brief(_session: object, names: list[str], utterance: str) -> None:+ received.append((names, utterance))+ called.set()++ monkeypatch.setattr(mgr, "_brief_spawned_agentic_ide_fleet", _brief)+ utterance = (+ "Kannst du bitte dazu Lee einen Deep Dive machen lassen? Und das fixen. "+ "Wenn es kein Terminal gibt, welches so heißt, spawn ein neues und lass "+ "es dann direkt da rein"+ ) # i18n-allow: production transcript under test++ reply = await mgr._run_agentic_ide_spawn_fast_path(utterance)+ await asyncio.wait_for(called.wait(), timeout=1)++ assert registry.session is not None+ opened = registry.session.terminals[2:]+ assert len(opened) == 1, "one pane was asked for — the four extra ones are the bug"+ assert received == [([opened[0].name], utterance)]+ assert reply is not None+ assert opened[0].name in reply, "the pane's real call-sign is spoken back"+++async def test_the_conditional_brief_carries_the_task_and_not_the_fallback(+ manager: tuple[BrainManager, FakeBus],+ registry: Registry,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """What the new pane is told has to be the work, not the spawn wording."""+ from jarvis.agentic_ide import fanout, fleet_actions++ mgr, _bus = manager+ session = await _open(registry, tmp_path, 1)+ names = [term.name for term in session.terminals]+ captured: dict[str, object] = {}++ async def _ready(_session: object, wanted: list[str]) -> tuple[str, ...]:+ return tuple(wanted)++ async def _deliver(**kwargs: object) -> object:+ captured.update(kwargs)+ return SimpleNamespace(delivered=(object(),))++ monkeypatch.setattr(fleet_actions, "wait_for_prompt_ready", _ready)+ monkeypatch.setattr(fanout, "deliver", _deliver)+ utterance = (+ "Have Lee investigate the huge empty area in the layout and fix it. "+ "If there is no terminal called that, open a new one and prompt it there"+ )++ await mgr._brief_spawned_agentic_ide_fleet(session, names, utterance)++ instruction = str(captured["instruction"])+ assert "empty area" in instruction+ assert "open a new one" not in instruction, "the fallback is not the work"diff --git a/tests/unit/brain/test_turn_planner.py b/tests/unit/brain/test_turn_planner.pyindex 4767447b7f..358d3127e7 100644--- a/tests/unit/brain/test_turn_planner.py+++ b/tests/unit/brain/test_turn_planner.py@@ -444,3 +444,65 @@ def test_calendar_trivia_stays_native(utterance: str) -> None:)def test_time_words_with_real_evidence_still_delegate(utterance: str) -> None:assert plan_turn(utterance).path is TurnPath.ORCHESTRATOR+++# --------------------------------------------------------------------------- #+# A turn naming an open coding terminal #+# --------------------------------------------------------------------------- #+# Live failure 2026-07-27 16:53 (Realtime): with a terminal called Dana running,+# "Was hat Dana gemacht?" was routed natively and the live model answered that+# it did not know which person Dana was. The utterance carries no lookup verb,+# no action, no possessive and no connected domain — the static vocabularies+# structurally cannot hold the evidence, because the call-signs are chosen per+# workspace at runtime. The NAME is the evidence, so it is passed in.++PANES = ("Alex", "Dana", "Logan")+++ "utterance",+ [+ "Was hat Dana gemacht?", # the verbatim live failure+ "Was hat Logan gebaut?", # i18n-allow: German speech-input fixture+ "Was ist mit Dana?", # i18n-allow: German speech-input fixture+ "Dana?",+ "What did Dana do?",+ "Que hizo Dana?",+ # A garbled call-sign still has to reach the orchestrator: only it can+ # ask "did you mean Dana?".+ "Was hat Danna gemacht?", # i18n-allow: German speech-input fixture+ ],+)+def test_a_turn_naming_an_open_terminal_delegates(utterance: str) -> None:+ assert plan_turn(utterance).path is TurnPath.NATIVE_REALTIME, (+ "precondition: without a workspace this turn is native"+ )+ plan = plan_turn(utterance, workspace_names=PANES)+ assert plan.path is TurnPath.ORCHESTRATOR+ assert TurnReason.WORKSPACE in plan.reasons+ # The pane's transcript is evidence the live model never holds.+ assert plan.requires_evidence is True+++ "utterance",+ [+ # A person who merely shares a first name with a pane.+ "Was hat Dana Schmidt gemacht?", # i18n-allow: German speech-input fixture+ # Somebody out in the world.+ "Was hat Elon Musk gemacht?", # i18n-allow: German speech-input fixture+ # Plain conversation while a workspace happens to be open.+ "Erzaehl mir einen Witz", # i18n-allow: German speech-input fixture+ ],+)+def test_an_open_workspace_does_not_capture_unrelated_turns(utterance: str) -> None:+ assert plan_turn(utterance, workspace_names=PANES).path is (+ TurnPath.NATIVE_REALTIME+ )+++def test_no_open_workspace_changes_nothing() -> None:+ """The parameter is inert when no terminals are running."""+ assert plan_turn("Was hat Dana gemacht?", workspace_names=()).path is (+ TurnPath.NATIVE_REALTIME+ )diff --git a/tests/unit/brain/test_turn_planner_skill_index.py b/tests/unit/brain/test_turn_planner_skill_index.pynew file mode 100644index 0000000000..f8dfad27d2--- /dev/null+++ b/tests/unit/brain/test_turn_planner_skill_index.py@@ -0,0 +1,189 @@+"""The planner becomes skill-aware without gaining IO or an import edge.++Realtime voice was completely skill-blind. ``turn_planner`` recognised only the+three literal trigger words in ``_SKILL_RE``, so an utterance naming an installed+skill produced no skill reason and never reached the orchestrator that could+run it. Meanwhile the live model in delegate mode sees exactly two function+declarations, neither of which is a skill.++Two properties matter here and they pull against each other:++* the planner must SEE installed skills, and+* it must keep its promise of no model call, no disk access, no network — which+ is why the index arrives as a frozen data snapshot through an optional+ parameter instead of being imported.+"""+from __future__ import annotations++import pytest++from jarvis.brain.turn_planner import TurnPath, TurnReason, plan_turn+from jarvis.skills.relevance import RelevanceRanking, ScoredSkill, build_index++# Speech input under test.+#: MEASURED to reach the FIRE band against the seven-skill fixture below.+#: Naming only one indexed term scores ~0.74 against a cut-off near 0.98, i.e.+#: NARROW — which is correct behaviour, so the fixture names both.+FOCUS_UTTERANCE = "aktiviere den fokus und den konzentrationsmodus" # i18n-allow+WEATHER_UTTERANCE = "wie ist das wetter heute in berlin" # i18n-allow+LITERAL_SKILL_WORD = "welche skills habe ich installiert" # i18n-allow+++class _FakeFrontmatter:+ def __init__(self, tags: list[str]) -> None:+ self.description = "A focus mode."+ self.when_to_use = ""+ self.category = "productivity"+ self.tags = tags+ self.triggers: list[object] = []+ self.intent_verbs: list[str] = []+ self.intent_objects: list[str] = []+++class _FakeSkill:+ def __init__(self, name: str, tags: list[str]) -> None:+ self.name = name+ self.frontmatter = _FakeFrontmatter(tags)+++def _index() -> object:+ skills = [_FakeSkill("deep-work-mode", ["konzentrationsmodus", "fokus"])] # i18n-allow+ skills += [_FakeSkill(f"filler-{i}", [f"topic{i}"]) for i in range(6)]+ return build_index(skills)+++# ---------------------------------------------------------------------------+# Backwards compatibility: the parameter is optional and inert+# ---------------------------------------------------------------------------+++def test_the_planner_still_works_without_an_index() -> None:+ """Every existing caller passes nothing — behaviour must be unchanged."""+ plan = plan_turn(WEATHER_UTTERANCE)+ assert TurnReason.SKILL not in plan.reasons+++def test_an_explicit_none_index_is_the_same_as_omitting_it() -> None:+ assert plan_turn(FOCUS_UTTERANCE, skill_index=None).reasons == plan_turn(+ FOCUS_UTTERANCE+ ).reasons+++def test_the_literal_skill_word_still_works_on_its_own() -> None:+ """The static vocabulary branch is untouched."""+ plan = plan_turn(LITERAL_SKILL_WORD)+ assert TurnReason.SKILL in plan.reasons+++# ---------------------------------------------------------------------------+# With an index: content-aware detection+# ---------------------------------------------------------------------------+++def test_an_installed_skill_is_now_recognised() -> None:+ """The gap this closes. Without the index this utterance produced no skill+ reason at all, so realtime never routed it anywhere that could run it."""+ plan = plan_turn(FOCUS_UTTERANCE, skill_index=_index())+ assert TurnReason.SKILL in plan.reasons+ assert plan.path is TurnPath.ORCHESTRATOR+ assert any(name.startswith("skill:") for name in plan.required_capabilities)+++def test_an_unrelated_utterance_gains_no_skill_reason() -> None:+ plan = plan_turn(WEATHER_UTTERANCE, skill_index=_index())+ assert TurnReason.SKILL not in plan.reasons+++def test_a_definitional_question_is_not_a_skill_turn() -> None:+ """Asking what something IS must never route as wanting it DONE."""+ plan = plan_turn(+ "was ist eigentlich ein konzentrationsmodus", # i18n-allow+ skill_index=_index(),+ )+ assert TurnReason.SKILL not in plan.reasons+++def test_only_a_fire_band_hit_counts() -> None:+ """A NARROW candidate is prompt material, not a reason to pay a delegation.++ A realtime delegation costs seconds of silence (BUG-087 measured 9.6 s to+ first audio), so a weak signal must not buy one.+ """++ class _NarrowIndex:+ fire_threshold = 10.0++ def rank(self, text: str, *, limit: int = 5) -> RelevanceRanking:+ return RelevanceRanking(+ ranked=(ScoredSkill(name="deep-work-mode", score=0.5),),+ clear_winner=True,+ fire_threshold=10.0,+ hint_threshold=0.1,+ )++ plan = plan_turn(FOCUS_UTTERANCE, skill_index=_NarrowIndex())+ assert TurnReason.SKILL not in plan.reasons+++def test_an_ambiguous_winner_does_not_count() -> None:+ """Two near-tied skills are ambiguity, not a decision."""++ class _TiedIndex:+ def rank(self, text: str, *, limit: int = 5) -> RelevanceRanking:+ return RelevanceRanking(+ ranked=(+ ScoredSkill(name="plugin-slack", score=2.0),+ ScoredSkill(name="plugin-discord", score=1.95),+ ),+ clear_winner=False,+ fire_threshold=1.0,+ hint_threshold=0.3,+ )++ plan = plan_turn("schick eine nachricht", skill_index=_TiedIndex()) # i18n-allow+ assert TurnReason.SKILL not in plan.reasons+++# ---------------------------------------------------------------------------+# Purity: no IO, no import edge, no crash+# ---------------------------------------------------------------------------+++def test_a_broken_index_degrades_to_the_static_vocabulary() -> None:+ """A scorer fault must never break a turn."""++ class _ExplodingIndex:+ def rank(self, text: str, *, limit: int = 5) -> RelevanceRanking:+ raise RuntimeError("index is on fire")++ plan = plan_turn(FOCUS_UTTERANCE, skill_index=_ExplodingIndex())+ assert TurnReason.SKILL not in plan.reasons+ # And the rest of the planning still happened.+ assert isinstance(plan.path, TurnPath)+++def test_the_planner_module_imports_nothing_from_jarvis_skills() -> None:+ """The purity promise, checked structurally.++ ``jarvis/skills/__init__.py`` is a heavy eager package init (registry,+ runner, watchdog, pydantic). A module-scope import here would drag all of it+ into every early import of the planner (AP-26) — which is exactly why the+ index is passed in as data.+ """+ from pathlib import Path++ import jarvis.brain.turn_planner as module++ source = Path(module.__file__).read_text(encoding="utf-8")+ code = "\n".join(+ line+ for line in source.splitlines()+ if not line.lstrip().startswith("#")+ )+ assert "from jarvis.skills" not in code+ assert "import jarvis.skills" not in code++[email protected]("text", ["", " "])+def test_empty_input_is_still_a_native_turn(text: str) -> None:+ assert plan_turn(text, skill_index=_index()).path is TurnPath.NATIVE_REALTIMEdiff --git a/tests/unit/brain/test_vision_resolver.py b/tests/unit/brain/test_vision_resolver.pynew file mode 100644index 0000000000..7b8c0e9602--- /dev/null+++ b/tests/unit/brain/test_vision_resolver.py@@ -0,0 +1,117 @@+"""``resolve_vision_brain`` — picking a model that can actually SEE.++The gate is the ``supports_vision`` capability and nothing else (AP-21). That+matters more here than in most resolvers because a text-only provider handed an+image does not fail loudly: it answers about the filename and the sentence around+it, confidently, and the caller ships that as a description of a picture nobody+looked at.+"""+from __future__ import annotations++import pytest++from jarvis.brain import resolver+++class _Blind:+ supports_vision = False+++class _Seeing:+ supports_vision = True+++class _Undeclared:+ """A provider that says nothing about vision at all."""++[email protected](autouse=True)+def _clean_cache() -> None:+ resolver._reset_for_tests()+++def _stage(monkeypatch: pytest.MonkeyPatch, chain: list, instances: dict) -> None:+ monkeypatch.setattr(resolver, "_resolve_chain", lambda _cfg: chain)++ class _Registry:+ def instantiate(self, provider: str, **_kwargs: object) -> object:+ made = instances.get(provider)+ if made is None:+ raise RuntimeError(f"{provider} not configured")+ return made()++ monkeypatch.setattr(resolver, "_get_registry", _Registry)+++def test_a_blind_provider_is_skipped_for_the_next_one_that_can_see(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _stage(+ monkeypatch,+ [("text-only", "m1"), ("multimodal", "m2")],+ {"text-only": _Blind, "multimodal": _Seeing},+ )++ brain = resolver.resolve_vision_brain(object())++ assert isinstance(brain, _Seeing)+++def test_nothing_that_can_see_returns_none_rather_than_a_blind_brain(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _stage(monkeypatch, [("text-only", "m1")], {"text-only": _Blind})++ assert resolver.resolve_vision_brain(object()) is None+++def test_a_provider_that_does_not_declare_vision_is_treated_as_blind(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Fail-closed: the caller's entire job is describing a picture, and a+ # confident description of an unseen one is worse than an honest "not+ # described".+ _stage(monkeypatch, [("mystery", "m1")], {"mystery": _Undeclared})++ assert resolver.resolve_vision_brain(object()) is None+++def test_an_uninstantiable_provider_does_not_stop_the_walk(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _stage(+ monkeypatch,+ [("missing-key", None), ("multimodal", "m2")],+ {"multimodal": _Seeing},+ )++ assert isinstance(resolver.resolve_vision_brain(object()), _Seeing)+++def test_a_broken_chain_is_none_not_an_exception(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _boom(_cfg: object) -> list:+ raise RuntimeError("config is a mess")++ monkeypatch.setattr(resolver, "_resolve_chain", _boom)++ assert resolver.resolve_vision_brain(object()) is None+++def test_the_choice_is_never_made_by_provider_name(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A name that looks multimodal but declares no vision must not win.++ This is the AP-21 shape: gate on the capability, never on what the provider+ is called — the name-based version breaks for every provider nobody thought+ of when the list was written.+ """+ _stage(+ monkeypatch,+ [("gpt-vision-ultra", "m1"), ("obscure-local-thing", "m2")],+ {"gpt-vision-ultra": _Blind, "obscure-local-thing": _Seeing},+ )++ assert isinstance(resolver.resolve_vision_brain(object()), _Seeing)diff --git a/tests/unit/realtime/test_session_workspace_directive.py b/tests/unit/realtime/test_session_workspace_directive.pynew file mode 100644index 0000000000..cefef4f781--- /dev/null+++ b/tests/unit/realtime/test_session_workspace_directive.py@@ -0,0 +1,95 @@+"""The live model must know which coding agents are running, by name.++Live failure 2026-07-27 16:53 (Realtime): with a terminal called Dana running in+front of the user, "Was hat Dana gemacht?" was answered with "I cannot tell you,+because I do not know which person Dana is" — and the model was right not to+know. Its session instructions carried the persona, the clock, the tool+directive and the user's preferences, and nothing whatsoever about the coding+workspace two feet away. The user only got a real answer after saying the words+"agentic IDE" out loud, which is not a workflow anybody should have to learn.++The roster is therefore part of the per-turn instructions. What is pinned here+is its two halves: the model is told the NAMES (it cannot route a name it has+never heard of), and it is NOT told the transcripts (those are kilobytes the+orchestrator already holds and re-sending them every turn buys nothing).+"""+from __future__ import annotations++from typing import Any++import pytest++from jarvis.agentic_ide import session as ide_session+from jarvis.realtime import session as session_module+++def workspace(monkeypatch: pytest.MonkeyPatch) -> Any:+ """Install a roster the directive will read, without opening terminals."""++ def _install(names: tuple[str, ...]) -> None:+ monkeypatch.setattr(+ ide_session, "running_call_signs", lambda: list(names)+ )++ return _install+++def _directive() -> str:+ """``_workspace_directive`` off a bare instance — it touches no other state."""+ instance = object.__new__(session_module.RealtimeVoiceSession)+ return session_module.RealtimeVoiceSession._workspace_directive(instance)+++def test_the_roster_names_every_running_terminal(workspace: Any) -> None:+ workspace(("Dana", "Logan", "Casey"))+ directive = _directive()+ for name in ("Dana", "Logan", "Casey"):+ assert name in directive+++def test_the_roster_tells_the_model_a_call_sign_is_not_a_person(+ workspace: Any,+) -> None:+ """The exact wrong answer of the live failure is what this must prevent."""+ workspace(("Dana",))+ directive = _directive().casefold()+ assert "not people" in directive+ assert "do not know who" in directive+++def test_no_open_workspace_adds_nothing(workspace: Any) -> None:+ """With no terminals running the instructions stay byte-identical."""+ workspace(())+ assert _directive() == ""+++def test_a_broken_workspace_never_breaks_the_call(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The coding surface is optional; a fault in it must degrade to silence."""++ def _boom() -> list[str]:+ raise RuntimeError("registry is mid-reload")++ monkeypatch.setattr(ide_session, "running_call_signs", _boom)+ assert _directive() == ""+++def test_the_directive_reaches_the_session_instructions(workspace: Any) -> None:+ workspace(("Dana",))+ rendered = session_module._session_instructions(+ "de", workspace_directive=_directive()+ )+ assert "Dana" in rendered+ # Omitting it must not smuggle a stale roster in from anywhere else.+ assert "Dana" not in session_module._session_instructions("de")+++def test_the_roster_carries_names_only_not_transcripts(workspace: Any) -> None:+ """Terminal output belongs to the orchestrator, not to every turn's prompt."""+ workspace(("Dana", "Logan"))+ directive = _directive()+ # Comfortably under a kilobyte for a two-pane workspace: this block is+ # re-sent on every single final transcript of a live call.+ assert len(directive) < 1_000diff --git a/tests/unit/web/test_agentic_ide_accounts_route.py b/tests/unit/web/test_agentic_ide_accounts_route.pynew file mode 100644index 0000000000..5fb2b89e04--- /dev/null+++ b/tests/unit/web/test_agentic_ide_accounts_route.py@@ -0,0 +1,99 @@+"""The endpoint behind the workspace's account switcher.++Route wiring only — which registry call a request makes and what the reply+carries. The behaviour underneath (what a switch does to the next pane, and what+it must NOT do to a running one) is pinned where it lives, in+``tests/unit/agentic_ide/test_account_spawn.py``, against the real registry and+a temporary account store.++The reply is checked for two things a client cannot work without: the label,+because an account id is not something anybody can read back, and the whole+workspace state, so a switch never needs a second round-trip to be visible.+"""+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.agentic_ide.session import SessionError+from jarvis.ui.web import agentic_ide_routes as routes+++class FakeRegistry:+ """Registry stand-in: records the switch, returns a scripted account."""++ def __init__(self, *, refuse: str | None = None) -> None:+ self.calls: list[tuple[str, str]] = []+ self._refuse = refuse++ async def set_active_account(self, agent: str, account_id: str):+ if self._refuse:+ raise SessionError(self._refuse)+ self.calls.append((agent, account_id))+ return SimpleNamespace(id=account_id, label="Work seat", platform=agent)++ def active_accounts(self) -> list[dict]:+ return [+ {+ "agent": "claude",+ "display_name": "Claude Code",+ "active_account": "claude:abc123",+ "active_label": "Work seat",+ "account_count": 2,+ }+ ]++ def state(self) -> dict:+ return {"active": True, "accounts": self.active_accounts()}+++async def test_the_switch_reaches_the_registry_and_names_the_plan(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ registry = FakeRegistry()+ monkeypatch.setattr(routes, "get_registry", lambda: registry)++ result = await routes.set_active_account(+ routes.ActiveAccountRequest(agent="claude", account_id="claude:abc123")+ )++ assert registry.calls == [("claude", "claude:abc123")]+ assert result["active_account"] == "claude:abc123"+ assert result["active_label"] == "Work seat"+ # Said in the CLI's display name, not its slug — this sentence is spoken.+ assert result["message"] == "New Claude Code terminals will use Work seat."+ # The whole state comes back, so the open workspace never has to re-read.+ assert result["state"]["accounts"][0]["active_label"] == "Work seat"+++async def test_an_account_that_is_gone_answers_with_the_reason(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """404 carrying the sentence to show — never a silent no-op on the old plan."""+ monkeypatch.setattr(+ routes,+ "get_registry",+ lambda: FakeRegistry(refuse="Claude Code has no account with id 'ghost'."),+ )++ with pytest.raises(routes.HTTPException) as caught:+ await routes.set_active_account(+ routes.ActiveAccountRequest(agent="claude", account_id="ghost")+ )++ assert caught.value.status_code == 404+ assert "no account" in caught.value.detail+++async def test_reading_the_active_accounts_needs_no_workspace(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The wizard asks this before anything is open, so it must answer there."""+ monkeypatch.setattr(routes, "get_registry", lambda: FakeRegistry())++ result = await routes.get_accounts()++ assert result["ok"] is True+ assert result["accounts"][0]["display_name"] == "Claude Code"+ assert result["accounts"][0]["account_count"] == 2diff --git a/tests/unit/web/test_agentic_ide_batch_route.py b/tests/unit/web/test_agentic_ide_batch_route.pyindex befcbd4b0f..d40c1b670d 100644--- a/tests/unit/web/test_agentic_ide_batch_route.py+++ b/tests/unit/web/test_agentic_ide_batch_route.py@@ -42,11 +42,13 @@ class FakeRegistry:def __init__(self, created: list[object], capped: bool, folder: Path) -> None:self._created = createdself._capped = capped- self.calls: list[tuple[int, str | None]] = []+ self.calls: list[tuple[int, str | None, str | None]] = []self.session = SimpleNamespace(id="ide_test", folder=str(folder))- async def add_terminals(self, count: int, *, agent: str | None = None):- self.calls.append((count, agent))+ async def add_terminals(+ self, count: int, *, agent: str | None = None, account: str | None = None+ ):+ self.calls.append((count, agent, account))return self._created, self._cappeddef state(self) -> dict:@@ -69,7 +71,9 @@ async def test_a_batch_opens_the_panes_and_tells_the_clients(assert result["requested"] == 2assert result["capped"] is Falseassert [t["name"] for t in result["terminals"]] == ["Juno", "Milo"]- assert registry.calls == [(2, "claude")]+ # No account named — the registry then opens every pane of the batch on the+ # workspace's active subscription (see Registry.add_terminal).+ assert registry.calls == [(2, "claude", None)]# Exactly one event for the batch, naming every pane — five panes must not# make the open view refetch five times.@@ -103,7 +107,9 @@ async def test_a_refusal_becomes_a_conflict_with_the_reason(class Refusing:session = None- async def add_terminals(self, count: int, *, agent: str | None = None):+ async def add_terminals(+ self, count: int, *, agent: str | None = None, account: str | None = None+ ):raise SessionError("This workspace already has the maximum of 12 terminals.")def state(self) -> dict:diff --git a/tests/unit/web/test_agentic_ide_close_agent_route.py b/tests/unit/web/test_agentic_ide_close_agent_route.pynew file mode 100644index 0000000000..f2ea9f0ea4--- /dev/null+++ b/tests/unit/web/test_agentic_ide_close_agent_route.py@@ -0,0 +1,58 @@+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.ui.web import agentic_ide_routes as routes+++class _Bus:+ def __init__(self) -> None:+ self.events: list[object] = []++ async def publish(self, event: object) -> None:+ self.events.append(event)+++async def test_close_by_agent_returns_state_and_refreshes_clients(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session = SimpleNamespace(id="workspace", folder="/project")+ registry = SimpleNamespace(+ session=session,+ state=lambda: {"active": True},+ )+ closed = [SimpleNamespace(name="Cody"), SimpleNamespace(name="Cole")]++ async def _close(_registry: object, agent: str) -> list[object]:+ assert _registry is registry+ assert agent == "codex"+ return closed++ bus = _Bus()+ request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(bus=bus)))+ monkeypatch.setattr(routes, "get_registry", lambda: registry)+ monkeypatch.setattr(routes, "close_agent_terminals", _close)++ result = await routes.close_terminals_by_agent(request, "CoDeX")++ assert result == {+ "ok": True,+ "agent": "codex",+ "closed": ["Cody", "Cole"],+ "state": {"active": True},+ }+ assert len(bus.events) == 1+ assert type(bus.events[0]).__name__ == "AgenticIdeTerminalsClosed"+++def test_close_by_agent_route_is_cli_visible_and_dangerous() -> None:+ route = next(+ route+ for route in routes.router.routes+ if getattr(route, "path", "") == "/api/agentic-ide/terminals/agent/{agent}"+ )+ assert route.methods == {"DELETE"}+ assert route.openapi_extra == {"x-jarvis-dangerous": True}