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.

feat(agentic-ide): divide one order across the fleet, and spawn mixed fleets

Ruben Lütkedb48a4473bea
diff --git a/jarvis/agentic_ide/intent.py b/jarvis/agentic_ide/intent.py
index 5ff5fceb27..70ba38da61 100644
--- a/jarvis/agentic_ide/intent.py
+++ b/jarvis/agentic_ide/intent.py
@@ -580,6 +580,73 @@ def _spoken_count(text: str) -> int:
return 1
+#: A count followed by an agent name — "5 Codex", "drei neue Claude Code",
+#: "tres terminales de Codex". The filler between them covers the words people
+#: actually put there: the pane noun itself (Spanish and English both say
+#: "three terminals of Codex" as often as "three Codex terminals") plus the
+#: usual qualifiers. Bounded at two words so the count and the agent cannot
+#: drift into different clauses of the sentence.
+_COUNT_AGENT_RE = re.compile(
+ r"\b(?P<count>\d{1,3}|[a-zäöüñ]+)\s+" # i18n-allow: input vocab
+ r"(?:(?:neue|weitere|zus[aä]tzliche|more|new|extra|additional|de|del|" # i18n-allow: input vocab
+ r"otros|otras|m[aá]s|terminals?|terminales|panes?|tabs?)\s+){0,2}"
+ r"(?P<agent>claude(?:\s+code)?|codex)\b",
+ re.IGNORECASE,
+)
+
+
+def _spoken_groups(text: str) -> tuple[SpawnGroup, ...]:
+ """The fleet the utterance describes, group by group.
+
+ Returns an empty tuple when no count/agent pair is spelled out, which is the
+ common single-group case ("three more terminals") and stays with the flat
+ count/agent fields.
+
+ Groups naming the SAME agent are merged: "two Codex and two more Codex" is
+ four Codex panes, and two groups would open them in two batches for no
+ reason.
+ """
+ from .session import MAX_TERMINALS
+
+ found: list[SpawnGroup] = []
+ for match in _COUNT_AGENT_RE.finditer(text):
+ raw = match.group("count").casefold()
+ if raw.isdigit():
+ count = int(raw)
+ else:
+ cleaned = "".join(ch for ch in raw if ch.isalpha())
+ if cleaned not in _NUMBER_WORDS:
+ continue
+ count = _NUMBER_WORDS[cleaned]
+ agent = (
+ "codex" if match.group("agent").casefold().startswith("codex") else "claude"
+ )
+ found.append(SpawnGroup(count=max(1, count), agent=agent))
+
+ if len(found) < 2:
+ # One pair is the plain single-agent request; the flat fields already
+ # describe it and going through groups would only duplicate the parse.
+ return ()
+
+ merged: dict[str, int] = {}
+ for group in found:
+ key = group.agent or ""
+ merged[key] = merged.get(key, 0) + group.count
+
+ # Clamp the TOTAL, not each group: the workspace maximum is a property of
+ # the workspace. Trimming from the back keeps the groups the user named
+ # first intact rather than shrinking all of them into uselessness.
+ out: list[SpawnGroup] = []
+ remaining = MAX_TERMINALS
+ for agent, count in merged.items():
+ if remaining <= 0:
+ break
+ take = min(count, remaining)
+ remaining -= take
+ out.append(SpawnGroup(count=take, agent=agent or None))
+ return tuple(out)
+
+
def detect_spawn(
user_text: str, *, names: list[str] | None = None
) -> SpawnTerminalsRequest | None:
@@ -603,12 +670,25 @@ def detect_spawn(
if detect(text, names=names) is not None:
return None
+ groups = _spoken_groups(text)
+ if groups:
+ return SpawnTerminalsRequest(
+ count=sum(g.count for g in groups),
+ agent=groups[0].agent,
+ utterance=text,
+ groups=groups,
+ )
+
agent_match = _AGENT_RE.search(text)
agent: str | None = None
if agent_match is not None:
agent = "codex" if agent_match.group(1).lower().startswith("codex") else "claude"
+ count = _spoken_count(text)
return SpawnTerminalsRequest(
- count=_spoken_count(text), agent=agent, utterance=text
+ count=count,
+ agent=agent,
+ utterance=text,
+ groups=(SpawnGroup(count=count, agent=agent),),
)
@@ -711,6 +791,7 @@ def owns_turn(user_text: str, *, names: list[str] | None = None) -> bool:
__all__ = [
"KIND_PROMPT",
"KIND_REPORT",
+ "SpawnGroup",
"SpawnTerminalsRequest",
"TerminalIntent",
"detect",
diff --git a/jarvis/agentic_ide/work_split.py b/jarvis/agentic_ide/work_split.py
new file mode 100644
index 0000000000..b5fcb106ae
--- /dev/null
+++ b/jarvis/agentic_ide/work_split.py
@@ -0,0 +1,403 @@
+"""Turn ONE order into N distinct assignments, one per coding agent.
+
+Handing five agents the same sentence is not a fan-out. They open the same
+files, reach five overlapping conclusions, and burn five subscriptions doing
+one agent's work — and on a shared worktree they will also fight over the same
+edits. What the maintainer asked for on 2026-07-26 is the other thing: "split
+the deep dive across areas and say exactly what each one has to do."
+
+That is a judgement call about a specific repository, so it is a model call —
+but one that must degrade all the way down, because a downloader whose only
+credential is for some other provider still has to be able to run a fleet (§3).
+Two layers, same shape as ``prompt_composer``:
+
+1. **Model split** — one bounded call to ``resolve_quality_brain`` returning
+ JSON. Deliberately not the full frontier chain: that chain ends in small
+ fast models so a core path never dies, and a split written by one of those
+ reads perfectly plausible while cutting the repository along seams that do
+ not exist.
+2. **Deterministic split** — by top-level directory, round-robin. Crude, but it
+ is grounded in what is actually on disk and it never overlaps, which is the
+ property that matters most.
+
+The validation is stricter than "did it parse", because both ways of getting
+this wrong are silent. Too few assignments means an agent sits idle while the
+user was told the fleet is working — the partial-delivery failure this whole
+change set exists to stop. Duplicate areas means two agents racing on one file.
+Either one sends the whole answer to the deterministic layer rather than
+shipping a fleet that looks briefed and is not.
+
+The assignments are handed to ``fanout.deliver`` as its ``assignments`` map;
+each pane's prompt is then composed from ITS slice, so the per-agent brief still
+gets the file references and repository conventions the composer adds.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+#: Bound for the one splitting call. Shorter than the composer's: this produces
+#: a short JSON plan rather than a full brief, and it runs BEFORE any prompt is
+#: composed — every second here is a second added in front of N compositions.
+SPLIT_TIMEOUT_S = 25.0
+
+#: A fleet larger than this is not a split any model plans usefully, and the
+#: deterministic layer runs out of real directories long before it. Above the
+#: cap the areas repeat by index, which stays honest (each agent still gets its
+#: own slice) without pretending the repository has 40 seams.
+MAX_PLANNED_AREAS = 24
+
+
+@dataclass(frozen=True, slots=True)
+class Assignment:
+ """One agent's slice of the order."""
+
+ area: str
+ """Short label of what this agent owns ("the wake pipeline")."""
+
+ task: str
+ """What this agent must do — always carries the original goal, because a
+ slice without the goal is an agent doing something adjacent."""
+
+ files: tuple[str, ...] = ()
+ done_when: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class WorkSplit:
+ """The plan for a fleet, plus how it came to be."""
+
+ assignments: tuple[Assignment, ...] = ()
+ split_by: str = "fallback"
+ """``llm`` when a model planned it, ``fallback`` when the directory split
+ did. Reported rather than hidden: a deterministic split is a coarser plan
+ and the user is entitled to know which one their fleet is running."""
+
+ note: str = ""
+ """Why the fallback was used, when it was. Empty on the happy path."""
+
+
+def _resolve_splitter() -> Any:
+ """The model that plans a split, or None when only fast tiers are up."""
+ from jarvis.brain.resolver import resolve_quality_brain
+ from jarvis.core.config import load_config
+
+ try:
+ return resolve_quality_brain(load_config())
+ except Exception: # noqa: BLE001 - resolution must never break a turn
+ logger.info("Agentic IDE work splitter could not be resolved", exc_info=True)
+ return None
+
+
+_SYSTEM_PROMPT = (
+ "You divide one software task across several coding agents working in the "
+ "SAME repository at the same time.\n\n"
+ "Return ONLY a JSON array, one object per agent, with these keys:\n"
+ ' "area" - two to five words naming the part of the repository this '
+ "agent owns\n"
+ ' "task" - one paragraph telling THIS agent what to do, restating '
+ "the overall goal so it can work without seeing the others\n"
+ ' "files" - repo-relative paths from the list you were given, or []\n'
+ ' "done_when" - one sentence describing this agent\'s finished state\n\n'
+ "Rules:\n"
+ "- Exactly as many objects as there are agents. Never fewer.\n"
+ "- The areas must not overlap. Two agents editing the same files is the "
+ "failure this split exists to prevent.\n"
+ "- Slice along real seams of THIS repository, using the directories and "
+ "files you were given. Never invent a path.\n"
+ "- Together the areas must cover the whole goal; a part nobody owns is a "
+ "part nobody does.\n"
+ "- No prose, no code fence, no commentary. The array only."
+)
+
+
+def _user_block(
+ *, instruction: str, count: int, folder: str, areas: list[str], profile: list[str]
+) -> str:
+ lines = [
+ f"Overall goal: {instruction}",
+ f"Number of agents: {count}",
+ f"Repository: {Path(folder).name}",
+ ]
+ if profile:
+ lines.append("Project: " + "; ".join(profile[:4]))
+ if areas:
+ lines.append("Top-level directories: " + ", ".join(areas))
+ return "\n".join(lines)
+
+
+async def _llm_split(*, brain: Any, system_prompt: str, user_block: str) -> str:
+ """One bounded call that plans the division of labour."""
+ from jarvis.core.protocols import BrainMessage, BrainRequest
+
+ request = BrainRequest(
+ messages=(BrainMessage(role="user", content=user_block),),
+ system=system_prompt,
+ # Planning, not writing: the same repository and the same goal should
+ # produce the same division of labour twice in a row.
+ temperature=0.1,
+ # Headroom for the thinking budget as well as the answer, same reason
+ # as the composer: a plan cut off mid-array validates as malformed and
+ # throws away the whole call.
+ max_tokens=4000,
+ stream=True,
+ reasoning_effort="medium",
+ )
+ chunks: list[str] = []
+ async for delta in brain.complete(request):
+ if delta.content:
+ chunks.append(delta.content)
+ return "".join(chunks).strip()
+
+
+def _strip_fence(text: str) -> str:
+ """Unwrap a fenced block. Models add one far too often to treat as failure."""
+ stripped = (text or "").strip()
+ fence = re.match(r"^```[a-zA-Z]*\s*\n(.*?)\n?```$", stripped, re.DOTALL)
+ return fence.group(1).strip() if fence else stripped
+
+
+def _parse(payload: str, *, count: int, instruction: str) -> list[Assignment] | None:
+ """Validated assignments, or None when the answer cannot be trusted.
+
+ Returning None rather than repairing the answer is deliberate. A plan that
+ is short by one agent, or that gives two agents the same area, is not a
+ plan with a small flaw — it is a fleet that will either idle or collide, and
+ the deterministic split is strictly better than either.
+ """
+ try:
+ data = json.loads(_strip_fence(payload))
+ except (ValueError, TypeError):
+ return None
+ if not isinstance(data, list) or len(data) != count:
+ return None
+
+ out: list[Assignment] = []
+ seen_areas: set[str] = set()
+ for item in data:
+ if not isinstance(item, dict):
+ return None
+ area = str(item.get("area") or "").strip()
+ task = str(item.get("task") or "").strip()
+ if not area or not task:
+ return None
+ key = area.casefold()
+ if key in seen_areas:
+ return None
+ seen_areas.add(key)
+ raw_files = item.get("files")
+ files = tuple(
+ str(f).strip()
+ for f in (raw_files if isinstance(raw_files, list) else [])
+ if str(f).strip()
+ )
+ out.append(
+ Assignment(
+ area=area,
+ task=task,
+ files=files,
+ done_when=str(item.get("done_when") or "").strip(),
+ )
+ )
+ return out
+
+
+def _top_level_areas(folder: str) -> list[str]:
+ """Directories of the workspace worth handing to an agent.
+
+ Reuses the same skip list the file index walks with, so a fleet is never
+ pointed at ``node_modules`` or ``.git``.
+ """
+ from .folders import _SKIP_DIRS
+
+ try:
+ root = Path(folder).expanduser()
+ names = sorted(
+ entry.name
+ for entry in root.iterdir()
+ if entry.is_dir()
+ and entry.name not in _SKIP_DIRS
+ and not entry.name.startswith(".")
+ )
+ except OSError:
+ return []
+ return names
+
+
+def _fallback(instruction: str, *, folder: str, count: int, note: str) -> WorkSplit:
+ """Split by top-level directory, round-robin, without a model.
+
+ Coarse on purpose. What it guarantees is what matters when nothing better
+ is available: every agent gets a slice, no two get the same one, and every
+ slice names a directory that actually exists.
+ """
+ areas = _top_level_areas(folder)
+ assignments: list[Assignment] = []
+ for index in range(count):
+ if areas:
+ # Round-robin so a repo with fewer directories than agents still
+ # gives everyone something: the second pass adds a distinct angle
+ # rather than a duplicate area.
+ owned = areas[index % len(areas)]
+ pass_number = index // len(areas)
+ area = owned if pass_number == 0 else f"{owned} (pass {pass_number + 1})"
+ where = f"Focus on the `{owned}` part of the repository."
+ else:
+ # Nothing readable on disk. Numbered slices keep the contract (one
+ # distinct assignment per agent) and the prompt composer still
+ # grounds each one in real files.
+ area = f"part {index + 1} of {count}"
+ where = (
+ f"You are agent {index + 1} of {count}. Take the "
+ f"{_ordinal(index + 1)} part of the work and agree the "
+ "boundary with the others by what you find."
+ )
+ assignments.append(
+ Assignment(
+ area=area,
+ task=(
+ f"{instruction}\n\n{where} Stay inside it: the other agents "
+ "are working on the rest of this repository at the same "
+ "time, so anything outside your area is theirs."
+ ),
+ )
+ )
+ return WorkSplit(
+ assignments=tuple(assignments), split_by="fallback", note=note
+ )
+
+
+def _ordinal(n: int) -> str:
+ if 10 <= n % 100 <= 20:
+ return f"{n}th"
+ return f"{n}{ {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th') }"
+
+
+async def split(
+ instruction: str,
+ *,
+ session: Any,
+ count: int,
+ brain: Any = None,
+ timeout_s: float = SPLIT_TIMEOUT_S,
+) -> WorkSplit:
+ """Divide ``instruction`` across ``count`` agents.
+
+ ``brain`` pins the planning model explicitly; left None a quality-tier model
+ is resolved and the deterministic split takes over when none is reachable.
+
+ Never raises. Every failure path lands on the directory split, because
+ "the fleet got a coarser plan" is a far better outcome than "your five
+ agents did nothing".
+ """
+ wanted = int(count)
+ if wanted <= 0:
+ return WorkSplit()
+
+ said = (instruction or "").strip()
+ folder = str(getattr(session, "folder", "") or "")
+
+ if wanted == 1:
+ # Splitting one way is not splitting. Saving the provider call here is
+ # not just thrift: the single-agent path is the common one, and it must
+ # not gain the latency of a planning round it cannot use.
+ return WorkSplit(
+ assignments=(Assignment(area="the whole task", task=said),),
+ split_by="single",
+ )
+
+ if wanted > MAX_PLANNED_AREAS:
+ logger.info(
+ "Agentic IDE work split: {} agents is past the planning cap ({}) "
+ "— splitting deterministically",
+ wanted,
+ MAX_PLANNED_AREAS,
+ )
+ return _fallback(
+ said, folder=folder, count=wanted, note="fleet larger than the planning cap"
+ )
+
+ planner = brain if brain is not None else _resolve_splitter()
+ if planner is None:
+ return _fallback(
+ said,
+ folder=folder,
+ count=wanted,
+ note="no quality-tier provider reachable",
+ )
+
+ profile_lines: list[str] = []
+ try:
+ profile = getattr(session, "profile", None)
+ if profile is not None:
+ profile_lines = list(profile.summary_lines())
+ except Exception: # noqa: BLE001 - a profile is context, never required
+ profile_lines = []
+
+ try:
+ areas = await asyncio.to_thread(_top_level_areas, folder)
+ payload = await asyncio.wait_for(
+ _llm_split(
+ brain=planner,
+ system_prompt=_SYSTEM_PROMPT,
+ user_block=_user_block(
+ instruction=said,
+ count=wanted,
+ folder=folder,
+ areas=areas,
+ profile=profile_lines,
+ ),
+ ),
+ timeout=timeout_s,
+ )
+ except TimeoutError:
+ return _fallback(
+ said,
+ folder=folder,
+ count=wanted,
+ note=f"the planner timed out after {timeout_s:g}s",
+ )
+ except Exception as exc: # noqa: BLE001 - any provider failure degrades
+ logger.info("Agentic IDE work split fell back: {}", exc)
+ return _fallback(
+ said,
+ folder=folder,
+ count=wanted,
+ note=f"the planner was unavailable ({type(exc).__name__})",
+ )
+
+ parsed = _parse(payload, count=wanted, instruction=said)
+ if parsed is None:
+ logger.info(
+ "Agentic IDE work split: planner answer rejected "
+ "(wanted {} distinct assignments) — splitting deterministically",
+ wanted,
+ )
+ return _fallback(
+ said,
+ folder=folder,
+ count=wanted,
+ note="the planner's answer was incomplete or overlapping",
+ )
+
+ logger.info(
+ "Agentic IDE work split: {} areas planned ({})",
+ len(parsed),
+ ", ".join(a.area for a in parsed),
+ )
+ return WorkSplit(assignments=tuple(parsed), split_by="llm")
+
+
+__all__ = [
+ "MAX_PLANNED_AREAS",
+ "SPLIT_TIMEOUT_S",
+ "Assignment",
+ "WorkSplit",
+ "split",
+]
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 98b607cba0..e1edb38010 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -5939,17 +5939,31 @@ class BrainManager:
if not entries:
return action_phrase("ide_terminals_nowhere", out_lang)
recent = entries[0]
- agent = request.agent or _recent_agent(recent)
- session = await registry.start(
- recent.path,
- [{"agent": agent} for _ in range(request.count)],
- )
+ fallback_agent = request.agent or _recent_agent(recent)
+ # One spec per pane, group by group: "5 Codex and 3 Claude Code
+ # terminals" is a mixed fleet, and collapsing it to one agent
+ # opened five of the first kind and silently dropped the rest
+ # (maintainer report 2026-07-26).
+ specs = [
+ {"agent": group.agent or fallback_agent}
+ for group in request.groups
+ for _ in range(group.count)
+ ]
+ session = await registry.start(recent.path, specs)
created = list(session.terminals)
folder_label = recent.name
else:
- created, _capped = await registry.add_terminals(
- request.count, agent=request.agent
- )
+ created = []
+ for group in request.groups:
+ opened, _capped = await registry.add_terminals(
+ group.count, agent=group.agent
+ )
+ created.extend(opened)
+ if _capped:
+ # The workspace filled up mid-fleet. Stop rather than
+ # asking for the next group and getting the same
+ # refusal — the readback already reports the shortfall.
+ break
except SessionError as exc:
# A full workspace, a missing CLI, an unreadable folder: every one of
# these already carries a user-facing English sentence, and speaking
diff --git a/tests/unit/agentic_ide/test_intent.py b/tests/unit/agentic_ide/test_intent.py
index 46197af21e..277dafa58a 100644
--- a/tests/unit/agentic_ide/test_intent.py
+++ b/tests/unit/agentic_ide/test_intent.py
@@ -228,3 +228,45 @@ def test_detect_still_returns_the_first_match_for_existing_callers() -> None:
def test_an_unrelated_turn_addresses_nobody() -> None:
weather = "Wie ist das Wetter heute?" # i18n-allow: fixture
assert intent.detect_all(weather, names=MULTI_NAMES) == []
+
+
+# --------------------------------------------------------------------------- #
+# "…and split the work between you" #
+# --------------------------------------------------------------------------- #
+# Addressing several panes does not by itself mean dividing the task: "both of
+# you run the tests" is one order for two agents, and splitting it would be
+# wrong. Only an explicit request to divide the work turns a fan-out into a
+# planned split, because planning costs a provider call and produces DIFFERENT
+# instructions per agent.
+
+
+ "utterance",
+ [
+ "Teilt euch die Analyse auf verschiedene Bereiche auf", # i18n-allow: fixture
+ "Teile den Deep Dive in Aufgabenbereiche auf", # i18n-allow: fixture
+ "Split the analysis across areas",
+ "Divide the work between you",
+ "Each of you takes a different part",
+ "Jeder von euch nimmt einen anderen Teil", # i18n-allow: fixture
+ "Reparte el trabajo entre vosotros",
+ ],
+)
+def test_a_request_to_divide_the_work_is_recognised(utterance: str) -> None:
+ assert intent.wants_split(utterance) is True
+
+
+ "utterance",
+ [
+ "Sag Iris und Bruno, sie sollen die Tests laufen lassen", # i18n-allow: fixture
+ "Both of you run the test suite",
+ "Analyse the codebase",
+ # "aufteilen" about the CODE, not about the agents: splitting a file is
+ # ordinary refactoring work and must not trigger a fleet plan.
+ "Teile die grosse Datei in kleinere Module auf", # i18n-allow: fixture
+ "Split the module into two files",
+ ],
+)
+def test_ordinary_orders_are_not_split_requests(utterance: str) -> None:
+ assert intent.wants_split(utterance) is False
diff --git a/tests/unit/agentic_ide/test_spawn_intent.py b/tests/unit/agentic_ide/test_spawn_intent.py
index 10694eaa1a..a6b602c38f 100644
--- a/tests/unit/agentic_ide/test_spawn_intent.py
+++ b/tests/unit/agentic_ide/test_spawn_intent.py
@@ -131,6 +131,78 @@ def test_workspace_owns_a_terminal_spawn_even_though_it_names_the_vehicle() -> N
assert intent.owns_turn("Spawne einen Agenten", names=NAMES) is False # i18n-allow: spoken input under test
+# --------------------------------------------------------------------------- #
+# Mixed fleets: "five Codex and three Claude Code terminals" #
+# --------------------------------------------------------------------------- #
+# The maintainer's ask on 2026-07-26: "you have to be able to manage 5 Codex and
+# 3 Claudes in one task". The detector read the FIRST number and the FIRST agent
+# it saw, so that sentence opened five Codex panes and silently dropped the
+# three Claude ones — a partial execution nobody was told about.
+
+
+def test_a_mixed_fleet_keeps_both_groups() -> None:
+ found = intent.detect_spawn(
+ "Mach mir 5 Codex Terminals und 3 Claude Code Terminals auf", # i18n-allow: fixture
+ names=NAMES,
+ )
+ assert found is not None
+ assert [(g.count, g.agent) for g in found.groups] == [(5, "codex"), (3, "claude")]
+ # The flat fields stay meaningful: total panes, first group's agent.
+ assert found.count == 8
+
+
+def test_a_mixed_fleet_works_in_english_and_spanish() -> None:
+ english = intent.detect_spawn(
+ "Open two Codex terminals and four Claude Code terminals", names=NAMES
+ )
+ assert english is not None
+ assert [(g.count, g.agent) for g in english.groups] == [(2, "codex"), (4, "claude")]
+
+ spanish = intent.detect_spawn(
+ "Abre tres terminales de Codex y dos de Claude", names=NAMES
+ )
+ assert spanish is not None
+ assert [(g.count, g.agent) for g in spanish.groups] == [(3, "codex"), (2, "claude")]
+
+
+def test_a_single_agent_request_is_still_one_group() -> None:
+ found = intent.detect_spawn(
+ "Spawne fünf neue Claude Code Terminals", names=NAMES # i18n-allow: spoken input under test
+ )
+ assert found is not None
+ assert [(g.count, g.agent) for g in found.groups] == [(5, "claude")]
+ assert found.count == 5
+ assert found.agent == "claude"
+
+
+def test_an_unnamed_agent_stays_unnamed_so_the_panes_inherit() -> None:
+ """"Three more terminals" must not be turned into a Claude request."""
+ found = intent.detect_spawn("Open three more terminals", names=NAMES)
+ assert found is not None
+ assert [(g.count, g.agent) for g in found.groups] == [(3, None)]
+ assert found.agent is None
+
+
+def test_the_same_agent_named_twice_is_merged() -> None:
+ """"Two Codex and two more Codex" is four Codex panes, not two groups."""
+ found = intent.detect_spawn(
+ "Open two Codex terminals and two more Codex terminals", names=NAMES
+ )
+ assert found is not None
+ assert [(g.count, g.agent) for g in found.groups] == [(4, "codex")]
+ assert found.count == 4
+
+
+def test_the_total_is_capped_at_the_workspace_maximum() -> None:
+ found = intent.detect_spawn(
+ f"Open {MAX_TERMINALS} Codex terminals and 5 Claude Code terminals",
+ names=NAMES,
+ )
+ assert found is not None
+ assert found.count <= MAX_TERMINALS
+ assert sum(g.count for g in found.groups) == found.count
+
+
def test_an_addressed_terminal_still_wins_over_the_spawn_grammar() -> None:
"""Telling a named pane to open a terminal is a prompt FOR that pane.
diff --git a/tests/unit/agentic_ide/test_work_split.py b/tests/unit/agentic_ide/test_work_split.py
new file mode 100644
index 0000000000..340c334d77
--- /dev/null
+++ b/tests/unit/agentic_ide/test_work_split.py
@@ -0,0 +1,252 @@
+"""Guards for turning ONE order into N distinct assignments.
+
+The feature the maintainer asked for on 2026-07-26: "spawn five deep-dive
+agents, split the analysis across areas, and say exactly what each has to do".
+Handing all five the same sentence is not a fan-out — it is five agents racing
+on the same file with five conflicting opinions, and it burns five subscriptions
+to do one agent's work.
+
+What is pinned here:
+
+* **Every agent gets a different slice.** Overlap is the failure mode, so the
+ areas are checked for distinctness, not just for existing.
+* **The count is exact.** Asking for five and briefing three is the partial
+ delivery this whole change set exists to stop.
+* **It works with no API key at all.** The deterministic split by top-level
+ directory is not a nicety: a downloader whose only credential is for some
+ other provider must still be able to run a fleet (§3).
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import file_index, work_split
+
+
+@dataclass
+class _Profile:
+ lines: list[str] = field(default_factory=lambda: ["Python project"])
+
+ def summary_lines(self) -> list[str]:
+ return self.lines
+
+
+@dataclass
+class _Session:
+ folder: str
+ profile: _Profile = field(default_factory=_Profile)
+
+
+class _Splitter:
+ """Stands in for a resolved quality-tier Brain."""
+
+
[email protected](autouse=True)
+def _splitter_available(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A quality-tier model is reachable unless a test says otherwise."""
+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: _Splitter())
+
+
+def workspace(tmp_path: Path) -> _Session:
+ for sub in ("jarvis/plugins/wake", "jarvis/ui/web", "docs", "tests/unit"):
+ (tmp_path / sub).mkdir(parents=True)
+ (tmp_path / sub / "module.py").write_text("x", encoding="utf-8")
+ file_index.reset_cache()
+ return _Session(folder=str(tmp_path))
+
+
+def _answer(monkeypatch: pytest.MonkeyPatch, payload: str) -> None:
+ """Pin what the model returns for the one splitting call."""
+
+ async def fake_llm_split(**_kwargs: object) -> str:
+ return payload
+
+ monkeypatch.setattr(work_split, "_llm_split", fake_llm_split)
+
+
+VALID_THREE = """
+[
+ {"area": "wake pipeline", "task": "audit the wake detectors end to end",
+ "files": ["jarvis/plugins/wake/module.py"], "done_when": "every path traced"},
+ {"area": "web UI", "task": "audit the web surface for cross-platform gaps",
+ "files": ["jarvis/ui/web/module.py"], "done_when": "all three OSes checked"},
+ {"area": "docs", "task": "check the docs against the code",
+ "files": ["docs/module.py"], "done_when": "drift listed"}
+]
+"""
+
+
+async def test_one_agent_gets_the_whole_task_without_a_model_call(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Splitting one way is not splitting — it must not cost a provider call."""
+
+ async def explode(**_kwargs: object) -> str:
+ raise AssertionError("the model must not be called for a single agent")
+
+ monkeypatch.setattr(work_split, "_llm_split", explode)
+
+ result = await work_split.split(
+ "analyse the whole codebase", session=workspace, count=1
+ )
+ assert len(result.assignments) == 1
+ assert "analyse the whole codebase" in result.assignments[0].task
+
+
+async def test_the_model_split_yields_one_assignment_per_agent(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _answer(monkeypatch, VALID_THREE)
+ result = await work_split.split(
+ "analyse the whole codebase", session=workspace, count=3
+ )
+ assert result.split_by == "llm"
+ assert len(result.assignments) == 3
+ assert [a.area for a in result.assignments] == ["wake pipeline", "web UI", "docs"]
+ assert result.assignments[0].done_when == "every path traced"
+
+
+async def test_areas_must_be_distinct(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Two agents on the same area is the exact waste this feature avoids."""
+ _answer(
+ monkeypatch,
+ '[{"area": "wake", "task": "audit wake"},'
+ ' {"area": "wake", "task": "audit wake again"}]',
+ )
+ result = await work_split.split("analyse it", session=workspace, count=2)
+ assert result.split_by == "fallback"
+
+
+async def test_too_few_assignments_fall_back(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Three agents asked for, two briefed, is a silent partial."""
+ _answer(
+ monkeypatch,
+ '[{"area": "a", "task": "audit a"}, {"area": "b", "task": "audit b"}]',
+ )
+ result = await work_split.split("analyse it", session=workspace, count=3)
+ assert result.split_by == "fallback"
+ assert len(result.assignments) == 3
+
+
+async def test_malformed_json_falls_back(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _answer(monkeypatch, "sure! here are the areas: wake, ui, docs")
+ result = await work_split.split("analyse it", session=workspace, count=3)
+ assert result.split_by == "fallback"
+ assert len(result.assignments) == 3
+
+
+async def test_an_empty_task_falls_back(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _answer(
+ monkeypatch,
+ '[{"area": "a", "task": ""}, {"area": "b", "task": "audit b"}]',
+ )
+ result = await work_split.split("analyse it", session=workspace, count=2)
+ assert result.split_by == "fallback"
+
+
+async def test_a_fenced_answer_is_still_read(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Models wrap JSON in a code fence far too often to treat as a failure."""
+ _answer(monkeypatch, f"```json\n{VALID_THREE}\n```")
+ result = await work_split.split("analyse it", session=workspace, count=3)
+ assert result.split_by == "llm"
+ assert len(result.assignments) == 3
+
+
+async def test_a_provider_failure_falls_back(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def boom(**_kwargs: object) -> str:
+ raise RuntimeError("provider down")
+
+ monkeypatch.setattr(work_split, "_llm_split", boom)
+ result = await work_split.split("analyse it", session=workspace, count=3)
+ assert result.split_by == "fallback"
+ assert len(result.assignments) == 3
+
+
+async def test_no_quality_provider_still_splits(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A downloader with no API key must still be able to run a fleet (§3)."""
+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)
+ result = await work_split.split("analyse it", session=workspace, count=3)
+ assert result.split_by == "fallback"
+ assert len(result.assignments) == 3
+ assert result.note
+
+
+async def test_the_deterministic_split_uses_real_directories(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)
+ result = await work_split.split("analyse it", session=workspace, count=3)
+ areas = " ".join(a.area for a in result.assignments)
+ # The fixture workspace has jarvis/, docs/ and tests/ — the split must name
+ # parts of THIS repository, never invented ones.
+ assert "jarvis" in areas or "docs" in areas or "tests" in areas
+
+
+async def test_the_deterministic_split_never_repeats_an_area(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)
+ result = await work_split.split("analyse it", session=workspace, count=3)
+ areas = [a.area for a in result.assignments]
+ assert len(set(areas)) == len(areas)
+
+
+async def test_every_assignment_carries_the_original_order(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A slice without the goal is an agent doing something else entirely."""
+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)
+ result = await work_split.split(
+ "check cross-platform support", session=workspace, count=3
+ )
+ for assignment in result.assignments:
+ assert "cross-platform" in assignment.task
+
+
+async def test_more_agents_than_directories_still_gets_everyone_a_slice(
+ workspace: _Session, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Eight agents on a four-directory repo: nobody may be left idle."""
+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)
+ result = await work_split.split("analyse it", session=workspace, count=8)
+ assert len(result.assignments) == 8
+ assert all(a.task.strip() for a in result.assignments)
+ assert len({a.area for a in result.assignments}) == 8
+
+
+async def test_an_empty_folder_still_produces_one_slice_per_agent(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """No readable structure is not a reason to brief nobody."""
+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)
+ file_index.reset_cache()
+ result = await work_split.split(
+ "analyse it", session=_Session(folder=str(tmp_path)), count=3
+ )
+ assert len(result.assignments) == 3
+ assert all(a.task.strip() for a in result.assignments)
+
+
+async def test_zero_or_negative_counts_are_refused_not_guessed(
+ workspace: _Session,
+) -> None:
+ result = await work_split.split("analyse it", session=workspace, count=0)
+ assert result.assignments == ()
diff --git a/tests/unit/brain/test_agentic_ide_fanout_fast_path.py b/tests/unit/brain/test_agentic_ide_fanout_fast_path.py
index 48470505ab..591d678779 100644
--- a/tests/unit/brain/test_agentic_ide_fanout_fast_path.py
+++ b/tests/unit/brain/test_agentic_ide_fanout_fast_path.py
@@ -183,6 +183,87 @@ async def test_a_single_addressed_pane_keeps_the_singular_reply(
assert not _sent_to(registry, second)
+def _prompt_of(registry: Registry, name: str) -> str:
+ assert registry.session is not None
+ term = registry.session.find(name)
+ assert term is not None
+ return term.last_prompt or ""
+
+
+async def test_a_split_request_gives_each_pane_its_own_brief(
+ manager: BrainManager,
+ registry: Registry,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The maintainer's actual ask: divide the deep dive across the fleet.
+
+ The planner is left unreachable on purpose, so this also proves the feature
+ works for a downloader with no quality-tier key at all (§3) — the
+ deterministic directory split has to carry it.
+ """
+ from jarvis.agentic_ide import work_split
+
+ monkeypatch.setattr(work_split, "_resolve_splitter", lambda: None)
+ for sub in ("jarvis", "docs", "tests"):
+ (tmp_path / sub).mkdir()
+ await _open(registry, tmp_path, 2)
+ first, second = _names(registry)
+
+ reply = await manager._run_agentic_ide_fast_path(
+ f"Tell {first} and {second} to analyse the codebase and "
+ "split the work between you"
+ )
+
+ assert reply is not None
+ assert _sent_to(registry, first)
+ assert _sent_to(registry, second)
+ # Different briefs, not the same sentence twice.
+ assert _prompt_of(registry, first) != _prompt_of(registry, second)
+
+
+async def test_without_a_split_request_both_panes_get_the_same_brief(
+ manager: BrainManager, registry: Registry, tmp_path: Path
+) -> None:
+ """"Both of you run the tests" is ONE order, not a division of labour."""
+ await _open(registry, tmp_path, 2)
+ first, second = _names(registry)
+
+ await manager._run_agentic_ide_fast_path(
+ f"Tell {first} and {second} to run the test suite"
+ )
+
+ # The fake composer echoes the instruction, so identical instructions mean
+ # identical prompts apart from the pane's own name.
+ one = _prompt_of(registry, first).replace(first, "X")
+ two = _prompt_of(registry, second).replace(second, "X")
+ assert one == two
+
+
+async def test_a_split_is_never_planned_for_a_single_pane(
+ manager: BrainManager,
+ registry: Registry,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """One agent cannot divide work with anyone — planning would be pure latency."""
+ from jarvis.agentic_ide import work_split
+
+ async def explode(*_a: object, **_kw: object) -> object:
+ raise AssertionError("no split may be planned for one pane")
+
+ monkeypatch.setattr(work_split, "split", explode)
+ await _open(registry, tmp_path, 2)
+ first, _second = _names(registry)
+
+ reply = await manager._run_agentic_ide_fast_path(
+ f"Tell {first} to analyse the codebase and split the work between areas"
+ )
+
+ assert reply is not None
+ assert _sent_to(registry, first)
+
+
async def test_nobody_reachable_is_never_reported_as_sent(
manager: BrainManager, registry: Registry, tmp_path: Path
) -> None:
diff --git a/tests/unit/brain/test_agentic_ide_spawn_fast_path.py b/tests/unit/brain/test_agentic_ide_spawn_fast_path.py
index bdd158b709..d43b3d258c 100644
--- a/tests/unit/brain/test_agentic_ide_spawn_fast_path.py
+++ b/tests/unit/brain/test_agentic_ide_spawn_fast_path.py
@@ -115,6 +115,29 @@ async def test_a_spoken_request_opens_panes_and_names_them(
assert bus.published[1].section == "agentic-ide"
+async def test_a_mixed_fleet_opens_both_kinds_of_agent(
+ manager: tuple[BrainManager, FakeBus], registry: Registry, tmp_path: Path
+) -> None:
+ """The maintainer's ask: "5 Codex and 3 Claudes in one task" (2026-07-26).
+
+ The detector used to read the first number and the first agent, so this
+ sentence opened five Codex panes and dropped the three Claude ones without
+ telling anyone.
+ """
+ mgr, _bus = manager
+ await _open(registry, tmp_path, 1, agent="claude")
+
+ reply = await mgr._run_agentic_ide_spawn_fast_path(
+ "Open 5 Codex terminals and 3 Claude Code terminals"
+ )
+
+ assert reply is not None
+ assert registry.session is not None
+ opened = [t.agent for t in registry.session.terminals[1:]]
+ assert opened.count("codex") == 5
+ assert opened.count("claude") == 3
+
+
async def test_a_named_agent_is_honoured_over_the_inherited_one(
manager: tuple[BrainManager, FakeBus], registry: Registry, tmp_path: Path
) -> None: