Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agents): resolve misheard agent names and route Jarvis agents vs coding panes
rubenluetke10-beep6476f668994f
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex d2225ecbd2..360f9b7160 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -15513,3 +15513,34 @@ plain daemon worker through a `queue.SimpleQueue` (documented reentrant andsafe in destructors); `__del__` only enqueues and takes no lock. The worker isstarted in ordinary code (`LockedRecognizer.__init__`, `release_recognizer`).Guard: `tests/unit/plugins/wake/test_vosk_native.py::test_dropping_the_proxy_inside_an_executor_submit_does_not_deadlock`.++## BUG-227: "send Jarvis Scout a message" found no agent when speech misheard the name (HIGH, FIXED 2026-10-02)++**Symptom.** On a voice call the user asked Jarvis to message their agent+Jarvis-Scout. Speech recognition delivered "the Java Scout and Quick Meshes";+Jarvis answered "I couldn't find agents with those names in the open+workspaces" and did nothing. The user's own later retelling was transcribed as+"Jarvis Code" — the same name garbled a third way.++**Cause.** Two gaps. (1) Every agent lookup compared strings exactly:+`Roster.resolve` (id, case-insensitive name, slug) and the coding-pane+resolver in `agentic_ide/orchestration.py` (exact or same word set), so any+misheard spelling was "unknown". (2) The live backend's instructions only+described `workspace-orchestrate`, so a request naming a Jarvis agent went to+the coding-pane tool, which knows nothing about the team and answered "nothing+open matches" — with no pointer to `delegate_to_agent` / `message_agent`.++**Fix.** `jarvis/core/spoken_names.py` resolves a spoken name with+normalization, aliases, Jaro-Winkler and Cologne phonetics, plus a small+coding-context bonus, and returns act / ask / none; every resolution is logged+(`name resolution [surface]: heard=... -> ... score=... method=...`).+`jarvis/society/agent_names.py` applies it to the roster (exact matches first,+so ids and REST paths are unchanged; title, role and user aliases stored as+`agent_aliases:<id>` in `society_meta`). `delegate_to_agent`, `society_status`+and the message tools use it: a close name returns `needs_clarification` with a+"did you mean" question, an unknown one lists the available agents and says+when it names a coding pane instead. `workspace-orchestrate` resolves misheard+custom pane names the same way (positions stay exact) and, when a name is no+pane but a Jarvis agent, says so in `jarvis_agent`. Guards:+`tests/unit/core/test_spoken_names.py`, `tests/unit/society/test_agent_names.py`,+`tests/unit/plugins/tool/test_delegate_to_agent.py`.diff --git a/jarvis/agentic_ide/orchestration.py b/jarvis/agentic_ide/orchestration.pyindex 588aeb9ce4..26a20e178f 100644--- a/jarvis/agentic_ide/orchestration.py+++ b/jarvis/agentic_ide/orchestration.py@@ -147,6 +147,30 @@ def _best(reference: str, items: list, key: Callable[[Any], tuple]) -> list:return [item for score, item in scored if top and score == top]+def _spoken_pane(reference: str, agents: list[dict]) -> tuple[list[dict], bool]:+ """Panes a misheard CUSTOM name means, and whether the match is certain.++ Positional call-signs ("T3") stay exact-only (see ``names.py``): "T1" and+ "T11" are two real panes, never one garbled word.+ """+ from jarvis.core.spoken_names import NameCandidate, resolve_name++ from .names import position_of++ custom = [a for a in agents if a.get("name") and position_of(a["name"]) is None]+ if not custom:+ return [], False+ resolution = resolve_name(+ reference,+ [NameCandidate(key=a["id"], label=a["name"], names=(a["name"],)) for a in custom],+ surface="workspace-orchestrate",+ )+ if resolution.decision == "none":+ return [], False+ keys = [m.key for m in resolution.candidates]+ return [a for key in keys for a in custom if a["id"] == key], resolution.decision == "act"++def _distance(a: str, b: str) -> int:"""Levenshtein distance, enough to recognise a mis-copied id."""if abs(len(a) - len(b)) > _NEAR_MISS:@@ -287,7 +311,13 @@ class WorkspaceOrchestrator:agents = [a for a in workspace["agents"] if a["accepts_tasks"]]if agent_ref:named = _best(agent_ref, agents, lambda a: ((a["id"],), (a["name"],)))- agents = named or [a for a in agents if _matches(agent_ref, a["agent"])]+ by_cli = [a for a in agents if _matches(agent_ref, a["agent"])]+ if not named and not by_cli:+ named, certain = _spoken_pane(agent_ref, agents)+ if named and not certain:+ # Close but not certain: a question, never a guess.+ return self._choice("agent", named, graph)+ agents = named or by_cliif len(agents) != 1:return self._choice("agent", agents, graph, unmatched=agent_ref)else:diff --git a/jarvis/brain/workspace_tool.py b/jarvis/brain/workspace_tool.pyindex 88e3282b71..d6293f703f 100644--- a/jarvis/brain/workspace_tool.py+++ b/jarvis/brain/workspace_tool.py@@ -6,6 +6,41 @@ from jarvis.core.agent_brief import AGENT_BRIEF_RULEfrom jarvis.core.protocols import ExecutionContext, ToolResult, WorkspaceOrchestrationGateway+def _point_at_jarvis_agent(args: dict, result: dict) -> dict:+ """Say so when a name no coding pane carries is one of the user's Jarvis agents.++ Live 2026-10-02: "send Jarvis Scout a quick message" went to this tool,+ found no pane called that, and the user heard "I couldn't find agents+ with those names" - while Jarvis-Scout sat idle on the team.+ """+ agent_ref = str(args.get("agent") or "").strip()+ if not agent_ref or result.get("status") not in {"needs_clarification", "unavailable"}:+ return result+ if args.get("action") == "create":+ return result+ try:+ from jarvis.society.agent_names import jarvis_agent_hint++ hint = jarvis_agent_hint(agent_ref, context=str(args.get("prompt") or ""))+ except Exception: # noqa: BLE001 - the hint is advisory; the pane result stands+ import logging++ logging.getLogger(__name__).warning("workspace tool: agent hint failed", exc_info=True)+ return result+ if hint is None:+ return result+ names = " or ".join(f"'{name}'" for name in hint["agents"])+ reason = (+ f"'{agent_ref}' is not a coding pane in the Agentic IDE; it names the user's Jarvis "+ f"agent {names}. Use delegate_to_agent (to assign work) or message_agent (to send a "+ "message) with that agent name instead."+ )+ if not hint["certain"]:+ reason += f" The name is not certain: ask the user whether they mean {names} first."+ earlier = str(result.get("reason") or "").strip()+ return {**result, "jarvis_agent": hint, "reason": f"{reason} {earlier}".strip()}++class WorkspaceOrchestrationTool:name = "workspace-orchestrate"# Handing a task to the user's own coding agent is Jarvis's job, not an@@ -14,7 +49,10 @@ class WorkspaceOrchestrationTool:risk_tier = "monitor"is_action_tool = Truedescription = (- "Route coding tasks to Projects > Workspaces > coding agents. "+ "Route coding tasks to Projects > Workspaces > coding agents (the coding panes of "+ "the Agentic IDE). The user's named Jarvis agents (their team, e.g. a Scout or a "+ "Gmail agent) are NOT panes: reach them with delegate_to_agent or message_agent. "+ "A resolve result carrying jarvis_agent means the name is such an agent. ""When the user asks for a NEW agent, terminal or session (for example 'spawn two ""Claude Code agents in the VMs workspace'), call create: it opens count new panes of ""the named cli in the named or visible workspace and, with prompt, hands each the "@@ -163,6 +201,7 @@ class WorkspaceOrchestrationTool:except ValueError as exc:return ToolResult(success=False, output=None, error=str(exc))status = result.get("status")+ result = _point_at_jarvis_agent(args, result)return ToolResult(success=result.get("success") is not Falseand status not in {"uncertain", "unavailable", "stale_target", "not_accepted"},diff --git a/jarvis/core/spoken_names.py b/jarvis/core/spoken_names.pynew file mode 100644index 0000000000..43747d6489--- /dev/null+++ b/jarvis/core/spoken_names.py@@ -0,0 +1,538 @@+"""Resolve a spoken or transcribed name to one of a known set of names.++Speech recognition rarely returns a name the way it is spelled: "Jarvis Code"+comes back as "Jarvis Kot", "Jarwis Code", "Davis Code" or "Jarvis Coder",+and "Jarvis Scout" as "Java Scout" (live 2026-10-02 — the hand-off silently+failed because every lookup compared strings exactly). This module is the one+place that turns such a reference into a ranked, scored decision:++1. **Normalization** — case, umlauts, accents, hyphens and punctuation are+ folded, and filler words a person wraps around a name ("the", "agent",+ "unseren") are dropped.+2. **Exact and alias** — the folded reference equals a name, an id, or one of+ the candidate's aliases.+3. **Fuzzy** — Jaro-Winkler similarity, word by word, so one garbled word does+ not sink a two-word name.+4. **Phonetic** — Cologne phonetics (Koelner Phonetik, built for German+ pronunciation) plus a spelling fold for the substitutions English and+ German transcripts produce (c/k, v/w/f, j/i ...): "Kot" and "Code" sound+ alike, so they match.+5. **Context** — when the surrounding request is clearly about programming, a+ candidate whose role is coding gets a small bonus. Context can tip a close+ call; it can never create a match on its own.++The result is a decision, not just a best guess: ``act`` (one clear winner),+``ask`` (close, or several close candidates — the caller asks "did you mean+...?"), or ``none`` (nothing close — the caller lists what exists). Every+resolution is logged with the raw text, winner, score and method so a future+miss can be traced from ``jarvis_desktop.log`` alone.++Pure Python, no dependencies, no I/O: safe on the voice path and on every OS.+"""++from __future__ import annotations++import logging+import math+import re+import unicodedata+from collections.abc import Iterable, Sequence+from dataclasses import dataclass, field+from typing import Final, Literal++log = logging.getLogger(__name__)++Decision = Literal["act", "ask", "none"]++#: At or above this score, with a clear margin, the caller acts on the match.+ACT_SCORE: Final[float] = 0.90+#: At or above this score the caller asks "did you mean ...?" instead of giving up.+ASK_SCORE: Final[float] = 0.68+#: The winner must lead the runner-up by this much to be acted on; two+#: candidates closer than this are a question, never a coin flip.+ACT_MARGIN: Final[float] = 0.06+#: What a request that is clearly about programming adds to a coding candidate.+CONTEXT_BONUS: Final[float] = 0.04+#: Score of a word pair whose Cologne codes are equal but whose spelling is not.+_PHONETIC_EQUAL: Final[float] = 0.92+#: Weight of a word that names the product rather than one agent ("Jarvis").+_WEAK_WEIGHT: Final[float] = 0.35+#: A name found INSIDE a longer reference ("Java Scout and Quick Meshes")+#: scores this fraction of a reference that is only the name.+_WINDOW_PENALTY: Final[float] = 0.92+#: How many "did you mean" candidates a resolution carries.+_MAX_CANDIDATES: Final[int] = 3++#: Words people wrap around a name when they say it. They never identify one.+_FILLER: Final[frozenset[str]] = frozenset(+ # i18n-allow: speech-recognition input vocabulary, not prose+ {+ "agent", "agents", "agenten", "agentin", "bot", "bots",+ "the", "our", "my", "your", "a", "an", "to", "please",+ "der", "die", "das", "den", "dem", "des", "ein", "eine", "einen", "einem", # i18n-allow+ "unser", "unsere", "unseren", "unserem", "unserer", "unseres", # i18n-allow+ "mein", "meine", "meinen", "meinem", "meiner", "dein", "deine", "deinen", # i18n-allow+ "bitte", "am", # i18n-allow+ "el", "la", "los", "las", "mi", "mis", "nuestro", "nuestra", "por", "favor",+ }+) # fmt: skip++#: Words that name the product, not an agent: "Jarvis Code" and "Jarvis Scout"+#: share "Jarvis", so it must not be what decides between them.+_WEAK: Final[frozenset[str]] = frozenset({"jarvis", "personal"})++#: Product names a user says on purpose. Speech recognition does not garble+#: an agent name INTO one of them, so a spoken product name only ever matches+#: itself: "Codex" must never land on an agent called "Jarvis Code".+_PRODUCTS: Final[frozenset[str]] = frozenset(+ {+ "claude", "codex", "gemini", "cursor", "copilot", "aider", "grok", "deepseek",+ "antigravity", "chatgpt", "openai", "gpt", "ollama",+ }+) # fmt: skip+_PRODUCT_CAP: Final[float] = 0.5++#: A request is "about programming" when it carries one of these stems.+_CODING_CONTEXT = re.compile(+ # i18n-allow: speech-recognition input vocabulary, not prose+ r"\b(?:cod(?:e|en|ing|er|ex)|programm\w*|entwickl\w*|implement\w*|refactor\w*|"+ r"bug\w*|fix\w*|commit\w*|pull request|repo\w*|codebase|debug\w*|"+ r"developer|programar|c[oó]digo)\b",+ re.IGNORECASE,+)++#: A candidate's role is coding when its name, title or description says so.+_CODING_ROLE = re.compile(+ # i18n-allow: speech-recognition input vocabulary, not prose+ r"\b(?:code|coder|coding|programm\w*|entwickl\w*|developer|dev|engineer\w*)\b",+ re.IGNORECASE,+)+++@dataclass(frozen=True)+class NameCandidate:+ """One thing a spoken name can resolve to.++ ``key`` is the stable identity (an agent id), ``label`` what a person sees.+ ``names`` are spellings that count as the name itself, ``aliases`` further+ ways to say it. ``roles`` are tags such as ``"coding"`` the context gate+ reads.+ """++ key: str+ label: str+ names: tuple[str, ...] = ()+ aliases: tuple[str, ...] = ()+ roles: frozenset[str] = frozenset()+++@dataclass(frozen=True)+class NameMatch:+ key: str+ label: str+ score: float+ method: str # exact | alias | fuzzy | phonetic+ form: str # the name or alias that matched++ def as_dict(self) -> dict[str, object]:+ return {+ "key": self.key,+ "label": self.label,+ "score": round(self.score, 3),+ "method": self.method,+ "matched": self.form,+ }+++@dataclass(frozen=True)+class NameResolution:+ """What a spoken reference resolved to, and what the caller should do."""++ raw: str+ decision: Decision+ best: NameMatch | None+ candidates: tuple[NameMatch, ...] = field(default_factory=tuple)+ context_used: bool = False++ @property+ def key(self) -> str | None:+ return self.best.key if self.best is not None and self.decision == "act" else None++ def as_dict(self) -> dict[str, object]:+ return {+ "heard": self.raw,+ "decision": self.decision,+ "best": self.best.as_dict() if self.best else None,+ "candidates": [c.as_dict() for c in self.candidates],+ "context_used": self.context_used,+ }+++# --------------------------------------------------------------------------- #+# Normalization #+# --------------------------------------------------------------------------- #++_UMLAUTS = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss"}) # i18n-allow: folding+++def normalize(text: str) -> str:+ """Lowercase ASCII words separated by single spaces.++ "Jarvis-Code!" and "jarvis code" both become "jarvis code"; umlauts fold+ to their two-letter spelling, other accents are dropped.+ """+ folded = str(text or "").casefold().translate(_UMLAUTS)+ folded = unicodedata.normalize("NFKD", folded).encode("ascii", "ignore").decode("ascii")+ return " ".join(re.sub(r"[^a-z0-9]+", " ", folded).split())+++def name_tokens(text: str) -> tuple[str, ...]:+ """The words of ``text`` that can identify a name (fillers dropped).++ A reference made only of fillers ("the agent") keeps its words, so it still+ compares as what it is rather than as nothing.+ """+ words = normalize(text).split()+ kept = [w for w in words if w not in _FILLER]+ return tuple(kept or words)+++# --------------------------------------------------------------------------- #+# Similarity #+# --------------------------------------------------------------------------- #+++def jaro_winkler(a: str, b: str, *, prefix_scale: float = 0.1) -> float:+ """Jaro-Winkler similarity in [0, 1]; 1.0 means identical."""+ if a == b:+ return 1.0 if a else 0.0+ if not a or not b:+ return 0.0+ window = max(0, max(len(a), len(b)) // 2 - 1)+ a_hits = [False] * len(a)+ b_hits = [False] * len(b)+ matches = 0+ for i, ch in enumerate(a):+ for j in range(max(0, i - window), min(len(b), i + window + 1)):+ if not b_hits[j] and b[j] == ch:+ a_hits[i] = b_hits[j] = True+ matches += 1+ break+ if not matches:+ return 0.0+ a_seq = [ch for ch, hit in zip(a, a_hits, strict=True) if hit]+ b_seq = [ch for ch, hit in zip(b, b_hits, strict=True) if hit]+ transpositions = sum(x != y for x, y in zip(a_seq, b_seq, strict=True)) / 2+ jaro = (matches / len(a) + matches / len(b) + (matches - transpositions) / matches) / 3+ prefix = 0+ for x, y in zip(a[:4], b[:4], strict=False):+ if x != y:+ break+ prefix += 1+ return jaro + prefix * prefix_scale * (1 - jaro)+++def koelner_phonetik(word: str) -> str:+ """Cologne phonetics code of one word ("Jarvis" -> "0738", "Kot" -> "42").++ The German counterpart of Soundex: letters that sound alike in German share+ a digit, so a transcript that spells a name the way it sounds lands on the+ same code as the real spelling.+ """+ letters = re.sub(r"[^a-z]", "", normalize(word).replace(" ", ""))+ if not letters:+ return ""+ digits: list[str] = []+ for i, ch in enumerate(letters):+ prev = letters[i - 1] if i else ""+ nxt = letters[i + 1] if i + 1 < len(letters) else ""+ if ch in "aeijouy":+ code = "0"+ elif ch == "h":+ code = ""+ elif ch == "b":+ code = "1"+ elif ch == "p":+ code = "3" if nxt == "h" else "1"+ elif ch in "dt":+ code = "8" if nxt in ("c", "s", "z") else "2"+ elif ch in "fvw":+ code = "3"+ elif ch in "gkq":+ code = "4"+ elif ch == "c":+ if i == 0:+ code = "4" if nxt in tuple("ahkloqrux") else "8"+ elif prev in ("s", "z"):+ code = "8"+ else:+ code = "4" if nxt in tuple("ahkoqux") else "8"+ elif ch == "x":+ code = "8" if prev in ("c", "k", "q") else "48"+ elif ch == "l":+ code = "5"+ elif ch in "mn":+ code = "6"+ elif ch == "r":+ code = "7"+ elif ch in "sz":+ code = "8"+ else: # digits never reach here; anything else carries no sound+ code = ""+ digits.append(code)+ raw = "".join(digits)+ squeezed = "".join(ch for i, ch in enumerate(raw) if i == 0 or ch != raw[i - 1])+ return squeezed[:1] + squeezed[1:].replace("0", "")+++_FOLD_DIGRAPHS: Final[tuple[tuple[str, str], ...]] = (+ ("sch", "s"),+ ("ph", "f"),+ ("ck", "k"),+ ("th", "t"),+ ("qu", "k"),+ ("ai", "ei"),+ ("ay", "ei"),+ ("ey", "ei"),+)+_FOLD_LETTERS = str.maketrans({"c": "k", "z": "s", "y": "i", "v": "f", "w": "f", "j": "i"})+++def spelling_fold(word: str) -> str:+ """Fold spellings that sound the same ("Jarwis" and "Jarvis" -> "iarfis").++ The substitutions transcripts actually make in English and German; it+ complements the Cologne code, which is coarser.+ """+ key = normalize(word).replace(" ", "")+ for src, dst in _FOLD_DIGRAPHS:+ key = key.replace(src, dst)+ key = key.translate(_FOLD_LETTERS)+ key = key[:1] + key[1:].replace("h", "")+ return "".join(ch for i, ch in enumerate(key) if i == 0 or ch != key[i - 1])+++def word_similarity(spoken: str, name: str) -> tuple[float, str]:+ """How close one spoken word is to one name word, and by which method."""+ if spoken == name:+ return 1.0, "exact"+ if spoken in _PRODUCTS or name in _PRODUCTS:+ return min(_PRODUCT_CAP, jaro_winkler(spoken, name)), "fuzzy"+ fold_a, fold_b = spelling_fold(spoken), spelling_fold(name)+ if fold_a and fold_a == fold_b:+ return 0.97, "phonetic" # "Jarwis" / "Jarvis": spelled apart, said alike+ fuzzy = max(jaro_winkler(spoken, name), jaro_winkler(fold_a, fold_b))+ phonetic = 0.0+ if min(len(spoken), len(name)) >= 3:+ code_a, code_b = koelner_phonetik(spoken), koelner_phonetik(name)+ # A two-digit code is shared by many short words ("Guide", "Gut" and+ # "Code" are all 42), so it only counts when the first sound agrees+ # too ("Kot" / "Code").+ same_onset = fold_a[:1] == fold_b[:1]+ if code_a == code_b and (len(code_a) >= 3 or (len(code_a) == 2 and same_onset)):+ phonetic = _PHONETIC_EQUAL+ if phonetic > fuzzy:+ return phonetic, "phonetic"+ return fuzzy, "fuzzy"+++def _weight(word: str, frequency: dict[str, int]) -> float:+ """Rare words decide; the product name and words shared by many names do not."""+ base = _WEAK_WEIGHT if word in _WEAK else 1.0+ return base / (1.0 + math.log(max(1, frequency.get(word, 1))))+++def _form_score(+ spoken: tuple[str, ...], form: tuple[str, ...], frequency: dict[str, int]+) -> tuple[float, str]:+ """Soft word-aligned F-score of a spoken reference against one name form.++ Precision asks "is every spoken word part of the name?", recall "is every+ name word in what was said?" — both weighted, so the product name or a word+ every agent carries cannot carry a match on its own.+ """+ if spoken == form:+ return 1.0, "exact"+ # One-to-one word alignment, best pairs first: a spoken word can stand+ # for ONE name word only, so "Claude Code" cannot use "code" twice to+ # look like "Jarvis Code".+ pairs = sorted(+ (+ (*word_similarity(a, b), i, j)+ for i, a in enumerate(spoken)+ for j, b in enumerate(form)+ ),+ key=lambda item: -item[0],+ )+ spoken_best = [0.0] * len(spoken)+ form_best = [0.0] * len(form)+ used_spoken: set[int] = set()+ used_form: set[int] = set()+ methods: list[str] = []+ for score, how, i, j in pairs:+ if i in used_spoken or j in used_form:+ continue+ used_spoken.add(i)+ used_form.add(j)+ spoken_best[i] = form_best[j] = score+ if score >= 0.8:+ methods.append(how)++ def side(words: tuple[str, ...], best: list[float]) -> float:+ weights = [_weight(word, frequency) for word in words]+ total = sum(w * b for w, b in zip(weights, best, strict=True))+ return total / sum(weights) if sum(weights) else 0.0++ precision = side(spoken, spoken_best)+ recall = side(form, form_best)+ score = 2 * precision * recall / (precision + recall) if precision + recall else 0.0+ # A name said as one glued word ("Jarviscode"), or a one-word name said as two.+ if (len(spoken) == 1) != (len(form) == 1):+ glued = jaro_winkler("".join(spoken), "".join(form))+ if glued * 0.95 > score:+ score, methods = glued * 0.95, ["fuzzy"]+ method = "phonetic" if "phonetic" in methods else "fuzzy"+ return score, method+++def _reference_score(+ spoken: tuple[str, ...], form: tuple[str, ...], frequency: dict[str, int]+) -> tuple[float, str]:+ """``_form_score``, also trying the name as a phrase inside a longer reference."""+ score, method = _form_score(spoken, form, frequency)+ if score >= 1.0 or len(spoken) <= len(form):+ return score, method+ size = len(form)+ for start in range(len(spoken) - size + 1):+ window, how = _form_score(spoken[start : start + size], form, frequency)+ if window * _WINDOW_PENALTY > score:+ score, method = window * _WINDOW_PENALTY, ("fuzzy" if how == "exact" else how)+ return score, method+++# --------------------------------------------------------------------------- #+# Resolution #+# --------------------------------------------------------------------------- #+++def is_coding_context(text: str) -> bool:+ """Whether a request is clearly about programming."""+ return bool(_CODING_CONTEXT.search(str(text or "")))+++def has_coding_role(*texts: str) -> bool:+ """Whether a name, title or description marks a coding role."""+ return any(_CODING_ROLE.search(normalize(t)) for t in texts if t)+++def resolve_name(+ spoken: str,+ candidates: Sequence[NameCandidate],+ *,+ context: str = "",+ surface: str = "",+) -> NameResolution:+ """Score ``spoken`` against every candidate and decide what to do.++ ``context`` is the rest of the request (the task text); it only ever adds+ ``CONTEXT_BONUS`` to a coding candidate in a coding request. ``surface``+ names the caller in the log line.+ """+ raw = str(spoken or "").strip()+ spoken_tokens = name_tokens(raw)+ if not raw or not spoken_tokens or not candidates:+ resolution = NameResolution(raw=raw, decision="none", best=None)+ _log(resolution, surface)+ return resolution++ forms: list[tuple[NameCandidate, str, tuple[str, ...], bool]] = []+ for cand in candidates:+ for text in cand.names:+ if tokens := name_tokens(text):+ forms.append((cand, text, tokens, False))+ for text in cand.aliases:+ if tokens := name_tokens(text):+ forms.append((cand, text, tokens, True))+ # How many candidates carry each word: shared words decide nothing.+ frequency: dict[str, int] = {}+ for cand in candidates:+ words = {w for _c, _t, toks, _a in forms if _c is cand for w in toks}+ for word in words:+ frequency[word] = frequency.get(word, 0) + 1++ coding = is_coding_context(context)+ per_candidate: dict[str, NameMatch] = {}+ for cand, text, tokens, is_alias in forms:+ score, method = _reference_score(spoken_tokens, tokens, frequency)+ if method == "exact":+ method = "alias" if is_alias else "exact"+ elif is_alias:+ # A loose match on an alias is weaker evidence than on the name.+ score *= 0.97+ if coding and "coding" in cand.roles and ASK_SCORE <= score < 1.0:+ score = min(0.99, score + CONTEXT_BONUS)+ current = per_candidate.get(cand.key)+ if current is None or score > current.score:+ per_candidate[cand.key] = NameMatch(cand.key, cand.label, score, method, text)++ ranked = sorted(per_candidate.values(), key=lambda m: (-m.score, m.label))+ best = ranked[0]+ runner_up = ranked[1].score if len(ranked) > 1 else 0.0+ close = tuple(m for m in ranked if m.score >= ASK_SCORE)[:_MAX_CANDIDATES]+ if best.score >= ACT_SCORE and best.score - runner_up >= ACT_MARGIN:+ decision: Decision = "act"+ elif best.score >= 1.0 and runner_up < 1.0:+ decision = "act" # an exact name beats any near miss, however close+ elif close:+ decision = "ask"+ else:+ decision = "none"+ resolution = NameResolution(+ raw=raw,+ decision=decision,+ best=best,+ candidates=close if decision != "act" else (best,),+ context_used=coding,+ )+ _log(resolution, surface, runner_up=ranked[1] if len(ranked) > 1 else None)+ return resolution+++def _log(resolution: NameResolution, surface: str, *, runner_up: NameMatch | None = None) -> None:+ best = resolution.best+ log.info(+ "name resolution [%s]: heard=%r -> %s score=%.3f method=%s decision=%s%s%s",+ surface or "-",+ resolution.raw,+ f"{best.label} ({best.key})" if best else "nothing",+ best.score if best else 0.0,+ best.method if best else "-",+ resolution.decision,+ f" runner_up={runner_up.label}:{runner_up.score:.3f}" if runner_up else "",+ " context=coding" if resolution.context_used else "",+ )+++def labels(matches: Iterable[NameMatch]) -> list[str]:+ return [m.label for m in matches]+++__all__ = [+ "ACT_MARGIN",+ "ACT_SCORE",+ "ASK_SCORE",+ "CONTEXT_BONUS",+ "NameCandidate",+ "NameMatch",+ "NameResolution",+ "has_coding_role",+ "is_coding_context",+ "jaro_winkler",+ "koelner_phonetik",+ "labels",+ "name_tokens",+ "normalize",+ "resolve_name",+ "spelling_fold",+ "word_similarity",+]diff --git a/jarvis/live/config.py b/jarvis/live/config.pyindex 7863c6b4bf..172f78c423 100644--- a/jarvis/live/config.py+++ b/jarvis/live/config.py@@ -55,6 +55,10 @@ class LiveConfig(BaseModel):"When a call returns confirmation_required, ask the user; after an explicit ""yes call confirm_action with its approval_id. Call end_call only when the ""user asks to hang up. "+ "The user's named Jarvis agents (their team) take work through "+ "delegate_to_agent and messages through message_agent; coding panes in the "+ "Agentic IDE are a different thing. When a named agent is not found on one "+ "side, check the other before telling the user it does not exist. ""For coding work use workspace-orchestrate: inspect and resolve the current ""Project/Workspace/agent graph, then send to the returned stable IDs. Explicit ""project or workspace references override visible context. Do not switch the UI "diff --git a/jarvis/plugins/tool/delegate_to_agent.py b/jarvis/plugins/tool/delegate_to_agent.pyindex 9fe5d381c6..4fc3c4dea9 100644--- a/jarvis/plugins/tool/delegate_to_agent.py+++ b/jarvis/plugins/tool/delegate_to_agent.py@@ -19,12 +19,14 @@ built on first use by the server, after the brain exists.from __future__ import annotations+import asyncioimport loggingfrom collections.abc import Callablefrom typing import Any, Finalfrom jarvis.core.agent_brief import AGENT_BRIEF_RULEfrom jarvis.core.protocols import ExecutionContext, ToolResult+from jarvis.society.agent_names import AgentLookup, coding_pane_hint, lookup_agentfrom jarvis.society.communication import REPLY_POLICY_SCHEMA, select_reply_policylog = logging.getLogger(__name__)@@ -56,6 +58,21 @@ _NO_AGENT: Final[dict[str, str]] = {"en": "I do not know an agent called {target}.","es": "No conozco ningún agente llamado {target}.",}+_ASK_AGENT: Final[dict[str, str]] = {+ "de": "Meinst du {names}?", # i18n-allow: spoken reply+ "en": "Did you mean {names}?",+ "es": "¿Te refieres a {names}?",+}+_OR: Final[dict[str, str]] = {+ "de": " oder ", # i18n-allow: spoken reply+ "en": " or ",+ "es": " o ",+}+_AVAILABLE: Final[dict[str, str]] = {+ "de": "Verfügbar sind: {names}.", # i18n-allow: spoken reply+ "en": "Available agents: {names}.",+ "es": "Agentes disponibles: {names}.",+}_NO_FIT: Final[dict[str, str]] = {"de": "Keiner deiner Agenten passt zu dieser Aufgabe.", # i18n-allow: spoken reply"en": "None of your agents fits this task.",@@ -135,6 +152,10 @@ class DelegateToAgentTool:"empty to let the lead pick the agent whose hands fit the task. The agent works in ""the background; you acknowledge now and its result follows reply_policy. ""Never for inventory/status questions or tasks the user wants done right here. "+ "Not for coding panes in the Agentic IDE (T1, or a named Claude Code / Codex "+ "session): those go through workspace-orchestrate. Pass the agent's name as heard; "+ "the app matches misheard names and, when unsure, returns needs_clarification with "+ "a question to ask before calling again. ""Turn the user's intent into an actionable brief: objective, known target, relevant ""context, scope, constraints and completion evidence. Do not merely paraphrase or ""invent facts. Include context and completion_criteria so the agent can act independently. "@@ -191,16 +212,15 @@ class DelegateToAgentTool:runtime = await self._runtime()if runtime is None:return ToolResult(success=False, output=_NOT_READY[lang], error="society unavailable")- target = await runtime.roster.resolve(target_key) if target_key else None- if not target_key:+ match_info = None+ if target_key:+ found = await lookup_agent(runtime, target_key, context=task, surface=self.name)+ if found.agent is None:+ return await _unresolved(found, lang)+ target, match_info = found.agent, found.match_info()+ else:target = runtime.pick_agent(task)if target is None:- if target_key:- return ToolResult(- success=False,- output=_NO_AGENT[lang].format(target=target_key),- error="target_unknown",- )return ToolResult(success=False, output=_NO_FIT[lang], error="no_agent_fits")from jarvis.society.events import MsgType@@ -244,6 +264,9 @@ class DelegateToAgentTool:"assignment_id": env.event_id,"trace_id": env.trace_id,"reply_policy": policy,+ # Said differently than it is spelled: the reply names the agent+ # that was actually reached, so the user hears who got the task.+ **({"name_match": match_info} if match_info else {}),}if outcome is not None and outcome.msg_type is MsgType.VETO:reason = str(outcome.payload.get("text") or outcome.payload.get("reason") or "")@@ -289,6 +312,54 @@ class DelegateToAgentTool:return runtime+def _join(names: list[str], lang: str) -> str:+ if len(names) <= 1:+ return "".join(names)+ return ", ".join(names[:-1]) + _OR[lang] + names[-1]+++async def _unresolved(found: AgentLookup, lang: str) -> ToolResult:+ """The honest answer for a name no agent clearly carries: ask, or list who exists.++ Never a silent "unknown": a close name becomes a question, and a name that+ is no Jarvis agent but a coding pane in the Agentic IDE says so, because+ the two kinds of agent are reached through different tools.+ """+ if found.decision == "ask" and found.candidates:+ names = [a.name for a in found.candidates]+ return ToolResult(+ success=False,+ output={+ "status": "needs_clarification",+ "heard": found.heard,+ "candidates": names,+ "question": _ASK_AGENT[lang].format(names=_join(names, lang)),+ "next_step": "Ask the user this question; call again with the confirmed name.",+ },+ error="target_ambiguous",+ )+ reply = _NO_AGENT[lang].format(target=found.heard)+ names = found.available_names()+ roster = _AVAILABLE[lang].format(names=", ".join(names)) if names else _EMPTY_ROSTER[lang]+ reply += " " + roster+ hint = await asyncio.to_thread(coding_pane_hint, found.heard)+ if hint:+ panes = ", ".join(f"{p['agent']} ({p['workspace']})" for p in hint["panes"])+ reply += (+ f" Note: '{found.heard}' matches a coding pane in the Agentic IDE ({panes}), not a "+ "Jarvis agent - reach it with workspace-orchestrate (resolve, then send)."+ )+ return ToolResult(success=False, output=reply, error="target_unknown")+++async def _status_target(runtime: Any, target_key: str, lang: str) -> Any:+ """The agent a status question names, or the ``ToolResult`` that explains why not."""+ found = await lookup_agent(runtime, target_key, surface="society_status")+ if found.agent is not None:+ return found.agent+ return await _unresolved(found, lang)++class SocietyStatusTool:"""What an agent (or the whole team) is doing — read-only, no model call."""@@ -355,9 +426,9 @@ class SocietyStatusTool:if latest_assignment:if not target_key:return ToolResult(success=False, output=None, error="agent required")- target = await runtime.roster.resolve(target_key)- if target is None:- return ToolResult(success=False, output=None, error="target_unknown")+ target = await _status_target(runtime, target_key, lang)+ if isinstance(target, ToolResult):+ return targetassignment = await runtime.store.latest_assignment_for_agent(target.agent_id,from_agent=runtime.lead_id,@@ -422,13 +493,9 @@ class SocietyStatusTool:if args.get("details") is True:targets = await runtime.roster.list()if target_key:- target = await runtime.roster.resolve(target_key)- if target is None:- return ToolResult(- success=False,- output=_NO_AGENT[lang].format(target=target_key),- error="target_unknown",- )+ target = await _status_target(runtime, target_key, lang)+ if isinstance(target, ToolResult):+ return targettargets = [target]rows = []for agent in targets:@@ -459,13 +526,9 @@ class SocietyStatusTool:if not names:return ToolResult(success=True, output=_EMPTY_ROSTER[lang])return ToolResult(success=True, output=_ROSTER[lang].format(names=names))- target = await runtime.roster.resolve(target_key)- if target is None:- return ToolResult(- success=False,- output=_NO_AGENT[lang].format(target=target_key),- error="target_unknown",- )+ target = await _status_target(runtime, target_key, lang)+ if isinstance(target, ToolResult):+ return targetif runtime.scheduler.active_runs(target.agent_id) > 0:events = await runtime.store.events_for_agent(target.agent_id, limit=5)text = next((e.text for e in reversed(events) if e.text), "")diff --git a/jarvis/society/agent_names.py b/jarvis/society/agent_names.pynew file mode 100644index 0000000000..81174a9f7c--- /dev/null+++ b/jarvis/society/agent_names.py@@ -0,0 +1,316 @@+"""Find the Jarvis agent a spoken name means — and say when it means a pane.++``Roster.resolve`` stays exact (ids, REST routes and the scheduler depend on+that). This module is the forgiving front door the voice and chat tools use:+it scores a spoken reference against every live agent with+``jarvis.core.spoken_names`` and returns act / ask / none.++Aliases come from three places, all merged here:++* the agent itself — its name, its id spelled as words, its title (unless the+ title is a generic tier word such as "Specialist");+* its role — an agent whose name or title says it codes also answers to+ "coding agent", "code agent", "coder", "Programmierer" ...+ (``ROLE_ALIASES`` — the one list to extend for a new role);+* the user — extra spellings stored per agent in ``society_meta`` under+ ``agent_aliases:<agent_id>`` (``set_custom_aliases``).++It also answers the cross-question that caused the 2026-10-02 miss: a name+that is no Jarvis agent may be a coding pane in the Agentic IDE, and a name a+coding-pane lookup cannot find may be a Jarvis agent. Each side can ask the+other (``coding_pane_hint`` / ``jarvis_agent_hint``), so a tool result can+point the model at the right tool instead of reporting "not found".+"""++from __future__ import annotations++import json+import logging+from collections.abc import Iterable, Sequence+from dataclasses import dataclass, field+from typing import Any, Final++from jarvis.core.spoken_names import (+ NameCandidate,+ NameResolution,+ has_coding_role,+ normalize,+ resolve_name,+)++from .roster import LEAD_AGENT_ID, AgentRecord, AgentState++log = logging.getLogger(__name__)++#: Meta key prefix for the user's own aliases of one agent (JSON list).+ALIAS_META_PREFIX: Final[str] = "agent_aliases:"+_MAX_ALIASES: Final[int] = 20+_MAX_ALIAS_LEN: Final[int] = 60++#: Extra ways to say an agent of a given role. Extend here for a new role.+ROLE_ALIASES: Final[dict[str, tuple[str, ...]]] = {+ "coding": (+ # i18n-allow: speech-recognition input vocabulary, not prose+ "coding agent",+ "code agent",+ "coder",+ "programmierer",+ "entwickler",+ "developer",+ ),+}++#: Titles that describe a tier, not one agent; never an alias.+_GENERIC_TITLES: Final[frozenset[str]] = frozenset(+ {"specialist", "assistant", "lead", "orchestrator", "agent", ""}+)++#: The user's aliases as last read, so the synchronous path (the coding-pane+#: tool) sees the same spellings the async tools do.+_alias_cache: dict[str, tuple[str, ...]] = {}+++@dataclass(frozen=True)+class AgentLookup:+ """A resolved agent reference: the decision plus what the tools report."""++ heard: str+ resolution: NameResolution+ agent: AgentRecord | None = None+ candidates: tuple[AgentRecord, ...] = ()+ roster: tuple[AgentRecord, ...] = field(default_factory=tuple)++ @property+ def decision(self) -> str:+ return self.resolution.decision++ def available_names(self) -> list[str]:+ return [a.name for a in self.roster if a.state is not AgentState.ARCHIVED]++ def match_info(self) -> dict[str, Any] | None:+ """How the name was matched, when it was not spelled exactly."""+ best = self.resolution.best+ if best is None or best.method == "exact":+ return None+ return {+ "heard": self.heard,+ "matched": best.label,+ "method": best.method,+ "score": round(best.score, 3),+ }+++def role_tags(agent: AgentRecord) -> frozenset[str]:+ return frozenset({"coding"}) if has_coding_role(agent.name, agent.title) else frozenset()+++def candidate_for(agent: AgentRecord, custom: Iterable[str] = ()) -> NameCandidate:+ roles = role_tags(agent)+ aliases: list[str] = []+ if normalize(agent.title) not in _GENERIC_TITLES:+ aliases.append(agent.title)+ for role in sorted(roles):+ aliases.extend(ROLE_ALIASES.get(role, ()))+ aliases.extend(custom)+ return NameCandidate(+ key=agent.agent_id,+ label=agent.name,+ names=(agent.name, agent.agent_id.replace("-", " ")),+ aliases=tuple(dict.fromkeys(a for a in aliases if a)),+ roles=roles,+ )+++def _clean_aliases(values: Iterable[Any]) -> tuple[str, ...]:+ out: list[str] = []+ for value in values:+ text = " ".join(str(value or "").split())[:_MAX_ALIAS_LEN]+ if text and normalize(text) and text not in out:+ out.append(text)+ return tuple(out[:_MAX_ALIASES])+++async def load_custom_aliases(store: Any) -> dict[str, tuple[str, ...]]:+ """Every agent's user-defined aliases; ``{}`` when the store cannot say."""+ try:+ rows = await store.meta_prefix(ALIAS_META_PREFIX)+ except Exception: # noqa: BLE001 - aliases are optional; matching works without them+ log.warning("agent names: custom aliases could not be read", exc_info=True)+ return dict(_alias_cache)+ aliases: dict[str, tuple[str, ...]] = {}+ for key, raw in rows.items():+ try:+ values = json.loads(raw)+ except ValueError:+ log.warning("agent names: ignoring malformed aliases under %s", key)+ continue+ if isinstance(values, list):+ aliases[key[len(ALIAS_META_PREFIX) :]] = _clean_aliases(values)+ _alias_cache.clear()+ _alias_cache.update(aliases)+ return aliases+++async def set_custom_aliases(store: Any, agent_id: str, aliases: Iterable[str]) -> tuple[str, ...]:+ """Replace one agent's user-defined aliases; returns what was stored."""+ clean = _clean_aliases(aliases)+ await store.set_meta(f"{ALIAS_META_PREFIX}{agent_id}", json.dumps(list(clean)))+ _alias_cache[agent_id] = clean+ return clean+++def lookup_in(+ agents: Sequence[AgentRecord],+ spoken: str,+ *,+ aliases: dict[str, tuple[str, ...]] | None = None,+ context: str = "",+ surface: str = "",+ include_lead: bool = False,+) -> AgentLookup:+ """Resolve ``spoken`` against ``agents`` (no I/O; any thread)."""+ custom = _alias_cache if aliases is None else aliases+ live = tuple(+ a+ for a in agents+ if a.state is not AgentState.ARCHIVED and (include_lead or a.agent_id != LEAD_AGENT_ID)+ )+ resolution = resolve_name(+ spoken,+ [candidate_for(a, custom.get(a.agent_id, ())) for a in live],+ context=context,+ surface=surface,+ )+ by_id = {a.agent_id: a for a in live}+ agent = by_id.get(resolution.key or "")+ candidates = tuple(by_id[m.key] for m in resolution.candidates if m.key in by_id)+ return AgentLookup(+ heard=str(spoken or "").strip(),+ resolution=resolution,+ agent=agent,+ candidates=candidates,+ roster=live,+ )+++async def lookup_agent(+ runtime: Any,+ spoken: str,+ *,+ context: str = "",+ surface: str = "",+ include_lead: bool = False,+) -> AgentLookup:+ """Resolve a spoken agent reference against the live roster.++ An exact id, name or slug wins first, exactly as ``Roster.resolve`` always+ did — so nothing that worked before changes. Only a reference that names+ no agent exactly (or only an archived one) goes through the scoring.+ """+ exact = await runtime.roster.resolve(spoken)+ if exact is not None and exact.state is not AgentState.ARCHIVED:+ resolution = resolve_name(+ spoken, [candidate_for(exact)], surface=surface+ ) # logs the exact hit with the same line shape as every other resolution+ return AgentLookup(+ heard=spoken.strip(),+ resolution=resolution,+ agent=exact,+ candidates=(exact,),+ roster=tuple(runtime.roster.snapshot()),+ )+ agents = await runtime.roster.list()+ aliases = await load_custom_aliases(runtime.store)+ found = lookup_in(+ agents,+ spoken,+ aliases=aliases,+ context=context,+ surface=surface,+ include_lead=include_lead,+ )+ if found.decision == "none" and exact is not None:+ # Only an archived agent carries this exact name: keep the old+ # behavior and hand it back, the caller decides what archived means.+ return AgentLookup(+ heard=found.heard,+ resolution=found.resolution,+ agent=exact,+ candidates=(exact,),+ roster=found.roster,+ )+ return found+++def jarvis_agent_hint(spoken: str, *, context: str = "") -> dict[str, Any] | None:+ """The Jarvis agent a name a coding-pane lookup could not place means.++ Synchronous and I/O-free (the roster snapshot and the alias cache), so the+ coding-pane tool can call it on its own result without a second hop.+ """+ try:+ from .runtime import current_runtime++ runtime = current_runtime()+ agents = runtime.roster.snapshot() if runtime is not None else []+ except Exception: # noqa: BLE001 - a missing society only means no hint+ log.warning("agent names: roster snapshot unavailable for a hint", exc_info=True)+ return None+ if not agents or not str(spoken or "").strip():+ return None+ found = lookup_in(agents, spoken, context=context, surface="workspace-orchestrate:hint")+ if found.decision == "act" and found.agent is not None:+ names, certain = [found.agent.name], True+ elif found.decision == "ask" and found.candidates:+ names, certain = [a.name for a in found.candidates], False+ else:+ return None+ return {"heard": found.heard, "agents": names, "certain": certain}+++def coding_pane_hint(spoken: str) -> dict[str, Any] | None:+ """The Agentic-IDE coding pane a name no Jarvis agent carries means, if any."""+ try:+ from jarvis.agentic_ide.names import position_of+ from jarvis.agentic_ide.orchestration import get_orchestrator++ graph = get_orchestrator().graph()+ except Exception: # noqa: BLE001 - no IDE (headless, stripped install): no hint+ log.debug("agent names: coding-pane graph unavailable for a hint", exc_info=True)+ return None+ panes: list[NameCandidate] = []+ where: dict[str, dict[str, str]] = {}+ for project in graph.get("projects", []):+ for workspace in project.get("workspaces", []):+ for pane in workspace.get("agents", []):+ name = str(pane.get("name") or "")+ if not name or position_of(name) is not None or not pane.get("accepts_tasks"):+ continue+ key = str(pane.get("id") or name)+ panes.append(NameCandidate(key=key, label=name, names=(name,)))+ where[key] = {"agent": name, "workspace": str(workspace.get("name") or "")}+ if not panes:+ return None+ resolution = resolve_name(spoken, panes, surface="delegate_to_agent:pane-hint")+ if resolution.decision == "none":+ return None+ return {+ "heard": str(spoken or "").strip(),+ "panes": [where[m.key] for m in resolution.candidates if m.key in where],+ "certain": resolution.decision == "act",+ }+++__all__ = [+ "ALIAS_META_PREFIX",+ "ROLE_ALIASES",+ "AgentLookup",+ "candidate_for",+ "coding_pane_hint",+ "jarvis_agent_hint",+ "load_custom_aliases",+ "lookup_agent",+ "lookup_in",+ "role_tags",+ "set_custom_aliases",+]diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.pyindex bd2c20ca89..a1c9db05d3 100644--- a/jarvis/society/agent_tools.py+++ b/jarvis/society/agent_tools.py@@ -94,7 +94,10 @@ class MessageAgentTool:"properties": {"target": {"type": "string",- "description": "The teammate's name or id, exactly as listed under Teammates.",+ "description": (+ "The teammate's name or id as listed under Teammates (a misheard "+ "name is matched; a close one comes back as did_you_mean)."+ ),},"text": {"type": "string",@@ -157,9 +160,24 @@ class MessageAgentTool:return _failure(FailureReason.BLOCKED_BY_POLICY, "message exceeds 8000 characters")if not target_key or not text:return _failure(FailureReason.BLOCKED_BY_POLICY, "target and text are required")- target = await rt.roster.resolve(target_key)+ from .agent_names import lookup_agent++ found = await lookup_agent(+ rt,+ target_key,+ context=text,+ surface=self.name,+ include_lead=caller.agent_id != rt.lead_id,+ )+ target = found.agentif target is None or target.state is AgentState.ARCHIVED:- return _failure(FailureReason.TARGET_UNKNOWN, f"no teammate named {target_key!r}")+ failure = _failure(FailureReason.TARGET_UNKNOWN, f"no teammate named {target_key!r}")+ if found.decision == "ask" and found.candidates:+ # Close, but not certain: name the candidates instead of a bare miss.+ failure.output["did_you_mean"] = [a.name for a in found.candidates]+ else:+ failure.output["available"] = found.available_names()+ return failureif target.agent_id == caller.agent_id:return _failure(FailureReason.BLOCKED_BY_POLICY, "you cannot message yourself")if target.state is AgentState.PAUSED:diff --git a/tests/unit/core/test_spoken_names.py b/tests/unit/core/test_spoken_names.pynew file mode 100644index 0000000000..e70fb5f9f3--- /dev/null+++ b/tests/unit/core/test_spoken_names.py@@ -0,0 +1,172 @@+"""Spoken-name resolution: misheard agent names land, unrelated words do not."""++from __future__ import annotations++import logging++import pytest++from jarvis.core.spoken_names import (+ ACT_SCORE,+ ASK_SCORE,+ NameCandidate,+ jaro_winkler,+ koelner_phonetik,+ name_tokens,+ normalize,+ resolve_name,+)++#: The live roster of 2026-10-02 plus a coding agent called "Jarvis Code".+ROSTER = (+ NameCandidate(+ "jarvis-code", "Jarvis Code", ("Jarvis Code", "jarvis code"),+ ("coding agent", "code agent", "coder"), frozenset({"coding"}),+ ),+ NameCandidate(+ "jarvis-scout", "Jarvis-Scout", ("Jarvis-Scout", "jarvis scout"),+ ("GitHub-Trends für Personal Jarvis",), # i18n-allow: agent title from the live roster+ ),+ NameCandidate("x-markring", "X markring", ("X markring", "x markring")),+ NameCandidate("gmail-tagesreport", "Gmail-Tagesreport", ("Gmail-Tagesreport",)),+ NameCandidate(+ "github-issue-sortieren", "GitHub Issue sortieren.", ("GitHub Issue sortieren.",)+ ),+) # fmt: skip+++ ("heard", "method"),+ [+ ("Jarvis Code", "exact"),+ ("jarvis-code", "exact"),+ ("JARVIS CODE!", "exact"),+ ("Jarviscode", "fuzzy"),+ ("Jarvis Kot", "phonetic"),+ ("Jarvis-Kot", "phonetic"),+ ("Jarwis Code", "phonetic"),+ ("Davis Code", "fuzzy"),+ ("Jarvis Coder", "fuzzy"),+ ("unseren Jarvis Code", "exact"), # i18n-allow: speech-recognition input+ ("der Code Agent", "alias"), # i18n-allow: speech-recognition input+ ("coder", "alias"),+ ],+)+def test_variants_of_jarvis_code_act(heard, method):+ result = resolve_name(heard, ROSTER)+ assert result.decision == "act", result.as_dict()+ assert result.key == "jarvis-code"+ assert result.best is not None and result.best.method == method+++def test_charles_code_is_asked_about_not_guessed():+ result = resolve_name("Charles Code", ROSTER)+ assert result.decision == "ask"+ assert [m.key for m in result.candidates] == ["jarvis-code"]+++def test_coding_context_tips_a_close_coding_name():+ result = resolve_name("Charles Code", ROSTER, context="bitte fix den Bug im Repo") # i18n-allow+ assert result.decision == "act" and result.key == "jarvis-code"+ assert result.context_used+++def test_context_never_creates_a_match_on_its_own():+ result = resolve_name("Telegram", ROSTER, context="programmiere das bitte") # i18n-allow+ assert result.decision == "none"+++ ("heard", "agent_id"),+ [+ ("Java Scout", "jarvis-scout"), # the live 2026-10-02 transcript+ ("Jarvis Scout", "jarvis-scout"),+ ("Scout", "jarvis-scout"),+ ("X Marketing Agent", "x-markring"), # live 2026-10-02 08:58+ ("GitHub Issue Sortierer", "github-issue-sortieren"), # live 2026-10-02 09:45+ ],+)+def test_other_agents_resolve_to_themselves(heard, agent_id):+ result = resolve_name(heard, ROSTER)+ assert result.decision == "act" and result.key == agent_id, result.as_dict()+++ "heard",+ [+ "Jarvis Scout",+ "Java Scout",+ "Gmail Agent",+ "Telegram",+ "Morgenbriefing", # i18n-allow: speech-recognition input+ "Charles",+ "Jarvis Guide", # same Cologne code as "Code" (42), different onset+ "Jarvis Gut", # i18n-allow: speech-recognition input+ "Claude Code", # a coding CLI, not this agent+ "Code Review",+ "Codex",+ "Jarvis Codex",+ "Jarvis",+ ],+)+def test_negatives_never_act_on_jarvis_code(heard):+ result = resolve_name(heard, ROSTER)+ assert not (result.decision == "act" and result.key == "jarvis-code"), result.as_dict()++[email protected]("heard", ["Telegram", "Morgenbriefing", "Charles", "Jarvis Gut"])+def test_unrelated_words_match_nothing(heard):+ assert resolve_name(heard, ROSTER).decision == "none"+++def test_a_long_reference_still_finds_the_name_inside_it():+ """Live 2026-10-02: the model passed the whole garbled phrase as the name."""+ result = resolve_name("Java Scout and Quick Meshes", ROSTER)+ assert result.decision == "ask"+ assert result.candidates[0].key == "jarvis-scout"+++def test_two_close_candidates_are_a_question():+ twins = (+ NameCandidate("mail-a", "Mail North", ("Mail North",)),+ NameCandidate("mail-b", "Mail South", ("Mail South",)),+ )+ result = resolve_name("Mail", twins)+ assert result.decision == "ask"+ assert {m.key for m in result.candidates} == {"mail-a", "mail-b"}+++def test_empty_inputs_decide_none():+ assert resolve_name("", ROSTER).decision == "none"+ assert resolve_name("Jarvis Code", ()).decision == "none"+++def test_every_resolution_is_logged(caplog):+ with caplog.at_level(logging.INFO, logger="jarvis.core.spoken_names"):+ resolve_name("Jarvis Kot", ROSTER, surface="delegate_to_agent")+ line = caplog.records[-1].getMessage()+ assert "[delegate_to_agent]" in line+ assert "heard='Jarvis Kot'" in line+ assert "Jarvis Code (jarvis-code)" in line+ assert "method=phonetic" in line and "decision=act" in line and "score=0.9" in line+++def test_normalization_folds_case_umlauts_and_punctuation():+ assert normalize("Jarvis-Code!") == "jarvis code"+ assert normalize("Gmail-Überblick") == "gmail ueberblick" # i18n-allow: folding input+ assert normalize("Grüße, Straße") == "gruesse strasse" # i18n-allow: folding input+ assert name_tokens("unseren Jarvis Code Agent") == ("jarvis", "code") # i18n-allow+ assert name_tokens("the agent") == ("the", "agent") # fillers only: kept+++def test_cologne_phonetics():+ assert koelner_phonetik("Jarvis") == koelner_phonetik("Jarwis") == "0738"+ assert koelner_phonetik("Kot") == koelner_phonetik("Code") == "42"+ assert koelner_phonetik("Müller-Lüdenscheidt") == "65752682" # i18n-allow: textbook+++def test_jaro_winkler_bounds():+ assert jaro_winkler("code", "code") == 1.0+ assert jaro_winkler("", "code") == 0.0+ assert 0.9 < jaro_winkler("coder", "code") < 1.0+ assert ASK_SCORE < ACT_SCOREdiff --git a/tests/unit/plugins/tool/test_delegate_to_agent.py b/tests/unit/plugins/tool/test_delegate_to_agent.pyindex 9f97215462..20a7ea1a50 100644--- a/tests/unit/plugins/tool/test_delegate_to_agent.py+++ b/tests/unit/plugins/tool/test_delegate_to_agent.py@@ -200,7 +200,11 @@ async def test_delegate_unknown_name_does_not_redirect_work(team):{"agent": "email agent", "task": "check my inbox in gmail", "turn_language": "en"},_ctx("email agent, check my inbox"),)- assert not res.success and res.error == "target_unknown"+ # "email agent" is close to "Gmail agent", so the user is asked - never a+ # silent redirect, and never a silent "unknown" either.+ assert not res.success and res.error == "target_ambiguous"+ assert res.output["candidates"] == ["Gmail agent"]+ assert res.output["question"] == "Did you mean Gmail agent?"assert not chat.sent@@ -435,3 +439,88 @@ async def test_exact_assignment_id_works_without_trace_and_rejects_mismatched_trassert not ambiguous.success and ambiguous.error == "agent required"empty = await tool.execute({"agent": "Archivist", "latest_assignment": True}, _ctx())assert not empty.success and empty.error == "assignment_unknown"+++# --------------------------------------------------------------- misheard names+++async def voice_team(tmp_path: Path):+ """The live roster of 2026-10-02 plus a coding agent called Jarvis Code."""+ chat = FakeChat(tmp_path / "agent_chat.db")+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))+ rt = SocietyRuntime(tmp_path, chat_service=lambda: chat, cfg=lambda: cfg)+ await rt.ensure_started()+ for name, title in (+ ("Jarvis-Scout", "GitHub trends for Personal Jarvis"),+ ("Jarvis Code", "Coding agent"),+ ("Gmail-Tagesreport", "Daily Gmail overview"),+ ):+ await rt.roster.create(name=name, title=title, provider="openai", model="gpt-5.2")+ try:+ yield rt, chat+ finally:+ await rt.close()+++ ("heard", "agent_id"),+ [+ ("Java Scout", "jarvis-scout"), # the live 2026-10-02 transcript+ ("Jarvis Kot", "jarvis-code"),+ ("Jarwis Code", "jarvis-code"),+ ("jarvis-code", "jarvis-code"),+ ],+)+async def test_delegate_reaches_a_misheard_agent(voice_team, heard, agent_id):+ rt, chat = voice_team+ tool = DelegateToAgentTool(runtime_resolver=lambda: rt)+ res = await tool.execute(+ {"agent": heard, "task": "Run another scout.", "turn_language": "en"}, _ctx(heard)+ )+ assert res.success, res.error+ assert res.output["agent_id"] == agent_id+ assert chat.sent and chat.sent[0][0] == f"society:{agent_id}:with:jarvis"+ if heard != "jarvis-code":+ # The reply carries how the name was matched, so Jarvis can say who got it.+ assert res.output["name_match"]["heard"] == heard+++async def test_delegate_asks_on_a_close_name_and_sends_nothing(voice_team):+ rt, chat = voice_team+ tool = DelegateToAgentTool(runtime_resolver=lambda: rt)+ res = await tool.execute(+ {"agent": "Charles Code", "task": "Write a poem.", "turn_language": "de"},+ _ctx("Charles Code soll ein Gedicht schreiben"), # i18n-allow: user speech+ )+ assert res.error == "target_ambiguous" and not chat.sent+ assert res.output["question"] == "Meinst du Jarvis Code?" # i18n-allow: spoken reply+++async def test_coding_context_settles_a_close_coding_name(voice_team):+ rt, chat = voice_team+ tool = DelegateToAgentTool(runtime_resolver=lambda: rt)+ res = await tool.execute(+ {"agent": "Charles Code", "task": "Fix the bug in the repo.", "turn_language": "en"},+ _ctx("Charles Code, fix the bug"),+ )+ assert res.success, res.error+ assert res.output["agent_id"] == "jarvis-code"+++async def test_delegate_unknown_name_lists_who_exists(voice_team):+ rt, chat = voice_team+ tool = DelegateToAgentTool(runtime_resolver=lambda: rt)+ res = await tool.execute(+ {"agent": "Telegram", "task": "x", "turn_language": "en"}, _ctx("telegram do x")+ )+ assert res.error == "target_unknown" and not chat.sent+ assert res.output.startswith("I do not know an agent called Telegram.")+ assert "Available agents: Gmail-Tagesreport, Jarvis Code, Jarvis-Scout." in res.output+++async def test_status_resolves_a_misheard_name(voice_team):+ rt, _ = voice_team+ status = SocietyStatusTool(runtime_resolver=lambda: rt)+ res = await status.execute({"agent": "Java Scout", "turn_language": "en"}, _ctx("x"))+ assert res.success and res.output == "Jarvis-Scout has nothing to do right now."diff --git a/tests/unit/society/test_agent_names.py b/tests/unit/society/test_agent_names.pynew file mode 100644index 0000000000..b5e3c2f1e8--- /dev/null+++ b/tests/unit/society/test_agent_names.py@@ -0,0 +1,168 @@+"""Jarvis agents by spoken name: aliases, messaging, and the pane/agent split."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace+from uuid import uuid4++import pytest++from jarvis.agentic_ide.orchestration import WorkspaceOrchestrator+from jarvis.brain.workspace_tool import _point_at_jarvis_agent+from jarvis.society import runtime as runtime_mod+from jarvis.society.agent_names import (+ ROLE_ALIASES,+ jarvis_agent_hint,+ load_custom_aliases,+ lookup_agent,+ role_tags,+ set_custom_aliases,+)+from jarvis.society.agent_tools import MessageAgentTool+from jarvis.society.runtime import SocietyRuntime++CTX = SimpleNamespace(trace_id=uuid4(), user_utterance="", config={}, memory_read=None)+++async def rt(tmp_path: Path):+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)+ await runtime.ensure_started()+ await runtime.roster.create(name="Jarvis-Scout", title="GitHub trends")+ await runtime.roster.create(name="Jarvis Code", title="Coding agent")+ await runtime.roster.create(name="Gmail-Tagesreport", title="Specialist")+ try:+ yield runtime+ finally:+ runtime_mod.set_current_runtime(None)+ await runtime.close()+++async def test_exact_names_and_ids_resolve_exactly_as_before(rt):+ for ref in ("Jarvis Code", "jarvis-code", "JARVIS CODE"):+ found = await lookup_agent(rt, ref)+ assert found.agent is not None and found.agent.agent_id == "jarvis-code"+ assert found.match_info() is None # exact: nothing to explain+ lead = await lookup_agent(rt, "jarvis")+ assert lead.agent is not None and lead.agent.agent_id == "jarvis"+++async def test_misheard_name_reports_how_it_matched(rt):+ found = await lookup_agent(rt, "Jarvis Kot", surface="test")+ assert found.agent is not None and found.agent.agent_id == "jarvis-code"+ assert found.match_info() == {+ "heard": "Jarvis Kot",+ "matched": "Jarvis Code",+ "method": "phonetic",+ "score": pytest.approx(found.resolution.best.score, abs=1e-3),+ }+++async def test_role_aliases_follow_the_title(rt):+ code = await rt.roster.resolve("jarvis-code")+ scout = await rt.roster.resolve("jarvis-scout")+ assert role_tags(code) == frozenset({"coding"})+ assert role_tags(scout) == frozenset()+ assert "programmierer" in ROLE_ALIASES["coding"] # i18n-allow: input vocabulary+ found = await lookup_agent(rt, "Programmierer") # i18n-allow: speech-recognition input+ assert found.agent is not None and found.agent.agent_id == "jarvis-code"+++async def test_custom_aliases_are_stored_and_used(rt):+ spoken = ["Ranger", " Ranger ", "Trendy"]+ stored = await set_custom_aliases(rt.store, "jarvis-scout", spoken)+ assert stored == ("Ranger", "Trendy")+ assert (await load_custom_aliases(rt.store))["jarvis-scout"] == ("Ranger", "Trendy")+ found = await lookup_agent(rt, "Trendy")+ assert found.agent is not None and found.agent.agent_id == "jarvis-scout"+ assert found.resolution.best.method == "alias"+++async def test_an_archived_exact_name_does_not_shadow_a_live_agent(rt):+ await rt.roster.create(name="Scout")+ await rt.roster.archive("scout")+ found = await lookup_agent(rt, "Scout")+ assert found.agent is not None and found.agent.agent_id == "jarvis-scout"+++async def test_message_agent_reaches_a_misheard_teammate(rt):+ tool = MessageAgentTool(rt, "jarvis")+ res = await tool.execute({"target": "Java Scout", "text": "Run another scout."}, CTX)+ assert res.success, res.error+ assert res.output["target"] == "Jarvis-Scout"+++async def test_message_agent_names_candidates_instead_of_a_bare_miss(rt):+ tool = MessageAgentTool(rt, "jarvis")+ close = await tool.execute({"target": "Charles Code", "text": "hi"}, CTX)+ assert close.success is False and close.output["reason"] == "target_unknown"+ assert close.output["did_you_mean"] == ["Jarvis Code"]+ unknown = await tool.execute({"target": "Telegram", "text": "hi"}, CTX)+ assert unknown.output["available"] == ["Gmail-Tagesreport", "Jarvis Code", "Jarvis-Scout"]+++async def test_a_pane_lookup_points_at_the_jarvis_agent(rt):+ """Live 2026-10-02: the name went to the coding-pane tool and was 'not found'."""+ runtime_mod.set_current_runtime(rt)+ await rt.roster.list() # the snapshot a synchronous reader sees+ assert jarvis_agent_hint("Java Scout") == {+ "heard": "Java Scout",+ "agents": ["Jarvis-Scout"],+ "certain": True,+ }+ miss = {+ "status": "needs_clarification",+ "kind": "agent",+ "candidates": [],+ "reason": "Nothing open matches 'Java Scout'.",+ }+ pointed = _point_at_jarvis_agent({"action": "resolve", "agent": "Java Scout"}, miss)+ assert pointed["jarvis_agent"]["agents"] == ["Jarvis-Scout"]+ assert "delegate_to_agent" in pointed["reason"] and "message_agent" in pointed["reason"]+ assert pointed["reason"].endswith("Nothing open matches 'Java Scout'.")+ # A pane that was found, or a create, is left alone.+ resolved = {"status": "resolved", "target": {}}+ args = {"action": "resolve", "agent": "Java Scout"}+ assert _point_at_jarvis_agent(args, resolved) is resolved+ assert _point_at_jarvis_agent({"action": "create", "agent": "Java Scout"}, miss) is miss+ assert jarvis_agent_hint("Telegram") is None+++def _graph(*names: str) -> dict:+ agents = [+ {"id": f"pane:{i}", "name": name, "agent": "claude", "status": "live",+ "activity": "waiting", "accepts_tasks": True}+ for i, name in enumerate(names)+ ] # fmt: skip+ return {+ "active_workspace_id": "ws",+ "projects": [+ {+ "id": "p",+ "name": "Personal Jarvis",+ "path": "/p",+ "workspaces": [+ {"id": "ws", "name": "Personal Jarvis", "status": "open", "agents": agents}+ ],+ }+ ],+ }+++def test_a_misheard_custom_pane_name_resolves():+ orchestrator = WorkspaceOrchestrator(None, None, None)+ graph = _graph("T1", "Update Deep Dive", "Security Audit")+ result = orchestrator.resolve({"agent": "Update Deep Drive"}, graph)+ assert result["status"] == "resolved", result+ assert result["target"]["agent"] == "Update Deep Dive"+++def test_a_close_pane_name_is_a_question_and_positions_stay_exact():+ orchestrator = WorkspaceOrchestrator(None, None, None)+ graph = _graph("T1", "T11", "Security Audit")+ close = orchestrator.resolve({"agent": "Secret Audio"}, graph)+ assert close["status"] == "needs_clarification"+ assert [c["name"] for c in close["candidates"]] == ["Security Audit"]+ # "T12" is not a garbled "T11": positions never fuzzy-match.+ assert orchestrator.resolve({"agent": "T12"}, graph)["status"] == "needs_clarification"