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): agents walk to the shop of the tools they use, and a typed turn counts as work
rubenluetke10-beep850b1b8782f4
diff --git a/docs/agent-society/world-behaviour-manual.md b/docs/agent-society/world-behaviour-manual.mdindex b4718b390f..34b0529a8f 100644--- a/docs/agent-society/world-behaviour-manual.md+++ b/docs/agent-society/world-behaviour-manual.md@@ -35,9 +35,10 @@ gesture becomes a typed event, and the figure follows because the truth changed.| `foundry` | Agent Foundry | being created (3 s), or changing its avatar || `wander` | the square and its own street | idle; the rest-biased model picks the beats |-V1 ships `desk | meeting | archive | gate | idle` (`data.ts`); this table is the M3d superset.-`hub:*` values join the five-layer parity set (Python enum ↔ SQL CHECK ↔ Pydantic ↔ TS ↔ UI, AP-4)-when they land in the schema — never as free strings.+Shipped vocabulary (2026-09-02): `desk | meeting | archive | gate | idle | hub:plugins | hub:skills |+hub:mcp | hub:cli` — in all five layers (Python enum ↔ SQL CHECK ↔ Pydantic ↔ TS ↔ UI, AP-4; an+older `society.db` is rebuilt to the wider CHECK on open). `home`, `gallery`, `hub:workshop` and+`hub:models` are still this table's superset and join the same way — never as free strings.## 3. Derivation — who decides the place (trusted Python, no LLM)@@ -53,7 +54,7 @@ sees. Rules, in priority order; the first that matches wins:capability catalog of `agent-definition.md` §3.1). The place changes only when a differentfamily has dominated for **≥ 20 s** — hysteresis, so a figure never ping-pongs between shops.A local-brain agent whose model is inferring right now → `hub:models` outranks the family.-6. A memory touch in the last 60 s → `archive` (the Memory House). **Built:** `jarvis/society/checkpoints.py` derives `paused → idle`, `gate`, `meeting`, `archive`, `desk`, `idle` over today's vocabulary and publishes `SocietyCheckpointChanged`; the `hub:*` rules join with the five-layer change.+6. A memory touch in the last 60 s → `archive` (the Memory House). **Built:** `jarvis/society/checkpoints.py` derives `paused → idle`, `gate`, `meeting`, `archive`, `hub:cli`, `hub:plugins | hub:skills | hub:mcp` (dominant family of the last 8 tool calls, 20 s hysteresis), `desk`, `idle` and publishes `SocietyCheckpointChanged`. "A worker runs under the agent's identity" means EITHER a scheduler run (`ASSIGN`) OR a turn typed into the agent's card: the society surface reports every turn start (`note_turn_started`), and the engine watches that turn's `tool_call` / `turn_finished` events. `hub:workshop` and `hub:models` are still open.7. Being created / avatar change → `foundry`.8. Otherwise → `wander`.diff --git a/jarvis/society/checkpoints.py b/jarvis/society/checkpoints.pyindex b6a2151f34..71064455a0 100644--- a/jarvis/society/checkpoints.py+++ b/jarvis/society/checkpoints.py@@ -1,22 +1,39 @@"""Where an agent IS on the island — derived, never decided by a model.``docs/agent-society/world-behaviour-manual.md`` §3 and ``memory-house.md``-§3.4. The rules run over facts the runtime already has and answer with one of-the checkpoints that exist in every layer today (``desk | meeting | archive |-gate | idle``). The first rule that matches wins:+§3.4. The rules run over facts the runtime already has and answer with one+checkpoint of the five-layer vocabulary (``events.Checkpoint``). The first+rule that matches wins:1. paused -> idle (home, until the superset lands)2. an open approval for the agent -> gate3. member of a running room -> meeting4. memory activity within the hold window -> archive (the Memory House, 60 s)-5. a run in flight under its identity -> desk (the workshop)+5. a turn or run in flight under its identity:+ on a CLI seat -> hub:cli (the Terminal Cantina)+ dominant tool family plugin/skill/mcp -> hub:<family>+ otherwise -> desk (the workshop)6. otherwise -> idle+"In flight" covers BOTH ways work reaches an agent: an ``ASSIGN`` the scheduler+dispatched (its run id sits in ``scheduler.running``) and a message typed+straight into the agent's card (a turn on its canonical chat session, which+never touches the scheduler). The society surface reports the start of every+turn (``note_turn_started``); from then on the engine watches the turn's own+event stream for ``tool_call`` and ``turn_finished``, so the figure walks to+the shop of the tools it actually uses and comes back when the turn ends.++The family behind a place is the dominant capability family of the last+``FAMILY_WINDOW`` tool calls; a figure changes shops only after a different+family has dominated for ``FAMILY_HYSTERESIS_S`` — hysteresis, so nobody+ping-pongs between the Docks and the Forge. The first family of a turn wins+at once: the walk itself is the delay.+The engine persists a change through the roster, publishes``SocietyCheckpointChanged`` on the app bus (the WebSocket forwards every busevent, so the island re-reads its roster within a second) and re-evaluates-by timer when a hold expires. Idle costs nothing: no timer runs unless a hold-is pending.+by timer when a hold or the hysteresis expires. Idle costs nothing: no timer+runs unless a hold is pending, and no watcher runs unless a turn does."""from __future__ import annotations@@ -24,16 +41,58 @@ from __future__ import annotationsimport asyncioimport loggingimport time+from collections import Counter, dequefrom collections.abc import Callablefrom dataclasses import dataclass-from typing import Any+from typing import Any, Final+from .capabilities import CapabilityKind, capability_id_for_toolfrom .events import AgentState, Checkpoint, MsgType, RoomState, SocietyEnvelopefrom .memory import MEMORY_HOLD_Slog = logging.getLogger(__name__)-__all__ = ["CheckpointEngine", "Facts", "derive"]+__all__ = [+ "FAMILY_HYSTERESIS_S",+ "FAMILY_WINDOW",+ "CheckpointEngine",+ "Facts",+ "derive",+ "family_of_tool",+]++#: Tool calls that decide the dominant family (world-behaviour-manual.md §3 rule 5).+FAMILY_WINDOW: Final[int] = 8+#: Seconds a different family must dominate before the figure changes shops.+FAMILY_HYSTERESIS_S: Final[float] = 20.0+#: The watcher re-checks a turn that emits nothing for this long (a stuck runner+#: never leaves a figure standing in a shop forever).+_WATCH_IDLE_S: Final[float] = 15.0++#: Capability family -> the hub the figure stands at. ``core`` is the workshop.+_FAMILY_HUB: Final[dict[str, Checkpoint]] = {+ str(CapabilityKind.PLUGIN): Checkpoint.HUB_PLUGINS,+ str(CapabilityKind.SKILL): Checkpoint.HUB_SKILLS,+ str(CapabilityKind.MCP): Checkpoint.HUB_MCP,+ str(CapabilityKind.CLI): Checkpoint.HUB_CLI,+}++#: Society-surface tools that are not plugins: the shell, the browser, the memory+#: hands and teammate messaging are core work; a learned skill is a skill.+_SOCIETY_SKILL_TOOL: Final[str] = "society_run_skill"+_SOCIETY_PREFIX: Final[str] = "society_"+++def family_of_tool(tool_name: str) -> str:+ """The capability family of a brain tool name: ``plugin | skill | mcp | cli | core``."""+ if tool_name == _SOCIETY_SKILL_TOOL:+ return str(CapabilityKind.SKILL)+ if tool_name.startswith(_SOCIETY_PREFIX):+ return str(CapabilityKind.CORE)+ cap = capability_id_for_tool(tool_name)+ if cap is None:+ return str(CapabilityKind.CORE)+ return cap.partition(":")[0]@dataclass(frozen=True, slots=True)@@ -42,7 +101,12 @@ class Facts:open_approval: bool = Falsein_room: bool = Falsememory_active: bool = False+ #: A scheduler run (ASSIGN) or a chat turn is in flight under the agent's identity.running: bool = False+ #: The agent answers on a coding-CLI seat (Claude Code, Codex, …).+ cli_seat: bool = False+ #: Dominant capability family of its recent tool calls, after hysteresis; None = none yet.+ family: str | None = Nonedef derive(facts: Facts) -> Checkpoint:@@ -56,10 +120,60 @@ def derive(facts: Facts) -> Checkpoint:if facts.memory_active:return Checkpoint.ARCHIVEif facts.running:+ if facts.cli_seat:+ return Checkpoint.HUB_CLI+ if facts.family is not None:+ return _FAMILY_HUB.get(facts.family, Checkpoint.DESK)return Checkpoint.DESKreturn Checkpoint.IDLE+@dataclass(slots=True)+class _FamilyTrack:+ """The recent tool calls of one agent and the hysteresis over them."""++ calls: deque[str]+ #: The family the figure currently stands for.+ current: str | None = None+ #: A different family that has started to dominate, and since when.+ candidate: str | None = None+ candidate_since: float = 0.0++ def dominant(self) -> str | None:+ if not self.calls:+ return None+ counts = Counter(self.calls)+ top = max(counts.values())+ # Ties go to the most recent call among the leaders.+ for name in reversed(self.calls):+ if counts[name] == top:+ return name+ return None # pragma: no cover — the loop always returns++ def settle(self, now: float) -> bool:+ """Apply hysteresis; returns True when ``current`` changed."""+ top = self.dominant()+ if top is None or top == self.current:+ self.candidate = None+ return False+ if self.current is None:+ self.current = top+ self.candidate = None+ return True+ if self.candidate != top:+ self.candidate, self.candidate_since = top, now+ return False+ if now - self.candidate_since >= FAMILY_HYSTERESIS_S:+ self.current, self.candidate = top, None+ return True+ return False++ def hysteresis_due_in(self, now: float) -> float | None:+ if self.candidate is None:+ return None+ return max(0.0, FAMILY_HYSTERESIS_S - (now - self.candidate_since))++#: Envelope types after which an agent's place may have changed._MOVING_TYPES = frozenset({@@ -88,10 +202,14 @@ class CheckpointEngine:self._publish = publishself._clock = clockself._memory_until: dict[str, float] = {}+ self._families: dict[str, _FamilyTrack] = {}#: One refresh per agent at a time: a RESULT and the VETO it may draw arrive together.self._locks: dict[str, asyncio.Lock] = {}- self._timers: dict[str, asyncio.TimerHandle] = {}+ #: Timers keyed by (agent, purpose): memory hold and family hysteresis are independent.+ self._timers: dict[tuple[str, str], asyncio.TimerHandle] = {}self._tasks: set[asyncio.Task[None]] = set()+ #: One turn watcher per agent; its canonical session runs one turn at a time.+ self._watchers: dict[str, asyncio.Task[None]] = {}self._unsubscribe: Callable[[], None] | None = None# ------------------------------------------------------------ lifecycle@@ -110,6 +228,9 @@ class CheckpointEngine:for task in list(self._tasks):task.cancel()self._tasks.clear()+ for task in list(self._watchers.values()):+ task.cancel()+ self._watchers.clear()# --------------------------------------------------------------- inputs@@ -117,7 +238,43 @@ class CheckpointEngine:"""The memory service touched the vault for ``agent_id``: the figure goes to the house."""self._memory_until[agent_id] = self._clock() + self._hold_sawait self.refresh(agent_id)- self._arm(agent_id, self._hold_s + 0.05)+ self._arm(agent_id, "memory", self._hold_s + 0.05)++ def note_turn_started(self, agent_id: str, session_id: str) -> None:+ """A turn began on the agent's chat session (the society surface reports every one).++ Starts the watcher that follows the turn's ``tool_call`` and+ ``turn_finished`` events; idempotent while a watcher for the agent runs.+ """+ running = self._watchers.get(agent_id)+ if running is not None and not running.done():+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return+ task = loop.create_task(self._watch_turn(agent_id, session_id))+ self._watchers[agent_id] = task+ task.add_done_callback(lambda t, a=agent_id: self._watcher_done(a, t))++ async def note_tool_call(self, agent_id: str, tool_name: str) -> None:+ """The agent called ``tool_name``: its dominant family may move it to a shop."""+ track = self._families.get(agent_id)+ if track is None:+ track = self._families[agent_id] = _FamilyTrack(calls=deque(maxlen=FAMILY_WINDOW))+ track.calls.append(family_of_tool(tool_name))+ now = self._clock()+ changed = track.settle(now)+ due = track.hysteresis_due_in(now)+ if due is not None:+ self._arm(agent_id, "family", due + 0.05)+ if changed or track.current is not None:+ await self.refresh(agent_id)++ def clear_tool_calls(self, agent_id: str) -> None:+ """The turn ended: the next one starts with a clean window."""+ self._families.pop(agent_id, None)+ self._disarm(agent_id, "family")async def _on_envelope(self, env: SocietyEnvelope) -> None:if env.msg_type is MsgType.DIGEST:@@ -136,11 +293,93 @@ class CheckpointEngine:if who and who != "user":await self.refresh(who)+ # -------------------------------------------------------- turn watcher++ async def _watch_turn(self, agent_id: str, session_id: str) -> None:+ svc = self._chat_service()+ if svc is None:+ return+ queue = svc.subscribe(session_id)+ try:+ await self.refresh(agent_id)+ while True:+ try:+ event = await asyncio.wait_for(queue.get(), timeout=_WATCH_IDLE_S)+ except TimeoutError:+ if not svc.is_running(session_id):+ break+ continue+ kind = event.get("kind")+ payload = event.get("payload") or {}+ if kind == "tool_call":+ name = str(payload.get("name") or payload.get("tool") or "")+ if name:+ await self.note_tool_call(agent_id, name)+ elif kind == "turn_finished":+ break+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — the world is a projection; a miss never breaks the turn+ log.warning("society checkpoints: turn watcher for %s failed", agent_id, exc_info=True)+ finally:+ svc.unsubscribe(session_id, queue)+ self.clear_tool_calls(agent_id)+ # Runs on the loop even when the task is cancelled during shutdown.+ self._fire(agent_id, "turn")++ def _watcher_done(self, agent_id: str, task: asyncio.Task[None]) -> None:+ if self._watchers.get(agent_id) is task:+ self._watchers.pop(agent_id, None)++ def _chat_service(self) -> Any | None:+ getter = getattr(self._runtime, "_get_chat", None)+ try:+ return getter() if getter is not None else None+ except Exception: # noqa: BLE001 — no chat service means no turns to watch+ log.debug("society checkpoints: chat service unavailable", exc_info=True)+ return None++ def turn_running(self, agent_id: str) -> bool:+ """True while the agent's canonical chat session runs a turn."""+ svc = self._chat_service()+ if svc is None:+ return False+ from .roster import canonical_session_id++ try:+ return bool(svc.is_running(canonical_session_id(agent_id)))+ except Exception: # noqa: BLE001 — a service without the probe reports no turn+ log.debug("society checkpoints: is_running probe failed", exc_info=True)+ return False++ def is_busy(self, agent_id: str) -> bool:+ """A run or a turn is in flight for the agent (rows show it as ``working``)."""+ return agent_id in self._runtime.scheduler.running.values() or self.turn_running(agent_id)+# ------------------------------------------------------------ derivationdef memory_active(self, agent_id: str) -> bool:return self._memory_until.get(agent_id, 0.0) > self._clock()+ def family_for(self, agent_id: str) -> str | None:+ track = self._families.get(agent_id)+ if track is None:+ return None+ track.settle(self._clock())+ return track.current++ def _cli_seat(self, agent: Any) -> bool:+ provider = str(getattr(agent, "provider", "") or "")+ if not provider:+ return False+ try:+ from jarvis.agent_chat.service import resolve_runner++ return resolve_runner(provider, surface="society").endswith("-cli")+ except Exception: # noqa: BLE001 — a missing catalog row is not a seat+ log.debug("society checkpoints: runner lookup failed for %s", provider, exc_info=True)+ return False+async def facts_for(self, agent_id: str) -> Facts | None:rt = self._runtimeagent = await rt.roster.get(agent_id)@@ -148,12 +387,15 @@ class CheckpointEngine:return Nonepending = await rt.approvals.pending()rooms = await rt.rooms.list(state=RoomState.RUNNING)+ running = self.is_busy(agent_id)return Facts(paused=agent.state is not AgentState.ACTIVE,open_approval=any(a.agent_id == agent_id for a in pending),in_room=any(agent_id in r.members for r in rooms),memory_active=self.memory_active(agent_id),- running=agent_id in rt.scheduler.running.values(),+ running=running,+ cli_seat=running and self._cli_seat(agent),+ family=self.family_for(agent_id) if running else None,)async def refresh(self, agent_id: str) -> Checkpoint | None:@@ -205,18 +447,27 @@ class CheckpointEngine:# ---------------------------------------------------------------- timers- def _arm(self, agent_id: str, delay_s: float) -> None:- old = self._timers.pop(agent_id, None)+ def _arm(self, agent_id: str, purpose: str, delay_s: float) -> None:+ self._disarm(agent_id, purpose)+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return+ self._timers[(agent_id, purpose)] = loop.call_later(delay_s, self._fire, agent_id, purpose)++ def _disarm(self, agent_id: str, purpose: str) -> None:+ old = self._timers.pop((agent_id, purpose), None)if old is not None:old.cancel()++ def _fire(self, agent_id: str, purpose: str) -> None:+ self._timers.pop((agent_id, purpose), None)try:loop = asyncio.get_running_loop()except RuntimeError:return- self._timers[agent_id] = loop.call_later(delay_s, self._fire, agent_id)-- def _fire(self, agent_id: str) -> None:- self._timers.pop(agent_id, None)- task = asyncio.create_task(self.refresh(agent_id))+ if loop.is_closed():+ return+ task = loop.create_task(self.refresh(agent_id))self._tasks.add(task)task.add_done_callback(self._tasks.discard)diff --git a/jarvis/society/events.py b/jarvis/society/events.pyindex 7152909c46..c03c2769f0 100644--- a/jarvis/society/events.py+++ b/jarvis/society/events.py@@ -92,6 +92,12 @@ class Checkpoint(StrEnum):ARCHIVE = "archive"GATE = "gate"IDLE = "idle"+ #: The hub shops of the island (world-behaviour-manual.md §2): a running+ #: agent stands at the shop of the capability family it is using.+ HUB_PLUGINS = "hub:plugins"+ HUB_SKILLS = "hub:skills"+ HUB_MCP = "hub:mcp"+ HUB_CLI = "hub:cli"class PermissionCeiling(StrEnum):diff --git a/jarvis/society/society_schema.sql b/jarvis/society/society_schema.sqlindex 1dc6fc0f57..afcf5de570 100644--- a/jarvis/society/society_schema.sql+++ b/jarvis/society/society_schema.sql@@ -18,7 +18,8 @@ CREATE TABLE IF NOT EXISTS society_agents (CHECK (state IN ('active', 'paused', 'archived')),avatar_json TEXT NOT NULL DEFAULT '{}',checkpoint TEXT NOT NULL DEFAULT 'idle'- CHECK (checkpoint IN ('desk', 'meeting', 'archive', 'gate', 'idle')),+ CHECK (checkpoint IN ('desk', 'meeting', 'archive', 'gate', 'idle',+ 'hub:plugins', 'hub:skills', 'hub:mcp', 'hub:cli')),provider TEXT NOT NULL DEFAULT '',model TEXT NOT NULL DEFAULT '',effort TEXT NOT NULL DEFAULT '',diff --git a/jarvis/society/store.py b/jarvis/society/store.pyindex 2ff9a371ee..5b66a27a8e 100644--- a/jarvis/society/store.py+++ b/jarvis/society/store.py@@ -113,6 +113,61 @@ class SocietyStore:"TEXT NOT NULL DEFAULT '[]'")log.info("society store: migration applied — added browser_allowed_domains")+ await self._migrate_checkpoint_vocabulary()++ async def _migrate_checkpoint_vocabulary(self) -> None:+ """Widen the ``checkpoint`` CHECK to today's vocabulary (the hub shops, 2026-09).++ SQLite cannot alter a CHECK constraint in place, so a database created+ by an older build gets the standard rebuild: create the table from the+ current schema under a scratch name, copy every column both versions+ share, drop the old table, rename. Idempotent — a table whose CHECK+ already lists every ``Checkpoint`` value is left alone.+ """+ from .events import Checkpoint++ cur = await self.conn.execute(+ "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'society_agents'"+ )+ row = await cur.fetchone()+ await cur.close()+ ddl = str(row[0]) if row and row[0] else ""+ if all(f"'{value}'" in ddl for value in Checkpoint):+ return+ schema = _SCHEMA_PATH.read_text(encoding="utf-8")+ start = schema.index("CREATE TABLE IF NOT EXISTS society_agents")+ end = schema.index(");", start) + 2+ fresh_ddl = schema[start:end].replace(+ "CREATE TABLE IF NOT EXISTS society_agents", "CREATE TABLE society_agents__new", 1+ )+ cur = await self.conn.execute("PRAGMA table_info(society_agents)")+ old_cols = [str(r[1]) for r in await cur.fetchall()]+ await cur.close()+ await self.conn.execute("PRAGMA foreign_keys=OFF")+ try:+ await self.conn.execute("BEGIN")+ await self.conn.execute(fresh_ddl)+ cur = await self.conn.execute("PRAGMA table_info(society_agents__new)")+ new_cols = {str(r[1]) for r in await cur.fetchall()}+ await cur.close()+ shared = ", ".join(c for c in old_cols if c in new_cols)+ # Column names come from PRAGMA table_info, never from input.+ copy_sql = (+ f"INSERT INTO society_agents__new ({shared}) SELECT {shared} FROM society_agents" # noqa: S608, E501+ )+ await self.conn.execute(copy_sql)+ await self.conn.execute("DROP TABLE society_agents")+ await self.conn.execute("ALTER TABLE society_agents__new RENAME TO society_agents")+ await self.conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_society_agents_state ON society_agents(state)"+ )+ await self.conn.execute("COMMIT")+ except Exception:+ await self.conn.execute("ROLLBACK")+ raise+ finally:+ await self.conn.execute("PRAGMA foreign_keys=ON")+ log.info("society store: migration applied — checkpoint vocabulary widened")async def _ensure_fts(self) -> None:"""FTS5 over knowledge summaries; optional — a sqlite without FTS5 stilldiff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex cf7eea2350..1cc519863f 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -80,7 +80,13 @@ their results arrive in this chat.- Approvals: actions above your permission ceiling queue for the user (chat card, Jarvis bar, \voice). A queued action is not refused — say what you are waiting for and continue with what \you can. Secrets are never typed into a chat; credentials come from the keyring.-- Language: answer in the language of the message you received."""+- Language: answer in the language of the message you received.+- The island: you live in a small island village with your fellow agents. Places: your house \+(rest), the market square (group discussions), the Plugin Docks (plugin tools), the Skill Forge \+(skills), the Relay Tower (MCP servers), the Terminal Cantina (coding CLIs), the Workshop (files \+and shell), the Memory House (the shared memory), the Harbor Gate (waiting for approval), the \+Agent Foundry (where agents are created). You are placed by what you actually do; you cannot \+move yourself. When you mention your location, use these names."""def agent_id_of(session_id: str) -> str | None:@@ -228,6 +234,9 @@ async def society_system_extra(cfg: Any, brain: Any, session: Any) -> str:if agent is None:return ""rt.cache_agent(agent)+ # The briefing is built once per turn: this is where the island learns that a+ # turn started, whoever started it (a typed message never passes the scheduler).+ rt.checkpoints.note_turn_started(agent.agent_id, str(getattr(session, "session_id", "")))catalog = rt.catalog()roster = await rt.roster.list()browser = rt.browser.status_for(agent)diff --git a/jarvis/ui/web/frontend/src/lib/societyApi.ts b/jarvis/ui/web/frontend/src/lib/societyApi.tsindex 71107380ba..1e4ad61dc9 100644--- a/jarvis/ui/web/frontend/src/lib/societyApi.ts+++ b/jarvis/ui/web/frontend/src/lib/societyApi.ts@@ -31,7 +31,17 @@ export type AgentState = (typeof AGENT_STATES)[number];export const RUN_STATES = ["idle", "working", "waiting", "paused"] as const;export type RunState = (typeof RUN_STATES)[number];-export const CHECKPOINTS = ["desk", "meeting", "archive", "gate", "idle"] as const;+export const CHECKPOINTS = [+ "desk",+ "meeting",+ "archive",+ "gate",+ "idle",+ "hub:plugins",+ "hub:skills",+ "hub:mcp",+ "hub:cli",+] as const;export type Checkpoint = (typeof CHECKPOINTS)[number];export const PERMISSION_CEILINGS = ["safe", "monitor", "ask"] as const;diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex c7aaa43ea3..47dca23a0e 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -151,13 +151,13 @@ class RoomSayBody(BaseModel):async def list_agents(request: Request, include_archived: bool = False) -> dict[str, Any]:rt = await _runtime(request)agents = await rt.roster.list(include_archived=include_archived)- running = rt.scheduler.runningrows = []for agent in agents:row = agent.to_dict()if agent.state == "paused":row["run_state"] = "paused"- elif agent.agent_id in running.values():+ elif rt.checkpoints.is_busy(agent.agent_id):+ # A scheduler run OR a turn typed into the card: both are work.row["run_state"] = "working"else:row["run_state"] = "idle"diff --git a/tests/unit/society/test_checkpoints.py b/tests/unit/society/test_checkpoints.pyindex 052e891411..82b54e7722 100644--- a/tests/unit/society/test_checkpoints.py+++ b/tests/unit/society/test_checkpoints.py@@ -7,7 +7,7 @@ from pathlib import Pathimport pytest-from jarvis.society.checkpoints import CheckpointEngine, Facts, derive+from jarvis.society.checkpoints import CheckpointEngine, Facts, derive, family_of_toolfrom jarvis.society.events import Checkpoint, MsgType, SocietyEnvelopefrom jarvis.society.runtime import SocietyRuntime@@ -98,3 +98,110 @@ async def test_paused_agent_stays_home(rt: SocietyRuntime):)assert (await rt.roster.get("scout")).checkpoint is Checkpoint.IDLEassert await rt.checkpoints.refresh("ghost") is None+++# ------------------------------------------------------------- the hub shops+++def test_running_agents_stand_at_the_shop_of_their_tools():+ assert derive(Facts(running=True, family="plugin")) is Checkpoint.HUB_PLUGINS+ assert derive(Facts(running=True, family="skill")) is Checkpoint.HUB_SKILLS+ assert derive(Facts(running=True, family="mcp")) is Checkpoint.HUB_MCP+ assert derive(Facts(running=True, family="cli")) is Checkpoint.HUB_CLI+ assert derive(Facts(running=True, family="core")) is Checkpoint.DESK+ # A CLI seat outranks the family; the memory hold outranks the shop.+ assert derive(Facts(running=True, cli_seat=True, family="plugin")) is Checkpoint.HUB_CLI+ assert derive(Facts(running=True, family="plugin", memory_active=True)) is Checkpoint.ARCHIVE+ # Nobody stands in a shop without a turn.+ assert derive(Facts(family="plugin")) is Checkpoint.IDLE+++def test_family_of_tool():+ assert family_of_tool("gmail") == "plugin"+ assert family_of_tool("cli_claude") == "cli"+ assert family_of_tool("github/search_issues") == "mcp"+ assert family_of_tool("society_run_skill") == "skill"+ assert family_of_tool("society_shell") == "core"+ assert family_of_tool("society_browser") == "core"+ assert family_of_tool("spawn-worker") == "core"+++class FakeChatService:+ """The slice of the agent-chat service the engine touches."""++ def __init__(self) -> None:+ self.queues: dict[str, list[asyncio.Queue]] = {}+ self.running: set[str] = set()++ def is_running(self, session_id: str) -> bool:+ return session_id in self.running++ def subscribe(self, session_id: str) -> asyncio.Queue:+ q: asyncio.Queue = asyncio.Queue()+ self.queues.setdefault(session_id, []).append(q)+ return q++ def unsubscribe(self, session_id: str, q: asyncio.Queue) -> None:+ self.queues.get(session_id, []).remove(q)++ def emit(self, session_id: str, kind: str, **payload) -> None:+ for q in self.queues.get(session_id, []):+ q.put_nowait({"kind": kind, "payload": payload})+++async def _settle() -> None:+ for _ in range(6):+ await asyncio.sleep(0.01)+++async def test_a_typed_turn_walks_to_the_docks_and_back(rt: SocietyRuntime):+ """A message typed into the card never passes the scheduler — the turn watcher+ still sends the figure to the shop of the tools it uses."""+ svc = FakeChatService()+ rt._get_chat = lambda: svc # noqa: SLF001+ pushed: list = []+ rt.checkpoints._publish = pushed.append # noqa: SLF001+ session = "society:scout"+ svc.running.add(session)+ rt.checkpoints.note_turn_started("scout", session)+ await _settle()+ assert (await rt.roster.get("scout")).checkpoint is Checkpoint.DESK+ assert rt.checkpoints.is_busy("scout")+ svc.emit(session, "tool_call", name="gmail", input={})+ await _settle()+ assert (await rt.roster.get("scout")).checkpoint is Checkpoint.HUB_PLUGINS+ # A second watcher for the same agent is not started while one runs.+ rt.checkpoints.note_turn_started("scout", session)+ assert len(svc.queues[session]) == 1+ svc.running.discard(session)+ svc.emit(session, "turn_finished", status="ok")+ await _settle()+ assert (await rt.roster.get("scout")).checkpoint is Checkpoint.IDLE+ assert svc.queues[session] == []+ assert [p.checkpoint for p in pushed] == ["desk", "hub:plugins", "idle"]+++async def test_family_hysteresis(rt: SocietyRuntime):+ """The first family wins at once; a different one must dominate 20 s before the+ figure changes shops, and the timer makes the switch without another call."""+ now = [1000.0]+ engine = CheckpointEngine(rt, publish=lambda _e: None, clock=lambda: now[0])+ rt.checkpoints.detach()+ rt.checkpoints = engine+ engine.attach()+ rt.scheduler.note_run_started("run-1", "scout")+ await engine.note_tool_call("scout", "gmail")+ assert (await rt.roster.get("scout")).checkpoint is Checkpoint.HUB_PLUGINS+ for _ in range(3):+ await engine.note_tool_call("scout", "github/list_prs")+ # MCP dominates the window (3 of 4) but has not for 20 s: still at the Docks.+ assert (await rt.roster.get("scout")).checkpoint is Checkpoint.HUB_PLUGINS+ now[0] += 21.0+ await engine.note_tool_call("scout", "github/list_prs")+ assert (await rt.roster.get("scout")).checkpoint is Checkpoint.HUB_MCP+ # The run ends: the window is cleared and the figure goes home.+ engine.clear_tool_calls("scout")+ rt.scheduler.note_run_ended("run-1")+ assert await engine.refresh("scout") is Checkpoint.IDLE+ assert engine.family_for("scout") is None+ engine.detach()diff --git a/tests/unit/society/test_store.py b/tests/unit/society/test_store.pyindex b6856ac53b..467ed1f65c 100644--- a/tests/unit/society/test_store.py+++ b/tests/unit/society/test_store.py@@ -120,3 +120,47 @@ async def test_open_is_idempotent(tmp_path: Path):await s.open()await s.close()await s.close()+++async def test_checkpoint_check_is_widened_on_an_old_database(tmp_path):+ """A society.db created before the hub shops carries the five-value CHECK;+ opening it rebuilds the table and keeps every row."""+ import sqlite3++ from jarvis.society.roster import Roster+ from jarvis.society.store import _SCHEMA_PATH, SocietyStore++ schema = _SCHEMA_PATH.read_text(encoding="utf-8")+ start = schema.index("CHECK (checkpoint IN (")+ end = schema.index("))", start) + 2+ old_schema = (+ schema[:start]+ + "CHECK (checkpoint IN ('desk', 'meeting', 'archive', 'gate', 'idle'))"+ + schema[end:]+ )+ db = tmp_path / "society.db"+ conn = sqlite3.connect(db)+ conn.executescript(old_schema)+ conn.execute(+ "INSERT INTO society_agents (agent_id, name, tier, created_ms, updated_ms) "+ "VALUES ('scout', 'Scout', 'specialist', 1, 1)"+ )+ conn.commit()+ with pytest.raises(sqlite3.IntegrityError):+ conn.execute("UPDATE society_agents SET checkpoint = 'hub:plugins'")+ conn.close()++ store = SocietyStore(db)+ await store.open()+ try:+ roster = Roster(store)+ scout = await roster.get("scout")+ assert scout is not None and scout.name == "Scout"+ await roster.update("scout", {"checkpoint": "hub:plugins"})+ assert str((await roster.get("scout")).checkpoint) == "hub:plugins"+ # Idempotent: a second open leaves the rebuilt table alone.+ await store.close()+ await store.open()+ assert str((await Roster(store).get("scout")).checkpoint) == "hub:plugins"+ finally:+ await store.close()