Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(brain): explicit-request gate for LLM-chosen agent spawns

Ruben Lütke1416292b2008
diff --git a/jarvis/brain/router.py b/jarvis/brain/router.py
index 5d5bc7d7e0..00afc6a549 100644
--- a/jarvis/brain/router.py
+++ b/jarvis/brain/router.py
@@ -112,21 +112,29 @@ Du bist der Dispatcher. Du sortierst nach AUFWAND, nicht nach Thema:
wiki-recall):
mach es SELBST. Denk ruhig einen Moment nach und mach 2-3 Tool-Calls —
das ist IMMER schneller als eine Hintergrund-Mission. KEIN spawn_worker.
-- SCHWER — nur echte Brocken: rufe spawn_worker mit der User-Utterance
- VERBATIM auf (nicht zusammenfassen, nicht umformulieren).
-
-SPAWN-CRITERIA — spawn_worker ist NUR fuer wirklich schwere Aufgaben:
- • Die Aufgabe BAUT ein Arbeitsergebnis: Code/App/Skript, ein Refactor,
- eine Datei, ein Dokument oder ein HTML-Report.
- • ODER sie braucht viele Schritte und laeuft laenger als ein paar Minuten
+- SCHWER — nur echte Brocken, die Ruben AUSDRUECKLICH delegiert: rufe
+ spawn_worker mit der User-Utterance VERBATIM auf (nicht zusammenfassen,
+ nicht umformulieren).
+
+SPAWN-CRITERIA — spawn_worker NUR bei AUSDRUECKLICHEM Delegations-Wunsch:
+ • PFLICHT-BEDINGUNG: Ruben verlangt die Delegation selbst — er nennt einen
+ "Agent"/"Subagenten"/"Worker", sagt "spawn"/"delegier", verlangt Arbeit
+ "im Hintergrund" — ODER er hat gerade dein Angebot, einen Agenten zu
+ starten, klar mit Ja bestaetigt. Ohne diese Bedingung ist spawn_worker
+ IMMER falsch, egal wie gross die Aufgabe wirkt: antworte inline und
+ BIETE hoechstens an, einen Agenten zu starten (ein deterministischer
+ Guard blockt jeden unaufgeforderten Spawn ohnehin).
+ • UND die Aufgabe ist wirklich schwer: sie BAUT ein Arbeitsergebnis
+ (Code/App/Skript, ein Refactor, eine Datei, ein Dokument, ein
+ HTML-Report) oder braucht viele Schritte ueber mehrere Minuten
fokussierter Arbeit (tiefe Multi-Quellen-Recherche MIT Bericht als
Ergebnis, grosse Code-Analyse).
- • ODER Ruben verlangt es explizit ("Sub-Agent", "im Hintergrund").
- Beispiel SCHWER: "hol meine E-Mails und bau eine schoene HTML-Uebersicht
- mit den wichtigsten Nachrichten" → spawn_worker.
- Beispiel NICHT schwer: "was sind die aktuellsten News?" → search_web und
+ Beispiel SCHWER: "spawn einen Agenten: hol meine E-Mails und bau eine
+ schoene HTML-Uebersicht mit den wichtigsten Nachrichten" → spawn_worker.
+ Beispiel NICHT: "was sind die aktuellsten News?" → search_web und
direkt antworten. NIEMALS spawn_worker fuer eine Frage, die du mit 1-2
- Suchanfragen oder einem einzelnen Tool-Read beantworten kannst.
+ Suchanfragen oder einem einzelnen Tool-Read beantworten kannst — und
+ NIEMALS mitten in normaler Konversation ohne ausdruecklichen Wunsch.
ABER: eine App oeffnen / den Bildschirm bedienen / in einer App klicken oder
tippen ist KEIN spawn_worker — das ist computer_use (siehe DIRECT_ACTION).
spawn_worker laeuft in einem isolierten Workspace und kann den Desktop nie
diff --git a/jarvis/brain/spawn_gate.py b/jarvis/brain/spawn_gate.py
new file mode 100644
index 0000000000..b6cae083e4
--- /dev/null
+++ b/jarvis/brain/spawn_gate.py
@@ -0,0 +1,233 @@
+"""Deterministic explicit-delegation gate for LLM-chosen agent spawns.
+
+Maintainer mandate 2026-07-18 (voice sessions 08:25 + 08:29): the model kept
+starting background agents mid-conversation ("... he could buy a Gulfstream
+every day", "I want to figure out where to move next") although the user never
+asked for one. Every prior fix was prompt-side (router SPAWN-CRITERIA, the
+realtime role directives, the spawn_worker tool description) — and the model
+kept ignoring it, because a tool description is advice, not enforcement.
+
+This module is the enforcement. An LLM-initiated spawn tool call executes
+ONLY when one of these holds:
+
+1. The CURRENT user turn explicitly requests delegation — it names the agent
+ vehicle ("agent", "subagent", "<wake-name> Agent", "worker", "mission",
+ "openclaw") or a delegation verb/marker ("spawn", "delegate", "in the
+ background"), in any supported language. Matching *input vocabulary*, not
+ prose — deliberately word-based (the router's force-spawn triggers work the
+ same way).
+2. The turn is a short, clear YES to a delegation offer the model made right
+ after the gate blocked the previous turn (the model is told to offer
+ instead of spawn; the user's confirmation then unlocks exactly one spawn).
+
+Everything else is blocked and fed back to the model as a tool error telling
+it to answer inline. The deterministic force-spawn path
+(``BrainManager._should_force_spawn``) does NOT run through this gate — it
+already fires only on explicit trigger phrases in strict mode and carries its
+own decline/negation guards.
+
+Consumers: ``jarvis.brain.tool_use_loop`` (classic pipeline + realtime
+delegate mode) and ``jarvis.realtime.tools`` (realtime direct tool mode).
+Both share the ONE module-level offer window because both feed the same
+single conversation per process; a mode switch keeps the pending offer.
+"""
+from __future__ import annotations
+
+import logging
+import re
+import time
+
+log = logging.getLogger(__name__)
+
+
+# Registered names of every tool that dispatches a background worker mission.
+# Kept tiny and explicit — mirrors ``_SPAWN_TOOL_NAMES`` in
+# ``jarvis.brain.manager`` (parity-tested in tests/unit/brain/test_spawn_gate.py).
+SPAWN_VEHICLE_TOOL_NAMES: frozenset[str] = frozenset({"spawn_worker", "multi_spawn"})
+
+
+# Explicit delegation vocabulary (DE/EN/ES). A bare "agent" is deliberately
+# included: the user-visible brand is "<wake-name> Agent" (dynamic, §4), so
+# "spawn einen Gustav Agent" must match for ANY wake word without resolving
+# the live brand. Over-matching is safe by construction — a match only means
+# the MODEL MAY spawn, it never forces a spawn.
+_DELEGATION_MARKER_RE: re.Pattern[str] = re.compile(
+ r"(?:"
+ # the vehicle, by name (incl. the dynamic "<wake-name> Agent" brand)
+ r"\bagent(?:en|es|e|s)?\b"
+ r"|\bsub-?agent\w*"
+ r"|\bopen[- ]?claw\w*"
+ r"|\bworker\w*|\btrabajador\w*"
+ r"|\bmission\w*|\bmisi[oó]n\w*"
+ # delegation verbs / markers
+ r"|\bspawn\w*"
+ r"|\bdelegier\w*|\bdelegate\w*|\bdeleg[aá]\w*"
+ r"|\bhintergrund\w*|\bbackground\b|\bsegundo\s+plano\b"
+ r")",
+ re.IGNORECASE,
+)
+
+
+# A delegation offer's confirmation is a SHORT stand-alone yes ("Ja, mach
+# das", "yes go ahead"). ``classify_response`` substring-matches, so a long
+# sentence that merely CONTAINS a yes-word ("Ja, und erzähl mir mehr # i18n-allow: counter-example
+# über Monaco") must never unlock a spawn — same bound as the # i18n-allow: counter-example
+# realtime answer pull-back (``_DELEGATE_ANSWER_MAX_TOKENS``).
+_CONFIRM_MAX_WORDS = 6
+
+# An offer is only fresh for the immediate follow-up exchange. Voice turns
+# arrive within seconds; two minutes comfortably covers a slow "hmm... yes"
+# without letting a stale offer unlock a spawn much later in the session.
+_OFFER_TTL_S = 120.0
+
+
+def _normalized(text: str) -> str:
+ return re.sub(r"\s+", " ", (text or "").strip().lower())
+
+
+def _is_decline_or_feature_talk(text: str) -> bool:
+ """True when the user declines a spawn or talks ABOUT the auto-spawn feature.
+
+ Reuses the battle-tested detectors in ``jarvis.brain.manager`` (negation
+ windows, "talk to me directly", "auto-spawn" feature naming). Imported
+ lazily to keep this a leaf module (manager → tool_use_loop → here would
+ otherwise cycle at import time); on any import fault the gate degrades to
+ "no decline detected" — the marker match then merely returns the choice
+ to the model, which has read the same negated sentence.
+ """
+ try:
+ from jarvis.brain.manager import ( # noqa: PLC0415
+ _is_spawn_decline,
+ _is_spawn_feature_reference,
+ )
+ except Exception: # noqa: BLE001 — gate must never crash a tool turn
+ return False
+ return _is_spawn_decline(text) or _is_spawn_feature_reference(text)
+
+
+def _confirm_verdicts(text: str) -> set[str]:
+ """Language-agnostic yes/no verdicts for a short answer turn.
+
+ The gate cannot trust a per-turn language tag (STT mislabels are a known
+ class), so the answer is classified under every supported language and the
+ verdicts are merged; veto keeps its safety priority at the call site.
+ """
+ try:
+ from jarvis.voice.echo_confirmation import classify_response # noqa: PLC0415
+ except Exception: # noqa: BLE001 — classifier fault = no confirmation
+ return set()
+ return {classify_response(text, language=lang) for lang in ("de", "en", "es")}
+
+
+class DelegationOfferWindow:
+ """One-shot confirm window armed by a gate-blocked spawn attempt.
+
+ When the gate blocks, the model is instructed to answer inline and — for
+ genuinely heavy tasks — OFFER delegation. The user's short affirmative on
+ the following turn must then unlock the spawn although it contains no
+ delegation vocabulary of its own. This window carries exactly that state:
+ armed with the blocked turn's text, consumed by one confirmed spawn.
+ """
+
+ def __init__(self, ttl_s: float = _OFFER_TTL_S) -> None:
+ self._ttl_s = ttl_s
+ self._armed_text = ""
+ self._armed_at = 0.0
+
+ def arm(self, blocked_turn_text: str) -> None:
+ self._armed_text = _normalized(blocked_turn_text)
+ self._armed_at = time.monotonic()
+
+ def disarm(self) -> None:
+ self._armed_text = ""
+ self._armed_at = 0.0
+
+ def consume_confirm(self, turn_text: str) -> bool:
+ """True exactly once, for a short clear YES within the TTL.
+
+ The turn that armed the window can never confirm itself, a long
+ sentence never confirms, and any veto wording closes the window for
+ good (declined offers must not linger as an unlockable spawn).
+ """
+ if not self._armed_text:
+ return False
+ if (time.monotonic() - self._armed_at) > self._ttl_s:
+ self.disarm()
+ return False
+ norm = _normalized(turn_text)
+ if not norm or norm == self._armed_text:
+ return False
+ verdicts = _confirm_verdicts(norm)
+ if "veto" in verdicts:
+ self.disarm()
+ return False
+ if len(norm.split()) > _CONFIRM_MAX_WORDS:
+ return False
+ if "confirm" in verdicts:
+ self.disarm()
+ return True
+ return False
+
+
+# ONE conversation per process (desktop app / headless session), so ONE shared
+# window across the classic and realtime paths. Tests reset via ``disarm()``.
+OFFER_WINDOW = DelegationOfferWindow()
+
+
+def llm_spawn_allowed(user_text: str) -> bool:
+ """Gate an LLM-chosen spawn tool call against the user's ACTUAL turn.
+
+ Side effects (documented contract, shared by both call sites): a blocked
+ conversational turn arms the offer window; an allowed spawn disarms it.
+ ``user_text`` must be the verbatim user turn (``ctx.user_utterance`` /
+ the realtime transcript), never the model's paraphrase — a paraphrase can
+ smuggle in delegation vocabulary the user never spoke.
+ """
+ text = (user_text or "").strip()
+ if not text:
+ return False
+ if _is_decline_or_feature_talk(text):
+ log.info("spawn gate: decline / feature talk — spawn blocked")
+ return False
+ if _DELEGATION_MARKER_RE.search(text):
+ OFFER_WINDOW.disarm()
+ return True
+ if OFFER_WINDOW.consume_confirm(text):
+ log.info("spawn gate: delegation offer confirmed — spawn allowed once")
+ return True
+ # Arm the offer window only on a SUBSTANTIVE turn (the one the model can
+ # make a delegation offer about). A veto turn closes any pending offer
+ # instead; a bare yes/no turn must never arm — otherwise two consecutive
+ # affirmations ("Ja bitte" ... "Ja mach") would read as offer + confirm
+ # and unlock a spawn nobody asked for.
+ verdicts = _confirm_verdicts(text)
+ if "veto" in verdicts:
+ OFFER_WINDOW.disarm()
+ elif "confirm" not in verdicts:
+ OFFER_WINDOW.arm(text)
+ log.info(
+ "spawn gate: no explicit delegation request in turn %r — spawn blocked",
+ text[:80],
+ )
+ return False
+
+
+# The one blocked-tool message both call sites feed back to the model. Keeping
+# it here guarantees the classic and realtime paths never drift apart in what
+# they teach the model to do next.
+SPAWN_BLOCKED_MODEL_FEEDBACK: str = (
+ "spawn_worker was not executed: the user did not explicitly ask to "
+ "delegate this to a background agent. Answer the user's turn directly "
+ "yourself, right now, inline. If (and only if) the task genuinely needs "
+ "multi-minute background work, you may ASK the user whether to start a "
+ "background agent — a clear yes on their next turn unlocks this function."
+)
+
+
+__all__ = [
+ "OFFER_WINDOW",
+ "SPAWN_BLOCKED_MODEL_FEEDBACK",
+ "SPAWN_VEHICLE_TOOL_NAMES",
+ "DelegationOfferWindow",
+ "llm_spawn_allowed",
+]
diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.py
index a67d606f88..93334ebf6f 100644
--- a/jarvis/brain/tool_use_loop.py
+++ b/jarvis/brain/tool_use_loop.py
@@ -20,6 +20,11 @@ from collections.abc import Awaitable, Callable
from typing import Any, Literal
from uuid import UUID, uuid4
+from jarvis.brain.spawn_gate import (
+ SPAWN_BLOCKED_MODEL_FEEDBACK,
+ SPAWN_VEHICLE_TOOL_NAMES,
+ llm_spawn_allowed,
+)
from jarvis.core.protocols import Brain, BrainMessage, BrainRequest, ImageBlock, Tool
from jarvis.core.turn_language import resolve_output_language, resolve_turn_language
from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL, ToolExecutor
@@ -868,6 +873,30 @@ class ToolUseLoop:
"confirmation phrase."
),
}
+ elif (
+ tool_name in SPAWN_VEHICLE_TOOL_NAMES
+ and not llm_spawn_allowed(user_utterance)
+ ):
+ # Explicit-delegation gate (maintainer mandate 2026-07-18):
+ # an LLM-chosen spawn runs ONLY when the user's own turn
+ # asks for an agent (or confirms an offer one turn later).
+ # Deterministic enforcement — the SPAWN-CRITERIA prompt and
+ # the tool description alone failed to stop conversational
+ # auto-spawns repeatedly. See jarvis/brain/spawn_gate.py.
+ log.info(
+ "tool_use_loop: %s blocked — no explicit delegation "
+ "request in the user turn", tool_name,
+ )
+ await self._publish_guard_denied(
+ tool_name,
+ "guard: no explicit delegation request — spawn not executed",
+ tid,
+ )
+ tool_result_payload = {
+ "success": False,
+ "output": None,
+ "error": SPAWN_BLOCKED_MODEL_FEEDBACK,
+ }
elif stt_blocked:
# Arg sanity guard: the tool args look like a Whisper
# hallucination (ad outro, copyright string, overly long app name).
diff --git a/jarvis/plugins/tool/spawn_worker.py b/jarvis/plugins/tool/spawn_worker.py
index 76ed9dae6f..3a2cfb61ec 100644
--- a/jarvis/plugins/tool/spawn_worker.py
+++ b/jarvis/plugins/tool/spawn_worker.py
@@ -305,20 +305,28 @@ class SpawnWorkerTool:
# LLMs pick tools primarily by description (ADR-0011, computer-use
# amendment). The old wording sold this tool for generic "Recherche",
# which pulled plain news/knowledge questions into multi-minute worker
- # missions (live complaint 2026-06-10). Keep the heavy-only contract and
- # the explicit negative boundary in sync with router.py SPAWN-CRITERIA
- # and tests/unit/plugins/tool/test_spawn_worker_description.py.
+ # missions (live complaint 2026-06-10). The 2026-07-18 mandate tightened
+ # the contract further: an unrequested conversational spawn is a defect,
+ # enforced deterministically by jarvis/brain/spawn_gate.py — this
+ # description mirrors that gate so the model does not waste a tool-call
+ # round trip on a doomed spawn. Keep it in sync with router.py
+ # SPAWN-CRITERIA and tests/unit/plugins/tool/test_spawn_worker_description.py.
description: str = (
"Delegates a GENUINELY HEAVY task to a background frontier worker "
- "(mission-manager orchestrated; runs for several minutes). Use it "
- "ONLY when the task builds a real work product (code, app, script, "
- "refactor, file, document, HTML report) or clearly needs many steps "
- "of multi-minute focused work (deep multi-source research WITH a "
- "deliverable report). NEVER use it for simple or medium requests: "
- "questions, news, quick lookups, single web searches, or anything "
- "you can answer inline with your own tools in this turn. Pass the "
- "user utterance verbatim plus optional 3-5 short brainstorm notes "
- "as ``context_hints``."
+ "(mission-manager orchestrated; runs for several minutes). Call it "
+ "ONLY when the user EXPLICITLY asked for delegation in their current "
+ "turn — they named an agent/subagent/worker/mission, said "
+ "spawn/delegate, asked for work in the background, or just gave a "
+ "clear yes to your offer to delegate — AND the task builds a real "
+ "work product (code, app, script, refactor, file, document, HTML "
+ "report) or clearly needs many steps of multi-minute focused work "
+ "(deep multi-source research WITH a deliverable report). NEVER call "
+ "it on your own initiative during ordinary conversation: questions, "
+ "remarks, news, quick lookups, single web searches, or anything you "
+ "can answer inline in this turn. Without an explicit request, answer "
+ "inline yourself and at most OFFER to start a background agent. Pass "
+ "the user utterance verbatim plus optional 3-5 short brainstorm "
+ "notes as ``context_hints``."
)
risk_tier: str = "monitor"
suppress_response: bool = True
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index ad82a04efb..ad116bcd3c 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -504,12 +504,17 @@ _TOOL_ROLE_DIRECTIVE = (
"computer. When the user asks you to DO something — create a file, write "
"code, research, start background work, open a view, change a setting, "
"control the computer — call the matching function instead of claiming "
- "you cannot act. Heavy multi-minute work (building files, coding, deep "
- "research) belongs to the Jarvis-Agent spawn function: start it, "
- "then briefly confirm what you started. If a function asks for a spoken "
- "confirmation, relay the question and wait for the user's answer. Never "
- "announce that you will check, open, save, or do something and then end the "
- "turn without a function call; an intention is not execution evidence."
+ "you cannot act. The Jarvis-Agent spawn function is EXPLICIT-REQUEST "
+ "ONLY: call it when the user themselves asks for an agent, a subagent, "
+ "spawning, delegating, or background work — or has just said yes to your "
+ "offer to start one. Never start it on your own initiative during "
+ "ordinary conversation, however heavy the topic sounds; answer inline "
+ "and at most offer to start an agent (an unrequested spawn is blocked "
+ "anyway). When you do start one, briefly confirm what you started. If a "
+ "function asks for a spoken confirmation, relay the question and wait "
+ "for the user's answer. Never announce that you will check, open, save, "
+ "or do something and then end the turn without a function call; an "
+ "intention is not execution evidence."
)
diff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.py
index 96bbd73789..154d26da60 100644
--- a/jarvis/realtime/tools.py
+++ b/jarvis/realtime/tools.py
@@ -9,6 +9,11 @@ from dataclasses import dataclass
from typing import Any, cast
from uuid import UUID, uuid4
+from jarvis.brain.spawn_gate import (
+ SPAWN_BLOCKED_MODEL_FEEDBACK,
+ SPAWN_VEHICLE_TOOL_NAMES,
+ llm_spawn_allowed,
+)
from jarvis.brain.tool_use_loop import (
_is_instructional_question,
_is_meta_debug_intent,
@@ -394,6 +399,13 @@ class RealtimeToolBridge:
message = "The user was introducing themselves; the side-effect tool was not run."
elif name == "spawn_worker" and _is_meta_debug_intent(user_text):
message = "A meta/debug request must be answered directly, not delegated."
+ elif name in SPAWN_VEHICLE_TOOL_NAMES and not llm_spawn_allowed(user_text):
+ # Explicit-delegation gate (maintainer mandate 2026-07-18): the
+ # realtime model may start a background agent ONLY when the user's
+ # spoken turn asks for one (or confirms an offer one turn later).
+ # Deterministic — prompt-side discouragement failed repeatedly.
+ # See jarvis/brain/spawn_gate.py.
+ message = SPAWN_BLOCKED_MODEL_FEEDBACK
elif _should_block_action_as_research(
descriptor,
name,
diff --git a/tests/unit/brain/test_spawn_gate.py b/tests/unit/brain/test_spawn_gate.py
new file mode 100644
index 0000000000..a10c60f1e5
--- /dev/null
+++ b/tests/unit/brain/test_spawn_gate.py
@@ -0,0 +1,163 @@
+"""Explicit-delegation gate for LLM-chosen agent spawns (spawn_gate.py).
+
+Maintainer mandate 2026-07-18: a background agent may be spawned by the model
+ONLY when the user explicitly asks for one (or confirms a delegation offer one
+turn later). The two live regression utterances pinned below come verbatim
+from the 2026-07-18 voice sessions (08:25 Gulfstream remark, 08:29 relocation
+remark) — both spawned an unrequested agent before the gate existed.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain.spawn_gate import (
+ OFFER_WINDOW,
+ SPAWN_VEHICLE_TOOL_NAMES,
+ DelegationOfferWindow,
+ llm_spawn_allowed,
+)
+
+
[email protected](autouse=True)
+def _fresh_offer_window():
+ OFFER_WINDOW.disarm()
+ yield
+ OFFER_WINDOW.disarm()
+
+
+# ── live regressions: conversational turns must NEVER unlock a spawn ──────
+
+
+ "utterance",
+ [
+ # voice-session 2026-07-18 08:25 — a remark, spawned an agent anyway
+ "Kann er jetzt überhaupt, der kann sich ja " # i18n-allow: live utterance
+ "jeden Tag 'ne Golf Stream kaufen.", # i18n-allow: live utterance
+ # voice-session 2026-07-18 08:29 — an intention, spawned an agent anyway
+ "Ah, ich will gucken, wo ich als nächstes hinziehe.", # i18n-allow: live utterance
+ "What is the richest place in Europe after Monaco?",
+ "Wie viele Milliardäre gibt es in Starnberg?", # i18n-allow: DE turn fixture
+ "Research the best cities to move to.",
+ "",
+ ],
+)
+def test_conversational_turn_blocks_spawn(utterance: str) -> None:
+ assert llm_spawn_allowed(utterance) is False
+
+
+# ── explicit requests: naming the vehicle unlocks the spawn ───────────────
+
+
+ "utterance",
+ [
+ "Spawn an agent to research the best cities.",
+ "Spawne einen Subagenten und recherchier das.", # i18n-allow: DE trigger
+ "Lass das einen Gustav Agent machen.", # i18n-allow: DE trigger
+ "Ein Nova-Agent soll das übernehmen.", # i18n-allow: DE trigger
+ "Delegate this to a worker, please.",
+ "Mach das im Hintergrund.", # i18n-allow: DE trigger
+ "Do that in the background and tell me later.",
+ "Starte eine Mission dafür.", # i18n-allow: DE trigger
+ "Delega esto a un agente.",
+ ],
+)
+def test_explicit_delegation_request_allows_spawn(utterance: str) -> None:
+ assert llm_spawn_allowed(utterance) is True
+
+
+def test_wake_word_brand_is_not_hardcoded() -> None:
+ """ANY '<wake-name> Agent' phrasing must match — the brand is dynamic (§4)."""
+ for brand in ("Gustav", "Harald", "Nova"):
+ OFFER_WINDOW.disarm()
+ utterance = f"Frag mal einen {brand} Agent dazu." # i18n-allow: DE trigger
+ assert llm_spawn_allowed(utterance) is True
+
+
+# ── declines and feature talk must not read as requests ───────────────────
+
+
+def test_spawn_decline_blocks_even_though_it_names_the_vehicle() -> None:
+ assert (
+ llm_spawn_allowed("Nee, spawne bitte keinen Subagenten dafür.") # i18n-allow: DE decline
+ is False
+ )
+
+
+def test_auto_spawn_feature_complaint_blocks() -> None:
+ assert (
+ llm_spawn_allowed(
+ "Das Auto-Spawn-Verhalten nervt, das müssen wir fixen." # i18n-allow: DE feature talk
+ )
+ is False
+ )
+
+
+# ── the offer window: blocked turn → model offers → short yes unlocks ─────
+
+
+def test_short_yes_after_blocked_turn_unlocks_exactly_once() -> None:
+ remark = "Ich will gucken, wo ich als nächstes hinziehe." # i18n-allow: live utterance
+ assert llm_spawn_allowed(remark) is False
+ # model offered delegation; the user's short yes unlocks ONE spawn ...
+ assert llm_spawn_allowed("Ja, mach das.") is True # i18n-allow: DE confirm
+ # ... and only one — the window is consumed
+ OFFER_WINDOW.disarm()
+ assert llm_spawn_allowed("Ja, mach das.") is False # i18n-allow: DE confirm
+
+
+def test_yes_in_english_and_spanish_unlocks_too() -> None:
+ assert llm_spawn_allowed("figure out where I should move next") is False
+ assert llm_spawn_allowed("Yes, go ahead.") is True
+ OFFER_WINDOW.disarm()
+ assert llm_spawn_allowed("figure out where I should move next") is False
+ assert llm_spawn_allowed("Sí, hazlo.") is True
+
+
+def test_long_sentence_containing_yes_does_not_unlock() -> None:
+ question = "Wo soll ich als nächstes hinziehen?" # i18n-allow: DE turn fixture
+ assert llm_spawn_allowed(question) is False
+ assert (
+ llm_spawn_allowed(
+ "Ja, und erzähl mir bitte noch mehr über Monaco." # i18n-allow: DE counter-example
+ )
+ is False
+ )
+
+
+def test_veto_closes_the_offer_window_for_good() -> None:
+ assert llm_spawn_allowed("Find out where I should move next.") is False
+ assert llm_spawn_allowed("No, don't.") is False
+ # a later bare yes must not resurrect the declined offer
+ assert llm_spawn_allowed("Yes.") is False
+
+
+def test_blocked_turn_cannot_confirm_itself() -> None:
+ # a bare affirmative with no pending offer arms the window with ITSELF —
+ # a second model attempt in the same turn must still be blocked
+ assert llm_spawn_allowed("Ja bitte.") is False # i18n-allow: DE confirm
+ assert llm_spawn_allowed("Ja bitte.") is False # i18n-allow: DE confirm
+
+
+def test_expired_offer_window_does_not_unlock() -> None:
+ window = DelegationOfferWindow(ttl_s=-1.0)
+ window.arm("find out where I should move next")
+ assert window.consume_confirm("yes, do it") is False
+
+
+def test_explicit_request_disarms_a_stale_offer() -> None:
+ assert llm_spawn_allowed("Find out where I should move next.") is False
+ assert llm_spawn_allowed("Spawn an agent for something else.") is True
+ # the explicit spawn consumed the conversation state — a stray later yes
+ # must not unlock another spawn from the stale offer
+ assert llm_spawn_allowed("Yes.") is False
+
+
+# ── parity with the manager's spawn-tool inventory ────────────────────────
+
+
+def test_vehicle_tool_names_match_manager_inventory() -> None:
+ from jarvis.brain.manager import _SPAWN_TOOL_NAMES
+
+ assert SPAWN_VEHICLE_TOOL_NAMES == _SPAWN_TOOL_NAMES
diff --git a/tests/unit/brain/test_tool_use_loop.py b/tests/unit/brain/test_tool_use_loop.py
index 365d6d6286..d314ffeb3c 100644
--- a/tests/unit/brain/test_tool_use_loop.py
+++ b/tests/unit/brain/test_tool_use_loop.py
@@ -613,3 +613,78 @@ async def test_tool_executes_despite_huge_per_turn_input_tokens() -> None:
assert executor.calls, "the Gmail tool must execute despite the large prompt"
assert "msg1 bis msg5" in result.text or "5 Mails" in result.text
assert len(brain.requests) == 2, "the loop must do a second turn to report"
+
+
+class _SpawnWorkerTool:
+ name = "spawn_worker"
+ schema: dict[str, Any] = {}
+
+
+class _SpawnThenAnswerBrain:
+ """Requests spawn_worker on round 1, answers inline on round 2."""
+
+ def __init__(self) -> None:
+ self.requests: list[BrainRequest] = []
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(req)
+ if len(self.requests) == 1:
+ yield BrainDelta(
+ tool_call={
+ "id": "spawn_1",
+ "name": "spawn_worker",
+ "input": {"utterance": "irrelevant", "action": "research"},
+ }
+ )
+ yield BrainDelta(finish_reason="tool_use")
+ return
+ yield BrainDelta(content="Answering inline instead.")
+ yield BrainDelta(finish_reason="stop")
+
+
+async def test_conversational_turn_blocks_llm_chosen_spawn() -> None:
+ """Explicit-delegation gate (mandate 2026-07-18, voice sessions 08:25 +
+ 08:29): the model chose spawn_worker on a plain conversational remark —
+ the gate must refuse execution and redirect the model to answer inline."""
+ from jarvis.brain.spawn_gate import OFFER_WINDOW
+
+ OFFER_WINDOW.disarm()
+ brain = _SpawnThenAnswerBrain()
+ executor = _Executor()
+ loop = ToolUseLoop(
+ brain,
+ {"spawn_worker": _SpawnWorkerTool()},
+ executor, # type: ignore[arg-type]
+ )
+
+ result = await loop.run(
+ [],
+ user_utterance="Ah, ich will gucken, wo ich als nächstes hinziehe.", # i18n-allow: live utterance
+ )
+
+ assert executor.calls == [], "unrequested spawn must never reach the executor"
+ assert "Answering inline" in result.text
+ tool_message = str(brain.requests[1].messages[-1].content)
+ assert "did not explicitly ask" in tool_message
+
+
+async def test_explicit_delegation_request_executes_spawn() -> None:
+ from jarvis.brain.spawn_gate import OFFER_WINDOW
+
+ OFFER_WINDOW.disarm()
+ brain = _SpawnThenAnswerBrain()
+ executor = _Executor()
+ loop = ToolUseLoop(
+ brain,
+ {"spawn_worker": _SpawnWorkerTool()},
+ executor, # type: ignore[arg-type]
+ )
+
+ await loop.run(
+ [],
+ user_utterance="Spawne einen Subagenten und recherchier Umzugsorte.", # i18n-allow: DE trigger
+ )
+
+ assert len(executor.calls) == 1, "an explicit spawn request must execute"
diff --git a/tests/unit/realtime/test_tools.py b/tests/unit/realtime/test_tools.py
index f30f05c54c..c31272f377 100644
--- a/tests/unit/realtime/test_tools.py
+++ b/tests/unit/realtime/test_tools.py
@@ -253,3 +253,79 @@ async def test_bridge_refresh_retains_a_tool_awaiting_voice_confirmation(
assert result["success"] is True
assert bridge.refresh_from_source() is True
assert [item["name"] for item in bridge.declarations] == ["new_tool"]
+
+
+class FakeSpawnTool:
+ """Minimal spawn_worker stand-in — no required args, monitor tier."""
+
+ def __init__(self) -> None:
+ self.name = "spawn_worker"
+ self.description = "Delegates a heavy task to a background worker."
+ self.schema = {"type": "object", "properties": {}, "required": []}
+ self.risk_tier = "monitor"
+
+ async def execute(self, *_args, **_kwargs):
+ raise AssertionError("Realtime must never execute a tool directly")
+
+
+def _spawn_bridge():
+ tool = FakeSpawnTool()
+ executor = FakeExecutor()
+ bridge = RealtimeToolBridge(
+ tools={"spawn_worker": tool}, executor=executor, language="en"
+ )
+ return bridge, executor
+
+
[email protected](autouse=True)
+def _fresh_spawn_offer_window():
+ from jarvis.brain.spawn_gate import OFFER_WINDOW
+
+ OFFER_WINDOW.disarm()
+ yield
+ OFFER_WINDOW.disarm()
+
+
+async def test_conversational_turn_blocks_realtime_spawn():
+ """Explicit-delegation gate (mandate 2026-07-18): the realtime model chose
+ spawn_worker on a plain conversational remark — blocked before the
+ executor, with the redirect message fed back to the model."""
+ bridge, executor = _spawn_bridge()
+ await bridge.handle_user_transcript(
+ "Ah, ich will gucken, wo ich als nächstes hinziehe." # i18n-allow: live utterance
+ )
+
+ name, result = await bridge.execute(wire_name="spawn_worker", arguments={})
+
+ assert name == "spawn_worker"
+ assert result["success"] is False
+ assert "did not explicitly ask" in result["error"]
+ assert executor.execute_calls == []
+
+
+async def test_explicit_agent_request_executes_realtime_spawn():
+ bridge, executor = _spawn_bridge()
+ await bridge.handle_user_transcript("Spawn an agent to research this.")
+
+ _name, result = await bridge.execute(wire_name="spawn_worker", arguments={})
+
+ assert result["success"] is True
+ assert len(executor.execute_calls) == 1
+
+
+async def test_confirmed_delegation_offer_unlocks_realtime_spawn():
+ """Blocked turn → the model offers delegation → a short yes unlocks it."""
+ bridge, executor = _spawn_bridge()
+ await bridge.handle_user_transcript("Figure out where I should move next.")
+ _name, blocked = await bridge.execute(wire_name="spawn_worker", arguments={})
+ assert blocked["success"] is False
+ assert executor.execute_calls == []
+
+ await bridge.handle_user_transcript("Yes, go ahead.")
+ _name, result = await bridge.execute(wire_name="spawn_worker", arguments={})
+
+ assert result["success"] is True
+ assert len(executor.execute_calls) == 1