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(society): ground voice orchestration in the persistent team

rubenluetke10-beepa5454e62afe2
diff --git a/docs/commands-reference.md b/docs/commands-reference.md
index cfd2a19314..15c952382b 100644
--- a/docs/commands-reference.md
+++ b/docs/commands-reference.md
@@ -11,6 +11,56 @@ Every command below is available on four surfaces backed by the SAME endpoint an
Commands marked **requires confirmation** never run on a bare voice request — Jarvis asks first (two-turn confirm); the CLI needs `--yes`.
+## `society-create-agent` — Create a persistent team agent
+
+Create an agent in the user's existing Agents team, only when requested. This creates a roster profile and starts no work. Responsibilities derive capabilities through the same service as the Agents UI. Read the returned agent and created flag: an existing name is adopted, never duplicated. Use society-switch-agent-model only if a specific provider is requested.
+
+- **Endpoint:** `POST /api/society/agents`
+- **Arguments:** `name` (string; required); `title` (string; optional); `description` (string; optional); `tier` (one of: specialist, orchestrator; optional); `focus` (array; optional); `skills` (array; optional); `daily_budget_usd` (number; optional); `max_concurrent_runs` (integer; optional)
+- **Requires confirmation:** no
+- **Desktop UI section:** `agents`
+- **Voice example (EN):** "create an agent for researching suppliers"
+
+## `society-update-agent` — Update a persistent team agent
+
+Change an existing agent's responsibilities, skills, focus, budget or paused/active state as requested by the user. Resolve its real id with society_status first. Only send requested fields. Existing learned focus and approval rules survive prose edits. Report the returned stored agent.
+
+- **Endpoint:** `PATCH /api/society/agents/{agent_id}`
+- **Arguments:** `agent_id` (string; required); `title` (string; optional); `description` (string; optional); `tier` (one of: specialist, orchestrator; optional); `focus` (array; optional); `skills` (array; optional); `daily_budget_usd` (number; optional); `max_concurrent_runs` (integer; optional); `state` (one of: active, paused; optional)
+- **Requires confirmation:** no
+- **Desktop UI section:** `agents`
+- **Voice example (EN):** "update Scout's responsibilities"
+
+## `society-capability-catalog` — Read the team's capability catalog
+
+Read the live capability ids, descriptions and connection state available to the persistent Agents team. Use these ids when setting agent focus; unconnected capabilities are not available hands. This reads no model catalog.
+
+- **Endpoint:** `GET /api/society/capabilities`
+- **Arguments:** none
+- **Requires confirmation:** no
+- **Desktop UI section:** `agents`
+- **Voice example (EN):** "which capabilities can my agents use"
+
+## `society-agent-catalog` — Read available agent models
+
+Read the live provider and model catalog for persistent society agents before a requested model change.
+
+- **Endpoint:** `GET /api/agent-chat/catalog`
+- **Arguments:** `surface` (one of: society; optional)
+- **Requires confirmation:** no
+- **Desktop UI section:** `agents`
+- **Voice example (EN):** "which models are available for my agents"
+
+## `society-switch-agent-model` — Change one team agent's model
+
+Change one persistent agent's provider/model/effort only on user request. Use society-agent-catalog to select a supported model. Reuses the Agents UI model-switch endpoint and preserves the canonical chat. Report the returned stored state and whether reseated is confirmed.
+
+- **Endpoint:** `POST /api/society/agents/{agent_id}/model`
+- **Arguments:** `agent_id` (string; required); `provider` (string; required); `model` (string; optional); `effort` (string; optional); `account_id` (string; optional)
+- **Requires confirmation:** no
+- **Desktop UI section:** `agents`
+- **Voice example (EN):** "change Scout's model"
+
## `brain-switch` — Switch brain provider
Switch the ACTIVE main brain (LLM) provider, e.g. from openai to claude-api. Reversible; validated against the provider catalog and stored credentials.
diff --git a/docs/os-parity.md b/docs/os-parity.md
index da3b29ca48..5daa78e001 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -1,5 +1,20 @@
# OS Feature Parity — macOS / Linux Gap Register
+**Society voice orchestration, 2026-09-07:** Persistent-team inventory,
+contextual assignments, assignment tracking and measured activity reuse the
+existing society roster, board and scheduler. Voice creation and profile/model
+updates use Command Registry tools mapped to the existing Agents REST routes.
+These paths share the same pure Python/SQLite/ASGI implementation on Windows,
+macOS and Linux, including headless installs; no native API, microphone, GPU or
+provider key is needed for roster management. An unavailable runtime/server
+returns an explicit failure. Execution of an assignment still depends on the
+agent's existing configured runner and scheduler policy; no provider is selected
+or changed globally. Contract coverage is in
+`tests/contract/test_society_voice_management.py`, with assignment/readback
+regressions in `tests/unit/plugins/tool/test_delegate_to_agent.py`. These are
+headless tests on the available host, not evidence of native macOS/Linux or
+paid-provider voice execution.
+
**Binding rule:** [`CLAUDE.md`](../CLAUDE.md) §3 *"OS feature parity — macOS
and Linux are first-class"*. Every feature ships working on Windows, macOS,
and Linux (desktop AND headless) in the same change. A Windows-only
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index eedbe41006..0d94993402 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -736,6 +736,21 @@ def _resolve_society_runtime() -> Any:
return _SOCIETY_FACTORY_REF[0]()
+async def prepare_society_context() -> None:
+ """Warm the existing team on first conversation use, outside app boot.
+
+ The server factory returns its one instance even while initialization is
+ in flight. The runtime's lock serializes concurrent voice/chat first turns.
+ Unavailable storage must never prevent an ordinary conversation.
+ """
+ try:
+ runtime = _resolve_society_runtime()
+ if runtime is not None:
+ await runtime.prepare_context()
+ except Exception: # noqa: BLE001 - optional team cannot prevent conversation
+ log.warning("society context initialization failed", exc_info=True)
+
+
def _resolve_mission_manager() -> Any:
"""Resolve the MissionManager for the ``spawn_worker`` tool.
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 7f2d128099..fe8cfbfbd8 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -7170,6 +7170,42 @@ class BrainManager:
except Exception: # noqa: BLE001 - optional surface, never fatal
return False
+ async def _run_society_inventory_fast_path(
+ self, user_text: str, *, trace_id: UUID | None = None,
+ ) -> str | None:
+ """Answer a plain roster question from the actual read-only tool.
+
+ This happens before generic routing, acknowledgements and worker
+ selection. Never let a missing runtime turn a roster read into work.
+ """
+ from jarvis.society.intent import is_inventory_question
+
+ if not is_inventory_question(user_text):
+ return None
+ out_lang = resolve_output_language(
+ self._reply_language, self._turn_detected_lang, user_text,
+ default=DEFAULT_LOCALE,
+ conversation_language=self._conversation_language,
+ )
+ unavailable = {
+ "de": "Ich kann die Agentenliste gerade nicht abrufen.", # i18n-allow
+ "en": "I cannot retrieve the agent roster right now.",
+ "es": "No puedo consultar la lista de agentes ahora.",
+ }.get(out_lang, "I cannot retrieve the agent roster right now.")
+ tool = self._tools.get("society_status")
+ if tool is None or self._tool_executor is None:
+ return unavailable
+ try:
+ result = await self._tool_executor.execute(
+ tool, {}, user_utterance=user_text,
+ config_snapshot={"output_language": out_lang},
+ trace_id=trace_id or uuid4(),
+ )
+ except Exception: # noqa: BLE001 - preserve a truthful answer on storage failure
+ log.warning("society inventory lookup failed", exc_info=True)
+ return unavailable
+ return str(result.output or unavailable)
+
async def _run_agentic_ide_fast_path(
self,
user_text: str,
@@ -8372,6 +8408,10 @@ class BrainManager:
t = (user_text or "").strip()
if not t:
return False
+ from jarvis.society.lead_card import society_owns_task
+
+ if society_owns_task(t):
+ return False
if "spawn_worker" not in self._tools or self._tool_executor is None:
return False
# BUG-LIVE-04 (Recon-Agent 3, 2026-05-16): Whisper transcribes
@@ -10761,6 +10801,12 @@ class BrainManager:
# refresh_tools() when they diverge. Never raises.
maybe_reconcile_tool_surface(self)
+ # Conversation use, never app boot: load the persistent team before
+ # planning or building the first prompt, even if Agents was never opened.
+ from jarvis.brain.factory import prepare_society_context
+
+ await prepare_society_context()
+
# auto mode: resolve this turn's language so _reply_language_directive()
# hard-pins it (a soft "mirror" drifts to German on tool-synthesis
# turns — live bug 2026-06-14: an English weather turn answered in
@@ -10836,6 +10882,16 @@ class BrainManager:
)
return confirmation
+ society_reply = await self._run_society_inventory_fast_path(
+ user_text, trace_id=turn_trace_id,
+ )
+ if society_reply is not None:
+ await self._record_response_side_effects(
+ user_text=user_text, response_text=society_reply,
+ use_history=use_history, trace_id=turn_trace_id,
+ )
+ return society_reply
+
# An addressed Agentic-IDE pane outranks every self-configuration gate
# below — the same precedence the desktop gate already honours further
# down (``_agentic_ide_owns_turn`` there), applied here because the
diff --git a/jarvis/brain/spawn_gate.py b/jarvis/brain/spawn_gate.py
index 592f1ae3de..d2f10a60b0 100644
--- a/jarvis/brain/spawn_gate.py
+++ b/jarvis/brain/spawn_gate.py
@@ -634,6 +634,12 @@ def llm_spawn_allowed(user_text: str) -> bool:
text = (user_text or "").strip()
if not text:
return False
+ from jarvis.society.lead_card import society_owns_task
+
+ if society_owns_task(text):
+ OFFER_WINDOW.disarm()
+ log.info("spawn gate: persistent team owns this turn")
+ return False
if _is_decline_or_feature_talk(text):
log.info("spawn gate: decline / feature talk — spawn blocked")
return False
diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.py
index fe94a427d8..6047b88aba 100644
--- a/jarvis/brain/turn_planner.py
+++ b/jarvis/brain/turn_planner.py
@@ -690,6 +690,10 @@ def _is_society_turn(text: str, agent_names: Sequence[str]) -> bool:
raw = str(text or "")
if not raw.strip():
return False
+ from jarvis.society.intent import is_inventory_question, is_team_management_request
+
+ if is_inventory_question(raw) or is_team_management_request(raw):
+ return True
folded = _normalize(raw)
for name in agent_names:
needle = _normalize(str(name or "")).strip()
@@ -884,6 +888,16 @@ def plan_turn(
if not normalized:
return TurnPlan(path=TurnPath.NATIVE_REALTIME)
+ from jarvis.society.intent import is_inventory_question
+
+ if is_inventory_question(text):
+ return TurnPlan(
+ path=TurnPath.ORCHESTRATOR,
+ reasons=frozenset({TurnReason.SOCIETY}),
+ required_capabilities=("society_status",),
+ requires_evidence=True,
+ )
+
reasons: set[TurnReason] = set()
# Same standing as a named pane, for the same reason: "what is the Gmail
# agent doing" reads as third-party smalltalk to every suppressor below,
diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.py
index 0ff7909afb..d1e9e7316a 100644
--- a/jarvis/commands/registry.py
+++ b/jarvis/commands/registry.py
@@ -158,10 +158,134 @@ def _provider_switch_params(
}
+def _society_profile_properties() -> dict[str, Any]:
+ """Voice-editable profile fields; execution uses the existing roster REST route."""
+ return {
+ "title": _str_param("The agent's responsibility or role.", max_length=120),
+ "description": _str_param("Detailed responsibilities and instructions.", max_length=20_000),
+ "tier": _str_param("Team role.", enum=["specialist", "orchestrator"]),
+ "focus": {
+ "type": "array", "items": {"type": "string"},
+ "description": "Capability ids; omit to derive from responsibilities.",
+ },
+ "skills": {
+ "type": "array", "items": {"type": "string"},
+ "description": "Skill ids explicitly requested by the user.",
+ },
+ "daily_budget_usd": {
+ "type": "number", "minimum": 0,
+ "description": "Daily spending limit requested by the user.",
+ },
+ "max_concurrent_runs": {
+ "type": "integer", "minimum": 1,
+ "description": "Maximum simultaneous assignments.",
+ },
+ }
+
+
def _build_registry() -> tuple[AppCommand, ...]:
"""Assemble the curated v1 command set (high-value commands first —
the long tail stays reachable through the dynamic CLI ``api`` layer)."""
return (
+ AppCommand(
+ id="society-create-agent",
+ title="Create a persistent team agent",
+ description=(
+ "Create an agent in the user's existing Agents team, only when requested. "
+ "This creates a roster profile and starts no work. Responsibilities derive "
+ "capabilities through the same service as the Agents UI. Read the returned "
+ "agent and created flag: an existing name is adopted, never duplicated. "
+ "Use society-switch-agent-model only if a specific provider is requested."
+ ),
+ method="POST", path="/api/society/agents", ui_section="agents",
+ params={"type": "object", "properties": {
+ "name": _str_param("Requested unique agent name.", min_length=1, max_length=40),
+ **_society_profile_properties(),
+ }, "required": ["name"]},
+ voice_aliases={
+ "de": ("erstelle einen rechercheagenten",), # i18n-allow: input vocab
+ "en": ("create an agent for researching suppliers",),
+ "es": ("crea un agente para investigar proveedores",), # i18n-allow: input vocab
+ },
+ ),
+ AppCommand(
+ id="society-update-agent",
+ title="Update a persistent team agent",
+ description=(
+ "Change an existing agent's responsibilities, skills, focus, budget or "
+ "paused/active state as requested by the user. Resolve its real id with "
+ "society_status first. Only send requested fields. Existing learned focus "
+ "and approval rules survive prose edits. Report the returned stored agent."
+ ),
+ method="PATCH", path="/api/society/agents/{agent_id}",
+ path_params=("agent_id",), ui_section="agents",
+ params={"type": "object", "properties": {
+ "agent_id": _str_param("Real agent id from society_status.", min_length=1),
+ **_society_profile_properties(),
+ "state": _str_param("Requested state.", enum=["active", "paused"]),
+ }, "required": ["agent_id"]},
+ voice_aliases={
+ "de": ("ändere Scouts aufgaben",), # i18n-allow: input vocab
+ "en": ("update Scout's responsibilities",),
+ "es": ("cambia las responsabilidades de Scout",), # i18n-allow: input vocab
+ },
+ ),
+ AppCommand(
+ id="society-capability-catalog",
+ title="Read the team's capability catalog",
+ description=(
+ "Read the live capability ids, descriptions and connection state available "
+ "to the persistent Agents team. Use these ids when setting agent focus; "
+ "unconnected capabilities are not available hands. This reads no model catalog."
+ ),
+ method="GET", path="/api/society/capabilities", ui_section="agents",
+ voice_aliases={
+ "de": ("welche werkzeuge können meine agenten nutzen",), # i18n-allow: input vocab
+ "en": ("which capabilities can my agents use",),
+ "es": ("qué capacidades pueden usar mis agentes",), # i18n-allow: input vocab
+ },
+ ),
+ AppCommand(
+ id="society-agent-catalog",
+ title="Read available agent models",
+ description=(
+ "Read the live provider and model catalog for persistent society agents "
+ "before a requested model change."
+ ),
+ method="GET", path="/api/agent-chat/catalog", ui_section="agents",
+ params={"type": "object", "properties": {
+ "surface": {"type": "string", "enum": ["society"], "default": "society"},
+ }},
+ voice_aliases={
+ "de": ("welche modelle gibt es für meine agenten",), # i18n-allow: input vocab
+ "en": ("which models are available for my agents",),
+ "es": ("qué modelos pueden usar mis agentes",), # i18n-allow: input vocab
+ },
+ ),
+ AppCommand(
+ id="society-switch-agent-model",
+ title="Change one team agent's model",
+ description=(
+ "Change one persistent agent's provider/model/effort only on user request. "
+ "Use society-agent-catalog to select a supported model. Reuses the Agents "
+ "UI model-switch endpoint and preserves the canonical chat. Report the "
+ "returned stored state and whether reseated is confirmed."
+ ),
+ method="POST", path="/api/society/agents/{agent_id}/model",
+ path_params=("agent_id",), ui_section="agents",
+ params={"type": "object", "properties": {
+ "agent_id": _str_param("Real agent id from society_status.", min_length=1),
+ "provider": _str_param("Provider id from the live society catalog.", min_length=1),
+ "model": _str_param("Model id offered for that provider."),
+ "effort": _str_param("Supported reasoning effort."),
+ "account_id": _str_param("Explicitly requested existing subscription account id."),
+ }, "required": ["agent_id", "provider"]},
+ voice_aliases={
+ "de": ("wechsle das modell von Scout",), # i18n-allow: input vocab
+ "en": ("change Scout's model",),
+ "es": ("cambia el modelo de Scout",), # i18n-allow: input vocab
+ },
+ ),
# ------------------------------------------------------ providers
AppCommand(
id="brain-switch",
diff --git a/jarvis/plugins/tool/delegate_to_agent.py b/jarvis/plugins/tool/delegate_to_agent.py
index dd17aae4a2..bf2977f256 100644
--- a/jarvis/plugins/tool/delegate_to_agent.py
+++ b/jarvis/plugins/tool/delegate_to_agent.py
@@ -34,6 +34,11 @@ _ACK: Final[dict[str, str]] = {
"en": "{name} is on it, I will let you know.",
"es": "{name} se encarga, te aviso.",
}
+_QUEUED: Final[dict[str, str]] = {
+ "de": "Aufgabe für {name} erfasst; Start noch nicht bestätigt.", # i18n-allow: spoken ack
+ "en": "The task for {name} is recorded; its start is not confirmed yet.",
+ "es": "La tarea para {name} está registrada; su inicio aún no está confirmado.",
+}
_NO_AGENT: Final[dict[str, str]] = {
"de": "Ich kenne keinen Agenten namens {target}.", # i18n-allow: spoken reply
"en": "I do not know an agent called {target}.",
@@ -70,9 +75,14 @@ _STATUS_LAST: Final[dict[str, str]] = {
"es": "{name}: último {kind}, {text}",
}
_ROSTER: Final[dict[str, str]] = {
- "de": "Aktive Agenten: {names}.", # i18n-allow: spoken reply
- "en": "Active agents: {names}.",
- "es": "Agentes activos: {names}.",
+ "de": "Deine Agenten: {names}.", # i18n-allow: spoken reply
+ "en": "Your agents: {names}.",
+ "es": "Tus agentes: {names}.",
+}
+_EMPTY_ROSTER: Final[dict[str, str]] = {
+ "de": "Du hast noch keine Team-Agenten.", # i18n-allow: spoken reply
+ "en": "You do not have any team agents yet.",
+ "es": "Todavía no tienes agentes en tu equipo.",
}
@@ -109,10 +119,13 @@ class DelegateToAgentTool:
description: str = (
"Hand a task to one of the user's named agents (their agent society, listed on your "
"team card): 'let Scout research X', 'Mailbox, answer the invoice mail', 'give that "
- "to the team'. Use when the user names an agent or asks for the team; leave `agent` "
+ "to the team'. Use when a background task fits the persistent team; leave `agent` "
"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 is announced when it lands. "
- "Never for tasks the user wants done right here in this turn."
+ "Never for inventory/status questions or tasks the user wants done right here. "
+ "Include relevant conversation context and completion criteria so the agent "
+ "can act independently. Report the acknowledgement and state exactly. Keep the "
+ "returned assignment_id and trace_id for society_status; never speak those ids."
)
schema: dict[str, Any] = {
"type": "object",
@@ -125,6 +138,19 @@ class DelegateToAgentTool:
),
},
"task": {"type": "string", "description": "The task, in full, in the user's words."},
+ "context": {
+ "type": "string",
+ "description": "Relevant prior decisions, constraints and facts; omit secrets.",
+ },
+ "completion_criteria": {
+ "type": "string",
+ "description": "Required output and the evidence needed to establish completion.",
+ },
+ "refs": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Relevant file, wiki or conversation references.",
+ },
},
"required": ["task"],
}
@@ -143,11 +169,8 @@ class DelegateToAgentTool:
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 target is None:
- # No name, or a name the roster does not know ("email agent" for
- # the Gmail agent): the task's own words pick the agent whose
- # hands fit. Nobody fits → say so; never guess a stranger.
- target = runtime.pick_agent(f"{target_key} {task}".strip())
+ if not target_key:
+ target = runtime.pick_agent(task)
if target is None:
if target_key:
return ToolResult(
@@ -158,43 +181,82 @@ class DelegateToAgentTool:
return ToolResult(success=False, output=_NO_FIT[lang], error="no_agent_fits")
from jarvis.society.events import MsgType
+ context = str(args.get("context") or "").strip()
+ criteria = str(args.get("completion_criteria") or "").strip()
+ brief = task
+ if context:
+ brief += "\n\nRelevant context:\n" + context
+ if criteria:
+ brief += "\n\nCompletion criteria:\n" + criteria
+ refs = args.get("refs") or []
+ if not isinstance(refs, list) or any(not isinstance(ref, str) for ref in refs):
+ return ToolResult(success=False, output=None, error="refs must be a list of strings")
+ if len(brief) > 20_000 or len(refs) > 20:
+ return ToolResult(success=False, output=None, error="assignment context exceeds limit")
env = await runtime.say(
from_agent=runtime.lead_id,
to_agent=target.agent_id,
- text=task,
+ text=brief,
trace_id=f"voice:{ctx.trace_id.hex[:12]}",
msg_type=MsgType.ASSIGN,
- payload={"text": task, "lang": lang},
+ payload={"text": brief, "lang": lang, "refs": refs},
)
# The scheduler answered synchronously on the same trace: a CLAIM
# means the agent took it, a VETO says why not — say so, no waiting.
outcome = None
for event in await runtime.store.events_for_trace(env.trace_id):
- if event.seq and env.seq and event.seq > env.seq:
+ if event.parent_event_id == env.event_id and event.msg_type in (
+ MsgType.CLAIM,
+ MsgType.VETO,
+ ):
outcome = event
break
+ tracking = {
+ "agent_id": target.agent_id,
+ "agent_name": target.name,
+ "assignment_id": env.event_id,
+ "trace_id": env.trace_id,
+ }
if outcome is not None and outcome.msg_type is MsgType.VETO:
reason = str(outcome.payload.get("text") or outcome.payload.get("reason") or "")
return ToolResult(
success=False,
- output=_REFUSED[lang].format(name=target.name, reason=reason),
+ output={
+ **tracking,
+ "state": "refused",
+ "acknowledgement": _REFUSED[lang].format(name=target.name, reason=reason),
+ },
error=str(outcome.payload.get("reason") or "vetoed"),
)
return ToolResult(
success=True,
- output=_ACK[lang].format(name=target.name),
- artifacts=(f"agent:{target.agent_id}",),
+ output={
+ **tracking,
+ "state": "running" if outcome is not None else "recorded",
+ "acknowledgement": (_ACK if outcome is not None else _QUEUED)[lang].format(
+ name=target.name,
+ ),
+ },
+ artifacts=(
+ f"agent:{target.agent_id}",
+ f"assignment:{env.event_id}",
+ f"trace:{env.trace_id}",
+ ),
)
async def _runtime(self) -> Any | None:
try:
runtime = self._resolve()
+ if runtime is not None:
+ prepare = getattr(runtime, "prepare_context", None)
+ if callable(prepare):
+ if not await prepare():
+ return None
+ else:
+ await runtime.ensure_started()
except Exception: # noqa: BLE001 — a missing society is a spoken "not ready"
- log.warning("delegate_to_agent: society runtime resolver failed", exc_info=True)
- return None
- if runtime is None:
+ log.warning("delegate_to_agent: society runtime unavailable", exc_info=True)
return None
- await runtime.ensure_started()
return runtime
@@ -205,12 +267,29 @@ class SocietyStatusTool:
risk_tier: str = "safe"
description: str = (
"Answer 'what is <agent> doing?', 'is Scout done?', 'who is on the team?' from the "
- "agent society's board. Read-only. Pass the agent's name, or nothing for the team."
+ "agent society's board. Read-only. Pass the agent's name, or nothing for the team. "
+ "Set details=true for responsibilities, capabilities, state and recorded activity/cost "
+ "statistics (these are observations, not quality scores). Pass assignment_id "
+ "to inspect that exact assignment; trace_id is optional. If prior tool ids are "
+ "no longer in context, use agent + latest_assignment=true to retrieve the newest "
+ "assignment Jarvis sent that agent from the stored board, including its task and "
+ "result. This means newest assignment, not an arbitrary recent event. If 'that task' "
+ "could mean an older task or several agents, clarify the agent/task first."
)
schema: dict[str, Any] = {
"type": "object",
"properties": {
"agent": {"type": "string", "description": "An agent's name; omit for the team."},
+ "details": {"type": "boolean", "description": "Include actual roster and evidence."},
+ "assignment_id": {"type": "string", "description": "Assignment event id."},
+ "trace_id": {"type": "string", "description": "Optional expected assignment trace."},
+ "latest_assignment": {
+ "type": "boolean",
+ "description": (
+ "With agent: inspect the newest assignment sent by Jarvis. "
+ "Do not combine with assignment_id."
+ ),
+ },
},
}
@@ -220,16 +299,136 @@ class SocietyStatusTool:
async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
lang = _lang(args, ctx)
try:
+ from jarvis.society.events import MsgType
+
runtime = self._resolve()
+ if runtime is not None:
+ prepare = getattr(runtime, "prepare_context", None)
+ if callable(prepare):
+ if not await prepare():
+ runtime = None
+ else:
+ await runtime.ensure_started()
except Exception: # noqa: BLE001 — see DelegateToAgentTool._runtime
+ log.warning("society_status: runtime resolver failed", exc_info=True)
runtime = None
if runtime is None:
return ToolResult(success=False, output=_NOT_READY[lang], error="society unavailable")
- await runtime.ensure_started()
+ assignment_id = str(args.get("assignment_id") or "").strip()
+ trace_id = str(args.get("trace_id") or "").strip()
target_key = str(args.get("agent") or "").strip()
+ latest_assignment = args.get("latest_assignment") is True
+ if assignment_id or trace_id or latest_assignment:
+ if latest_assignment and assignment_id:
+ return ToolResult(
+ success=False, output=None, error="choose assignment_id or latest_assignment"
+ )
+ 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")
+ assignment = await runtime.store.latest_assignment_for_agent(
+ target.agent_id,
+ from_agent=runtime.lead_id,
+ )
+ elif assignment_id:
+ assignment = await runtime.store.get_event(assignment_id)
+ else:
+ return ToolResult(success=False, output=None, error="assignment_id required")
+ if assignment is None or assignment.msg_type is not MsgType.ASSIGN:
+ return ToolResult(success=False, output=None, error="assignment_unknown")
+ if trace_id and trace_id != assignment.trace_id:
+ return ToolResult(success=False, output=None, error="assignment_trace_mismatch")
+ assignment_id, trace_id = assignment.event_id, assignment.trace_id
+ events = await runtime.store.events_for_trace(trace_id)
+ related = [
+ e
+ for e in events
+ if e.parent_event_id == assignment_id
+ and e.msg_type in (MsgType.CLAIM, MsgType.RESULT, MsgType.VETO)
+ ]
+ # The fallback mission runner's bridge publishes its terminal result
+ # on mission:<run_id>, without the original assignment parent. Follow
+ # only the scheduler's matching claim and verify both run and owner;
+ # another mission or agent must never complete this assignment.
+ run_ids = {
+ str(event.payload["run_id"])
+ for event in related
+ if event.msg_type is MsgType.CLAIM
+ and event.from_agent == assignment.to_agent
+ and event.payload.get("run_id")
+ }
+ for run_id in run_ids:
+ if run_id.startswith("turn:"):
+ continue
+ mission_events = await runtime.store.events_for_trace(f"mission:{run_id}")
+ related.extend(
+ event
+ for event in mission_events
+ if event.msg_type is MsgType.RESULT
+ and event.from_agent == assignment.to_agent
+ and event.payload.get("run_id") == run_id
+ )
+ related.sort(key=lambda event: event.seq or 0)
+ last = related[-1] if related else None
+ state = "recorded"
+ if last is not None:
+ state = {
+ MsgType.CLAIM: "running",
+ MsgType.VETO: "refused",
+ MsgType.RESULT: str(last.payload.get("status") or "finished"),
+ }[last.msg_type]
+ return ToolResult(
+ success=True,
+ output={
+ "assignment_id": assignment_id,
+ "trace_id": trace_id,
+ "state": state,
+ "assignment": assignment.model_dump(mode="json"),
+ "events": [e.model_dump(mode="json") for e in related],
+ },
+ )
+ 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",
+ )
+ targets = [target]
+ rows = []
+ for agent in targets:
+ if agent.agent_id == runtime.lead_id:
+ continue
+ recent = await runtime.store.events_for_agent(agent.agent_id, limit=10)
+ rows.append(
+ {
+ "agent": agent.to_dict(),
+ "active_runs": runtime.scheduler.active_runs(agent.agent_id),
+ "stats": await runtime.store.agent_stats(agent.agent_id),
+ "recent_events": [e.model_dump(mode="json") for e in recent],
+ }
+ )
+ return ToolResult(
+ success=True,
+ output={
+ "agents": rows,
+ "measurement_note": (
+ "Runs count recorded RESULT events, including failures; costs are "
+ "recorded costs only. No independent quality rating is available."
+ ),
+ },
+ )
if not target_key:
agents = await runtime.roster.list()
- names = ", ".join(a.name for a in agents if a.agent_id != runtime.lead_id) or "—"
+ names = ", ".join(a.name for a in agents if a.agent_id != runtime.lead_id)
+ 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:
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 96fc93c336..315badca12 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -3147,12 +3147,18 @@ class RealtimeVoiceSession:
the orchestrator, which owns delegate_to_agent and society_status.
"""
names = self._society_agent_names()
- if not names:
- return ""
- roster = ", ".join(names)
+ roster = ", ".join(names) if names else "not loaded; use society_status to verify"
return (
"[Agent society — the user's own agents, live right now]\n"
f"Agents on the user's team: {roster}.\n"
+ "For an agent-list or status QUESTION call society_status via your action "
+ "function. This is a read-only lookup: do not assign work, spawn a worker, "
+ "or announce that any agent is starting. An empty name snapshot does not "
+ "prove the user has no agents. Creation and reconfiguration use the "
+ "society-create-agent, society-update-agent and society-switch-agent-model "
+ "app commands; inspect society-capability-catalog for valid capabilities "
+ "and society-agent-catalog for models. "
+ "Report management changes only after a successful tool result. "
"To send a message TO an agent, use message_agent (target, text), or "
"ask jarvis_action to use message_agent if it is not directly available. "
"This is an internal chat message, not an email: never use gmail or "
@@ -3766,6 +3772,9 @@ class RealtimeVoiceSession:
return status, self._has_viable_alternate(provider)
async def _open(self) -> None:
+ from jarvis.brain.factory import prepare_society_context
+
+ await prepare_society_context()
loop = asyncio.get_running_loop()
# A provider may DECLARE a larger handshake need (a capability, never
# a provider-name check — AP-21): the Codex subscription transport
@@ -5319,7 +5328,10 @@ class RealtimeVoiceSession:
)
planner_forces_delegate = bool(
turn_plan.requires_orchestrator
- and (not hybrid_turn or screen_context_turn)
+ and (
+ not hybrid_turn or screen_context_turn
+ or "society_status" in turn_plan.required_capabilities
+ )
)
if (
self._last_user_text
@@ -5329,6 +5341,7 @@ class RealtimeVoiceSession:
self._delegate_enabled
or screen_context_turn
or grounding_turn
+ or "society_status" in turn_plan.required_capabilities
)
):
self._delegate_required_for_turn = (
diff --git a/jarvis/society/intent.py b/jarvis/society/intent.py
new file mode 100644
index 0000000000..c81b206f70
--- /dev/null
+++ b/jarvis/society/intent.py
@@ -0,0 +1,95 @@
+"""Pure intent boundaries for the persistent team, shared by voice and brain."""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Sequence
+
+# Full utterances only: a combined question and assignment must reach the
+# orchestrator rather than lose the requested assignment in a read-only path.
+# i18n-allow: multilingual spoken-input vocabulary
+_INVENTORY = re.compile(
+ r"(?:"
+ r"(?:was|welche|wie viele|wieviele) (?:hast du|habe ich|haben wir) "
+ r"(?:(?:fuer|für) )?agent(?:en|s)?" # i18n-allow: spoken-input vocabulary
+ r"|(?:welche|wie viele|wieviele) agent(?:en|s)? "
+ r"(?:hast du|habe ich|haben wir|gibt es|" # i18n-allow: spoken-input vocabulary
+ r"stehen (?:dir|mir|uns) zur verf(?:ue|ü)gung)" # i18n-allow: spoken-input vocabulary
+ r"|(?:which|what|how many) agents (?:do you have(?: access to)?|do i have|"
+ r"do we have|are there|are on (?:the|my|our) team|are available)"
+ r"|who is (?:on|in) (?:the|my|our|your) team"
+ r"|(?:list|show|tell me) (?:all |me )?(?:(?:my|your|our|the) )?agents"
+ r"|(?:zeig(?:e)?|nenn(?:e)?) (?:mir )?(?:(?:alle|meine|deine|unsere|die) )?agenten"
+ r"|(?:qué|que|cuántos|cuantos|cuáles|cuales) agentes (?:tienes|tengo|tenemos|hay)"
+ r")",
+ re.IGNORECASE,
+)
+
+
+def is_inventory_question(text: str) -> bool:
+ """An unambiguous roster request; never an assignment or management action."""
+ normalized = re.sub(r"\s+", " ", str(text or "")).strip(" .?!¿¡")
+ normalized = re.sub(
+ r"\b(?:eigentlich|denn|bitte|actually|currently|please" # i18n-allow
+ r"|right now|por favor)\b",
+ "",
+ normalized,
+ flags=re.IGNORECASE,
+ )
+ normalized = re.sub(r"\s+", " ", normalized).strip()
+ return _INVENTORY.fullmatch(normalized) is not None
+
+
+def names_team_member(text: str, names: Sequence[str]) -> bool:
+ """Match even short real names at word boundaries, never substrings."""
+ return any(
+ name.strip() and re.search(rf"(?<!\w){re.escape(name.strip())}(?!\w)", text, re.IGNORECASE)
+ for name in names
+ )
+
+
+def blocks_background_spawn(text: str, names: Sequence[str] = ()) -> bool:
+ """Team reads and addressed members must not become anonymous workers.
+
+ Explicit creation of a background worker remains a separate request; a
+ specialist can be mentioned as context in such a request.
+ """
+ if is_inventory_question(text) or is_team_management_request(text):
+ return True
+ if not names_team_member(text, names):
+ return False
+ return not explicitly_requests_worker(text)
+
+
+def is_team_management_request(text: str) -> bool:
+ """Profile creation/reconfiguration belongs to the existing Agents surface.
+
+ This only selects the orchestrator; it does not execute a management
+ action. Explicit worker creation retains its separate routing semantics.
+ """
+ if explicitly_requests_worker(text):
+ return False
+ return (
+ re.search(
+ r"\b(?:creat\w*|add|updat\w*|reconfigur\w*|renam\w*|"
+ r"erstell\w*|konfigurier\w*|aender\w*|änder\w*|crea\w*|actualiza\w*)\b" # i18n-allow
+ r"[^.?!]{0,70}\bagent(?:en|s|e|es)?\b",
+ text,
+ re.IGNORECASE,
+ )
+ is not None
+ )
+
+
+def explicitly_requests_worker(text: str) -> bool:
+ """Whether a new background worker is the explicitly requested vehicle."""
+ # i18n-allow: multilingual spoken-input vocabulary
+ return (
+ re.search(
+ r"\b(?:spawn\w*|start\w*|creat\w*|erstell\w*|crea\w*)\b"
+ r"[^.?!]{0,45}\b(?:sub-?agent\w*|worker\w*|background agent|mission\w*)\b",
+ text,
+ re.IGNORECASE,
+ )
+ is not None
+ )
diff --git a/jarvis/society/lead_card.py b/jarvis/society/lead_card.py
index 0794a7d33d..32a44ffd63 100644
--- a/jarvis/society/lead_card.py
+++ b/jarvis/society/lead_card.py
@@ -62,15 +62,24 @@ def _rule_block(lead_name: str) -> str:
"specialist is not email: never call gmail for this. Internal messages need no extra "
"confirmation. Report the actual queued/delivered/failed receipt.\n"
"- Hand work to an agent with delegate_to_agent (the agent's name and the task in "
- "full). The agent works in the background; you acknowledge now and its result "
- "comes back to this conversation.\n"
+ "full, relevant conversation context, completion_criteria and refs). Report "
+ "the actual assignment receipt, keep its assignment and trace identifiers, "
+ "and use society_status to follow results.\n"
"- Answer \"which agents do you have\", \"who is on the team\", \"what is X "
- "doing\", \"is X done\" from this card or with society_status — never from the "
- "retired sub-agent or mission-worker system.\n"
+ "doing\", \"is X done\" with society_status — never from the "
+ "retired sub-agent or mission-worker system. These are read-only questions: "
+ "never assign work or announce a spawn for them. Use details=true for actual "
+ "roles, capabilities and measured event history; never invent performance scores.\n"
"- A task that fits an agent's hands (mail to a mail agent, research to a "
- "research agent) goes to that agent when the user asks for the team or names it; "
+ "research agent) goes to that agent for suitable background work, even when "
+ "the user does not name it. Honor requests to handle work directly; "
"when no agent fits, do it yourself. spawn_worker is only for heavy background "
"work the user explicitly asked to run in the background that no agent covers.\n"
+ "- Create or reconfigure an agent only when requested: use society-create-agent, "
+ "society-update-agent or society-switch-agent-model through the app commands. "
+ "Inspect society-capability-catalog for capabilities and society-agent-catalog "
+ "for models. These commands share the "
+ "Agents section's validation. Verify the returned state before claiming success.\n"
"- Coding terminals in the Agentic IDE (Claude Code, Codex and the like) are NOT "
"agents of this society; they are reached through the workspace tools."
)
@@ -189,12 +198,34 @@ def society_agent_names() -> tuple[str, ...]:
return ()
return tuple(
sorted(
- (a.name for a in agents if a.agent_id != rt.lead_id and str(a.state) == "active"),
+ (a.name for a in agents if a.agent_id != rt.lead_id and str(a.state) != "archived"),
key=str.casefold,
)
)
+def society_owns_task(text: str) -> bool:
+ """Keep matching tasks with the team before generic mission heuristics.
+
+ This only defers tool selection to the orchestrator; it never assigns
+ work. The same catalog/roster fit rule powers delegate_to_agent.
+ """
+ from .intent import blocks_background_spawn, explicitly_requests_worker
+
+ if blocks_background_spawn(text, society_agent_names()):
+ return True
+ if explicitly_requests_worker(text):
+ return False
+ runtime = current_runtime()
+ if runtime is None:
+ return False
+ try:
+ return runtime.pick_agent(text) is not None
+ except Exception: # noqa: BLE001 - optional fit hint must not break routing
+ log.debug("society task fit unavailable", exc_info=True)
+ return False
+
+
def lead_card_section(*, lead_name: str = "Jarvis") -> str:
"""The card for THIS process's society, or ``""`` when there is none.
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
index a16c9719d5..7fd08d1412 100644
--- a/jarvis/society/runtime.py
+++ b/jarvis/society/runtime.py
@@ -158,9 +158,35 @@ class SocietyRuntime:
self._delivery_task: asyncio.Task[None] | None = None
self._delivery_unsubscribe: Callable[[], None] | None = None
self._started = False
+ self._context_start_task: asyncio.Task[bool] | None = None
# ------------------------------------------------------------ lifecycle
+ async def prepare_context(self, *, timeout_s: float = 0.3) -> bool:
+ """Bound first-turn team hydration without canceling partial startup.
+
+ Voice/chat may continue while storage is slow. One owned task does the
+ work; close cancels and reaps it before dismantling runtime components.
+ """
+ if self._started:
+ return True
+ task = self._context_start_task
+ if task is None or task.done():
+ task = asyncio.create_task(self._start_for_context(), name="society-context")
+ self._context_start_task = task
+ try:
+ return await asyncio.wait_for(asyncio.shield(task), timeout=timeout_s)
+ except TimeoutError:
+ return False
+
+ async def _start_for_context(self) -> bool:
+ try:
+ await self.ensure_started()
+ except Exception: # noqa: BLE001 - optional team must not prevent conversation
+ log.warning("society context startup failed", exc_info=True)
+ return False
+ return True
+
async def ensure_started(self) -> SocietyRuntime:
async with self._start_lock:
if self._started:
@@ -227,6 +253,10 @@ class SocietyRuntime:
return self._get_cfg()
async def close(self) -> None:
+ if self._context_start_task is not None:
+ self._context_start_task.cancel()
+ await asyncio.gather(self._context_start_task, return_exceptions=True)
+ self._context_start_task = None
if self._delivery_task is not None:
self._delivery_task.cancel()
await asyncio.gather(self._delivery_task, return_exceptions=True)
diff --git a/jarvis/society/store.py b/jarvis/society/store.py
index 5a46b5445e..762e290edd 100644
--- a/jarvis/society/store.py
+++ b/jarvis/society/store.py
@@ -93,15 +93,22 @@ class SocietyStore:
return
self._db_path.parent.mkdir(parents=True, exist_ok=True)
conn = await aiosqlite.connect(self._db_path, isolation_level=None)
- await conn.execute("PRAGMA journal_mode=WAL")
- await conn.execute("PRAGMA synchronous=NORMAL")
- await conn.execute("PRAGMA busy_timeout=5000")
- await conn.execute("PRAGMA foreign_keys=ON")
- await conn.executescript(_SCHEMA_PATH.read_text(encoding="utf-8"))
- self._conn = conn
- await self._apply_migrations()
- await self._ensure_fts()
- await self.set_meta(_KEY_SCHEMA_VERSION, str(SCHEMA_VERSION))
+ try:
+ await conn.execute("PRAGMA journal_mode=WAL")
+ await conn.execute("PRAGMA synchronous=NORMAL")
+ await conn.execute("PRAGMA busy_timeout=5000")
+ await conn.execute("PRAGMA foreign_keys=ON")
+ await conn.executescript(_SCHEMA_PATH.read_text(encoding="utf-8"))
+ self._conn = conn
+ await self._apply_migrations()
+ await self._ensure_fts()
+ await self.set_meta(_KEY_SCHEMA_VERSION, str(SCHEMA_VERSION))
+ except BaseException:
+ # Includes cancellation of first-turn initialization on shutdown.
+ # The provisional connection is owned here until open completes.
+ self._conn = None
+ await conn.close()
+ raise
async def _apply_migrations(self) -> None:
"""Idempotent column migrations for databases created by older builds."""
@@ -294,6 +301,30 @@ class SocietyStore:
await cur.close()
return [_row_to_envelope(r) for r in rows]
+ async def get_event(self, event_id: str) -> SocietyEnvelope | None:
+ """Read a durable event by its exact id, independently of recent-history limits."""
+ cur = await self.conn.execute(
+ f"SELECT {_EVENT_COLUMNS} FROM society_events WHERE event_id = ?", # noqa: S608 — fixed identifiers, bound values
+ (event_id,),
+ )
+ row = await cur.fetchone()
+ await cur.close()
+ return _row_to_envelope(row) if row is not None else None
+
+ async def latest_assignment_for_agent(
+ self, agent_id: str, *, from_agent: str
+ ) -> SocietyEnvelope | None:
+ """Newest assignment from one sender to one agent, across the complete board."""
+ cur = await self.conn.execute(
+ f"SELECT {_EVENT_COLUMNS} FROM society_events " # noqa: S608 — fixed identifiers, bound values
+ "WHERE msg_type = 'ASSIGN' AND to_agent = ? AND from_agent = ? "
+ "ORDER BY seq DESC LIMIT 1",
+ (agent_id, from_agent),
+ )
+ row = await cur.fetchone()
+ await cur.close()
+ return _row_to_envelope(row) if row is not None else None
+
async def events_for_trace(self, trace_id: str) -> list[SocietyEnvelope]:
cur = await self.conn.execute(
f"SELECT {_EVENT_COLUMNS} FROM society_events WHERE trace_id = ? ORDER BY seq ASC", # noqa: S608 — identifiers from a fixed allowlist, values bound
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index b8065d23f4..722eba5d86 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -5347,10 +5347,13 @@ class SpeechPipeline:
return
try:
from jarvis.brain.ack_generator import is_voice_control_utterance
+ from jarvis.society.lead_card import society_agent_names, society_owns_task
if is_voice_control_utterance(text):
return
- plan = plan_instant_ack(plan_turn(text), text)
+ if society_owns_task(text):
+ return
+ plan = plan_instant_ack(plan_turn(text, agent_names=society_agent_names()), text)
except Exception: # noqa: BLE001 — planning must never break the turn
log.debug("Instant ack: planning failed", exc_info=True)
return
@@ -14829,7 +14832,11 @@ class SpeechPipeline:
# ``SpeechPipeline.__new__(SpeechPipeline)`` (see e.g.
# tests/unit/speech/test_turn_taking.py:65) and don't always
# set every attribute. Treat a missing _ack_brain as disabled.
- if getattr(self, "_ack_brain", None) is not None:
+ from jarvis.brain.factory import prepare_society_context
+ from jarvis.society.intent import is_inventory_question
+
+ await prepare_society_context()
+ if getattr(self, "_ack_brain", None) is not None and not is_inventory_question(text):
asyncio.create_task( # noqa: RUF006 — intentional fire-and-forget
self._spawn_flash_brain_ack(text, lang),
name="flash-brain-ack",
diff --git a/jarvis/ui/web/chats_routes.py b/jarvis/ui/web/chats_routes.py
index e1001dccc9..2e791adc72 100644
--- a/jarvis/ui/web/chats_routes.py
+++ b/jarvis/ui/web/chats_routes.py
@@ -31,6 +31,7 @@ from typing import Any
from fastapi import APIRouter, HTTPException, Query, Request
from pydantic import BaseModel, Field
+from jarvis.sessions.formatter import _jarvis_outputs_for_turn
from jarvis.state.chat_store import ChatStore
from jarvis.state.conversation_constants import (
CONVERSATION_KIND_TEXT,
@@ -209,13 +210,24 @@ def _normalized_messages(
out.append(
ChatTurn(role="user", text=turn.user_text, ts_ms=int(turn.started_ms))
)
- if getattr(turn, "jarvis_text", ""):
+ turn_id = str(getattr(turn, "id", "") or "")
+ turn_events = [
+ event for event in events
+ if turn_id and getattr(event, "turn_id", None) == turn_id
+ ]
+ # Use the export's audible-track projection: preambles and progress
+ # can be all the user heard before hanging up. They remain spoken
+ # history even when no final brain reply or tool call exists.
+ for output in _jarvis_outputs_for_turn(turn, turn_events):
out.append(
ChatTurn(
role="assistant",
- text=turn.jarvis_text,
- ts_ms=int(turn.ended_ms or turn.started_ms),
- trace=_voice_turn_trace(turn, events),
+ text=output.text,
+ ts_ms=output.ts_ms,
+ trace=(
+ _voice_turn_trace(turn, events)
+ if output.is_reply else None
+ ),
)
)
return out
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 307667ec3b..a5d62246cb 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -3575,6 +3575,9 @@ class WebServer:
data_dir = Path(getattr(getattr(self.cfg, "memory", None), "data_dir", None) or "data")
state = self.app.state
+ if getattr(state, "society", None) is not None:
+ return state.society
+
def _manager() -> Any | None:
return getattr(state, "mission_manager", None)
@@ -3610,7 +3613,7 @@ class WebServer:
lambda: _service_from_state(state),
lambda: self.cfg,
)
- return SocietyRuntime(
+ state.society = SocietyRuntime(
data_dir,
mission_manager=_manager,
mission_bus=_mission_bus,
@@ -3624,6 +3627,7 @@ class WebServer:
# WebSocket forwards (SocietyCheckpointChanged).
event_publish=self.bus.publish,
)
+ return state.society
def _build_agent_chat_service(self) -> Any:
"""Build the agent-chat service on first use (see agent_chat_routes)."""
diff --git a/jarvis/voice/instant_ack.py b/jarvis/voice/instant_ack.py
index 5f28fa612e..8dfce29b52 100644
--- a/jarvis/voice/instant_ack.py
+++ b/jarvis/voice/instant_ack.py
@@ -107,6 +107,10 @@ def plan_instant_ack(turn_plan: TurnPlan | None, utterance: str = "") -> Instant
if turn_plan is None or not turn_plan.requires_orchestrator:
return None
reasons = set(turn_plan.reasons)
+ if TurnReason.SOCIETY in reasons:
+ # The team tools return their own factual receipts quickly. A planner
+ # reason is not evidence that an agent was assigned or a worker started.
+ return None
if TurnReason.MISSION in reasons:
return InstantAckPlan(WorkClass.MISSION, IMMEDIATE_DELAY_S, False)
if TurnReason.SCREEN_CONTEXT in reasons:
diff --git a/tests/contract/test_society_voice_management.py b/tests/contract/test_society_voice_management.py
new file mode 100644
index 0000000000..7d9b871580
--- /dev/null
+++ b/tests/contract/test_society_voice_management.py
@@ -0,0 +1,238 @@
+"""Headless voice management uses the same persisted roster as the Agents UI.
+
+No provider, microphone, GPU, native API or background worker is needed to
+create/reconfigure/read a persistent agent. Assignment remains scheduler-owned.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from uuid import uuid4
+
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from jarvis.commands.registry import get_command
+from jarvis.plugins.tool.app_command import AppCommandTool
+from jarvis.plugins.tool.delegate_to_agent import DelegateToAgentTool, SocietyStatusTool
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.ui.web.society_routes import router
+
+
+async def society(tmp_path):
+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)
+ app = FastAPI()
+ app.include_router(router)
+ app.state.society_factory = lambda: runtime
+ loader = AppCommandTool(transport=httpx.ASGITransport(app=app))
+ commands = {tool.name: tool for tool in loader.expand()}
+ try:
+ yield runtime, commands
+ finally:
+ await runtime.close()
+
+
+def context():
+ return SimpleNamespace(config={"output_language": "en"}, trace_id=uuid4())
+
+
+async def test_management_persists_and_echoes_same_roster_without_starting_work(society):
+ runtime, commands = society
+ created = await commands["society-create-agent"].execute(
+ {
+ "name": "Scout",
+ "title": "Supplier researcher",
+ "description": "Compare hosting suppliers and cite sources.",
+ },
+ context(),
+ )
+ assert created.success, created.error
+ body = created.output["response"]
+ assert body["created"] is True
+ assert body["agent"]["agent_id"] == "scout"
+ adopted = await commands["society-create-agent"].execute({"name": "Scout"}, context())
+ assert adopted.output["response"]["created"] is False
+ updated = await commands["society-update-agent"].execute(
+ {
+ "agent_id": "scout",
+ "title": "Invoice reviewer",
+ "state": "paused",
+ "daily_budget_usd": 2,
+ },
+ context(),
+ )
+ assert updated.success, updated.error
+ stored = await runtime.roster.get("scout")
+ assert updated.output["response"]["agent"] == stored.to_dict()
+ assert stored.title == "Invoice reviewer" and stored.state == "paused"
+ assert stored.daily_budget_usd == 2
+ status = await SocietyStatusTool(runtime_resolver=lambda: runtime).execute(
+ {
+ "agent": "scout",
+ "details": True,
+ },
+ context(),
+ )
+ assert status.output["agents"][0]["agent"]["title"] == "Invoice reviewer"
+ assert runtime.scheduler.active_runs("scout") == 0
+ assert not await runtime.store.events_since(0)
+
+
+async def test_management_preserves_learned_focus_and_explicit_approval_rules(society):
+ runtime, commands = society
+ await runtime.ensure_started()
+ await runtime.roster.create(
+ name="Scout",
+ focus=["core:search-web"],
+ approval_rules={"require_approval": ["send"], "always_allow": []},
+ )
+ result = await commands["society-update-agent"].execute(
+ {
+ "agent_id": "scout",
+ "description": "Research new suppliers.",
+ },
+ context(),
+ )
+ assert result.success
+ row = result.output["response"]["agent"]
+ assert "core:search-web" in row["focus"]
+ assert row["approval_rules"]["require_approval"] == ["send"]
+
+
+async def test_management_rejects_missing_agent_invalid_model_and_unexposed_fields(society):
+ runtime, commands = society
+ missing = await commands["society-update-agent"].execute(
+ {
+ "agent_id": "unknown",
+ "title": "Researcher",
+ },
+ context(),
+ )
+ assert not missing.success and "404" in missing.error
+ invalid = await commands["society-create-agent"].execute(
+ {
+ "name": "Bad/Name",
+ },
+ context(),
+ )
+ assert not invalid.success
+ await runtime.roster.create(name="Scout")
+ model = await commands["society-switch-agent-model"].execute(
+ {
+ "agent_id": "scout",
+ "provider": "nonexistent-provider",
+ },
+ context(),
+ )
+ assert not model.success and "422" in model.error
+ escalation = await commands["society-update-agent"].execute(
+ {
+ "agent_id": "scout",
+ "permission_ceiling": "unrestricted",
+ },
+ context(),
+ )
+ assert not escalation.success and "unknown argument" in escalation.error
+
+
+def test_management_is_supervisor_only_and_degrades_without_server():
+ for name in (
+ "society-create-agent",
+ "society-update-agent",
+ "society-agent-catalog",
+ "society-capability-catalog",
+ "society-switch-agent-model",
+ ):
+ command = get_command(name)
+ assert command is not None and not command.worker_allowed
+
+
+async def test_management_unavailable_server_returns_honest_error():
+ commands = {tool.name: tool for tool in AppCommandTool().expand()}
+ result = await commands["society-create-agent"].execute({"name": "Scout"}, context())
+ assert not result.success and "server is not available" in result.error
+
+
+async def test_capability_catalog_reads_the_live_shared_catalog(society):
+ runtime, commands = society
+ before = await commands["society-capability-catalog"].execute({}, context())
+ assert before.success, before.error
+ assert before.output["response"]["capabilities"] == [row.to_dict() for row in runtime.catalog()]
+ assert not await runtime.store.events_since(0)
+
+
+ "terminal_event,expected_state",
+ [
+ ("MissionApproved", "done"),
+ ("MissionFailed", "blocked"),
+ ],
+)
+async def test_voice_assignment_tracks_fallback_mission_bridge(
+ tmp_path, terminal_event, expected_state
+):
+ from jarvis.society.events import MsgType
+
+ class FakeManager:
+ async def dispatch(self, **kwargs):
+ return "mission-1"
+
+ runtime = SocietyRuntime(tmp_path, mission_manager=lambda: FakeManager())
+ try:
+ await runtime.ensure_started()
+ await runtime.roster.create(name="Scout")
+ result = await DelegateToAgentTool(runtime_resolver=lambda: runtime).execute(
+ {"agent": "Scout", "task": "Compare suppliers."},
+ context(),
+ )
+ assert result.success, result.error
+ assignment_id, trace_id = result.output["assignment_id"], result.output["trace_id"]
+ # Same mission trace, wrong agent/run: neither is proof for this assignment.
+ await runtime.say(
+ from_agent="other-agent",
+ to_agent="jarvis",
+ text="Unrelated result.",
+ trace_id="mission:mission-1",
+ msg_type=MsgType.RESULT,
+ payload={"run_id": "mission-1", "status": "done"},
+ )
+ await runtime.say(
+ from_agent="scout",
+ to_agent="jarvis",
+ text="Another run.",
+ trace_id="mission:mission-1",
+ msg_type=MsgType.RESULT,
+ payload={"run_id": "mission-2", "status": "done"},
+ )
+ status_tool = SocietyStatusTool(runtime_resolver=lambda: runtime)
+ pending = await status_tool.execute(
+ {
+ "assignment_id": assignment_id,
+ "trace_id": trace_id,
+ },
+ context(),
+ )
+ assert pending.output["state"] == "running"
+ await runtime.bridge.on_mission_envelope(
+ SimpleNamespace(
+ mission_id="mission-1",
+ payload=SimpleNamespace(event_type=terminal_event, summary="Supplier comparison."),
+ )
+ )
+ status = await status_tool.execute(
+ {
+ "assignment_id": assignment_id,
+ "trace_id": trace_id,
+ },
+ context(),
+ )
+ assert status.output["state"] == expected_state
+ final = status.output["events"][-1]
+ assert final["trace_id"] == "mission:mission-1"
+ assert final["parent_event_id"] is None
+ assert final["payload"]["output"] == ["mission:mission-1"]
+ assert final["payload"]["done"] == "Supplier comparison."
+ finally:
+ await runtime.close()
diff --git a/tests/unit/brain/test_society_inventory.py b/tests/unit/brain/test_society_inventory.py
new file mode 100644
index 0000000000..f601fae119
--- /dev/null
+++ b/tests/unit/brain/test_society_inventory.py
@@ -0,0 +1,195 @@
+"""A roster read is factual, read-only and silent until the roster is known."""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from uuid import uuid4
+
+import pytest
+
+from jarvis.brain import factory
+from jarvis.brain.manager import BrainManager
+from jarvis.brain.spawn_gate import llm_spawn_allowed
+from jarvis.brain.turn_planner import TurnReason, plan_turn
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.core.protocols import ExecutionContext
+from jarvis.plugins.tool.delegate_to_agent import SocietyStatusTool
+from jarvis.society import runtime as runtime_module
+from jarvis.society.intent import blocks_background_spawn, is_inventory_question
+from jarvis.society.lead_card import society_agent_names
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.voice.instant_ack import plan_instant_ack
+
+
+ "text",
+ [
+ "Was hast du für Agenten?", # i18n-allow: reported voice input
+ "Welche Agenten hast du?", # i18n-allow: voice input
+ "Was haben wir fuer Agenten?", # i18n-allow: voice input
+ "Was hast du eigentlich fuer Agenten?", # i18n-allow: voice input
+ "Please show my agents right now",
+ "Which agents do you have access to?",
+ "Who is on my team?",
+ "Show my agents",
+ "¿Qué agentes tienes?", # i18n-allow: voice input
+ ],
+)
+def test_inventory_cannot_announce_or_spawn(text):
+ plan = plan_turn(text)
+ assert plan.reasons == {TurnReason.SOCIETY}
+ assert plan.required_capabilities == ("society_status",)
+ assert plan_instant_ack(plan, text) is None
+ assert not llm_spawn_allowed(text)
+ manager = BrainManager(config=JarvisConfig(), bus=EventBus(), tools={})
+ assert not manager._should_force_spawn(text)
+
+
+ "text",
+ [
+ "List my agents and ask Scout to research this.",
+ "Which agents do you have? Give Scout this task.",
+ "Create a research agent called Scout.",
+ "Which agents are used in chemistry?",
+ "My travel agent booked a flight.",
+ ],
+)
+def test_other_requests_are_not_consumed_as_inventory(text):
+ assert not is_inventory_question(text)
+
+
+ "text",
+ [
+ "Create a persistent research agent called Scout.",
+ "Erstelle einen Agenten fuer meine E-Mails.", # i18n-allow: voice input
+ "Crea un agente para investigar proveedores.", # i18n-allow: voice input
+ "Update my agent's responsibilities.",
+ ],
+)
+def test_team_management_never_announces_or_spawns_a_worker(text):
+ plan = plan_turn(text)
+ assert TurnReason.SOCIETY in plan.reasons
+ assert plan_instant_ack(plan, text) is None
+ assert not llm_spawn_allowed(text)
+
+
+def test_addressed_specialist_is_not_an_anonymous_worker():
+ assert blocks_background_spawn("Scout, do a deep dive on this", ("Scout",))
+ assert not blocks_background_spawn("Spawn a worker to help Scout", ("Scout",))
+ assert not blocks_background_spawn("Research scouting opportunities", ("Scout",))
+
+
+class RecordingExecutor:
+ def __init__(self):
+ self.calls = []
+
+ async def execute(self, tool, args, *, user_utterance, config_snapshot, trace_id):
+ self.calls.append(tool.name)
+ return await tool.execute(
+ args,
+ ExecutionContext(
+ trace_id=trace_id,
+ user_utterance=user_utterance,
+ config=config_snapshot,
+ memory_read=None,
+ ),
+ )
+
+
+async def test_first_turn_loads_saved_team_and_inventory_executes_only_status(
+ tmp_path, monkeypatch
+):
+ saved = SocietyRuntime(tmp_path, seed_starter_team=False)
+ await saved.ensure_started()
+ await saved.roster.create(name="Archive", title="Research librarian")
+ await saved.close()
+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)
+ monkeypatch.setattr(runtime_module, "_current", None)
+ monkeypatch.setattr(factory, "_SOCIETY_FACTORY_REF", [lambda: runtime])
+ assert society_agent_names() == ()
+ try:
+ await asyncio.gather(factory.prepare_society_context(), factory.prepare_society_context())
+ assert society_agent_names() == ("Archive",)
+ tool = SocietyStatusTool(runtime_resolver=lambda: runtime)
+ manager = BrainManager(
+ config=JarvisConfig(), bus=EventBus(), tools={"society_status": tool}
+ )
+ manager._reply_language = "en"
+ executor = RecordingExecutor()
+ manager._tool_executor = executor
+ text = await manager.generate(
+ "Which agents do you have?", use_history=False, trace_id=uuid4()
+ )
+ assert "Archive" in text
+ assert executor.calls == ["society_status"]
+ assert runtime.scheduler.active_runs("archive") == 0
+ finally:
+ await runtime.close()
+
+
+async def test_inventory_with_no_tool_returns_honest_failure():
+ manager = BrainManager(config=JarvisConfig(), bus=EventBus(), tools={})
+ manager._reply_language = "en"
+ result = await manager._run_society_inventory_fast_path("Who is on the team?")
+ assert "cannot retrieve the agent roster" in result
+
+
+async def test_unavailable_team_does_not_break_conversation(monkeypatch):
+ def unavailable():
+ raise OSError("storage unavailable")
+
+ monkeypatch.setattr(runtime_module, "_current", None)
+ monkeypatch.setattr(factory, "_SOCIETY_FACTORY_REF", [unavailable])
+ await factory.prepare_society_context()
+ assert society_agent_names() == ()
+
+
+async def test_slow_team_start_is_shared_bounded_and_reaped_on_close(tmp_path, monkeypatch):
+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)
+ started = 0
+
+ async def slow_start():
+ nonlocal started
+ started += 1
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(runtime, "ensure_started", slow_start)
+ assert not await runtime.prepare_context(timeout_s=0.01)
+ assert not await runtime.prepare_context(timeout_s=0.01)
+ task = runtime._context_start_task
+ assert started == 1 and not task.done()
+ await runtime.close()
+ assert task.cancelled()
+
+
+async def test_named_and_unnamed_matching_tasks_stay_with_team(tmp_path, monkeypatch):
+ search = SimpleNamespace(name="search-web", description="Search the web.", risk_tier="safe")
+ runtime = SocietyRuntime(
+ tmp_path,
+ seed_starter_team=False,
+ brain_tools=lambda: {"search-web": search},
+ )
+ await runtime.ensure_started()
+ try:
+ await runtime.roster.create(name="Scout", focus=["core:search-web"])
+ manager = BrainManager(
+ config=JarvisConfig(),
+ bus=EventBus(),
+ tools={"spawn_worker": search},
+ )
+ manager._tool_executor = RecordingExecutor()
+ monkeypatch.setattr(manager, "_heavy_worker_provider_viable", lambda: True)
+ for text in (
+ "Scout, research current suppliers in the background.",
+ "Do a deep dive and research current hosting suppliers in the background.",
+ ):
+ assert runtime.pick_agent(text).name == "Scout"
+ assert not llm_spawn_allowed(text)
+ assert not manager._should_force_spawn(text)
+ assert llm_spawn_allowed("Spawn a worker to research suppliers.")
+ finally:
+ await runtime.close()
diff --git a/tests/unit/plugins/tool/test_delegate_to_agent.py b/tests/unit/plugins/tool/test_delegate_to_agent.py
index 2fa616fae1..7da4f5ceae 100644
--- a/tests/unit/plugins/tool/test_delegate_to_agent.py
+++ b/tests/unit/plugins/tool/test_delegate_to_agent.py
@@ -65,8 +65,13 @@ async def test_delegate_acks_and_assigns(runtime):
{"agent": "Scout", "task": "Find the best VPS.", "turn_language": "de"}, _ctx()
)
assert res.success, res.error
- assert res.output == "Scout ist dran, ich sage Bescheid." # i18n-allow: spoken ack
- assert res.artifacts == ("agent:scout",)
+ assert res.output["acknowledgement"] == (
+ "Scout ist dran, ich sage Bescheid." # i18n-allow: spoken ack
+ )
+ assert res.output["state"] == "running" and res.output["agent_id"] == "scout"
+ assert res.artifacts[0] == "agent:scout"
+ assert res.artifacts[1].startswith("assignment:")
+ assert res.artifacts[2].startswith("trace:voice:")
# The assignment went through the scheduler into Scout's canonical chat.
assert chat.sent and chat.sent[0][0] == "society:scout"
assert "Find the best VPS." in chat.sent[0][1]
@@ -81,7 +86,7 @@ async def test_delegate_speaks_english_when_the_turn_is_english(runtime):
res = await tool.execute(
{"agent": "scout", "task": "Find it.", "turn_language": "en"}, _ctx("let scout find it")
)
- assert res.output == "Scout is on it, I will let you know."
+ assert res.output["acknowledgement"] == "Scout is on it, I will let you know."
async def test_delegate_unknown_agent(runtime):
@@ -102,7 +107,8 @@ async def test_delegate_reads_the_veto_back(runtime):
{"agent": "scout", "task": "x", "turn_language": "en"}, _ctx("let scout do x")
)
assert res.success is False and res.error == "kill_switch"
- assert res.output.startswith("Scout cannot take that right now")
+ assert res.output["acknowledgement"].startswith("Scout cannot take that right now")
+ assert res.output["state"] == "refused" and res.output["assignment_id"]
async def test_not_ready_paths():
@@ -126,7 +132,7 @@ async def test_status_answers_from_the_board(runtime):
rt, _ = runtime
status = SocietyStatusTool(runtime_resolver=lambda: rt)
team = await status.execute({"turn_language": "en"}, _ctx("who is on the team"))
- assert team.output == "Active agents: Archivist, Scout."
+ assert team.output == "Your agents: Archivist, Scout."
idle = await status.execute(
{"agent": "archivist", "turn_language": "en"}, _ctx("what is archivist doing")
)
@@ -182,20 +188,20 @@ async def test_delegate_without_a_name_picks_by_the_task(team):
_ctx("give that to the team"),
)
assert res.success, res.error
- assert res.output == "Gmail agent is on it, I will let you know."
+ assert res.output["acknowledgement"] == "Gmail agent is on it, I will let you know."
assert chat.sent and chat.sent[0][0] == "society:gmail-agent"
-async def test_delegate_with_a_misheard_name_still_finds_the_fit(team):
- """'email agent' is not on the roster; the task's words are."""
+async def test_delegate_unknown_name_does_not_redirect_work(team):
+ """A task fit must never override the user's explicit recipient."""
rt, chat = team
tool = DelegateToAgentTool(runtime_resolver=lambda: rt)
res = await tool.execute(
{"agent": "email agent", "task": "check my inbox in gmail", "turn_language": "en"},
_ctx("email agent, check my inbox"),
)
- assert res.success, res.error
- assert chat.sent and chat.sent[0][0] == "society:gmail-agent"
+ assert not res.success and res.error == "target_unknown"
+ assert not chat.sent
async def test_delegate_without_a_fit_says_so(team):
@@ -207,3 +213,225 @@ async def test_delegate_without_a_fit_says_so(team):
assert res.success is False and res.error == "no_agent_fits"
assert res.output == "None of your agents fits this task."
assert not chat.sent
+
+
+async def test_assignment_preserves_context_criteria_and_tracking(runtime):
+ rt, chat = runtime
+ result = await DelegateToAgentTool(runtime_resolver=lambda: rt).execute(
+ {
+ "agent": "Scout",
+ "task": "Compare suppliers.",
+ "turn_language": "en",
+ "context": "Only European hosting; budget under 20 per month.",
+ "completion_criteria": "Return three cited quotes and a comparison table.",
+ "refs": ["wiki:requirements"],
+ },
+ _ctx(),
+ )
+ assert result.success
+ assert "Only European hosting" in chat.sent[0][1]
+ assert "three cited quotes" in chat.sent[0][1]
+ assert "wiki:requirements" in chat.sent[0][1]
+ assignment_id = result.output["assignment_id"]
+ trace_id = result.output["trace_id"]
+ assert result.artifacts[1] == f"assignment:{assignment_id}"
+ assert result.artifacts[2] == f"trace:{trace_id}"
+ status = await SocietyStatusTool(runtime_resolver=lambda: rt).execute(
+ {
+ "assignment_id": assignment_id,
+ "trace_id": trace_id,
+ },
+ _ctx(),
+ )
+ assert status.output["state"] == "running"
+ assert status.output["events"][0]["parent_event_id"] == assignment_id
+ await rt.say(
+ from_agent="scout",
+ to_agent="jarvis",
+ text="Waiting for supplier access.",
+ trace_id=trace_id,
+ msg_type=MsgType.RESULT,
+ parent_event_id=assignment_id,
+ payload={
+ "status": "blocked",
+ "done": "Compared two suppliers.",
+ "output": ["wiki:comparison"],
+ "evidence": ["wiki:quotes"],
+ "open": ["Third supplier requires access."],
+ "next_owner": None,
+ },
+ )
+ blocked = await SocietyStatusTool(runtime_resolver=lambda: rt).execute(
+ {"assignment_id": assignment_id, "trace_id": trace_id},
+ _ctx(),
+ )
+ assert blocked.output["state"] == "blocked"
+ assert blocked.output["events"][-1]["payload"]["evidence"] == ["wiki:quotes"]
+
+
+async def test_unrelated_claim_does_not_confirm_assignment(runtime):
+ from jarvis.society.events import SocietyEnvelope
+
+ rt, chat = runtime
+ rt.scheduler.detach()
+
+ async def noisy_say(**kwargs):
+ assignment = await rt.say(**kwargs)
+ await rt.store.append_and_publish(
+ SocietyEnvelope(
+ msg_type=MsgType.CLAIM,
+ from_agent="scout",
+ to_agent="jarvis",
+ trace_id=assignment.trace_id,
+ parent_event_id="some-other-assignment",
+ )
+ )
+ return assignment
+
+ proxy = SimpleNamespace(
+ ensure_started=rt.ensure_started,
+ roster=rt.roster,
+ store=rt.store,
+ say=noisy_say,
+ lead_id=rt.lead_id,
+ )
+ result = await DelegateToAgentTool(runtime_resolver=lambda: proxy).execute(
+ {
+ "agent": "scout",
+ "task": "Find it.",
+ "turn_language": "en",
+ },
+ _ctx(),
+ )
+ assert result.success
+ assert "not confirmed" in result.output["acknowledgement"]
+ assert result.output["state"] == "recorded"
+ assert not chat.sent
+
+
+async def test_status_details_exposes_roles_paused_state_and_observed_stats(runtime):
+ rt, _ = runtime
+ await rt.roster.update("scout", {"title": "Researcher", "state": "paused"})
+ before = await rt.store.last_seq()
+ result = await SocietyStatusTool(runtime_resolver=lambda: rt).execute(
+ {
+ "agent": "Scout",
+ "details": True,
+ },
+ _ctx(),
+ )
+ row = result.output["agents"][0]
+ assert row["agent"]["title"] == "Researcher"
+ assert row["agent"]["state"] == "paused"
+ assert row["stats"]["runs"] == 0
+ assert "No independent quality rating" in result.output["measurement_note"]
+ assert await rt.store.last_seq() == before
+
+
[email protected]("tool_class", [DelegateToAgentTool, SocietyStatusTool])
+async def test_runtime_start_failure_is_an_honest_tool_result(tool_class):
+ async def fail_to_start():
+ raise OSError("database unavailable")
+
+ runtime = SimpleNamespace(ensure_started=fail_to_start)
+ result = await tool_class(runtime_resolver=lambda: runtime).execute(
+ {"agent": "Scout", "task": "Research it.", "turn_language": "en"},
+ _ctx(),
+ )
+ assert not result.success
+ assert result.error == "society unavailable"
+ assert result.output == "The agents are not ready yet."
+
+
+async def test_roster_names_do_not_claim_paused_agents_are_active(runtime):
+ rt, _ = runtime
+ await rt.roster.update("scout", {"state": "paused"})
+ tool = SocietyStatusTool(runtime_resolver=lambda: rt)
+ result = await tool.execute({"turn_language": "en"}, _ctx())
+ assert result.output == "Your agents: Archivist, Scout."
+ await rt.roster.update("scout", {"state": "archived"})
+ await rt.roster.update("archivist", {"state": "archived"})
+ empty = await tool.execute({"turn_language": "en"}, _ctx())
+ assert empty.output == "You do not have any team agents yet."
+
+
[email protected]("tool_class", [DelegateToAgentTool, SocietyStatusTool])
+async def test_runtime_still_starting_returns_not_ready(tool_class):
+ async def prepare():
+ return False
+
+ runtime = SimpleNamespace(prepare_context=prepare)
+ result = await tool_class(runtime_resolver=lambda: runtime).execute(
+ {"agent": "Scout", "task": "Research it.", "turn_language": "en"},
+ _ctx(),
+ )
+ assert not result.success and result.error == "society unavailable"
+
+
+async def test_latest_assignment_survives_unrelated_history_without_previous_tool_ids(runtime):
+ rt, _ = runtime
+ rt.scheduler.detach()
+ await rt.say(
+ from_agent="jarvis",
+ to_agent="scout",
+ text="Old task.",
+ msg_type=MsgType.ASSIGN,
+ )
+ newest = await rt.say(
+ from_agent="jarvis",
+ to_agent="scout",
+ text="Compare supplier prices.",
+ msg_type=MsgType.ASSIGN,
+ )
+ await rt.say(
+ from_agent="scout",
+ to_agent="jarvis",
+ text="Compared three suppliers.",
+ msg_type=MsgType.RESULT,
+ trace_id=newest.trace_id,
+ parent_event_id=newest.event_id,
+ payload={"status": "done", "evidence": ["wiki:supplier-quotes"]},
+ )
+ # A later user assignment is not the latest assignment sent by the lead.
+ await rt.say(
+ from_agent="user",
+ to_agent="scout",
+ text="Separate user task.",
+ msg_type=MsgType.ASSIGN,
+ )
+ for i in range(25):
+ await rt.say(from_agent="scout", to_agent="jarvis", text=f"Unrelated message {i}.")
+ status = await SocietyStatusTool(runtime_resolver=lambda: rt).execute(
+ {"agent": "Scout", "latest_assignment": True},
+ _ctx(),
+ )
+ assert status.success
+ assert status.output["assignment_id"] == newest.event_id
+ assert status.output["assignment"]["payload"]["text"] == "Compare supplier prices."
+ assert status.output["state"] == "done"
+ assert status.output["events"][-1]["payload"]["evidence"] == ["wiki:supplier-quotes"]
+
+
+async def test_exact_assignment_id_works_without_trace_and_rejects_mismatched_trace(runtime):
+ rt, _ = runtime
+ result = await DelegateToAgentTool(runtime_resolver=lambda: rt).execute(
+ {"agent": "Scout", "task": "Compare suppliers."},
+ _ctx(),
+ )
+ assignment_id = result.output["assignment_id"]
+ tool = SocietyStatusTool(runtime_resolver=lambda: rt)
+ status = await tool.execute({"assignment_id": assignment_id}, _ctx())
+ assert status.success and status.output["state"] == "running"
+ assert status.output["trace_id"] == result.output["trace_id"]
+ mismatch = await tool.execute(
+ {
+ "assignment_id": assignment_id,
+ "trace_id": "wrong-trace",
+ },
+ _ctx(),
+ )
+ assert not mismatch.success and mismatch.error == "assignment_trace_mismatch"
+ ambiguous = await tool.execute({"latest_assignment": True}, _ctx())
+ assert 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"
diff --git a/tests/unit/realtime/test_session_society_directive.py b/tests/unit/realtime/test_session_society_directive.py
index e18ab3b210..7367f21f6a 100644
--- a/tests/unit/realtime/test_session_society_directive.py
+++ b/tests/unit/realtime/test_session_society_directive.py
@@ -48,9 +48,10 @@ def test_the_directive_routes_the_team_to_the_action_function(society: Any) -> N
assert "do not know who" in directive
-def test_no_society_no_directive(society: Any) -> None:
+def test_empty_snapshot_requires_verified_lookup(society: Any) -> None:
society(())
- assert _directive() == ""
+ assert "use society_status to verify" in _directive()
+ assert "read-only lookup" in _directive()
def test_the_instructions_carry_the_directive_in_both_profiles() -> None:
diff --git a/tests/unit/society/test_lead_card.py b/tests/unit/society/test_lead_card.py
index ae64e1ebdf..774f80b0a1 100644
--- a/tests/unit/society/test_lead_card.py
+++ b/tests/unit/society/test_lead_card.py
@@ -186,7 +186,7 @@ async def test_society_agent_names_feed_the_realtime_path(rt: SocietyRuntime):
await rt.roster.create(name="Scout", focus=["core:search-web"])
await rt.roster.create(name="Sleeper", focus=[])
await rt.roster.update("sleeper", {"state": "paused"})
- assert society_agent_names() == ("Gmail agent", "Scout")
+ assert society_agent_names() == ("Gmail agent", "Scout", "Sleeper")
def test_without_a_runtime_everything_is_quiet():
diff --git a/tests/unit/society/test_store.py b/tests/unit/society/test_store.py
index 467ed1f65c..31fff7eece 100644
--- a/tests/unit/society/test_store.py
+++ b/tests/unit/society/test_store.py
@@ -114,6 +114,38 @@ async def test_survives_a_crash_between_persist_and_publish(store: SocietyStore,
assert len(await store.events_since(0)) == 1
+async def test_cancelled_open_closes_provisional_connection(tmp_path, monkeypatch):
+ import asyncio
+
+ from jarvis.society import store as store_module
+
+ entered = asyncio.Event()
+
+ class Connection:
+ closed = False
+
+ async def execute(self, _statement):
+ entered.set()
+ await asyncio.Event().wait()
+
+ async def close(self):
+ self.closed = True
+
+ connection = Connection()
+
+ async def connect(*args, **kwargs):
+ return connection
+
+ monkeypatch.setattr(store_module.aiosqlite, "connect", connect)
+ store = store_module.SocietyStore(tmp_path / "cancel.db")
+ opening = asyncio.create_task(store.open())
+ await entered.wait()
+ opening.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await opening
+ assert connection.closed and store._conn is None
+
+
async def test_open_is_idempotent(tmp_path: Path):
s = SocietyStore(tmp_path / "society.db")
await s.open()
diff --git a/tests/unit/state/test_chats_routes.py b/tests/unit/state/test_chats_routes.py
index 1a764ceded..b5ca17cd20 100644
--- a/tests/unit/state/test_chats_routes.py
+++ b/tests/unit/state/test_chats_routes.py
@@ -152,6 +152,70 @@ async def test_get_voice_conversation_flattens_turns() -> None:
]
+async def test_voice_history_keeps_preambles_when_hangup_precedes_reply() -> None:
+ app, _ = await _make_app(with_session=True, with_brain=True)
+ turn = app.state.session_store.get_turns("v1")[0]
+ turn.id = "v1-auto-1"
+ turn.jarvis_text = ""
+ events = [
+ SimpleNamespace(
+ turn_id=turn.id,
+ kind="SpeechSpoken",
+ ts_ms=timestamp,
+ seq=index,
+ payload={"text": text, "spoken_kind": "preamble"},
+ )
+ for index, (timestamp, text) in enumerate(
+ [(1_200, "I am checking the team."), (1_400, "Still working on it.")]
+ )
+ ]
+ app.state.session_store.get_events = lambda cid: events
+
+ async with _client(app) as client:
+ detail = (await client.get("/api/chats/voice/v1")).json()
+ resumed = await client.post("/api/chats/voice/v1/resume")
+
+ assert [(m["role"], m["text"], m["ts_ms"]) for m in detail["messages"]] == [
+ ("user", "how is the weather", 1_000),
+ ("assistant", "I am checking the team.", 1_200),
+ ("assistant", "Still working on it.", 1_400),
+ ]
+ assert all(m["trace"] is None for m in detail["messages"])
+ assert resumed.status_code == 200
+ assert app.state.brain.seeded[-1] == ("assistant", "Still working on it.")
+
+
+async def test_voice_history_prefers_heard_reply_and_keeps_spoken_fallback() -> None:
+ app, _ = await _make_app(with_session=True)
+ turn = app.state.session_store.get_turns("v1")[0]
+ turn.id = "v1-turn-1"
+ turn.jarvis_text = "Unspoken original reply."
+ events = [
+ SimpleNamespace(
+ turn_id=turn_id,
+ kind=kind,
+ ts_ms=1_100 + index * 50,
+ seq=index,
+ payload={"text": text, "spoken_kind": spoken_kind},
+ )
+ for index, (turn_id, kind, spoken_kind, text) in enumerate([
+ (turn.id, "ResponseGenerated", "", "Unspoken original reply."),
+ (turn.id, "SpeechSpoken", "preamble", "Checking now."),
+ (turn.id, "SpeechSpoken", "withheld", "I could not finish that answer."),
+ (turn.id, "SpeechSpoken", "reply", "The reply actually heard."),
+ ("another-turn", "SpeechSpoken", "reply", "Someone else's reply."),
+ ])
+ ]
+ app.state.session_store.get_events = lambda cid: events
+
+ async with _client(app) as client:
+ detail = (await client.get("/api/chats/voice/v1")).json()
+
+ assert [m["text"] for m in detail["messages"] if m["role"] == "assistant"] == [
+ "Checking now.", "I could not finish that answer.", "The reply actually heard.",
+ ]
+
+
async def test_get_unknown_conversation_404() -> None:
app, _ = await _make_app()
async with _client(app) as c: