Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): capability catalog, focus, bounded rooms, scheduler, mission bridge
rubenluetke10-beep906a7819894d
diff --git a/jarvis/society/bridge.py b/jarvis/society/bridge.pynew file mode 100644index 0000000000..614731ca04--- /dev/null+++ b/jarvis/society/bridge.py@@ -0,0 +1,165 @@+"""Mission envelopes → society events: one world feed (MASTERPLAN §2.6).++Every mission the app runs — society-dispatched or not — appears on the+board, so the world, the ledger and the cost HUD read ONE stream. Work the+scheduler started is attributed to the agent that owns it; everything else+belongs to the lead (Jarvis), because that is who dispatched it.++Only the envelopes that mean something to the society are mirrored; worker+chatter (progress ticks, bus stats, critic verdicts) stays in the mission+log where the Missions view reads it.+"""++from __future__ import annotations++import logging+from collections.abc import Callable+from typing import Any++from .events import MsgType, SocietyEnvelope+from .roster import LEAD_AGENT_ID+from .store import SocietyStore++log = logging.getLogger(__name__)++__all__ = ["MissionBridge"]++_TERMINAL_OK = frozenset({"MissionApproved"})+_TERMINAL_BAD = {+ "MissionFailed": "blocked",+ "MissionCancelled": "blocked",+ "MissionTimedOut": "blocked",+}+++class MissionBridge:+ def __init__(+ self,+ store: SocietyStore,+ *,+ owner_of: Callable[[str], str | None],+ on_run_ended: Callable[[str], Any] | None = None,+ ) -> None:+ self._store = store+ self._owner_of = owner_of+ self._on_run_ended = on_run_ended+ self._unsubscribe: Callable[[], None] | None = None+ self._cost: dict[str, float] = {}++ def attach(self, mission_bus: Any) -> MissionBridge:+ if self._unsubscribe is None:+ self._unsubscribe = mission_bus.subscribe_all(self.on_mission_envelope)+ return self++ def detach(self) -> None:+ if self._unsubscribe is not None:+ self._unsubscribe()+ self._unsubscribe = None++ async def on_mission_envelope(self, env: Any) -> None:+ payload = getattr(env, "payload", None)+ event_type = str(getattr(payload, "event_type", "") or "")+ mission_id = str(getattr(env, "mission_id", "") or "")+ if not event_type or not mission_id:+ return+ agent_id = self._owner_of(mission_id) or LEAD_AGENT_ID+ trace_id = f"mission:{mission_id}"+ try:+ await self._mirror(event_type, mission_id, agent_id, trace_id, env, payload)+ except Exception: # noqa: BLE001 — a mirror failure must not reach the mission bus+ log.warning(+ "society bridge: could not mirror %s for %s", event_type, mission_id, exc_info=True+ )++ async def _mirror(+ self, event_type: str, mission_id: str, agent_id: str, trace_id: str, env: Any, payload: Any+ ) -> None:+ if event_type == "MissionDispatched":+ await self._append(+ MsgType.CLAIM,+ agent_id,+ trace_id,+ {"run_id": mission_id, "text": str(getattr(payload, "prompt", "") or "")[:500]},+ )+ elif event_type == "WorkerSpawned":+ await self._append(+ MsgType.DIGEST,+ agent_id,+ trace_id,+ {+ "run_id": mission_id,+ "kind": "worker_spawned",+ "worker": str(getattr(payload, "cli", "") or ""),+ "model": str(getattr(payload, "model", "") or ""),+ "text": "worker started",+ },+ )+ elif event_type == "WorkerDraftReady":+ cost = float(getattr(payload, "cost_usd", 0.0) or 0.0)+ self._cost[mission_id] = self._cost.get(mission_id, 0.0) + cost+ await self._append(+ MsgType.DIGEST,+ agent_id,+ trace_id,+ {"run_id": mission_id, "kind": "draft_ready", "text": "draft ready"},+ cost_usd=cost,+ )+ elif event_type == "WorkerKilled":+ await self._append(+ MsgType.DIGEST,+ agent_id,+ trace_id,+ {+ "run_id": mission_id,+ "kind": "worker_killed",+ "text": str(getattr(payload, "reason", "") or "worker killed"),+ },+ )+ elif event_type in _TERMINAL_OK or event_type in _TERMINAL_BAD:+ status = "done" if event_type in _TERMINAL_OK else _TERMINAL_BAD[event_type]+ summary = str(+ getattr(payload, "summary", None)+ or getattr(payload, "reason", None)+ or getattr(payload, "error", None)+ or event_type+ )+ self._cost.pop(mission_id, None)+ await self._append(+ MsgType.RESULT,+ agent_id,+ trace_id,+ {+ "run_id": mission_id,+ "status": status,+ "done": summary[:2000],+ "output": [f"mission:{mission_id}"],+ "evidence": [],+ "open": [] if status == "done" else [summary[:500]],+ "next_owner": None,+ "text": summary[:500],+ },+ to_agent=LEAD_AGENT_ID if agent_id != LEAD_AGENT_ID else None,+ )+ if self._on_run_ended is not None:+ self._on_run_ended(mission_id)++ async def _append(+ self,+ msg_type: MsgType,+ agent_id: str,+ trace_id: str,+ payload: dict[str, Any],+ *,+ cost_usd: float = 0.0,+ to_agent: str | None = None,+ ) -> None:+ await self._store.append_and_publish(+ SocietyEnvelope(+ msg_type=msg_type,+ from_agent=agent_id,+ to_agent=to_agent,+ trace_id=trace_id,+ cost_usd=cost_usd,+ payload=payload,+ )+ )diff --git a/jarvis/society/capabilities.py b/jarvis/society/capabilities.pynew file mode 100644index 0000000000..35e1515510--- /dev/null+++ b/jarvis/society/capabilities.py@@ -0,0 +1,292 @@+"""ONE catalog over everything a society agent could be handed.++Plugins (``jarvis.tool`` entry points, marketplace included), connected CLIs+(``cli_<name>`` tools), MCP servers (``<server>/<tool>`` adapters), skills+(``active`` lifecycle only) and the built-in core tools all already exist in+their own registries. This module is a read-only view that gives each of+them one id (``plugin:gmail``, ``cli:gh``, ``mcp:github/create_issue``,+``skill:daily-brief``, ``core:search-web``) so a roster row can grant, focus+or deny them, and the model card can list them grouped by kind.++Never granted, structurally (AP-5/AP-14): every dispatch tool and every app+control tool. They are filtered out here, so no later layer can hand them to+an agent by accident.++Pure functions over the objects passed in — no registry is imported at+module import time (AP-26); the runtime wires the live sources.+"""++from __future__ import annotations++from collections.abc import Callable, Iterable, Mapping+from dataclasses import dataclass+from enum import StrEnum+from typing import Any, Final++__all__ = [+ "CapabilityKind",+ "CapabilityRow",+ "NEVER_GRANTED",+ "build_catalog",+ "capability_id_for_tool",+ "select_tools",+ "tool_name_for_capability",+]+++class CapabilityKind(StrEnum):+ PLUGIN = "plugin"+ CLI = "cli"+ MCP = "mcp"+ SKILL = "skill"+ CORE = "core"+++#: Tool names that never enter any society tool set. Dispatch is the+#: scheduler's privilege; app control stays with Jarvis.+NEVER_GRANTED: Final[frozenset[str]] = frozenset(+ {+ "spawn-worker",+ "spawn-subagents",+ "multi-spawn",+ "dispatch-to-harness",+ "dispatch-to-admin",+ "dispatch-with-review",+ "create-artifact",+ "navigate",+ "switch-provider",+ "manage-mcp-server",+ "app-command",+ "create-skill",+ "reveal-key-preview",+ "profile-update",+ "society_message_agent",+ }+)++#: Built-in hands that are not "a plugin someone connected".+_CORE_TOOLS: Final[frozenset[str]] = frozenset(+ {+ "search-web",+ "search-backends",+ "run-shell",+ "screen-snapshot",+ "computer-use",+ "remember",+ "whoami",+ "wiki-recall",+ "wiki-ingest",+ "wiki-list",+ "wiki-page-read",+ "awareness-recall",+ "awareness-snapshot",+ "run-skill",+ "inspect-pointer",+ "open-app",+ "type-text",+ "hotkey",+ "click",+ "click-element",+ "scroll",+ "drag",+ "move-mouse",+ "switch-window",+ "read-visible-ui-state",+ "wait-for-ui-state",+ "wait-for-element",+ "describe-app-settings",+ "contact-lookup",+ "contact-upsert",+ "start-preview-server",+ "verify-localhost",+ "verify-via-curl",+ "Read",+ "Write",+ "Edit",+ "Ls",+ "Glob",+ "Grep",+ "RunCommand",+ }+)+++@dataclass(frozen=True, slots=True)+class CapabilityRow:+ id: str+ kind: CapabilityKind+ label: str+ one_liner: str+ risk_tier: str+ connected: bool+ #: The tool name in the brain's registry (empty for skills).+ tool_name: str+ #: Extra words the focus matcher may use (server name, aliases).+ aliases: tuple[str, ...] = ()++ def to_dict(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "kind": str(self.kind),+ "label": self.label,+ "one_liner": self.one_liner,+ "risk_tier": self.risk_tier,+ "connected": self.connected,+ "tool_name": self.tool_name,+ "aliases": list(self.aliases),+ }+++def capability_id_for_tool(tool_name: str) -> str | None:+ """The catalog id of a brain tool name; ``None`` for never-granted tools."""+ if tool_name in NEVER_GRANTED:+ return None+ if tool_name.startswith("cli_"):+ return f"cli:{tool_name[4:]}"+ if "/" in tool_name:+ return f"mcp:{tool_name}"+ if tool_name in _CORE_TOOLS:+ return f"core:{tool_name}"+ return f"plugin:{tool_name}"+++def tool_name_for_capability(capability_id: str) -> str | None:+ """Inverse of :func:`capability_id_for_tool`; ``None`` for skills."""+ kind, _, rest = capability_id.partition(":")+ if kind == "cli":+ return f"cli_{rest}"+ if kind in ("mcp", "core", "plugin"):+ return rest+ return None+++def _one_liner(text: str, limit: int = 140) -> str:+ first = " ".join((text or "").strip().split())+ # MCP descriptions carry the adapter's warning banner; keep the server's words.+ if first.startswith("[ACTION-ONLY"):+ close = first.find("]")+ if close > 0:+ first = first[close + 1 :].strip()+ if "." in first[:limit]:+ first = first[: first.index(".") + 1]+ return first[:limit]+++def _label(tool_name: str, kind: CapabilityKind) -> str:+ if kind is CapabilityKind.CLI:+ return tool_name[4:]+ if kind is CapabilityKind.MCP:+ return tool_name+ return tool_name.replace("_", "-")+++def _skill_fields(skill: Any) -> tuple[str, str, str]:+ """``(slug, label, one_liner)`` from a Skill or a look-alike."""+ fm = getattr(skill, "frontmatter", None)+ slug = getattr(skill, "slug", None) or getattr(fm, "name", None) or getattr(skill, "name", None)+ if not slug:+ path = getattr(skill, "path", None)+ slug = getattr(path, "stem", None) or "skill"+ label = getattr(fm, "title", None) or getattr(fm, "name", None) or str(slug)+ desc = getattr(fm, "description", None) or getattr(skill, "description", "") or ""+ return str(slug), str(label), _one_liner(str(desc))+++def _skill_is_active(skill: Any) -> bool:+ state = getattr(skill, "state", None)+ value = getattr(state, "value", state)+ return str(value).lower() == "active"+++def build_catalog(+ tools: Mapping[str, Any] | None,+ skills: Iterable[Any] | None = None,+ *,+ connected: Callable[[str, CapabilityKind], bool] | None = None,+) -> list[CapabilityRow]:+ """The catalog for a brain tool registry plus a skill registry.++ ``connected(tool_name, kind)`` may report a plugin whose credential is+ missing; by default everything the brain loaded counts as connected.+ Rows come back connected-first within each kind, kinds in the order the+ card shows them (plugin, cli, mcp, skill, core).+ """+ rows: list[CapabilityRow] = []+ for name, tool in (tools or {}).items():+ cap_id = capability_id_for_tool(name)+ if cap_id is None:+ continue+ kind = CapabilityKind(cap_id.split(":", 1)[0])+ aliases: tuple[str, ...] = ()+ if kind is CapabilityKind.MCP:+ server = name.split("/", 1)[0]+ aliases = (server,)+ is_connected = True if connected is None else bool(connected(name, kind))+ rows.append(+ CapabilityRow(+ id=cap_id,+ kind=kind,+ label=_label(name, kind),+ one_liner=_one_liner(getattr(tool, "description", "") or ""),+ risk_tier=str(getattr(tool, "risk_tier", "monitor") or "monitor"),+ connected=is_connected,+ tool_name=name,+ aliases=aliases,+ )+ )+ for skill in skills or ():+ if not _skill_is_active(skill):+ continue+ slug, label, one_liner = _skill_fields(skill)+ rows.append(+ CapabilityRow(+ id=f"skill:{slug}",+ kind=CapabilityKind.SKILL,+ label=label,+ one_liner=one_liner,+ risk_tier="monitor",+ connected=True,+ tool_name="",+ )+ )+ order = {k: i for i, k in enumerate(CapabilityKind)}+ rows.sort(key=lambda r: (order[r.kind], not r.connected, r.label.lower()))+ return rows+++def select_tools(+ tools: Mapping[str, Any],+ *,+ grant_mode: str,+ grants: Iterable[str],+ focus: Iterable[str],+ denies: Iterable[str],+) -> dict[str, Any]:+ """The agent's tool dict per agent-definition §3.2, in deterministic order.++ 1. start from everything (``all``) or the allow-list;+ 2. drop denies and every never-granted tool;+ 3. order focus first, the rest alphabetically — prompt-cache safe because+ the order depends only on the roster row.+ """+ granted = set(grants)+ denied = set(denies)+ focus_list = [f for f in focus]+ keep: dict[str, Any] = {}+ for name, tool in tools.items():+ cap_id = capability_id_for_tool(name)+ if cap_id is None or cap_id in denied:+ continue+ if grant_mode == "allowlist" and cap_id not in granted:+ continue+ keep[cap_id] = (name, tool)+ ordered: dict[str, Any] = {}+ for cap_id in focus_list:+ if cap_id in keep:+ name, tool = keep[cap_id]+ ordered[name] = tool+ for cap_id in sorted(keep):+ name, tool = keep[cap_id]+ if name not in ordered:+ ordered[name] = tool+ return ordereddiff --git a/jarvis/society/focus.py b/jarvis/society/focus.pynew file mode 100644index 0000000000..325b905942--- /dev/null+++ b/jarvis/society/focus.py@@ -0,0 +1,160 @@+"""What an agent reaches for first — derived from its title and description.++Deterministic keyword matching, no model call (agent-definition §3.2): it has+to work with any single key and cost nothing. The alias table maps the words+people use ("Mails", "inbox", "Termine", "PRs") onto capability ids; catalog+labels, one-liners and MCP server names are matched too, so a freshly+connected MCP server is reachable by its own name without a table edit.++``derive_approval_rules`` reads the same text for an approval boundary+("only after approval", "nur nach Freigabe") and turns it into Grok-style+require-approval patterns on the focus tools' sending verbs.+"""++from __future__ import annotations++import re+from typing import Final++from .capabilities import CapabilityKind, CapabilityRow++__all__ = ["derive_approval_rules", "derive_focus"]++# capability id (or prefix) → words that mean it. Lower-case, matched as whole+# words on a folded text. German and English on purpose: the description is+# product-surface text the person writes in their own language.+_ALIASES: Final[dict[str, tuple[str, ...]]] = {+ "plugin:gmail": ("gmail", "mail", "mails", "email", "emails", "e-mail", "inbox", "postfach"),+ "plugin:google-calendar": (+ "calendar",+ "kalender",+ "termin",+ "termine",+ "meeting",+ "meetings",+ "appointment",+ "appointments",+ ),+ "plugin:drive": ("drive", "google drive", "gdrive"),+ "plugin:spotify": ("spotify", "playlist", "playlists", "musik", "music", "song", "songs"),+ "plugin:youtube-music": ("youtube music", "youtube-music"),+ "plugin:home-assistant": ("home assistant", "smart home", "smarthome", "licht", "lights"),+ "plugin:vercel": ("vercel", "deployment", "deployments", "deploy"),+ "cli:gh": ("github", "gh", "pull request", "pull requests", "pr", "prs", "issue", "issues"),+ "cli:git": ("git", "commit", "commits", "branch", "branches"),+ "cli:gcloud": ("gcloud", "google cloud", "gcp"),+ "cli:docker": ("docker", "container", "containers"),+ "cli:npm": ("npm", "node", "package.json"),+ "core:search-web": (+ "web",+ "internet",+ "recherche",+ "research",+ "search",+ "suche",+ "news",+ "nachrichten",+ ),+ "core:wiki-recall": ("wiki", "wissen", "knowledge", "notes", "notizen", "obsidian"),+ "core:computer-use": ("browser", "website", "webseite", "click", "klicken", "screen"),+ "core:run-shell": ("shell", "terminal", "script", "scripts", "command", "befehl"),+ "core:contact-lookup": ("kontakt", "kontakte", "contact", "contacts", "people", "leute"),+ "core:Read": ("files", "dateien", "file", "datei", "ordner", "folder", "code", "repo"),+}++_APPROVAL_PHRASES: Final[tuple[str, ...]] = (+ "only after approval",+ "after approval",+ "with approval",+ "ask before",+ "ask me before",+ "ask first",+ "nur nach freigabe",+ "nach freigabe",+ "erst nach freigabe",+ "mit freigabe",+ "frag vorher",+ "frage vorher",+ "vorher fragen",+ "nur mit erlaubnis",+)++#: Sending verbs per capability kind that an approval boundary should gate.+_SEND_VERBS: Final[dict[str, tuple[str, ...]]] = {+ "plugin:gmail": ("send",),+ "plugin:google-calendar": ("create", "update", "delete"),+ "plugin:spotify": ("play",),+ "plugin:vercel": ("deploy",),+ "cli:gh": ("create", "merge", "close"),+}++_WORD_RE: Final[re.Pattern[str]] = re.compile(r"[a-z0-9][a-z0-9.\-]*")+++def _fold(text: str) -> str:+ text = text.lower()+ for src, dst in (("ä", "ae"), ("ö", "oe"), ("ü", "ue"), ("ß", "ss")):+ text = text.replace(src, dst)+ return text+++def _mentions(text: str, phrase: str) -> bool:+ phrase = _fold(phrase)+ return re.search(rf"(?<![a-z0-9]){re.escape(phrase)}(?![a-z0-9])", text) is not None+++def derive_focus(+ title: str, description: str, catalog: list[CapabilityRow], *, limit: int = 6+) -> list[str]:+ """Capability ids the text points at, strongest first, at most ``limit``.++ Scoring: a title hit weighs 3, a description hit 1 per distinct word;+ alias-table hits and catalog-name hits are both counted. Only ids that+ exist in ``catalog`` (connected or not) come back, so a description about+ Gmail on a box without the plugin yields nothing rather than a dead id.+ """+ folded_title = _fold(title or "")+ folded_desc = _fold(description or "")+ if not folded_title and not folded_desc:+ return []+ by_id = {row.id: row for row in catalog}+ scores: dict[str, int] = {}++ def _bump(cap_id: str, weight: int) -> None:+ if cap_id in by_id:+ scores[cap_id] = scores.get(cap_id, 0) + weight++ for cap_id, words in _ALIASES.items():+ for word in words:+ if _mentions(folded_title, word):+ _bump(cap_id, 3)+ if _mentions(folded_desc, word):+ _bump(cap_id, 1)+ for row in catalog:+ names = {row.label, *row.aliases}+ if row.kind is CapabilityKind.MCP:+ names.add(row.tool_name.split("/", 1)[0])+ for name in names:+ folded = _fold(name)+ if len(folded) < 3:+ continue+ if _mentions(folded_title, folded):+ _bump(row.id, 3)+ if _mentions(folded_desc, folded):+ _bump(row.id, 1)+ ranked = sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))+ return [cap_id for cap_id, _ in ranked[:limit]]+++def derive_approval_rules(description: str, focus: list[str]) -> dict[str, list[str]]:+ """Require-approval patterns when the description draws an approval line."""+ folded = _fold(description or "")+ if not any(_mentions(folded, phrase) for phrase in _APPROVAL_PHRASES):+ return {"require_approval": [], "always_allow": []}+ patterns: list[str] = []+ for cap_id in focus:+ for verb in _SEND_VERBS.get(cap_id, ()):+ patterns.append(f"{cap_id}:{verb}")+ if not patterns:+ patterns = [f"{cap_id}:*" for cap_id in focus if cap_id.startswith(("plugin:", "cli:"))]+ return {"require_approval": sorted(set(patterns)), "always_allow": []}diff --git a/jarvis/society/rooms.py b/jarvis/society/rooms.pynew file mode 100644index 0000000000..43750fdb26--- /dev/null+++ b/jarvis/society/rooms.py@@ -0,0 +1,297 @@+"""Bounded group discussions — the meeting pavilion, and the token brake.++A room is a deterministic policy over the board (MASTERPLAN §2.2): 2–6+members, at most 3 serial rounds, at most 10 messages, silence allowed. It+is never an open model loop: the policy decides whose turn it is and when+the room settles; models only fill in the words of a ``SAY``.++History lives in ``society_events`` (``ROOM_OPEN → SAY* → ROOM_SETTLE`` on+the room's ``trace_id``); state (members, round, counters, driver state)+lives in ``society_rooms``. A restart reconstructs a room from the row and+continues instead of orphaning it.+"""++from __future__ import annotations++import json+from dataclasses import dataclass+from typing import Any, Final++from .events import MsgType, RoomState, SocietyEnvelope, now_ms+from .failure_reasons import FailureReason+from .store import SocietyStore++__all__ = ["MAX_MEMBERS", "MAX_MESSAGES", "MAX_ROUNDS", "MIN_MEMBERS", "Room", "RoomError", "Rooms"]++MIN_MEMBERS: Final[int] = 2+MAX_MEMBERS: Final[int] = 6+MAX_ROUNDS: Final[int] = 3+MAX_MESSAGES: Final[int] = 10+_MAX_TEXT: Final[int] = 8_000+++class RoomError(ValueError):+ def __init__(self, reason: FailureReason, message: str) -> None:+ super().__init__(message)+ self.reason = reason+++@dataclass(slots=True)+class Room:+ room_id: str+ trace_id: str+ opened_by: str+ topic: str+ members: list[str]+ round: int+ message_count: int+ state: RoomState+ settle_reason: str+ created_ms: int+ updated_ms: int+ #: Members who have had their turn in the current round (spoke or passed).+ turned: list[str]+ #: Whether anybody spoke in the current round.+ spoke_this_round: bool++ @property+ def next_speaker(self) -> str | None:+ if self.state is not RoomState.RUNNING:+ return None+ for member in self.members:+ if member not in self.turned:+ return member+ return None++ def to_dict(self) -> dict[str, Any]:+ return {+ "room_id": self.room_id,+ "trace_id": self.trace_id,+ "opened_by": self.opened_by,+ "topic": self.topic,+ "members": list(self.members),+ "round": self.round,+ "max_rounds": MAX_ROUNDS,+ "message_count": self.message_count,+ "max_messages": MAX_MESSAGES,+ "state": str(self.state),+ "settle_reason": self.settle_reason,+ "next_speaker": self.next_speaker,+ "created_ms": self.created_ms,+ "updated_ms": self.updated_ms,+ }++ @classmethod+ def from_row(cls, row: dict[str, Any]) -> Room:+ members = json.loads(row["members_json"])+ extra = members if isinstance(members, dict) else {"members": members}+ return cls(+ room_id=str(row["room_id"]),+ trace_id=str(row["trace_id"]),+ opened_by=str(row["opened_by"]),+ topic=str(row.get("topic") or ""),+ members=list(extra.get("members", [])),+ round=int(row.get("round") or 0),+ message_count=int(row.get("message_count") or 0),+ state=RoomState(str(row.get("state") or "queued")),+ settle_reason=str(row.get("settle_reason") or ""),+ created_ms=int(row.get("created_ms") or 0),+ updated_ms=int(row.get("updated_ms") or 0),+ turned=list(extra.get("turned", [])),+ spoke_this_round=bool(extra.get("spoke_this_round", False)),+ )++ def _members_json(self) -> str:+ return json.dumps(+ {+ "members": self.members,+ "turned": self.turned,+ "spoke_this_round": self.spoke_this_round,+ }+ )+++class Rooms:+ def __init__(self, store: SocietyStore) -> None:+ self._store = store++ async def open(+ self, *, opened_by: str, members: list[str], topic: str = "", room_id: str | None = None+ ) -> Room:+ unique = list(dict.fromkeys(m.strip() for m in members if m and m.strip()))+ if not MIN_MEMBERS <= len(unique) <= MAX_MEMBERS:+ raise RoomError(+ FailureReason.BLOCKED_BY_POLICY,+ f"a room has {MIN_MEMBERS}-{MAX_MEMBERS} members, not {len(unique)}",+ )+ rid = room_id or f"room-{now_ms():x}-{abs(hash(tuple(unique))) & 0xFFFF:04x}"+ trace_id = f"room:{rid}"+ now = now_ms()+ room = Room(+ room_id=rid,+ trace_id=trace_id,+ opened_by=opened_by,+ topic=topic[:_MAX_TEXT],+ members=unique,+ round=1,+ message_count=0,+ state=RoomState.RUNNING,+ settle_reason="",+ created_ms=now,+ updated_ms=now,+ turned=[],+ spoke_this_round=False,+ )+ await self._store.insert_room(+ {+ "room_id": rid,+ "trace_id": trace_id,+ "opened_by": opened_by,+ "topic": room.topic,+ "members_json": room._members_json(),+ "round": 1,+ "message_count": 0,+ "state": str(RoomState.RUNNING),+ "settle_reason": "",+ "created_ms": now,+ "updated_ms": now,+ }+ )+ await self._store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.ROOM_OPEN,+ from_agent=opened_by,+ to_agent=None,+ trace_id=trace_id,+ payload={+ "room_id": rid,+ "members": unique,+ "text": topic,+ "max_rounds": MAX_ROUNDS,+ "max_messages": MAX_MESSAGES,+ },+ )+ )+ return room++ async def get(self, room_id: str) -> Room | None:+ row = await self._store.get_room_row(room_id)+ return Room.from_row(row) if row else None++ async def list(self, *, state: RoomState | None = None) -> list[Room]:+ rows = await self._store.list_room_rows(state=str(state) if state else None)+ return [Room.from_row(r) for r in rows]++ async def say(self, room_id: str, member: str, text: str, *, cost_usd: float = 0.0) -> Room:+ """``member`` speaks. Refused when it is not their turn or the room+ is not running; settles the room when a cap is reached."""+ room = await self._require_running(room_id)+ self._require_turn(room, member)+ text = (text or "").strip()[:_MAX_TEXT]+ if not text:+ return await self.pass_turn(room_id, member)+ await self._store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.SAY,+ from_agent=member,+ to_agent=None,+ trace_id=room.trace_id,+ cost_usd=cost_usd,+ payload={"room_id": room.room_id, "round": room.round, "text": text},+ )+ )+ room.message_count += 1+ room.spoke_this_round = True+ room.turned.append(member)+ return await self._advance(room)++ async def pass_turn(self, room_id: str, member: str) -> Room:+ """``member`` stays silent this round (silence is allowed)."""+ room = await self._require_running(room_id)+ self._require_turn(room, member)+ room.turned.append(member)+ return await self._advance(room)++ async def settle(self, room_id: str, *, reason: str, by: str = "scheduler") -> Room:+ room = await self.get(room_id)+ if room is None:+ raise RoomError(FailureReason.TARGET_UNKNOWN, f"room {room_id!r} not found")+ if room.state in (RoomState.SETTLED, RoomState.FAILED):+ return room+ room.state = RoomState.SETTLED+ room.settle_reason = reason+ await self._persist(room)+ await self._store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.ROOM_SETTLE,+ from_agent=by,+ to_agent=None,+ trace_id=room.trace_id,+ payload={+ "room_id": room.room_id,+ "reason": reason,+ "rounds": room.round,+ "messages": room.message_count,+ },+ )+ )+ return room++ async def fail(self, room_id: str, *, reason: str) -> Room:+ room = await self.get(room_id)+ if room is None:+ raise RoomError(FailureReason.TARGET_UNKNOWN, f"room {room_id!r} not found")+ room.state = RoomState.FAILED+ room.settle_reason = reason+ await self._persist(room)+ return room++ # ------------------------------------------------------------- policy++ async def _require_running(self, room_id: str) -> Room:+ room = await self.get(room_id)+ if room is None:+ raise RoomError(FailureReason.TARGET_UNKNOWN, f"room {room_id!r} not found")+ if room.state is not RoomState.RUNNING:+ raise RoomError(FailureReason.BLOCKED_BY_POLICY, f"room {room_id!r} is {room.state}")+ return room++ @staticmethod+ def _require_turn(room: Room, member: str) -> None:+ if member not in room.members:+ raise RoomError(FailureReason.TARGET_UNKNOWN, f"{member!r} is not in the room")+ if room.next_speaker != member:+ raise RoomError(+ FailureReason.BLOCKED_BY_POLICY,+ f"not {member!r}'s turn (next: {room.next_speaker!r})",+ )++ async def _advance(self, room: Room) -> Room:+ if room.message_count >= MAX_MESSAGES:+ await self._persist(room)+ return await self.settle(room.room_id, reason="message_cap")+ if len(room.turned) >= len(room.members):+ # A full pass over the members ends the round.+ if not room.spoke_this_round:+ await self._persist(room)+ return await self.settle(room.room_id, reason="silence")+ if room.round >= MAX_ROUNDS:+ await self._persist(room)+ return await self.settle(room.room_id, reason="round_cap")+ room.round += 1+ room.turned = []+ room.spoke_this_round = False+ await self._persist(room)+ return room++ async def _persist(self, room: Room) -> None:+ await self._store.update_room(+ room.room_id,+ {+ "members_json": room._members_json(),+ "round": room.round,+ "message_count": room.message_count,+ "state": str(room.state),+ "settle_reason": room.settle_reason,+ },+ )diff --git a/jarvis/society/scheduler.py b/jarvis/society/scheduler.pynew file mode 100644index 0000000000..d966e2b44e--- /dev/null+++ b/jarvis/society/scheduler.py@@ -0,0 +1,309 @@+"""The scheduler — trusted Python that turns envelopes into activity.++Nothing else in the society may start work. The scheduler consumes the+board and applies, in order, for every ``ASSIGN``:++1. the master kill switch;+2. the tier wall — only ``lead`` and ``orchestrator`` may assign;+3. the delegation depth — an ASSIGN whose parent chain already holds two+ ASSIGNs is refused (depth ≤ 2, no recursion);+4. the target — must resolve to exactly one active agent;+5. the budgets — the global ``BudgetTracker`` pre-spawn check and the+ target's own ``daily_budget_usd`` against today's spend;+6. the target's concurrency cap;+7. the per-trace message cap.++A refusal is itself an event: a ``VETO`` from ``scheduler`` on the same+trace, carrying the typed reason — so the chat card, the ledger and the+voice path all learn why, from the board.++``SAY`` / ``QUERY`` / ``ANSWER`` / ``PROPOSE`` addressed to an agent are+delivered by waking the target's canonical chat (the ``deliver`` hook; the+chat binding provides it in M2). ``RESULT`` is validated against the+handoff record (agent-definition §4.3) and releases the sender's run slot.++The two hooks are injected so the scheduler is testable with fakes and so+the mission machinery is imported only when it is actually used.+"""++from __future__ import annotations++import logging+from collections.abc import Awaitable, Callable+from datetime import UTC, datetime+from typing import Any, Final++from .events import SCHEDULER_ACTOR as _SCHEDULER+from .events import MsgType, SocietyEnvelope, Tier+from .failure_reasons import FailureReason, classify_error, retry_action+from .roster import AgentRecord, AgentState, Roster+from .store import SocietyStore++log = logging.getLogger(__name__)++__all__ = ["DispatchHook", "DeliverHook", "SocietyScheduler", "validate_result"]++#: ``dispatch(target, assign_envelope) -> run_id`` — starts real work under+#: the target's identity and returns the mission/run id it started.+DispatchHook = Callable[[AgentRecord, SocietyEnvelope], Awaitable[str]]+#: ``deliver(target, envelope)`` — wakes the target's canonical chat.+DeliverHook = Callable[[AgentRecord, SocietyEnvelope], Awaitable[None]]++MAX_DEPTH: Final[int] = 2+DEFAULT_TRACE_MESSAGE_CAP: Final[int] = 24+_DELIVERED: Final[frozenset[MsgType]] = frozenset(+ {MsgType.SAY, MsgType.QUERY, MsgType.ANSWER, MsgType.PROPOSE, MsgType.HOLD, MsgType.RELEASE}+)+_RESULT_REQUIRED: Final[tuple[str, ...]] = ("done",)+++def validate_result(payload: dict[str, Any]) -> str | None:+ """``None`` when the handoff record is complete, else what is missing."""+ for key in _RESULT_REQUIRED:+ value = payload.get(key)+ if not isinstance(value, str) or not value.strip():+ return f"RESULT.{key} must be a non-empty string"+ output = payload.get("output")+ open_items = payload.get("open")+ if not output and not open_items:+ return "RESULT needs output (where the work is) or open (what remains)"+ status = payload.get("status", "done")+ if status not in ("done", "partial", "blocked"):+ return "RESULT.status must be done | partial | blocked"+ return None+++def _day_start_ms(now_ms: int) -> int:+ day = datetime.fromtimestamp(now_ms / 1000, tz=UTC).replace(+ hour=0, minute=0, second=0, microsecond=0+ )+ return int(day.timestamp() * 1000)+++class SocietyScheduler:+ def __init__(+ self,+ store: SocietyStore,+ roster: Roster,+ *,+ dispatch: DispatchHook | None = None,+ deliver: DeliverHook | None = None,+ budget_tracker: Any | None = None,+ trace_message_cap: int = DEFAULT_TRACE_MESSAGE_CAP,+ ) -> None:+ self._store = store+ self._roster = roster+ self._dispatch = dispatch+ self._deliver = deliver+ self._budget = budget_tracker+ self._trace_cap = trace_message_cap+ #: run_id → agent_id of work the scheduler started and has not seen end.+ self._running: dict[str, str] = {}+ self._unsubscribe: Callable[[], None] | None = None++ # ------------------------------------------------------------ wiring++ def attach(self) -> SocietyScheduler:+ if self._unsubscribe is None:+ self._unsubscribe = self._store.bus.subscribe_all(self.on_envelope)+ return self++ def detach(self) -> None:+ if self._unsubscribe is not None:+ self._unsubscribe()+ self._unsubscribe = None++ @property+ def running(self) -> dict[str, str]:+ return dict(self._running)++ def active_runs(self, agent_id: str) -> int:+ return sum(1 for a in self._running.values() if a == agent_id)++ def note_run_started(self, run_id: str, agent_id: str) -> None:+ self._running[run_id] = agent_id++ def note_run_ended(self, run_id: str) -> str | None:+ return self._running.pop(run_id, None)++ async def halt_all(self) -> int:+ """Kill switch engaged: forget every run slot; returns how many."""+ count = len(self._running)+ self._running.clear()+ return count++ # ------------------------------------------------------------ handler++ async def on_envelope(self, env: SocietyEnvelope) -> None:+ if env.from_agent == _SCHEDULER:+ return+ if env.msg_type is MsgType.ASSIGN:+ await self._on_assign(env)+ elif env.msg_type is MsgType.RESULT:+ await self._on_result(env)+ elif env.msg_type in _DELIVERED and env.to_agent:+ await self._on_deliver(env)++ async def _veto(self, env: SocietyEnvelope, reason: FailureReason, detail: str) -> None:+ log.info(+ "society scheduler: %s on %s from %s: %s", reason, env.msg_type, env.from_agent, detail+ )+ await self._store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.VETO,+ from_agent=_SCHEDULER,+ to_agent=env.from_agent,+ trace_id=env.trace_id,+ parent_event_id=env.event_id,+ payload={+ "reason": str(reason),+ "retry": str(retry_action(reason)),+ "text": detail,+ "vetoed_event_id": env.event_id,+ },+ )+ )++ async def _depth(self, env: SocietyEnvelope) -> int:+ """How many ASSIGNs sit on the parent chain, this one included."""+ depth = 1+ parent_id = env.parent_event_id+ seen: set[str] = set()+ events = {e.event_id: e for e in await self._store.events_for_trace(env.trace_id)}+ while parent_id and parent_id not in seen:+ seen.add(parent_id)+ parent = events.get(parent_id)+ if parent is None:+ break+ if parent.msg_type is MsgType.ASSIGN:+ depth += 1+ parent_id = parent.parent_event_id+ return depth++ async def _resolve_target(self, env: SocietyEnvelope) -> AgentRecord | FailureReason:+ if not env.to_agent:+ return FailureReason.TARGET_UNKNOWN+ target = await self._roster.resolve(env.to_agent)+ if target is None:+ return FailureReason.TARGET_UNKNOWN+ if target.state is AgentState.ARCHIVED:+ return FailureReason.TARGET_UNKNOWN+ if target.state is AgentState.PAUSED:+ return FailureReason.TARGET_PAUSED+ return target++ async def _on_assign(self, env: SocietyEnvelope) -> None:+ if await self._store.kill_switch():+ await self._veto(env, FailureReason.KILL_SWITCH, "the society is halted")+ return+ sender = await self._roster.resolve(env.from_agent)+ if env.from_agent != "user" and (sender is None or not sender.may_assign):+ await self._veto(+ env, FailureReason.TIER_NOT_ALLOWED, "only the lead and orchestrators may assign"+ )+ return+ if sender is not None and sender.tier is Tier.SPECIALIST:+ await self._veto(env, FailureReason.TIER_NOT_ALLOWED, "a specialist cannot assign")+ return+ depth = await self._depth(env)+ if depth > MAX_DEPTH:+ await self._veto(+ env, FailureReason.DEPTH_EXCEEDED, f"delegation depth {depth} > {MAX_DEPTH}"+ )+ return+ target = await self._resolve_target(env)+ if isinstance(target, FailureReason):+ await self._veto(env, target, f"target {env.to_agent!r} cannot take work")+ return+ if target.agent_id == env.from_agent:+ await self._veto(+ env, FailureReason.BLOCKED_BY_POLICY, "an agent cannot assign to itself"+ )+ return+ if await self._store.count_in_trace(env.trace_id) > self._trace_cap:+ await self._veto(+ env, FailureReason.MESSAGE_CAP, f"trace exceeded {self._trace_cap} messages"+ )+ return+ if self._budget is not None:+ try:+ self._budget.assert_under_limit(env.trace_id)+ except Exception as exc: # noqa: BLE001 — BudgetExceeded is the tracker's own type+ await self._veto(env, FailureReason.BUDGET_EXHAUSTED, str(exc))+ return+ if target.daily_budget_usd > 0:+ spent = await self._store.cost_since(target.agent_id, _day_start_ms(env.ts_ms))+ if spent >= target.daily_budget_usd:+ await self._veto(+ env,+ FailureReason.BUDGET_EXHAUSTED,+ f"{target.name} spent ${spent:.2f} of ${target.daily_budget_usd:.2f} today",+ )+ return+ if self.active_runs(target.agent_id) >= target.max_concurrent_runs:+ await self._veto(+ env,+ FailureReason.CONCURRENCY_CAP,+ f"{target.name} already runs {target.max_concurrent_runs} task(s)",+ )+ return+ if self._dispatch is None:+ await self._veto(env, FailureReason.INTERNAL_ERROR, "no dispatcher is wired")+ return+ try:+ run_id = await self._dispatch(target, env)+ except Exception as exc: # noqa: BLE001 — a failed spawn is a typed veto, never a crash+ await self._veto(env, classify_error(exc), f"dispatch failed: {exc}")+ return+ self._running[run_id] = target.agent_id+ await self._store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.CLAIM,+ from_agent=target.agent_id,+ to_agent=env.from_agent,+ trace_id=env.trace_id,+ parent_event_id=env.event_id,+ payload={"run_id": run_id, "text": f"{target.name} took the task"},+ )+ )++ async def _on_result(self, env: SocietyEnvelope) -> None:+ problem = validate_result(env.payload)+ if problem is not None:+ await self._veto(env, FailureReason.INVALID_RESULT, problem)+ return+ run_id = env.payload.get("run_id")+ if isinstance(run_id, str):+ self._running.pop(run_id, None)+ else:+ # No run id: release one slot of the sender, oldest first.+ for rid, agent in list(self._running.items()):+ if agent == env.from_agent:+ self._running.pop(rid, None)+ break+ next_owner = env.payload.get("next_owner")+ if isinstance(next_owner, str) and next_owner and self._deliver is not None:+ target = await self._resolve_target(env.model_copy(update={"to_agent": next_owner}))+ if isinstance(target, AgentRecord):+ await self._deliver(target, env)++ async def _on_deliver(self, env: SocietyEnvelope) -> None:+ if await self._store.kill_switch():+ await self._veto(env, FailureReason.KILL_SWITCH, "the society is halted")+ return+ if await self._store.count_in_trace(env.trace_id) > self._trace_cap:+ await self._veto(+ env, FailureReason.MESSAGE_CAP, f"trace exceeded {self._trace_cap} messages"+ )+ return+ target = await self._resolve_target(env)+ if isinstance(target, FailureReason):+ await self._veto(env, target, f"target {env.to_agent!r} cannot receive")+ return+ if self._deliver is None:+ log.debug("society scheduler: no deliverer wired; %s stays in the inbox", env.msg_type)+ return+ try:+ await self._deliver(target, env)+ except Exception as exc: # noqa: BLE001 — delivery failure is a typed veto+ await self._veto(env, classify_error(exc), f"delivery failed: {exc}")diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txtindex 7dcca2422c..8091fb6107 100644--- a/scripts/ci/german-allowlist.txt+++ b/scripts/ci/german-allowlist.txt@@ -478,3 +478,7 @@ tests/unit/dictation/test_prompt_mode.py# USER.md capture recognises ARE the content under test, and the negative# corpus only proves precision if it holds real German near-misses ---tests/unit/memory/test_profile_capture.py++# --- Agent society (2026-09-01): the focus alias table maps the words people+# write in agent descriptions (de/en) onto capability ids ---+jarvis/society/focus.pydiff --git a/tests/unit/society/test_bridge.py b/tests/unit/society/test_bridge.pynew file mode 100644index 0000000000..1b87707ae4--- /dev/null+++ b/tests/unit/society/test_bridge.py@@ -0,0 +1,95 @@+"""Mission envelopes reach the board attributed to the right agent."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.society.bridge import MissionBridge+from jarvis.society.events import MsgType+from jarvis.society.store import SocietyStore+++class FakeMissionBus:+ def __init__(self) -> None:+ self.handlers = []++ def subscribe_all(self, handler):+ self.handlers.append(handler)++ def _off():+ self.handlers.remove(handler)++ return _off++ async def publish(self, env):+ for h in list(self.handlers):+ await h(env)+++def _env(mission_id: str, event_type: str, **fields):+ return SimpleNamespace(+ mission_id=mission_id, payload=SimpleNamespace(event_type=event_type, **fields)+ )+++async def setup(tmp_path: Path):+ store = SocietyStore(tmp_path / "society.db")+ await store.open()+ bus = FakeMissionBus()+ owners = {"m-scout": "scout"}+ ended: list[str] = []+ bridge = MissionBridge(store, owner_of=owners.get, on_run_ended=ended.append).attach(bus)+ try:+ yield store, bus, ended, bridge+ finally:+ bridge.detach()+ await store.close()+++async def test_owned_mission_is_attributed_and_costed(setup):+ store, bus, ended, _ = setup+ await bus.publish(_env("m-scout", "MissionDispatched", prompt="find things"))+ await bus.publish(_env("m-scout", "WorkerSpawned", cli="claude", model="x"))+ await bus.publish(_env("m-scout", "WorkerDraftReady", cost_usd=0.4))+ await bus.publish(_env("m-scout", "MissionApproved", summary="all good"))+ events = await store.events_for_trace("mission:m-scout")+ assert [e.msg_type for e in events] == [+ MsgType.CLAIM,+ MsgType.DIGEST,+ MsgType.DIGEST,+ MsgType.RESULT,+ ]+ assert all(e.from_agent == "scout" for e in events)+ assert events[-1].payload["status"] == "done"+ assert events[-1].to_agent == "jarvis"+ assert (await store.agent_stats("scout"))["total_cost_usd"] == pytest.approx(0.4)+ assert ended == ["m-scout"]+++async def test_unowned_mission_belongs_to_the_lead(setup):+ store, bus, _, _ = setup+ await bus.publish(_env("m-other", "MissionDispatched", prompt="p"))+ await bus.publish(_env("m-other", "MissionFailed", error="quota"))+ events = await store.events_for_trace("mission:m-other")+ assert [e.from_agent for e in events] == ["jarvis", "jarvis"]+ assert events[-1].payload["status"] == "blocked"+ assert events[-1].payload["open"] == ["quota"]+ assert events[-1].to_agent is None+++async def test_noise_is_not_mirrored(setup):+ store, bus, _, _ = setup+ await bus.publish(_env("m-scout", "WorkerProgress", pct=0.5))+ await bus.publish(_env("m-scout", "BusStats"))+ await bus.publish(SimpleNamespace(mission_id="", payload=None))+ assert await store.events_since(0) == []+++async def test_bridge_never_raises_into_the_mission_bus(setup):+ store, bus, _, _ = setup+ await store.close() # the store is gone; the bridge must swallow and log+ await bus.publish(_env("m-scout", "MissionDispatched", prompt="p"))diff --git a/tests/unit/society/test_capabilities.py b/tests/unit/society/test_capabilities.pynew file mode 100644index 0000000000..090ca1ff5a--- /dev/null+++ b/tests/unit/society/test_capabilities.py@@ -0,0 +1,127 @@+"""One catalog over plugins, CLIs, MCPs, skills and core; dispatch never inside."""++from __future__ import annotations++from types import SimpleNamespace++from jarvis.society.capabilities import (+ NEVER_GRANTED,+ CapabilityKind,+ build_catalog,+ capability_id_for_tool,+ select_tools,+ tool_name_for_capability,+)+++def _tool(name: str, desc: str = "does things.", tier: str = "monitor") -> SimpleNamespace:+ return SimpleNamespace(name=name, description=desc, risk_tier=tier, schema={})+++def _skill(slug: str, state: str = "active", desc: str = "A skill.") -> SimpleNamespace:+ return SimpleNamespace(+ slug=slug,+ state=SimpleNamespace(value=state),+ frontmatter=SimpleNamespace(name=slug, description=desc, title=None),+ path=SimpleNamespace(stem=slug),+ )+++TOOLS = {+ "gmail": _tool("gmail", "Read and send mail via Gmail. Also drafts."),+ "cli_gh": _tool("cli_gh", "Run gh commands."),+ "github/create_issue": _tool(+ "github/create_issue", "[ACTION-ONLY · MCP: github] Create an issue."+ ),+ "search-web": _tool("search-web", "Search the web.", "safe"),+ "spawn-worker": _tool("spawn-worker", "Spawn a worker."),+ "navigate": _tool("navigate", "Switch sidebar section."),+ "wiki-recall": _tool("wiki-recall", "Search the wiki.", "safe"),+}+++def test_ids_by_kind():+ assert capability_id_for_tool("gmail") == "plugin:gmail"+ assert capability_id_for_tool("cli_gh") == "cli:gh"+ assert capability_id_for_tool("github/create_issue") == "mcp:github/create_issue"+ assert capability_id_for_tool("search-web") == "core:search-web"+ assert capability_id_for_tool("spawn-worker") is None+ for name in NEVER_GRANTED:+ assert capability_id_for_tool(name) is None+++def test_ids_roundtrip_to_tool_names():+ for name in ("gmail", "cli_gh", "github/create_issue", "search-web"):+ cap = capability_id_for_tool(name)+ assert cap is not None+ assert tool_name_for_capability(cap) == name+ assert tool_name_for_capability("skill:daily-brief") is None+++def test_catalog_groups_orders_and_filters():+ rows = build_catalog(TOOLS, [_skill("daily-brief"), _skill("draft-one", state="draft")])+ ids = [r.id for r in rows]+ assert ids == [+ "plugin:gmail",+ "cli:gh",+ "mcp:github/create_issue",+ "skill:daily-brief",+ "core:search-web",+ "core:wiki-recall",+ ]+ gmail = rows[0]+ assert gmail.kind is CapabilityKind.PLUGIN+ assert gmail.one_liner == "Read and send mail via Gmail."+ mcp = rows[2]+ assert mcp.one_liner == "Create an issue."+ assert mcp.aliases == ("github",)+ assert all("spawn" not in r.id and "navigate" not in r.id for r in rows)+++def test_catalog_marks_disconnected_and_sorts_them_last():+ tools = {"gmail": _tool("gmail"), "spotify": _tool("spotify")}+ rows = build_catalog(tools, connected=lambda name, kind: name != "gmail")+ assert [(r.id, r.connected) for r in rows] == [+ ("plugin:spotify", True),+ ("plugin:gmail", False),+ ]+++def test_select_tools_all_mode_focus_first_denies_out():+ picked = select_tools(+ TOOLS,+ grant_mode="all",+ grants=[],+ focus=["plugin:gmail"],+ denies=["core:wiki-recall"],+ )+ names = list(picked)+ assert names[0] == "gmail"+ assert "wiki-recall" not in names+ assert "spawn-worker" not in names and "navigate" not in names+ assert names[1:] == sorted(names[1:], key=lambda n: capability_id_for_tool(n) or "")+++def test_select_tools_allowlist_mode():+ picked = select_tools(+ TOOLS,+ grant_mode="allowlist",+ grants=["plugin:gmail", "core:search-web", "plugin:spawn-worker"],+ focus=[],+ denies=[],+ )+ assert set(picked) == {"gmail", "search-web"}+++def test_select_tools_is_deterministic():+ a = list(select_tools(TOOLS, grant_mode="all", grants=[], focus=["cli:gh"], denies=[]))+ b = list(+ select_tools(+ dict(reversed(list(TOOLS.items()))),+ grant_mode="all",+ grants=[],+ focus=["cli:gh"],+ denies=[],+ )+ )+ assert a == bdiff --git a/tests/unit/society/test_focus.py b/tests/unit/society/test_focus.pynew file mode 100644index 0000000000..859f2c2c1b--- /dev/null+++ b/tests/unit/society/test_focus.py@@ -0,0 +1,93 @@+"""Focus and approval rules are derived from the description, no model call."""++from __future__ import annotations++from types import SimpleNamespace++from jarvis.society.capabilities import build_catalog+from jarvis.society.focus import derive_approval_rules, derive_focus+++def _tool(name: str, desc: str = "x.") -> SimpleNamespace:+ return SimpleNamespace(name=name, description=desc, risk_tier="monitor", schema={})+++CATALOG = build_catalog(+ {+ "gmail": _tool("gmail", "Read and send mail."),+ "google-calendar": _tool("google-calendar", "Calendar events."),+ "cli_gh": _tool("cli_gh", "GitHub CLI."),+ "search-web": _tool("search-web", "Search the web."),+ "wiki-recall": _tool("wiki-recall", "Search the wiki."),+ "notebooklm/ask": _tool("notebooklm/ask", "Ask NotebookLM."),+ }+)+++def test_gmail_agent_gets_gmail_first():+ focus = derive_focus(+ "Gmail agent",+ "You read, sort and answer my mail; external mail only after approval.",+ CATALOG,+ )+ assert focus[0] == "plugin:gmail"+++def test_german_description_works_too():+ focus = derive_focus(+ "Mail-Assistent", # i18n-allow: sample agent title+ "Du liest mein Postfach und trägst Termine in den Kalender ein.", # i18n-allow: sample+ CATALOG,+ )+ assert focus[:2] == ["plugin:gmail", "plugin:google-calendar"] or set(focus[:2]) == {+ "plugin:gmail",+ "plugin:google-calendar",+ }+++def test_mcp_server_name_is_reachable_without_a_table_entry():+ focus = derive_focus("Notebook helper", "Use NotebookLM for every question.", CATALOG)+ assert focus[0] == "mcp:notebooklm/ask"+++def test_unknown_capabilities_never_come_back():+ focus = derive_focus("DJ", "Play spotify playlists all day.", CATALOG)+ assert "plugin:spotify" not in focus+++def test_empty_text_yields_nothing():+ assert derive_focus("", "", CATALOG) == []+++def test_focus_is_deterministic_and_limited():+ text = "mail calendar github web wiki notebooklm search inbox pr issues"+ a = derive_focus("all", text, CATALOG, limit=3)+ b = derive_focus("all", text, CATALOG, limit=3)+ assert a == b and len(a) == 3+++def test_approval_rules_from_the_boundary_phrase():+ rules = derive_approval_rules("External mail only after approval.", ["plugin:gmail"])+ assert rules == {"require_approval": ["plugin:gmail:send"], "always_allow": []}+ rules_de = derive_approval_rules(+ "Externe Mails nur nach Freigabe.", # i18n-allow: sample description+ ["plugin:gmail", "cli:gh"],+ )+ assert rules_de["require_approval"] == [+ "cli:gh:close",+ "cli:gh:create",+ "cli:gh:merge",+ "plugin:gmail:send",+ ]+++def test_no_boundary_no_rules():+ assert derive_approval_rules("Just do it.", ["plugin:gmail"]) == {+ "require_approval": [],+ "always_allow": [],+ }+++def test_boundary_without_known_verbs_gates_the_whole_capability():+ rules = derive_approval_rules("Ask me before anything.", ["plugin:drive", "core:search-web"])+ assert rules["require_approval"] == ["plugin:drive:*"]diff --git a/tests/unit/society/test_rooms.py b/tests/unit/society/test_rooms.pynew file mode 100644index 0000000000..fc4368087e--- /dev/null+++ b/tests/unit/society/test_rooms.py@@ -0,0 +1,120 @@+"""Rooms: 2-6 members, <=3 rounds, <=10 messages, silence allowed, deterministic."""++from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.society.events import MsgType, RoomState+from jarvis.society.failure_reasons import FailureReason+from jarvis.society.rooms import MAX_MESSAGES, MAX_ROUNDS, RoomError, Rooms+from jarvis.society.store import SocietyStore+++async def rooms(tmp_path: Path):+ store = SocietyStore(tmp_path / "society.db")+ await store.open()+ try:+ yield Rooms(store), store+ finally:+ await store.close()+++async def test_member_bounds(rooms):+ service, _ = rooms+ with pytest.raises(RoomError) as exc:+ await service.open(opened_by="jarvis", members=["a"])+ assert exc.value.reason is FailureReason.BLOCKED_BY_POLICY+ with pytest.raises(RoomError):+ await service.open(opened_by="jarvis", members=list("abcdefg"))+ room = await service.open(opened_by="jarvis", members=["a", "b", "a"], topic="plan")+ assert room.members == ["a", "b"]+ assert room.state is RoomState.RUNNING+ assert room.next_speaker == "a"+++async def test_open_writes_room_open_event(rooms):+ service, store = rooms+ room = await service.open(opened_by="jarvis", members=["a", "b"], topic="t")+ events = await store.events_for_trace(room.trace_id)+ assert [e.msg_type for e in events] == [MsgType.ROOM_OPEN]+ assert events[0].payload["members"] == ["a", "b"]+++async def test_turn_order_is_enforced(rooms):+ service, _ = rooms+ room = await service.open(opened_by="jarvis", members=["a", "b"])+ with pytest.raises(RoomError):+ await service.say(room.room_id, "b", "me first")+ with pytest.raises(RoomError) as exc:+ await service.say(room.room_id, "zed", "hi")+ assert exc.value.reason is FailureReason.TARGET_UNKNOWN+ room = await service.say(room.room_id, "a", "hello")+ assert room.next_speaker == "b"+ assert room.message_count == 1+++async def test_round_cap_settles(rooms):+ service, store = rooms+ room = await service.open(opened_by="jarvis", members=["a", "b"])+ for _ in range(MAX_ROUNDS):+ room = await service.say(room.room_id, "a", "x")+ room = await service.say(room.room_id, "b", "y")+ assert room.state is RoomState.SETTLED+ assert room.settle_reason == "round_cap"+ assert room.round == MAX_ROUNDS+ events = await store.events_for_trace(room.trace_id)+ assert events[-1].msg_type is MsgType.ROOM_SETTLE+ with pytest.raises(RoomError):+ await service.say(room.room_id, "a", "more")+++async def test_message_cap_settles(rooms):+ service, _ = rooms+ room = await service.open(opened_by="jarvis", members=list("abcdef"))+ speakers = room.members+ i = 0+ while room.state is RoomState.RUNNING:+ room = await service.say(room.room_id, speakers[i % 6], f"m{i}")+ i += 1+ assert room.settle_reason == "message_cap"+ assert room.message_count == MAX_MESSAGES+++async def test_silence_settles(rooms):+ service, _ = rooms+ room = await service.open(opened_by="jarvis", members=["a", "b"])+ room = await service.say(room.room_id, "a", "one thing")+ room = await service.pass_turn(room.room_id, "b")+ assert room.round == 2 and room.state is RoomState.RUNNING+ room = await service.pass_turn(room.room_id, "a")+ room = await service.say(room.room_id, "b", "") # empty = silence+ assert room.state is RoomState.SETTLED+ assert room.settle_reason == "silence"+++async def test_room_survives_reopen(rooms, tmp_path: Path):+ service, store = rooms+ room = await service.open(opened_by="jarvis", members=["a", "b"])+ await service.say(room.room_id, "a", "hi")+ again = Rooms(store)+ loaded = await again.get(room.room_id)+ assert loaded is not None+ assert loaded.next_speaker == "b"+ assert loaded.message_count == 1+ assert (await again.list(state=RoomState.RUNNING))[0].room_id == room.room_id+++async def test_manual_settle_and_fail(rooms):+ service, _ = rooms+ room = await service.open(opened_by="jarvis", members=["a", "b"])+ settled = await service.settle(room.room_id, reason="kill_switch")+ assert settled.state is RoomState.SETTLED+ assert (await service.settle(room.room_id, reason="again")).settle_reason == "kill_switch"+ other = await service.open(opened_by="jarvis", members=["c", "d"])+ failed = await service.fail(other.room_id, reason="boom")+ assert failed.state is RoomState.FAILED+ with pytest.raises(RoomError):+ await service.settle("nope", reason="x")diff --git a/tests/unit/society/test_scheduler.py b/tests/unit/society/test_scheduler.pynew file mode 100644index 0000000000..9e80123c66--- /dev/null+++ b/tests/unit/society/test_scheduler.py@@ -0,0 +1,278 @@+"""The scheduler: tier wall, depth, target, budget, caps, kill switch, RESULT."""++from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.society.events import MsgType, SocietyEnvelope, Tier+from jarvis.society.failure_reasons import FailureReason+from jarvis.society.roster import AgentRecord, Roster+from jarvis.society.scheduler import SocietyScheduler, validate_result+from jarvis.society.store import SocietyStore+++class FakeDispatcher:+ def __init__(self, *, fail: Exception | None = None) -> None:+ self.calls: list[tuple[str, str]] = []+ self.fail = fail+ self._n = 0++ async def __call__(self, target: AgentRecord, env: SocietyEnvelope) -> str:+ if self.fail is not None:+ raise self.fail+ self._n += 1+ self.calls.append((target.agent_id, env.trace_id))+ return f"run-{self._n}"+++class FakeDeliverer:+ def __init__(self) -> None:+ self.delivered: list[tuple[str, MsgType]] = []++ async def __call__(self, target: AgentRecord, env: SocietyEnvelope) -> None:+ self.delivered.append((target.agent_id, env.msg_type))+++class FakeBudget:+ def __init__(self, *, exceeded: bool = False) -> None:+ self.exceeded = exceeded++ def assert_under_limit(self, trace_id: str) -> None:+ if self.exceeded:+ raise RuntimeError("Daily limit exceeded")+++async def world(tmp_path: Path):+ store = SocietyStore(tmp_path / "society.db")+ await store.open()+ roster = Roster(store)+ await roster.create(name="Jarvis", tier=Tier.LEAD)+ await roster.create(name="Planner", tier=Tier.ORCHESTRATOR)+ await roster.create(name="Scout")+ await roster.create(name="Archivist")+ dispatcher = FakeDispatcher()+ deliverer = FakeDeliverer()+ scheduler = SocietyScheduler(+ store, roster, dispatch=dispatcher, deliver=deliverer, budget_tracker=FakeBudget()+ ).attach()+ try:+ yield store, roster, scheduler, dispatcher, deliverer+ finally:+ scheduler.detach()+ await store.close()+++def _assign(frm: str, to: str, trace: str = "t1", parent: str | None = None) -> SocietyEnvelope:+ return SocietyEnvelope(+ msg_type=MsgType.ASSIGN,+ from_agent=frm,+ to_agent=to,+ trace_id=trace,+ parent_event_id=parent,+ payload={"text": "do the thing"},+ )+++async def _vetoes(store: SocietyStore, trace: str) -> list[str]:+ return [+ e.payload["reason"]+ for e in await store.events_for_trace(trace)+ if e.msg_type is MsgType.VETO+ ]+++async def test_lead_assign_dispatches_and_claims(world):+ store, _, scheduler, dispatcher, _ = world+ await store.append_and_publish(_assign("jarvis", "scout"))+ assert dispatcher.calls == [("scout", "t1")]+ types = [e.msg_type for e in await store.events_for_trace("t1")]+ assert types == [MsgType.ASSIGN, MsgType.CLAIM]+ assert scheduler.running == {"run-1": "scout"}+++async def test_specialist_cannot_assign(world):+ store, _, _, dispatcher, _ = world+ await store.append_and_publish(_assign("scout", "archivist"))+ assert dispatcher.calls == []+ assert await _vetoes(store, "t1") == [str(FailureReason.TIER_NOT_ALLOWED)]+++async def test_unknown_sender_cannot_assign(world):+ store, _, _, dispatcher, _ = world+ await store.append_and_publish(_assign("ghost", "scout"))+ assert dispatcher.calls == []+ assert await _vetoes(store, "t1") == [str(FailureReason.TIER_NOT_ALLOWED)]+++async def test_user_may_assign(world):+ store, _, _, dispatcher, _ = world+ await store.append_and_publish(_assign("user", "scout"))+ assert dispatcher.calls == [("scout", "t1")]+++async def test_depth_wall(world):+ store, roster, _, dispatcher, _ = world+ await roster.create(name="Deputy", tier=Tier.ORCHESTRATOR)+ first = await store.append_and_publish(_assign("jarvis", "planner"))+ second = await store.append_and_publish(_assign("planner", "deputy", parent=first.event_id))+ await store.append_and_publish(_assign("deputy", "scout", parent=second.event_id))+ assert [c[0] for c in dispatcher.calls] == ["planner", "deputy"]+ assert await _vetoes(store, "t1") == [str(FailureReason.DEPTH_EXCEEDED)]+++async def test_target_rules(world):+ store, roster, _, dispatcher, _ = world+ await store.append_and_publish(_assign("jarvis", "nobody", trace="a"))+ await roster.update("scout", {"state": "paused"})+ await store.append_and_publish(_assign("jarvis", "scout", trace="b"))+ await store.append_and_publish(_assign("jarvis", "jarvis", trace="c"))+ assert dispatcher.calls == []+ assert await _vetoes(store, "a") == [str(FailureReason.TARGET_UNKNOWN)]+ assert await _vetoes(store, "b") == [str(FailureReason.TARGET_PAUSED)]+ assert await _vetoes(store, "c") == [str(FailureReason.BLOCKED_BY_POLICY)]+++async def test_kill_switch_halts_everything(world):+ store, _, scheduler, dispatcher, deliverer = world+ await store.set_kill_switch(True)+ await store.append_and_publish(_assign("jarvis", "scout"))+ await store.append_and_publish(+ SocietyEnvelope(msg_type=MsgType.SAY, from_agent="jarvis", to_agent="scout", trace_id="t2")+ )+ assert dispatcher.calls == [] and deliverer.delivered == []+ assert await _vetoes(store, "t1") == [str(FailureReason.KILL_SWITCH)]+ assert await _vetoes(store, "t2") == [str(FailureReason.KILL_SWITCH)]+++async def test_global_budget_vetoes(tmp_path: Path):+ store = SocietyStore(tmp_path / "b.db")+ await store.open()+ roster = Roster(store)+ await roster.create(name="Jarvis", tier=Tier.LEAD)+ await roster.create(name="Scout")+ dispatcher = FakeDispatcher()+ SocietyScheduler(+ store, roster, dispatch=dispatcher, budget_tracker=FakeBudget(exceeded=True)+ ).attach()+ await store.append_and_publish(_assign("jarvis", "scout"))+ assert dispatcher.calls == []+ assert await _vetoes(store, "t1") == [str(FailureReason.BUDGET_EXHAUSTED)]+ await store.close()+++async def test_agent_daily_budget_vetoes(world):+ store, roster, _, dispatcher, _ = world+ await roster.update("scout", {"daily_budget_usd": 1.0})+ await store.append_and_publish(+ SocietyEnvelope(msg_type=MsgType.DIGEST, from_agent="scout", trace_id="old", cost_usd=1.5)+ )+ await store.append_and_publish(_assign("jarvis", "scout"))+ assert dispatcher.calls == []+ assert await _vetoes(store, "t1") == [str(FailureReason.BUDGET_EXHAUSTED)]+++async def test_concurrency_cap_and_result_release(world):+ store, _, scheduler, dispatcher, _ = world+ await store.append_and_publish(_assign("jarvis", "scout", trace="a"))+ await store.append_and_publish(_assign("jarvis", "scout", trace="b"))+ assert [c[1] for c in dispatcher.calls] == ["a"]+ assert await _vetoes(store, "b") == [str(FailureReason.CONCURRENCY_CAP)]+ await store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.RESULT,+ from_agent="scout",+ to_agent="jarvis",+ trace_id="a",+ payload={"run_id": "run-1", "done": "did it", "output": ["file:x"]},+ )+ )+ assert scheduler.running == {}+ await store.append_and_publish(_assign("jarvis", "scout", trace="c"))+ assert [c[1] for c in dispatcher.calls] == ["a", "c"]+++async def test_invalid_result_is_vetoed(world):+ store, _, _, _, _ = world+ await store.append_and_publish(+ SocietyEnvelope(msg_type=MsgType.RESULT, from_agent="scout", trace_id="r", payload={})+ )+ assert await _vetoes(store, "r") == [str(FailureReason.INVALID_RESULT)]+++def test_validate_result_rules():+ assert validate_result({"done": "x", "output": ["a"]}) is None+ assert validate_result({"done": "x", "open": ["a"]}) is None+ assert validate_result({"done": "", "output": ["a"]}) is not None+ assert validate_result({"done": "x"}) is not None+ assert validate_result({"done": "x", "output": ["a"], "status": "weird"}) is not None+++async def test_result_with_next_owner_is_delivered(world):+ store, _, _, _, deliverer = world+ await store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.RESULT,+ from_agent="scout",+ trace_id="r",+ payload={"done": "x", "output": ["a"], "next_owner": "archivist"},+ )+ )+ assert deliverer.delivered == [("archivist", MsgType.RESULT)]+++async def test_say_is_delivered_and_capped(world):+ store, _, _, _, deliverer = world+ for _ in range(3):+ await store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.SAY, from_agent="scout", to_agent="archivist", trace_id="s"+ )+ )+ assert deliverer.delivered == [("archivist", MsgType.SAY)] * 3+ await store.append_and_publish(+ SocietyEnvelope(msg_type=MsgType.SAY, from_agent="scout", to_agent="ghost", trace_id="s")+ )+ assert await _vetoes(store, "s") == [str(FailureReason.TARGET_UNKNOWN)]+++async def test_trace_message_cap(tmp_path: Path):+ store = SocietyStore(tmp_path / "c.db")+ await store.open()+ roster = Roster(store)+ await roster.create(name="Scout")+ await roster.create(name="Archivist")+ deliverer = FakeDeliverer()+ SocietyScheduler(store, roster, deliver=deliverer, trace_message_cap=2).attach()+ for _ in range(4):+ await store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.SAY, from_agent="scout", to_agent="archivist", trace_id="s"+ )+ )+ assert len(deliverer.delivered) == 2+ assert FailureReason.MESSAGE_CAP in await _vetoes(store, "s")+ await store.close()+++async def test_dispatch_failure_becomes_typed_veto(tmp_path: Path):+ store = SocietyStore(tmp_path / "d.db")+ await store.open()+ roster = Roster(store)+ await roster.create(name="Jarvis", tier=Tier.LEAD)+ await roster.create(name="Scout")+ SocietyScheduler(+ store, roster, dispatch=FakeDispatcher(fail=RuntimeError("401 unauthorized"))+ ).attach()+ await store.append_and_publish(_assign("jarvis", "scout"))+ assert await _vetoes(store, "t1") == [str(FailureReason.AUTH_FAILED)]+ await store.close()+++async def test_no_spawn_tool_in_never_granted_is_a_dispatch_path(world):+ """AP-5/14: the only way work starts is the scheduler's dispatch hook."""+ from jarvis.society.capabilities import NEVER_GRANTED++ assert {"spawn-worker", "spawn-subagents", "multi-spawn"} <= NEVER_GRANTED