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): a lead for every agent team that plans, assigns and reviews on its own (#537)
Ruben Lütke39801d31bea4
diff --git a/docs/agent-society/team-leads.md b/docs/agent-society/team-leads.mdnew file mode 100644index 0000000000..a216c10814--- /dev/null+++ b/docs/agent-society/team-leads.md@@ -0,0 +1,112 @@+# Team leads++A team (a group of agents in the Agents section) can have a **lead**: one of+its members that manages the team for the person. The person gives the team a+goal. The lead breaks it into tasks, hands each task to the member whose role+fits, checks what comes back, sends rework or re-assigns, and reports when the+goal is done. The person steps in only for what is theirs: answering a+question the lead cannot decide, continuing a paused goal, or stopping one.++Code: `jarvis/society/team_lead.py` (the engine), `jarvis/society/team_tools.py`+(the lead's tools), `/api/society/chat-groups/{id}/…` in+`jarvis/ui/web/society_routes.py`, and the board in+`src/components/society/chat/TeamLeadBoard.tsx`.++## Naming a lead++Open a team and choose **Lead**. Either create a lead (a new agent whose+standing instructions are to manage this team) or make an existing member the+lead. A lead is an `orchestrator` on the roster, the tier the scheduler allows+to assign work; a promoted member returns to its previous tier when it stops+leading. An agent leads at most one team, and the assistant itself is never a+team lead because it already leads every agent.++The team's **mission** is a short standing purpose. The lead reads it on every+managing turn.++## How a goal runs++1. **Plan.** The lead gets a managing turn in its own chat with the goal, the+ mission and the members. It hands out tasks with `society_team_assign`.+2. **Work.** Every task is one `ASSIGN` on the society board, on its own+ trace. The scheduler decides whether the member starts, exactly as for any+ other assignment. A busy member is not a failure: the task waits and knocks+ again by itself.+3. **Review.** When a result lands, the engine wakes the lead with it. Results+ that arrive while the lead is mid-turn are batched into its next turn.+4. **Report.** The lead closes the goal with `society_team_report`. A lead+ that ends a turn with nothing running and no report is asked once to say+ which it is, the result or a question for the person. If it still reports+ nothing, its answer is the report.++A team works on one goal at a time; further goals queue and start in order.++Work handed to a lead from elsewhere becomes a team goal as well: when the+assistant delegates to a lead by voice or chat, or a quest is routed to one,+the goal's report answers that assignment. A goal may queue or wait for the+person for a long time, so it never holds one of the lead's run slots; the+team's own queue is what bounds it.++Every state change of a goal is a compare-and-swap on its current state, so a+stop always wins over a pause, a resume or a report that was decided on an+older read.++## The lead's tools++Offered only in the chats of an agent that currently leads a team.++| Tool | What it does |+|---|---|+| `society_team_assign` | Hand one task to one member. Returns at once with the task's state. |+| `society_team_board` | Read the mission, the members and every open goal with its tasks. |+| `society_team_report` | `progress`, `needs_input` (one question for the person), `done`, `failed`. |++None of them starts work by itself. Assigning appends an envelope; the+scheduler (trusted Python) applies the tier wall, the delegation depth, the+budgets and the concurrency cap.++## Goal and task states++| Goal | Meaning |+|---|---|+| `queued` | Waits behind the team's current goal. |+| `running` | The lead or a member is working on it. |+| `needs_input` | The lead asked the person a question. |+| `paused` | Stopped until the person continues it. |+| `done`, `failed`, `cancelled` | Finished. |++| Task | Meaning |+|---|---|+| `waiting` | The member was busy; the assignment knocks again. |+| `assigned` | The assignment is on the board. |+| `running` | The member took it. |+| `done`, `blocked` | The member's result, or a final refusal. |+| `cancelled` | The goal was stopped first. |++Both vocabularies are pinned across Python, SQL and TypeScript by+`tests/unit/society/test_society_enum_parity.py`.++## Bounds++- The engine never calls a model. A lead's turns run on the lead's seat and a+ member's on the member's seat.+- Every turn belongs to a goal the person started, or to a check-in they+ switched on.+- A goal has a budget of managing turns. When it is spent the goal pauses and+ the person decides whether to continue.+- A goal has a task limit, and a team a limit of open goals.+- The society kill switch pauses every running goal.+- Goals that were running when the app closed come back `paused`, with their+ open tasks marked as interrupted. Opening the app never resumes one.+- A task with no sign of life is checked against the scheduler; a run that+ ended without a result reaches the lead as `blocked` instead of being+ waited on forever.++## Check-ins++Off by default. When the person switches them on (every hour, every four+hours, or once a day), the lead looks at its team unprompted: it follows up on+stuck work and starts standing duties the mission names. A check-in is an+ordinary agent routine tagged `team-checkin:<team id>`, so it appears with the+lead's other routines and follows the same rules for which seat may run+background work.diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex ef9ff0147f..3bc90d7608 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -2476,6 +2476,23 @@ class SocietyQuestChanged(Event):title: str = ""+@dataclass(frozen=True, slots=True)+class SocietyTeamChanged(Event):+ """A team's lead, goals or tasks changed.++ Published by :class:`jarvis.society.team_lead.TeamLeads` after the rows+ were updated: a lead was named, a goal started, a member took or finished+ a task, the lead reported. The WebSocket forwards it; the team board+ re-reads within a second instead of on the next poll.+ """++ group_id: str = ""+ goal_id: str = ""+ state: str = ""+ #: What moved: ``goal``, ``task``, ``turn``, ``lead``, ``mission``, ``checkin``.+ reason: str = ""++@dataclass(frozen=True, slots=True)class SocietyMessageSent(Event):"""One agent said something to another, or into a room.diff --git a/jarvis/society/README.md b/jarvis/society/README.mdindex d921f735df..a783eb5581 100644--- a/jarvis/society/README.md+++ b/jarvis/society/README.md@@ -30,6 +30,8 @@ or reopening the app never resumes paid discussion.| `browser/` | the agent's browser: one-click venv install of browser-use, the in-venv runner, per-agent persistent profiles + login sessions, `society_browser` || `learning.py` | automatic learning: turn digest → skill in the agent's own namespace, `society_run_skill`, promotion to the global registry as a draft || `quests.py` | the Quest Board: a job the person posts becomes ONE `ASSIGN` to the agent deterministic routing picks (focus overlap, name/title, description words); nobody fits → the foundry forges the seed teammate for the quest's capability, else the one generalist `Runner`; the lifecycle is read back off the trace (CLAIM → running, RESULT → done/failed, VETO → failed) and pushed as `SocietyQuestChanged` |+| `team_lead.py` | team leads (`docs/agent-society/team-leads.md`): one member manages a team toward the person's goals; a goal becomes tasks, each task ONE `ASSIGN` on its own trace, and the engine reads the lifecycle off the board, knocks again on a busy member, wakes the lead with every result and pauses a goal at its turn budget, on the kill switch and after a restart; pushed as `SocietyTeamChanged` |+| `team_tools.py` | the lead's tools, offered only while an agent leads a team: `society_team_assign`, `society_team_board`, `society_team_report` || `seeds.py` | the starter team (Scout + Archivist) and proposals from connected capabilities || `chat_binding.py` | roster row → canonical `agent_chat` session; delivers board envelopes as framed turns || `runtime.py` | the lazily built singleton wiring all of it; `current_runtime()` for the surface |diff --git a/jarvis/society/capabilities.py b/jarvis/society/capabilities.pyindex 1ce17aedd2..8dcf859d9c 100644--- a/jarvis/society/capabilities.py+++ b/jarvis/society/capabilities.py@@ -74,6 +74,9 @@ NEVER_GRANTED: Final[frozenset[str]] = frozenset("reveal-key-preview","profile-update","society_message_agent",+ "society_team_assign",+ "society_team_board",+ "society_team_report","message_agent","message-agent",}diff --git a/jarvis/society/checkpoints.py b/jarvis/society/checkpoints.pyindex 6e7d70896f..04f7b074f8 100644--- a/jarvis/society/checkpoints.py+++ b/jarvis/society/checkpoints.py@@ -117,6 +117,7 @@ _WORK_FAMILY: Final[dict[str, str]] = {"contact-upsert": FAMILY_COMMS,"call-contact": FAMILY_COMMS,"society_message_agent": FAMILY_COMMS,+ "society_team_assign": FAMILY_COMMS,# The hand on the desktop: every pointer, key and window tool."open-app": FAMILY_DESKTOP,"type-text": FAMILY_DESKTOP,diff --git a/jarvis/society/events.py b/jarvis/society/events.pyindex 2ca096e448..a0f8a61aa2 100644--- a/jarvis/society/events.py+++ b/jarvis/society/events.py@@ -36,6 +36,8 @@ __all__ = ["RoomState","RunState","SocietyEnvelope",+ "TeamGoalState",+ "TeamTaskState","Tier","now_ms",]@@ -190,6 +192,42 @@ class QuestState(StrEnum):CANCELLED = "cancelled"+class TeamGoalState(StrEnum):+ """A goal the person gave a team; its lead plans, assigns and reports.++ ``queued`` = waits behind the team's current goal; ``running`` = the lead+ or a member is working on it; ``needs_input`` = the lead asked the person+ something only they can decide; ``paused`` = stopped without an answer+ (society halted, app restart, turn budget) until the person resumes it;+ the three terminal states never change again.+ """++ QUEUED = "queued"+ RUNNING = "running"+ NEEDS_INPUT = "needs_input"+ PAUSED = "paused"+ DONE = "done"+ FAILED = "failed"+ CANCELLED = "cancelled"+++class TeamTaskState(StrEnum):+ """One task a team lead handed to a member, read off the board.++ ``waiting`` = the member was busy and the assignment knocks again;+ ``assigned`` = the ASSIGN is on the board; ``running`` = the member+ CLAIMed it; ``done`` / ``blocked`` come from its RESULT (or a final+ refusal); ``cancelled`` = the goal was stopped first.+ """++ WAITING = "waiting"+ ASSIGNED = "assigned"+ RUNNING = "running"+ DONE = "done"+ BLOCKED = "blocked"+ CANCELLED = "cancelled"++class ApprovalState(StrEnum):PENDING = "pending"APPROVED = "approved"diff --git a/jarvis/society/lead_card.py b/jarvis/society/lead_card.pyindex eb1c648ade..0610ab51d8 100644--- a/jarvis/society/lead_card.py+++ b/jarvis/society/lead_card.py@@ -27,8 +27,8 @@ from __future__ import annotationsimport hashlibimport logging-from collections.abc import Callable, Sequence-from typing import Final+from collections.abc import Callable, Mapping, Sequence+from typing import Any, Finalfrom .capabilities import CapabilityRowfrom .communication import COMMUNICATION_GUIDANCE@@ -131,6 +131,7 @@ def render_lead_card(lead_id: str = LEAD_AGENT_ID,busy: Callable[[str], int] | None = None,terminals: Sequence[str] = (),+ teams: Sequence[Mapping[str, Any]] = (),) -> str:"""The lead's system-prompt block.@@ -162,6 +163,9 @@ def render_lead_card("task would suit a standing agent, offer to set one up there — never invent ""an agent that is not on this card.")+ team_lines = _team_lines(teams, {a.agent_id: a for a in team})+ if team_lines:+ parts.append("\n".join(team_lines))names = [str(t).strip() for t in terminals if str(t or "").strip()]if names:parts.append(@@ -173,6 +177,35 @@ def render_lead_card(return "\n\n".join(parts)+def _team_lines(+ teams: Sequence[Mapping[str, Any]], by_id: Mapping[str, AgentRecord]+) -> list[str]:+ """Teams that have their own lead: a goal for the team goes to that lead."""+ rows: list[str] = []+ for group in sorted(teams, key=lambda g: str(g.get("name") or "").casefold()):+ lead = by_id.get(str(group.get("lead_agent_id") or ""))+ if lead is None or str(lead.state) != "active":+ continue+ members = [+ by_id[m].name+ for m in group.get("members", [])+ if m in by_id and m != lead.agent_id+ ]+ rows.append(+ f"- {group.get('name')} — lead: {lead.name} · members: "+ + (", ".join(members) or "none yet")+ )+ if not rows:+ return []+ return [+ "Teams with their own lead (team — lead · members). A goal for a whole team "+ "goes to its LEAD with delegate_to_agent: the lead plans it, hands tasks to "+ "the members, checks the results and reports back when the goal is done. "+ "Do not split such a goal across the members yourself.",+ *rows,+ ]++def _terminal_names() -> tuple[str, ...]:"""Call-signs of the open Agentic-IDE terminals — in-memory, never fatal."""try:@@ -240,6 +273,7 @@ def lead_card_section(*, lead_name: str = "Jarvis") -> str:agents = rt.roster.snapshot()catalog = rt.catalog()busy = rt.scheduler.active_runs+ teams = rt.team_leads.teams_snapshot()except Exception: # noqa: BLE001 — the card is a convenience; the turn must run without itlog.warning("society: lead card unavailable", exc_info=True)return ""@@ -250,4 +284,5 @@ def lead_card_section(*, lead_name: str = "Jarvis") -> str:lead_id=rt.lead_id,busy=busy,terminals=_terminal_names(),+ teams=teams,)diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.pyindex ce63bb8a41..be0f954a40 100644--- a/jarvis/society/runtime.py+++ b/jarvis/society/runtime.py@@ -179,6 +179,10 @@ class SocietyRuntime:self._review_lock = asyncio.Lock()#: The Quest Board: the person's jobs, routed to one taker, read back off the board.self.quests = Quests(self)+ from .team_lead import TeamLeads++ #: Team leads: a member that manages its team toward the person's goals.+ self.team_leads = TeamLeads(self, publish=event_publish)#: Speech on the board, projected onto the island: two agents talking#: turn to each other, two agents apart call across the map.self.world_feed = WorldFeed(self, publish=event_publish)@@ -281,6 +285,8 @@ class SocietyRuntime:# synchronous reader on the brain's prompt build — sees the team from# the first turn, not from the first REST listing.await self.roster.refresh()+ # After the roster: the lead prompts read names off its snapshot.+ await self.team_leads.start()self._require_open_owner()self._started = Trueself._delivery_task = asyncio.create_task(self._deliver_pending())@@ -458,6 +464,7 @@ class SocietyRuntime:cleanup.push_async_callback(asyncio.to_thread, self.conversations.close)for release in (self.world_feed.detach,+ self.team_leads.detach,self.quests.detach,self.checkpoints.detach,self.bridge.detach,@@ -547,6 +554,10 @@ class SocietyRuntime:# often a silent pass; reviewing each one would add a model call# per member to every message the person sends.return+ if self.team_leads.is_managing(session.session_id):+ # A lead's managing turn hands out and checks work; a review after+ # each one would add a model call to every step of every goal.+ returnwindow_key = ""if completion.turn.direct_user:# The person's turns are reviewed per window, not per answer.@@ -802,6 +813,15 @@ class SocietyRuntime:if reply_policy(env) != "always":raise RuntimeError("this reply policy requires an available agent chat service")return await self._dispatch_mission(target, env)+ from .team_lead import TRACE_PREFIX as TEAM_TRACE_PREFIX++ if (+ self.team_leads.group_led_by(target.agent_id) is not None+ and not env.trace_id.startswith(TEAM_TRACE_PREFIX)+ ):+ # Work handed to a team lead is a goal for its team: the lead+ # plans, assigns and answers this assignment with its report.+ return await self.team_leads.accept_assignment(target, env)return await self._dispatch_chat(target, env)async def _dispatch_chat(self, target: AgentRecord, env: SocietyEnvelope) -> str:@@ -1135,6 +1155,7 @@ class SocietyRuntime:async def engage_kill_switch(self) -> dict[str, Any]:await self.store.set_kill_switch(True)halted = await self.scheduler.halt_all()+ goals_paused = await self.team_leads.halt()await self._cancel_active_society_chats()await self.browser.close()settled = 0@@ -1155,6 +1176,7 @@ class SocietyRuntime:"runs_halted": halted,"rooms_settled": settled,"missions_cancelled": killed,+ "team_goals_paused": goals_paused,}async def release_kill_switch(self) -> dict[str, Any]:diff --git a/jarvis/society/society_schema.sql b/jarvis/society/society_schema.sqlindex 6e6143e595..9adc712654 100644--- a/jarvis/society/society_schema.sql+++ b/jarvis/society/society_schema.sql@@ -84,9 +84,60 @@ CREATE TABLE IF NOT EXISTS society_chat_groups (name TEXT NOT NULL,members_json TEXT NOT NULL,created_ms INTEGER NOT NULL,- updated_ms INTEGER NOT NULL+ updated_ms INTEGER NOT NULL,+ -- The member that manages this team (jarvis/society/team_lead.py); NULL = no lead.+ lead_agent_id TEXT DEFAULT NULL,+ -- The team's standing purpose, read by its lead on every managing turn.+ mission TEXT NOT NULL DEFAULT '');+-- Goals the person gives a team. The lead breaks a goal into tasks, hands+-- them to members and reports back; trusted Python reads the lifecycle off+-- society_events and wakes the lead when a result arrives.+CREATE TABLE IF NOT EXISTS society_team_goals (+ goal_id TEXT PRIMARY KEY,+ group_id TEXT NOT NULL,+ lead_agent_id TEXT NOT NULL,+ title TEXT NOT NULL,+ text TEXT NOT NULL DEFAULT '',+ state TEXT NOT NULL DEFAULT 'queued'+ CHECK (state IN ('queued', 'running', 'needs_input', 'paused',+ 'done', 'failed', 'cancelled')),+ report TEXT NOT NULL DEFAULT '', -- the lead's latest report to the person+ note TEXT NOT NULL DEFAULT '', -- why it waits, paused or failed+ lead_turns INTEGER NOT NULL DEFAULT 0, -- managing turns spent since the last resume+ lang TEXT NOT NULL DEFAULT '',+ origin_json TEXT NOT NULL DEFAULT '{}', -- the board assignment it answers, if any+ created_ms INTEGER NOT NULL,+ updated_ms INTEGER NOT NULL,+ done_ms INTEGER+);++CREATE INDEX IF NOT EXISTS idx_society_team_goals_group+ ON society_team_goals(group_id, created_ms);++CREATE TABLE IF NOT EXISTS society_team_tasks (+ task_id TEXT PRIMARY KEY,+ goal_id TEXT NOT NULL,+ agent_id TEXT NOT NULL, -- the member doing it+ title TEXT NOT NULL,+ brief TEXT NOT NULL DEFAULT '',+ state TEXT NOT NULL DEFAULT 'assigned'+ CHECK (state IN ('waiting', 'assigned', 'running', 'done', 'blocked',+ 'cancelled')),+ trace_id TEXT NOT NULL UNIQUE,+ assign_event_id TEXT,+ run_id TEXT NOT NULL DEFAULT '',+ result TEXT NOT NULL DEFAULT '',+ reviewed INTEGER NOT NULL DEFAULT 0, -- the lead has read the outcome+ attempts INTEGER NOT NULL DEFAULT 0, -- knocks on a busy member+ created_ms INTEGER NOT NULL,+ updated_ms INTEGER NOT NULL,+ done_ms INTEGER+);++CREATE INDEX IF NOT EXISTS idx_society_team_tasks_goal ON society_team_tasks(goal_id, created_ms);+-- Bounded group discussions: state lives here, history in society_events-- (msg_type ROOM_OPEN / SAY / ROOM_SETTLE sharing the room's trace_id).CREATE TABLE IF NOT EXISTS society_rooms (diff --git a/jarvis/society/store.py b/jarvis/society/store.pyindex dd4a574c88..b87758d3c4 100644--- a/jarvis/society/store.py+++ b/jarvis/society/store.py@@ -16,6 +16,7 @@ from __future__ import annotationsimport jsonimport logging+from collections.abc import Iterablefrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any@@ -55,6 +56,21 @@ _EVENT_COLUMNS = ()+_GROUP_COLUMNS = "group_id, name, members_json, created_ms, updated_ms, lead_agent_id, mission"+++def _row_to_group(row: Any) -> dict[str, Any]:+ return {+ "group_id": row[0],+ "name": row[1],+ "members": json.loads(row[2]),+ "created_ms": row[3],+ "updated_ms": row[4],+ "lead_agent_id": row[5] or None,+ "mission": row[6] or "",+ }++def _row_to_envelope(row: Any) -> SocietyEnvelope:return SocietyEnvelope(seq=int(row[0]),@@ -155,8 +171,26 @@ class SocietyStore:"CHECK (runtime IN ('jarvis', 'hermes', 'openclaw'))")log.info("society store: migration applied — added runtime")+ await self._migrate_chat_groups()await self._migrate_checkpoint_vocabulary()+ async def _migrate_chat_groups(self) -> None:+ """Team leads (2026-10): a group may name its lead and carry a mission."""+ cur = await self.conn.execute("PRAGMA table_info(society_chat_groups)")+ existing = {str(r[1]) for r in await cur.fetchall()}+ await cur.close()+ if "lead_agent_id" not in existing:+ # NULL = no lead; every existing team keeps working as before.+ await self.conn.execute(+ "ALTER TABLE society_chat_groups ADD COLUMN lead_agent_id TEXT DEFAULT NULL"+ )+ log.info("society store: migration applied — added chat group lead_agent_id")+ if "mission" not in existing:+ await self.conn.execute(+ "ALTER TABLE society_chat_groups ADD COLUMN mission TEXT NOT NULL DEFAULT ''"+ )+ log.info("society store: migration applied — added chat group mission")+async def _migrate_checkpoint_vocabulary(self) -> None:"""Widen the ``checkpoint`` CHECK to today's vocabulary (the hub shops, 2026-09).@@ -395,44 +429,26 @@ class SocietyStore:async def list_chat_groups(self) -> list[dict[str, Any]]:async with self.conn.execute(- "SELECT group_id, name, members_json, created_ms, updated_ms "- "FROM society_chat_groups ORDER BY created_ms ASC"+ f"SELECT {_GROUP_COLUMNS} FROM society_chat_groups ORDER BY created_ms ASC" # noqa: S608 — fixed column list) as cur:rows = await cur.fetchall()- return [- {- "group_id": row[0],- "name": row[1],- "members": json.loads(row[2]),- "created_ms": row[3],- "updated_ms": row[4],- }- for row in rows- ]+ return [_row_to_group(row) for row in rows]async def get_chat_group(self, group_id: str) -> dict[str, Any] | None:async with self.conn.execute(- "SELECT group_id, name, members_json, created_ms, updated_ms "- "FROM society_chat_groups WHERE group_id = ?",+ f"SELECT {_GROUP_COLUMNS} FROM society_chat_groups WHERE group_id = ?", # noqa: S608 — fixed column list(group_id,),) as cur:row = await cur.fetchone()- if row is None:- return None- return {- "group_id": row[0],- "name": row[1],- "members": json.loads(row[2]),- "created_ms": row[3],- "updated_ms": row[4],- }+ return _row_to_group(row) if row is not None else Noneasync def create_chat_group(self, group_id: str, name: str, members: list[str]) -> dict[str, Any]:stamp = now_ms()await self.conn.execute(- "INSERT INTO society_chat_groups VALUES (?, ?, ?, ?, ?)",+ "INSERT INTO society_chat_groups "+ "(group_id, name, members_json, created_ms, updated_ms) VALUES (?, ?, ?, ?, ?)",(group_id, name, json.dumps(members), stamp, stamp),)return (await self.get_chat_group(group_id)) or {}@@ -447,9 +463,130 @@ class SocietyStore:)return (await self.get_chat_group(group_id)) or {}+ async def set_chat_group_lead(+ self, group_id: str, lead_agent_id: str | None+ ) -> dict[str, Any]:+ await self.conn.execute(+ "UPDATE society_chat_groups SET lead_agent_id = ?, updated_ms = ? WHERE group_id = ?",+ (lead_agent_id, now_ms(), group_id),+ )+ return (await self.get_chat_group(group_id)) or {}++ async def set_chat_group_mission(self, group_id: str, mission: str) -> dict[str, Any]:+ await self.conn.execute(+ "UPDATE society_chat_groups SET mission = ?, updated_ms = ? WHERE group_id = ?",+ (mission, now_ms(), group_id),+ )+ return (await self.get_chat_group(group_id)) or {}+async def delete_chat_group(self, group_id: str) -> None:await self.conn.execute("DELETE FROM society_chat_groups WHERE group_id = ?", (group_id,))+ # ---------------------------------------------------- team goals and tasks++ async def _insert(self, table: str, row: dict[str, Any]) -> None:+ cols = ", ".join(row)+ marks = ", ".join("?" for _ in row)+ await self.conn.execute(+ f"INSERT INTO {table} ({cols}) VALUES ({marks})", # noqa: S608 — identifiers from the caller's fixed dict, values bound+ tuple(row.values()),+ )++ async def _update(self, table: str, key: str, key_value: str, fields: dict[str, Any]) -> bool:+ if not fields:+ return False+ sets = ", ".join(f"{k} = ?" for k in fields)+ cur = await self.conn.execute(+ f"UPDATE {table} SET {sets} WHERE {key} = ?", # noqa: S608 — identifiers from a fixed allowlist, values bound+ (*fields.values(), key_value),+ )+ await cur.close()+ return bool(cur.rowcount)++ async def _select(self, sql: str, args: tuple[Any, ...] = ()) -> list[dict[str, Any]]:+ self.conn.row_factory = aiosqlite.Row+ cur = await self.conn.execute(sql, args)+ rows = await cur.fetchall()+ await cur.close()+ return [dict(r) for r in rows]++ async def insert_team_goal(self, row: dict[str, Any]) -> None:+ await self._insert("society_team_goals", row)++ async def update_team_goal(self, goal_id: str, fields: dict[str, Any]) -> bool:+ return await self._update("society_team_goals", "goal_id", goal_id, fields)++ async def transition_team_goal(+ self, goal_id: str, from_states: Iterable[str], fields: dict[str, Any]+ ) -> bool:+ """Update a goal only while it is in one of ``from_states``.++ The compare-and-swap every state change goes through: two callers+ that read the same state cannot both move the goal (a stop that+ lands between a resume's read and its write must win).+ """+ states = tuple(from_states)+ sets = ", ".join(f"{k} = ?" for k in fields)+ marks = ", ".join("?" for _ in states)+ cur = await self.conn.execute(+ f"UPDATE society_team_goals SET {sets} " # noqa: S608 — identifiers from a fixed allowlist, values bound+ f"WHERE goal_id = ? AND state IN ({marks})",+ (*fields.values(), goal_id, *states),+ )+ await cur.close()+ return bool(cur.rowcount)++ async def get_team_goal_row(self, goal_id: str) -> dict[str, Any] | None:+ rows = await self._select("SELECT * FROM society_team_goals WHERE goal_id = ?", (goal_id,))+ return rows[0] if rows else None++ async def list_team_goal_rows(+ self, *, group_id: str | None = None, limit: int = 200+ ) -> list[dict[str, Any]]:+ """Newest first; every group's goals when ``group_id`` is ``None``."""+ if group_id is None:+ return await self._select(+ "SELECT * FROM society_team_goals ORDER BY created_ms DESC, goal_id DESC LIMIT ?",+ (int(limit),),+ )+ return await self._select(+ "SELECT * FROM society_team_goals WHERE group_id = ? "+ "ORDER BY created_ms DESC, goal_id DESC LIMIT ?",+ (group_id, int(limit)),+ )++ async def delete_team_goals(self, group_id: str) -> None:+ await self.conn.execute(+ "DELETE FROM society_team_tasks WHERE goal_id IN "+ "(SELECT goal_id FROM society_team_goals WHERE group_id = ?)",+ (group_id,),+ )+ await self.conn.execute("DELETE FROM society_team_goals WHERE group_id = ?", (group_id,))++ async def insert_team_task(self, row: dict[str, Any]) -> None:+ await self._insert("society_team_tasks", row)++ async def update_team_task(self, task_id: str, fields: dict[str, Any]) -> bool:+ return await self._update("society_team_tasks", "task_id", task_id, fields)++ async def get_team_task_row(self, task_id: str) -> dict[str, Any] | None:+ rows = await self._select("SELECT * FROM society_team_tasks WHERE task_id = ?", (task_id,))+ return rows[0] if rows else None++ async def get_team_task_row_by_trace(self, trace_id: str) -> dict[str, Any] | None:+ rows = await self._select(+ "SELECT * FROM society_team_tasks WHERE trace_id = ?", (trace_id,)+ )+ return rows[0] if rows else None++ async def list_team_task_rows(self, goal_id: str) -> list[dict[str, Any]]:+ """A goal's tasks, oldest first."""+ return await self._select(+ "SELECT * FROM society_team_tasks WHERE goal_id = ? "+ "ORDER BY created_ms ASC, task_id ASC",+ (goal_id,),+ )+async def last_seq(self) -> int:cur = await self.conn.execute("SELECT COALESCE(MAX(seq), 0) FROM society_events")row = await cur.fetchone()diff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex db278f921e..9169396745 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -60,6 +60,7 @@ from .roster import (from .routine_runner import is_routine_sessionfrom .runtime import current_runtimefrom .share_tool import ShareTemplateTool+from .team_tools import team_lead_toolslog = logging.getLogger(__name__)@@ -428,6 +429,8 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:),})+ # A team's lead plans, assigns and reports with three more tools.+ tools.update(cast(dict[str, Tool], team_lead_tools(rt, agent_id)))session_id = str(getattr(session, "session_id", "") or "")# A routine runs unattended: it never gets a way to ask the user.if not is_routine_session(session_id):@@ -889,6 +892,9 @@ async def society_system_extra(cfg: Any, brain: Any, session: Any) -> str:"\nThis is an unattended routine run: society_request_credential is not available. ""If a credential is missing, report which one in your result.")+ team = rt.team_leads.briefing(agent.agent_id)+ if team:+ context += "\n\n" + teamreturn (build_briefing(agent, catalog, roster, browser=browser, learned=learned, memory=memory)+ contextdiff --git a/jarvis/society/team_lead.py b/jarvis/society/team_lead.pynew file mode 100644index 0000000000..ff764e3643--- /dev/null+++ b/jarvis/society/team_lead.py@@ -0,0 +1,1746 @@+"""Team leads: one member manages a team toward the person's goals.++A team is a society chat group. Its lead is one of its members, an+``orchestrator`` on the roster, and the only member that hands out work. The+person gives the TEAM a goal; from there the lead works on its own:++1. **Plan.** The lead gets a managing turn in its own chat: the goal, the+ team's mission and who is on the team. It breaks the goal into tasks and+ hands each to a member with ``society_team_assign`` (``team_tools.py``).+2. **Work.** Every task is one ``ASSIGN`` on the board, on its own trace. The+ scheduler — trusted Python — decides whether the member starts. A busy+ member is not a failure: the task waits and knocks again by itself.+3. **Review.** When a result lands, this module wakes the lead with it. The+ lead accepts, sends rework, re-assigns a blocked task or asks the person.+ Results that arrive while the lead is mid-turn are batched into the next.+4. **Report.** The lead closes the goal with ``society_team_report``; the+ next queued goal starts. A goal that came in as a board assignment (from+ Jarvis by voice, or a quest) answers that assignment with its report.++Nothing here calls a model. The lead's turns run on the lead's own seat, the+members' on theirs, and every turn belongs to a goal the person started (or a+check-in they switched on, which is an ordinary agent routine). Opening the+app never resumes one: goals that were running when the app closed come back+``paused`` and wait for the person.++Bounds, so a goal can never run away: one active goal per team, a turn budget+per goal (:data:`MAX_LEAD_TURNS`, reset when the person resumes), a task cap+(:data:`MAX_TASKS_PER_GOAL`) and the society kill switch.+"""++from __future__ import annotations++import asyncio+import json+import logging+import re+from collections.abc import Callable, Mapping+from dataclasses import dataclass+from functools import partial+from typing import Any, Final++from jarvis.missions.ids import uuid7_str++from .events import (+ USER_ACTOR,+ AgentState,+ MsgType,+ SocietyEnvelope,+ TeamGoalState,+ TeamTaskState,+ Tier,+ now_ms,+)+from .roster import LEAD_AGENT_ID, AgentRecord, slugify++log = logging.getLogger(__name__)++__all__ = [+ "CHECKIN_TAG",+ "MAX_LEAD_TURNS",+ "MAX_TASKS_PER_GOAL",+ "TRACE_PREFIX",+ "TeamGoal",+ "TeamLeadError",+ "TeamLeads",+ "TeamTask",+]++TRACE_PREFIX: Final[str] = "team:"+#: Run id the scheduler gets for work handed to a lead: the goal, not a turn.+GOAL_RUN_PREFIX: Final[str] = "goal:"+#: Managing turns a lead may spend on one goal before it pauses for the person.+MAX_LEAD_TURNS: Final[int] = 24+MAX_TASKS_PER_GOAL: Final[int] = 40+#: Goals a team may hold that are not finished yet (the active one included).+MAX_OPEN_GOALS: Final[int] = 20+MAX_GOAL_TEXT: Final[int] = 20_000+MAX_MISSION: Final[int] = 4_000+#: How much of a member's result the lead reads per task in a review.+RESULT_CHARS: Final[int] = 3_000++#: Scheduler refusals that mean "not now" rather than "never".+WAIT_REASONS: Final[frozenset[str]] = frozenset({"target_busy", "concurrency_cap"})+RETRY_DELAY_S: Final[float] = 15.0+MAX_WAIT_ATTEMPTS: Final[int] = 120+#: Results landing close together reach the lead as one review.+REVIEW_DELAY_S: Final[float] = 1.5+LEAD_RETRY_S: Final[float] = 10.0+MAX_LEAD_WAIT_ATTEMPTS: Final[int] = 90+LEAD_TURN_TIMEOUT_S: Final[float] = 30 * 60.0+SWEEP_S: Final[float] = 60.0+#: A task with no sign of life for this long is checked against the scheduler.+STALL_MS: Final[int] = 3 * 60 * 1000++CHECKIN_TAG: Final[str] = "team-checkin:"+CHECKIN_MINUTES: Final[tuple[int, ...]] = (0, 60, 240, 1440)+_PROMOTED_KEY: Final[str] = "team_lead_promoted:"++GOAL_TERMINAL: Final[frozenset[TeamGoalState]] = frozenset(+ {TeamGoalState.DONE, TeamGoalState.FAILED, TeamGoalState.CANCELLED}+)+#: Every state a goal can still be closed from.+GOAL_OPEN: Final[tuple[TeamGoalState, ...]] = (+ TeamGoalState.QUEUED,+ TeamGoalState.RUNNING,+ TeamGoalState.NEEDS_INPUT,+ TeamGoalState.PAUSED,+)+#: States that hold the team: no other goal starts while one is in them.+GOAL_ACTIVE: Final[frozenset[TeamGoalState]] = frozenset(+ {TeamGoalState.RUNNING, TeamGoalState.NEEDS_INPUT, TeamGoalState.PAUSED}+)+TASK_OPEN: Final[frozenset[TeamTaskState]] = frozenset(+ {TeamTaskState.WAITING, TeamTaskState.ASSIGNED, TeamTaskState.RUNNING}+)+TASK_FINISHED: Final[frozenset[TeamTaskState]] = frozenset(+ {TeamTaskState.DONE, TeamTaskState.BLOCKED}+)++#: Standing instructions of a lead created from the team board.+LEAD_DESCRIPTION: Final[str] = (+ "You manage a team of agents for the person. You own the outcome of every goal the "+ "team is given: break it into concrete tasks, hand each task to the member whose role "+ "fits best, check what comes back against the goal, send rework when it falls short, "+ "and report the finished result. You plan, coordinate and review; the members do the "+ "specialist work. Keep work moving without being asked, and bring a decision to the "+ "person only when it is truly theirs to make."+)++_LEAD_RULES: Final[str] = (+ "How you lead:\n"+ "- Hand out work with society_team_assign: one task per call, to the member whose role "+ "fits. Give an independently actionable brief: objective, what you already know, scope, "+ "and what output proves it is done. Members work in parallel, so assign everything that "+ "can start now in the same turn.\n"+ "- Never wait or poll inside a turn. After assigning, end your turn with one short line "+ "on what is in progress. You are woken automatically the moment a result arrives.\n"+ "- When woken with results, judge them against the goal. Send follow-up or rework as a "+ "new assignment, give a blocked task to another member, or answer a member's question "+ "inside a new assignment so the answer is tracked.\n"+ "- Do a task yourself only when no member fits it.\n"+ "- Close the goal with society_team_report status=done and the complete result for the "+ "person: what was achieved, where the output is, what remains open. Use "+ "status=needs_input for a decision only the person can make (ask one precise question), "+ "status=progress for an interim update on long work, status=failed when the goal cannot "+ "be reached and why.\n"+ "- society_team_board shows the goal and every task at any time."+)++CHECKIN_PROMPT: Final[str] = (+ "Team check-in. Call society_team_board first. If a goal is stuck, blocked or waiting on "+ "a member, act on it: follow up, re-assign, or report to the person. If the team mission "+ "names standing duties that are due and no open goal covers them, start that work with "+ "society_team_assign. If nothing needs you, say so in one line and stop. Never invent "+ "work the mission or an open goal does not call for."+)++_NAME_UNSAFE: Final[re.Pattern[str]] = re.compile(r"[/\\:@#<>\"'`]")+++class TeamLeadError(ValueError):+ """A team-lead request that cannot be honored; ``status`` is the HTTP answer."""++ def __init__(self, message: str, *, status: int = 409) -> None:+ super().__init__(message)+ self.status = status+++def _loads(value: Any) -> dict[str, Any]:+ if isinstance(value, dict):+ return value+ try:+ data = json.loads(value) if value else {}+ except (TypeError, ValueError): # An unreadable stored blob reads as empty.+ return {}+ return data if isinstance(data, dict) else {}+++def goal_title(text: str, explicit: str = "") -> str:+ """A short title: the explicit one, else the first line of the goal."""+ title = " ".join((explicit or "").split())+ if not title:+ first = next((line.strip() for line in text.splitlines() if line.strip()), "")+ title = " ".join(first.split())+ if not title:+ return "Goal"+ return title if len(title) <= 90 else title[:89].rstrip() + "…"+++@dataclass(slots=True)+class TeamTask:+ task_id: str+ goal_id: str+ agent_id: str+ title: str+ brief: str+ state: TeamTaskState+ trace_id: str+ assign_event_id: str | None+ run_id: str+ result: str+ reviewed: bool+ attempts: int+ created_ms: int+ updated_ms: int+ done_ms: int | None++ @classmethod+ def from_row(cls, row: Mapping[str, Any]) -> TeamTask:+ return cls(+ task_id=str(row["task_id"]),+ goal_id=str(row["goal_id"]),+ agent_id=str(row["agent_id"]),+ title=str(row.get("title") or ""),+ brief=str(row.get("brief") or ""),+ state=TeamTaskState(str(row.get("state") or "assigned")),+ trace_id=str(row["trace_id"]),+ assign_event_id=row.get("assign_event_id"),+ run_id=str(row.get("run_id") or ""),+ result=str(row.get("result") or ""),+ reviewed=bool(row.get("reviewed")),+ attempts=int(row.get("attempts") or 0),+ created_ms=int(row.get("created_ms") or 0),+ updated_ms=int(row.get("updated_ms") or 0),+ done_ms=row.get("done_ms"),+ )++ def to_dict(self) -> dict[str, Any]:+ return {+ "task_id": self.task_id,+ "goal_id": self.goal_id,+ "agent_id": self.agent_id,+ "title": self.title,+ "brief": self.brief,+ "state": str(self.state),+ "result": self.result,+ "reviewed": self.reviewed,+ "created_ms": self.created_ms,+ "updated_ms": self.updated_ms,+ "done_ms": self.done_ms,+ }+++@dataclass(slots=True)+class TeamGoal:+ goal_id: str+ group_id: str+ lead_agent_id: str+ title: str+ text: str+ state: TeamGoalState+ report: str+ note: str+ lead_turns: int+ lang: str+ origin: dict[str, Any]+ created_ms: int+ updated_ms: int+ done_ms: int | None++ @classmethod+ def from_row(cls, row: Mapping[str, Any]) -> TeamGoal:+ return cls(+ goal_id=str(row["goal_id"]),+ group_id=str(row["group_id"]),+ lead_agent_id=str(row["lead_agent_id"]),+ title=str(row.get("title") or ""),+ text=str(row.get("text") or ""),+ state=TeamGoalState(str(row.get("state") or "queued")),+ report=str(row.get("report") or ""),+ note=str(row.get("note") or ""),+ lead_turns=int(row.get("lead_turns") or 0),+ lang=str(row.get("lang") or ""),+ origin=_loads(row.get("origin_json")),+ created_ms=int(row.get("created_ms") or 0),+ updated_ms=int(row.get("updated_ms") or 0),+ done_ms=row.get("done_ms"),+ )++ def to_dict(self, tasks: list[TeamTask] | None = None) -> dict[str, Any]:+ return {+ "goal_id": self.goal_id,+ "group_id": self.group_id,+ "lead_agent_id": self.lead_agent_id,+ "title": self.title,+ "text": self.text,+ "state": str(self.state),+ "report": self.report,+ "note": self.note,+ "lead_turns": self.lead_turns,+ "source": str(self.origin.get("kind") or "board"),+ "created_ms": self.created_ms,+ "updated_ms": self.updated_ms,+ "done_ms": self.done_ms,+ "tasks": [task.to_dict() for task in tasks or []],+ }+++class TeamLeads:+ """Leadership, goals and tasks of every team, over the society runtime."""++ def __init__(+ self,+ runtime: Any,+ *,+ publish: Callable[[Any], Any] | None = None,+ retry_delay_s: float = RETRY_DELAY_S,+ review_delay_s: float = REVIEW_DELAY_S,+ lead_retry_s: float = LEAD_RETRY_S,+ sweep_s: float = SWEEP_S,+ ) -> None:+ self._rt = runtime+ self._publish = publish+ self._retry_delay = retry_delay_s+ self._review_delay = review_delay_s+ self._lead_retry = lead_retry_s+ self._sweep_s = sweep_s+ self._unsubscribe: Callable[[], None] | None = None+ #: lead agent id -> the group it leads (a synchronous read for the tool set).+ self._leads: dict[str, str] = {}+ #: Every group as last read, for the synchronous prompt builders.+ self._groups: dict[str, dict[str, Any]] = {}+ #: goal id -> (lead session, turn id) of the managing turn in flight.+ self._turns: dict[str, tuple[str, str]] = {}+ #: lead agent id -> the goal its managing turn belongs to.+ self._lead_goal: dict[str, str] = {}+ #: What the person said about a goal that its lead has not read yet.+ self._told: dict[str, list[str]] = {}+ #: Goals the person resumed whose lead has not picked them up yet.+ self._resumed: set[str] = set()+ #: Goals whose lead was asked once for a typed report after a plain answer.+ self._nudged: set[str] = set()+ self._timers: dict[str, asyncio.TimerHandle] = {}+ self._tasks: set[asyncio.Task[Any]] = set()+ self._locks: dict[str, asyncio.Lock] = {}+ self._sweeper: asyncio.Task[None] | None = None++ # ------------------------------------------------------------ wiring++ async def start(self) -> None:+ """Subscribe to the board, load who leads what, park interrupted goals."""+ if self._unsubscribe is None:+ self._unsubscribe = self._rt.store.bus.subscribe_all(self._on_envelope)+ await self.refresh()+ await self._recover()+ if self._sweeper is None:+ self._sweeper = asyncio.create_task(self._sweep_loop(), name="society-team-sweep")++ def detach(self) -> None:+ if self._unsubscribe is not None:+ self._unsubscribe()+ self._unsubscribe = None+ for handle in self._timers.values():+ handle.cancel()+ self._timers.clear()+ if self._sweeper is not None:+ self._sweeper.cancel()+ self._sweeper = None+ for task in list(self._tasks):+ task.cancel()+ self._tasks.clear()++ async def refresh(self) -> None:+ """Re-read the groups into the synchronous caches."""+ groups = await self._rt.store.list_chat_groups()+ self._groups = {str(g["group_id"]): g for g in groups}+ self._leads = {+ str(g["lead_agent_id"]): str(g["group_id"]) for g in groups if g.get("lead_agent_id")+ }++ def group_led_by(self, agent_id: str) -> str | None:+ """The group ``agent_id`` leads, else ``None``. Synchronous, no IO."""+ return self._leads.get(agent_id)++ def is_managing(self, session_id: str) -> bool:+ """Whether ``session_id`` runs a lead's managing turn right now. Such a+ turn is coordination, not the agent's own work (no review follows it)."""+ return any(turn[0] == session_id for turn in self._turns.values())++ def teams_snapshot(self) -> list[dict[str, Any]]:+ """Teams that have a lead, as last read. Synchronous, no IO."""+ return [dict(g) for g in self._groups.values() if g.get("lead_agent_id")]++ def _lock(self, group_id: str) -> asyncio.Lock:+ lock = self._locks.get(group_id)+ if lock is None:+ lock = self._locks[group_id] = asyncio.Lock()+ return lock++ def _spawn(self, coro: Any) -> asyncio.Task[Any]:+ task = asyncio.create_task(self._guarded(coro))+ self._tasks.add(task)+ task.add_done_callback(self._tasks.discard)+ return task++ @staticmethod+ async def _guarded(coro: Any) -> None:+ try:+ await coro+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — a failed step is logged; the sweep parks a stuck goal+ log.warning("society team lead: background step failed", exc_info=True)++ def _arm(self, key: str, delay_s: float, factory: Callable[[], Any]) -> None:+ old = self._timers.pop(key, None)+ if old is not None:+ old.cancel()+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError: # No running loop (shutdown): there is nothing left to schedule on.+ return++ def fire() -> None:+ self._timers.pop(key, None)+ self._spawn(factory())++ self._timers[key] = loop.call_later(max(0.0, delay_s), fire)++ def _disarm(self, key: str) -> None:+ handle = self._timers.pop(key, None)+ if handle is not None:+ handle.cancel()++ # ------------------------------------------------------------- reads++ async def get_goal(self, goal_id: str) -> TeamGoal | None:+ row = await self._rt.store.get_team_goal_row(goal_id)+ return TeamGoal.from_row(row) if row else None++ async def goals(self, group_id: str, *, limit: int = 50) -> list[TeamGoal]:+ rows = await self._rt.store.list_team_goal_rows(group_id=group_id, limit=limit)+ return [TeamGoal.from_row(r) for r in rows]++ async def tasks(self, goal_id: str) -> list[TeamTask]:+ return [TeamTask.from_row(r) for r in await self._rt.store.list_team_task_rows(goal_id)]++ async def _active_goal(self, group_id: str) -> TeamGoal | None:+ """The goal that holds the team right now (running, waiting or paused)."""+ active = [g for g in await self.goals(group_id, limit=200) if g.state in GOAL_ACTIVE]+ running = [g for g in active if g.state is TeamGoalState.RUNNING]+ pick = running or active+ return min(pick, key=lambda g: g.created_ms) if pick else None++ async def snapshot(self, group_id: str) -> dict[str, Any]:+ """Everything the team board shows; reading it never starts a turn."""+ group = await self._rt.store.get_chat_group(group_id)+ if group is None:+ raise TeamLeadError("chat group not found", status=404)+ lead_id = group.get("lead_agent_id")+ lead = await self._rt.roster.get(lead_id) if lead_id else None+ goals = await self.goals(group_id)+ rows = [goal.to_dict(await self.tasks(goal.goal_id)) for goal in goals]+ return {+ "group_id": group_id,+ "lead_agent_id": lead_id,+ "lead_available": lead is not None and lead.state is AgentState.ACTIVE,+ "mission": group.get("mission") or "",+ "checkin_minutes": await self.checkin_minutes(group_id) if lead is not None else 0,+ "goals": rows,+ "working": any(goal.goal_id in self._turns for goal in goals),+ "max_lead_turns": MAX_LEAD_TURNS,+ }++ # -------------------------------------------------------- leadership++ async def _require_group(self, group_id: str) -> dict[str, Any]:+ group = await self._rt.store.get_chat_group(group_id)+ if group is None:+ raise TeamLeadError("chat group not found", status=404)+ return group++ async def _promote(self, agent: AgentRecord) -> None:+ """A lead assigns work, which the scheduler allows an orchestrator only."""+ if agent.tier is not Tier.SPECIALIST:+ return+ await self._rt.store.set_meta(+ _PROMOTED_KEY + agent.agent_id,+ json.dumps({"max_concurrent_runs": agent.max_concurrent_runs}),+ )+ await self._rt.roster.update(+ agent.agent_id,+ {"tier": Tier.ORCHESTRATOR, "max_concurrent_runs": max(3, agent.max_concurrent_runs)},+ )++ async def _demote(self, agent_id: str) -> None:+ """Undo :meth:`_promote`; an agent that was an orchestrator before stays one."""+ saved = await self._rt.store.get_meta(_PROMOTED_KEY + agent_id, "")+ if not saved:+ return+ await self._rt.store.set_meta(_PROMOTED_KEY + agent_id, "")+ agent = await self._rt.roster.get(agent_id)+ if agent is None or agent.tier is not Tier.ORCHESTRATOR:+ return+ runs = int(_loads(saved).get("max_concurrent_runs") or 1)+ await self._rt.roster.update(+ agent_id, {"tier": Tier.SPECIALIST, "max_concurrent_runs": max(1, runs)}+ )++ async def set_lead(self, group_id: str, agent_id: str | None) -> dict[str, Any]:+ """Name the member that manages the team, or clear the lead with ``None``."""+ async with self._lock(group_id):+ group = await self._require_group(group_id)+ current = group.get("lead_agent_id")+ if agent_id == current:+ return group+ if current and await self._active_goal(group_id) is not None:+ raise TeamLeadError("Stop the team's current goal before changing its lead.")+ minutes = await self.checkin_minutes(group_id) if current else 0+ if agent_id is None:+ await self._drop_checkin(group_id)+ group = await self._rt.store.set_chat_group_lead(group_id, None)+ await self._demote(str(current))+ await self.refresh()+ await self._announce(group_id, reason="lead")+ return group+ agent = await self._rt.roster.get(agent_id)+ if agent is None or agent.state is AgentState.ARCHIVED:+ raise TeamLeadError("That agent is not available.", status=404)+ if agent.agent_id == LEAD_AGENT_ID:+ raise TeamLeadError(+ "Jarvis already leads every agent; pick another member.", status=422+ )+ other = self._leads.get(agent.agent_id)+ if other and other != group_id:+ raise TeamLeadError(f"{agent.name} already leads another team.")+ if current:+ await self._drop_checkin(group_id)+ members = list(group["members"])+ if agent.agent_id not in members:+ members.append(agent.agent_id)+ await self._rt.store.update_chat_group(group_id, group["name"], members)+ await self._promote(agent)+ group = await self._rt.store.set_chat_group_lead(group_id, agent.agent_id)+ if current:+ await self._demote(str(current))+ await self.refresh()+ if minutes:+ try:+ await self.set_checkin(group_id, minutes)+ except TeamLeadError:+ log.info("society team lead: check-in not moved to the new lead")+ await self._announce(group_id, reason="lead")+ return group++ async def create_lead(+ self, group_id: str, *, name: str = "", fields: dict[str, Any] | None = None+ ) -> tuple[dict[str, Any], AgentRecord]:+ """Create a new agent whose job is managing this team, and make it the lead."""+ group = await self._require_group(group_id)+ if group.get("lead_agent_id") and await self._active_goal(group_id) is not None:+ raise TeamLeadError("Stop the team's current goal before changing its lead.")+ base = " ".join(_NAME_UNSAFE.sub(" ", name or f"{group['name']} Lead").split())[:36]+ base = base or "Team Lead"+ candidate, number = base, 2+ while await self._rt.roster.resolve(candidate) is not None:+ candidate = f"{base} {number}"+ number += 1+ agent, _ = await self._rt.roster.create(+ name=candidate,+ title="Team lead",+ description=LEAD_DESCRIPTION,+ tier=Tier.ORCHESTRATOR,+ **(fields or {}),+ )+ return await self.set_lead(group_id, agent.agent_id), agent++ async def set_mission(self, group_id: str, mission: str) -> dict[str, Any]:+ await self._require_group(group_id)+ group = await self._rt.store.set_chat_group_mission(group_id, mission.strip()[:MAX_MISSION])+ await self.refresh()+ await self._announce(group_id, reason="mission")+ return group++ async def members_changed(self, group_id: str, members: list[str]) -> None:+ """A group edit: a lead that left the team stops leading it."""+ group = self._groups.get(group_id) or await self._rt.store.get_chat_group(group_id) or {}+ lead_id = group.get("lead_agent_id")+ if lead_id and lead_id not in members:+ if await self._active_goal(group_id) is not None:+ raise TeamLeadError("Stop the team's current goal before removing its lead.")+ await self.set_lead(group_id, None)+ else:+ await self.refresh()++ async def group_deleted(self, group_id: str) -> None:+ """The team is gone: stop its goals, free its lead, forget its history."""+ for goal in await self.goals(group_id, limit=1000):+ if goal.state not in GOAL_TERMINAL:+ await self.cancel(goal.goal_id)+ group = await self._rt.store.get_chat_group(group_id)+ lead_id = (group or {}).get("lead_agent_id")+ if lead_id:+ await self._drop_checkin(group_id)+ await self._rt.store.set_chat_group_lead(group_id, None)+ await self._demote(str(lead_id))+ await self._rt.store.delete_team_goals(group_id)+ self._locks.pop(group_id, None)++ # ----------------------------------------------------------- check-ins++ async def _checkin_rows(self, group_id: str) -> list[dict[str, Any]]:+ store, _ = self._rt.task_services()+ group = self._groups.get(group_id) or {}+ lead_id = group.get("lead_agent_id")+ if store is None or not lead_id:+ return []+ from .routines import list_routines++ ended = {"completed", "cancelled", "failed", "interrupted"}+ return [+ row+ for row in await list_routines(store, str(lead_id))+ if CHECKIN_TAG + group_id in row.get("tags", ()) and row.get("state") not in ended+ ]++ async def checkin_minutes(self, group_id: str) -> int:+ """How often the lead looks at its team unprompted; ``0`` = never."""+ try:+ rows = await self._checkin_rows(group_id)+ except Exception: # noqa: BLE001 — an unreadable task store reads as "off" on the board+ log.warning("society team lead: check-in state unreadable", exc_info=True)+ return 0+ for row in rows:+ seconds = float((row.get("trigger") or {}).get("interval_seconds") or 0)+ if seconds > 0:+ return int(round(seconds / 60))+ return 0++ async def _drop_checkin(self, group_id: str) -> None:+ store, scheduler = self._rt.task_services()+ if store is None or scheduler is None:+ return+ for row in await self._checkin_rows(group_id):+ task_id = str(row.get("id"))+ await scheduler.cancel_task(task_id)+ await store.delete(task_id)++ async def set_checkin(self, group_id: str, minutes: int) -> int:+ """Switch the lead's unprompted check-in on (an agent routine) or off."""+ if minutes not in CHECKIN_MINUTES:+ raise TeamLeadError("Unknown check-in interval.", status=422)+ group = await self._require_group(group_id)+ lead_id = group.get("lead_agent_id")+ lead = await self._rt.roster.get(lead_id) if lead_id else None+ if lead is None:+ raise TeamLeadError("This team has no lead yet.")+ store, scheduler = self._rt.task_services()+ if store is None or scheduler is None:+ raise TeamLeadError("The task scheduler is unavailable.", status=503)+ await self.refresh()+ await self._drop_checkin(group_id)+ if minutes:+ from .routines import build_task_spec, create_routine++ spec = build_task_spec(+ lead,+ title=f"Team check-in: {group['name']}",+ prompt=CHECKIN_PROMPT,+ schedule={"kind": "every", "interval_seconds": minutes * 60},+ )+ spec = spec.model_copy(update={"tags": (*spec.tags, CHECKIN_TAG + group_id)})+ await create_routine(store, scheduler, spec)+ await self._announce(group_id, reason="checkin")+ return minutes++ # ------------------------------------------------------------- goals++ def _language(self, text: str, lang: str | None) -> str:+ if lang:+ return str(lang)+ try:+ from jarvis.core.turn_language import resolve_output_language++ cfg = self._rt.config()+ pinned = getattr(getattr(cfg, "brain", None), "reply_language", "auto")+ return str(resolve_output_language(pinned, "", text) or "")+ except Exception: # noqa: BLE001 — without a language the lead answers in the goal's own+ log.debug("society team lead: output language unresolved", exc_info=True)+ return ""++ async def start_goal(+ self,+ group_id: str,+ text: str,+ *,+ title: str = "",+ lang: str | None = None,+ origin: dict[str, Any] | None = None,+ ) -> TeamGoal:+ """Give the team a goal. It starts at once, or queues behind the current one."""+ clean = text.strip()[:MAX_GOAL_TEXT]+ if not clean:+ raise TeamLeadError("A goal needs a description.", status=422)+ group = await self._require_group(group_id)+ lead_id = group.get("lead_agent_id")+ if not lead_id:+ raise TeamLeadError("This team has no lead yet.")+ if await self._rt.store.kill_switch():+ raise TeamLeadError("The society is paused.")+ goals = await self.goals(group_id, limit=200)+ open_goals = [g for g in goals if g.state not in GOAL_TERMINAL]+ if len(open_goals) >= MAX_OPEN_GOALS:+ raise TeamLeadError("This team already has too many open goals.")+ goal_id = uuid7_str()+ stamp = now_ms()+ await self._rt.store.insert_team_goal(+ {+ "goal_id": goal_id,+ "group_id": group_id,+ "lead_agent_id": str(lead_id),+ "title": goal_title(clean, title),+ "text": clean,+ "state": str(TeamGoalState.QUEUED),+ "lang": self._language(clean, lang),+ "origin_json": json.dumps(origin or {}),+ "created_ms": stamp,+ "updated_ms": stamp,+ }+ )+ await self._announce(group_id, goal_id=goal_id, state=TeamGoalState.QUEUED)+ await self._advance(group_id)+ goal = await self.get_goal(goal_id)+ assert goal is not None+ return goal++ async def accept_assignment(self, lead: AgentRecord, env: SocietyEnvelope) -> str:+ """An ``ASSIGN`` to a team lead (from Jarvis, the person or a quest)+ becomes the team's goal; its report answers the assignment."""+ group_id = self._leads.get(lead.agent_id)+ if group_id is None:+ raise TeamLeadError("This agent leads no team.")+ goal = await self.start_goal(+ group_id,+ env.text or str(env.payload.get("task") or ""),+ title=str(env.payload.get("title") or ""),+ lang=str(env.payload.get("lang") or "") or None,+ origin={+ "kind": "jarvis" if env.from_agent == LEAD_AGENT_ID else "assignment",+ "event_id": env.event_id,+ },+ )+ return f"{GOAL_RUN_PREFIX}{goal.goal_id}"++ async def _advance(self, group_id: str) -> None:+ """Start the team's oldest queued goal when nothing else holds the team."""+ async with self._lock(group_id):+ goals = await self.goals(group_id, limit=200)+ if any(goal.state in GOAL_ACTIVE for goal in goals):+ return+ queued = sorted(+ (g for g in goals if g.state is TeamGoalState.QUEUED), key=lambda g: g.created_ms+ )+ if not queued:+ return+ goal = queued[0]+ if not await self._move(+ goal, TeamGoalState.RUNNING, (TeamGoalState.QUEUED,), lead_turns=0, note=""+ ):+ return+ self._wake_lead(goal.goal_id)++ async def tell(self, goal_id: str, text: str) -> TeamGoal:+ """The person answers the lead's question or steers a goal in progress."""+ message = text.strip()[:MAX_GOAL_TEXT]+ if not message:+ raise TeamLeadError("A message is required.", status=422)+ goal = await self._require_goal(goal_id)+ if goal.state in GOAL_TERMINAL or goal.state is TeamGoalState.QUEUED:+ raise TeamLeadError("This goal is not in progress.")+ if await self._rt.store.kill_switch():+ raise TeamLeadError("The society is paused.")+ # A goal that waited gets a fresh turn budget; one in progress keeps its own.+ waited = (TeamGoalState.NEEDS_INPUT, TeamGoalState.PAUSED)+ moved = await self._move(+ goal, TeamGoalState.RUNNING, waited, note="", lead_turns=0+ ) or await self._move(goal, TeamGoalState.RUNNING, (TeamGoalState.RUNNING,), note="")+ if not moved:+ raise TeamLeadError("This goal is not in progress.")+ self._nudged.discard(goal_id)+ self._told.setdefault(goal_id, []).append(message)+ self._wake_lead(goal_id)+ return await self._require_goal(goal_id)++ async def resume(self, goal_id: str) -> TeamGoal:+ """Continue a paused goal, retry a failed one, or start a queued one."""+ goal = await self._require_goal(goal_id)+ if goal.state is TeamGoalState.QUEUED:+ await self._advance(goal.group_id)+ return await self._require_goal(goal_id)+ if goal.state not in (TeamGoalState.PAUSED, TeamGoalState.FAILED):+ raise TeamLeadError("This goal is not paused.")+ if await self._rt.store.kill_switch():+ raise TeamLeadError("The society is paused.")+ stopped = (TeamGoalState.PAUSED, TeamGoalState.FAILED)+ active = await self._active_goal(goal.group_id)+ if active is not None and active.goal_id != goal_id:+ # Another goal holds the team: the retried one waits its turn.+ if not await self._move(+ goal, TeamGoalState.QUEUED, stopped, note="", done_ms=None+ ):+ raise TeamLeadError("This goal is not paused.")+ return await self._require_goal(goal_id)+ if not await self._move(+ goal, TeamGoalState.RUNNING, stopped, lead_turns=0, note="", done_ms=None+ ):+ raise TeamLeadError("This goal is not paused.")+ self._nudged.discard(goal_id)+ self._resumed.add(goal_id)+ self._wake_lead(goal_id)+ return await self._require_goal(goal_id)++ async def cancel(self, goal_id: str) -> TeamGoal:+ """Stop a goal: its lead turn and every member task that still runs."""+ goal = await self._require_goal(goal_id)+ if goal.state in GOAL_TERMINAL:+ return goal+ turn = self._turns.get(goal_id)+ await self._finish(goal, TeamGoalState.CANCELLED, note="cancelled")+ if turn is not None and turn[1]:+ await self._cancel_turn(turn[0], turn[1])+ return await self._require_goal(goal_id)++ async def halt(self) -> int:+ """The kill switch: every running goal pauses; nothing is retried."""+ for key in list(self._timers):+ self._disarm(key)+ paused = 0+ for row in await self._rt.store.list_team_goal_rows(limit=1000):+ goal = TeamGoal.from_row(row)+ if goal.state is TeamGoalState.RUNNING and await self._move(+ goal, TeamGoalState.PAUSED, (TeamGoalState.RUNNING,), note="society_paused"+ ):+ paused += 1+ return paused++ async def _require_goal(self, goal_id: str) -> TeamGoal:+ goal = await self.get_goal(goal_id)+ if goal is None:+ raise TeamLeadError("goal not found", status=404)+ return goal++ async def _move(+ self,+ goal: TeamGoal,+ state: TeamGoalState,+ expected: tuple[TeamGoalState, ...],+ **fields: Any,+ ) -> bool:+ """Move a goal to ``state`` only while it is in one of ``expected``.++ Every state change goes through here, so a stop that lands while+ another caller holds a stale read wins instead of being undone.+ """+ fields["state"] = str(state)+ fields["updated_ms"] = now_ms()+ moved = await self._rt.store.transition_team_goal(+ goal.goal_id, [str(s) for s in expected], fields+ )+ if moved:+ await self._announce(goal.group_id, goal_id=goal.goal_id, state=state)+ return bool(moved)++ async def _cancel_turn(self, session_id: str, turn_id: str) -> None:+ svc = self._rt.chat_service()+ if svc is None or not turn_id:+ return+ try:+ await svc.cancel(session_id, expected_turn_id=turn_id)+ except Exception: # noqa: BLE001 — the goal is closed either way; the turn ends on its own+ log.warning("society team lead: turn %s could not be stopped", turn_id, exc_info=True)++ async def _finish(+ self, goal: TeamGoal, state: TeamGoalState, *, report: str | None = None, note: str = ""+ ) -> bool:+ """Close a goal: stop what still runs, answer its origin, start the next.++ ``False`` when the goal was already closed by someone else.+ """+ fields: dict[str, Any] = {"note": note, "done_ms": now_ms()}+ if report is not None:+ fields["report"] = report+ if not await self._move(goal, state, GOAL_OPEN, **fields):+ return False+ self._disarm(f"lead:{goal.goal_id}")+ self._told.pop(goal.goal_id, None)+ self._resumed.discard(goal.goal_id)+ self._nudged.discard(goal.goal_id)+ for task in await self.tasks(goal.goal_id):+ if task.state not in TASK_OPEN:+ continue+ self._disarm(f"task:{task.task_id}")+ await self._rt.store.update_team_task(+ task.task_id,+ {+ "state": str(TeamTaskState.CANCELLED),+ "updated_ms": now_ms(),+ "done_ms": now_ms(),+ "reviewed": 1,+ },+ )+ if task.run_id:+ self._rt.scheduler.note_run_ended(task.run_id)+ if task.run_id.startswith("turn:"):+ from .roster import canonical_session_id++ await self._cancel_turn(+ canonical_session_id(task.agent_id), task.run_id.removeprefix("turn:")+ )+ await self._answer_origin(goal, state, report if report is not None else goal.report, note)+ await self._announce(goal.group_id, goal_id=goal.goal_id, state=state)+ if goal.goal_id not in self._turns:+ await self._advance(goal.group_id)+ return True++ async def _answer_origin(+ self, goal: TeamGoal, state: TeamGoalState, report: str, note: str+ ) -> None:+ """A goal that came in as a board assignment answers it with a RESULT."""+ event_id = str(goal.origin.get("event_id") or "")+ if not event_id or goal.origin.get("answered"):+ return+ request = await self._rt.store.get_event(event_id)+ if request is None:+ return+ done = state is TeamGoalState.DONE+ summary = (report or note or "The team goal ended without a report.").strip()+ try:+ await self._rt.store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.RESULT,+ from_agent=goal.lead_agent_id,+ to_agent=request.from_agent if request.from_agent != USER_ACTOR else None,+ trace_id=request.trace_id,+ parent_event_id=request.event_id,+ payload={+ "run_id": f"{GOAL_RUN_PREFIX}{goal.goal_id}",+ "status": "done" if done else "blocked",+ "done": summary[:2000],+ "output": [f"team:{goal.group_id}"],+ "evidence": [],+ "open": [] if done else [(note or str(state))[:500]],+ "next_owner": None,+ "text": summary[:500],+ },+ )+ )+ except Exception: # noqa: BLE001 — the report stays on the team board either way+ log.warning("society team lead: origin of %s not answered", goal.goal_id, exc_info=True)+ return+ await self._rt.store.update_team_goal(+ goal.goal_id, {"origin_json": json.dumps({**goal.origin, "answered": True})}+ )+ lead = await self._rt.roster.get(goal.lead_agent_id)+ if lead is not None:+ await self._rt.report_to_lead(+ lead, request, status="done" if done else "blocked", summary=summary+ )++ # ------------------------------------------------------ the lead turn++ def _roster_lines(self, group: Mapping[str, Any], lead_id: str) -> list[str]:+ by_id = {a.agent_id: a for a in self._rt.roster.snapshot()}+ lines: list[str] = []+ for member_id in group.get("members", []):+ agent = by_id.get(member_id)+ if agent is None or member_id in (lead_id, LEAD_AGENT_ID):+ continue+ if agent.state is AgentState.ARCHIVED:+ continue+ line = f"- {agent.name}"+ if agent.title.strip():+ line += f" — {agent.title.strip()}"+ state = "paused" if agent.state is AgentState.PAUSED else (+ "working" if self._rt.scheduler.active_runs(agent.agent_id) else "free"+ )+ lines.append(f"{line} ({state})")+ return lines++ def _name(self, agent_id: str) -> str:+ for agent in self._rt.roster.snapshot():+ if agent.agent_id == agent_id:+ return str(agent.name)+ return agent_id++ def _board_lines(self, tasks: list[TeamTask], *, results: bool) -> list[str]:+ lines: list[str] = []+ for task in tasks:+ line = f'- {self._name(task.agent_id)} — "{task.title}": {task.state}'+ lines.append(line)+ if results and task.state in TASK_FINISHED and task.result:+ lines.append(" " + task.result[:RESULT_CHARS].replace("\n", "\n "))+ return lines++ def _frame(self, goal: TeamGoal, kind: str, body: list[str]) -> str:+ group = self._groups.get(goal.group_id) or {}+ lines = [f"[{kind} for team {group.get('name') or goal.group_id}]", *body]+ lines.append(f"Goal id: {goal.goal_id}. Managing turns left: "+ f"{max(0, MAX_LEAD_TURNS - goal.lead_turns - 1)}.")+ return "\n".join(lines)++ def _plan_prompt(self, goal: TeamGoal) -> tuple[str, str, list[str]]:+ group = self._groups.get(goal.group_id) or {}+ team = self._roster_lines(group, goal.lead_agent_id)+ body = ["The person gave your team this goal:", goal.text, ""]+ if str(group.get("mission") or "").strip():+ body += ["Team mission: " + str(group["mission"]).strip(), ""]+ body += ["Your team right now:", *(team or ["- (no other members yet)"]), ""]+ body += [+ "Plan the work and hand out every task that can start now. If the goal is too "+ "unclear to plan, ask the person with society_team_report status=needs_input.",+ ]+ return self._frame(goal, "team goal", body), goal.text, []++ def _news_body(self, goal: TeamGoal, tasks: list[TeamTask]) -> tuple[list[str], list[str]]:+ """What happened since the lead last looked, and the task ids it covers."""+ news = [t for t in tasks if t.state in TASK_FINISHED and not t.reviewed]+ open_tasks = [t for t in tasks if t.state in TASK_OPEN]+ body: list[str] = []+ if news:+ body += ["New results:", *self._board_lines(news, results=True), ""]+ if open_tasks:+ body += ["Still in progress:", *self._board_lines(open_tasks, results=False), ""]+ elif not news:+ body += ["No task is in progress.", ""]+ return body, [t.task_id for t in news]++ def _compose(self, goal: TeamGoal, tasks: list[TeamTask]) -> tuple[str, str, list[str]] | None:+ """What the lead needs to hear now: the person's words first, then a+ resume, the first plan, or new results. ``None`` = nothing to say."""+ told = self._told.get(goal.goal_id)+ if told:+ news, reported = self._news_body(goal, tasks)+ body = [f"Goal: {goal.title}", "", "The person says about this goal:", *told, ""]+ body += [*news, "Continue leading the goal with this answer."]+ return self._frame(goal, "team goal reply", body), told[-1], reported+ if goal.goal_id in self._resumed:+ news, reported = self._news_body(goal, tasks)+ body = ["The person asked you to continue this goal:", goal.text, ""]+ body += news if tasks else ["No task was handed out yet.", ""]+ body.append(+ "Pick the goal up from this state: re-assign what was interrupted or "+ "blocked, then lead it to its report."+ )+ return self._frame(goal, "team goal resumed", body), goal.title, reported+ if not tasks and goal.lead_turns == 0:+ return self._plan_prompt(goal)+ news, reported = self._news_body(goal, tasks)+ if not reported:+ if goal.goal_id not in self._nudged or any(t.state in TASK_OPEN for t in tasks):+ return None+ body = [+ f"Goal: {goal.title}",+ "",+ "Your last turn ended with no task running and no report, so the person "+ "has no result yet. If the goal is achieved, call society_team_report "+ "status=done with the complete result. If only the person can decide "+ "something, use status=needs_input with one question. If work is still "+ "needed, hand it out now.",+ ]+ return self._frame(goal, "team goal check", body), goal.title, []+ body = [f"Goal: {goal.title}", "", *news]+ body.append(+ "Decide now. Accept what is good, send rework or the next step as a new "+ "assignment, re-assign what is blocked, or close the goal with "+ "society_team_report. If work is still running and nothing needs a decision, "+ "end the turn in one line; you are woken again."+ )+ shown = f"{goal.title}: {len(reported)} result" + ("s" if len(reported) != 1 else "")+ return self._frame(goal, "team update", body), shown, reported++ async def _park(self, goal: TeamGoal, note: str) -> None:+ """Pause a running goal with the reason; a goal already stopped stays so."""+ if await self._move(goal, TeamGoalState.PAUSED, (TeamGoalState.RUNNING,), note=note):+ self._disarm(f"lead:{goal.goal_id}")++ def _wake_lead(self, goal_id: str, delay_s: float = 0.0, attempt: int = 0) -> None:+ """Ask for a managing turn; several asks before it starts become one."""+ self._arm(f"lead:{goal_id}", delay_s, lambda: self._lead_turn(goal_id, attempt))++ async def _lead_turn(self, goal_id: str, attempt: int = 0) -> None:+ """Give the lead one managing turn for ``goal_id``; a busy lead is retried.++ One turn per goal at a time. Whatever arrives while it runs — a result,+ the person's reply — stays pending and :meth:`_after_lead_turn` asks+ again, so nothing is lost and nothing is said twice.+ """+ if goal_id in self._turns:+ return+ # Claimed before the first await, so a second caller cannot start a twin.+ self._turns[goal_id] = ("", "")+ lead_id = ""+ started = False+ try:+ goal = await self.get_goal(goal_id)+ if goal is None or goal.state is not TeamGoalState.RUNNING:+ return+ lead_id = goal.lead_agent_id+ if await self._rt.store.kill_switch():+ await self._park(goal, "society_paused")+ return+ lead = await self._rt.roster.get(lead_id)+ svc = self._rt.chat_service()+ if lead is None or lead.state is not AgentState.ACTIVE or svc is None:+ await self._park(goal, "lead_unavailable")+ return+ if goal.lead_turns >= MAX_LEAD_TURNS:+ await self._park(goal, "turn_budget")+ return+ await self.refresh()+ await self._rt.roster.refresh()+ built = self._compose(goal, await self.tasks(goal_id))+ if built is None:+ return+ prompt, shown, reported = built+ told = len(self._told.get(goal_id, ()))+ from jarvis.agent_chat.service import SessionBusy++ from .chat_binding import agent_busy, ensure_session++ self._lead_goal[lead_id] = goal_id+ try:+ session = ensure_session(svc, self._rt.config(), lead)+ if svc.is_running(session.session_id) or agent_busy(svc, lead):+ raise SessionBusy(session.session_id)+ self._turns[goal_id] = (session.session_id, "")+ turn_id = str(+ await svc.send(+ session.session_id,+ prompt,+ direct_user=False,+ display_text=shown[:2000],+ output_language=goal.lang,+ )+ )+ except SessionBusy: # Busy is not a failure: knock again, then say so on the board.+ if attempt >= MAX_LEAD_WAIT_ATTEMPTS:+ await self._park(goal, "lead_busy")+ else:+ self._wake_lead(goal_id, self._lead_retry, attempt + 1)+ return+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 — the person sees why and can resume+ log.warning("society team lead: turn for %s did not start", goal_id, exc_info=True)+ await self._park(goal, f"error:{str(exc)[:300] or type(exc).__name__}")+ return+ self._turns[goal_id] = (session.session_id, turn_id)+ fresh = await self.get_goal(goal_id)+ if fresh is None or fresh.state is not TeamGoalState.RUNNING:+ # Stopped or paused while the turn was starting: it must not run on.+ await self._cancel_turn(session.session_id, turn_id)+ return+ started = True+ # Only what this prompt carried is consumed; later words stay pending.+ rest = self._told.get(goal_id, [])[told:]+ if rest:+ self._told[goal_id] = rest+ else:+ self._told.pop(goal_id, None)+ self._resumed.discard(goal_id)+ await self._rt.store.update_team_goal(+ goal_id, {"lead_turns": goal.lead_turns + 1, "updated_ms": now_ms()}+ )+ for task_id in reported:+ await self._rt.store.update_team_task(task_id, {"reviewed": 1})+ await self._announce(goal.group_id, goal_id=goal_id, state=goal.state, reason="turn")+ self._spawn(self._watch_lead(goal_id, lead_id, session.session_id, turn_id))+ finally:+ if not started:+ self._release_turn(goal_id, lead_id)++ def _release_turn(self, goal_id: str, lead_id: str) -> None:+ self._turns.pop(goal_id, None)+ if lead_id and self._lead_goal.get(lead_id) == goal_id:+ self._lead_goal.pop(lead_id, None)++ async def _watch_lead(self, goal_id: str, lead_id: str, session_id: str, turn_id: str) -> None:+ """Wait for the managing turn to end, then decide what the goal needs."""+ svc = self._rt.chat_service()+ ok, final, error = False, "", ""+ try:+ try:+ await asyncio.wait_for(svc.wait_turn(session_id), timeout=LEAD_TURN_TIMEOUT_S)+ except TimeoutError: # A turn this long is stopped; the person may resume.+ error = "The lead's turn took too long and was stopped."+ await self._cancel_turn(session_id, turn_id)+ else:+ terminal = None+ for _ in range(6):+ terminal = await asyncio.to_thread(+ svc.store.turn_terminal, session_id, turn_id+ )+ if terminal is not None:+ break+ await asyncio.sleep(0.5)+ payload = (terminal or {}).get("payload", {})+ ok = payload.get("status") in ("ok", "done", "completed")+ if not ok:+ error = str(payload.get("error") or payload.get("status") or "")+ error = error or "The lead's turn did not finish."+ events = await asyncio.to_thread(svc.store.list_events, session_id, tail=200)+ final = next(+ (+ str(e["payload"].get("text") or "")+ for e in reversed(events)+ if e["kind"] == "assistant_text" and e["payload"].get("turn_id") == turn_id+ ),+ "",+ )+ except asyncio.CancelledError:+ self._release_turn(goal_id, lead_id)+ raise+ except Exception as exc: # noqa: BLE001 — an unreadable turn pauses the goal, visibly+ log.warning("society team lead: turn %s could not be read", turn_id, exc_info=True)+ ok, error = False, str(exc)[:300] or type(exc).__name__+ self._release_turn(goal_id, lead_id)+ await self._after_lead_turn(goal_id, ok=ok, final=final.strip(), error=error)++ async def _after_lead_turn(self, goal_id: str, *, ok: bool, final: str, error: str) -> None:+ goal = await self.get_goal(goal_id)+ if goal is None:+ return+ if goal.state in GOAL_TERMINAL:+ await self._advance(goal.group_id)+ return+ await self._announce(goal.group_id, goal_id=goal_id, state=goal.state, reason="turn")+ if goal.state is not TeamGoalState.RUNNING:+ return+ if goal_id in self._turns:+ return # A newer turn owns the goal now; it decides what comes next.+ if self._told.get(goal_id) or goal_id in self._resumed:+ # The person spoke or resumed after this turn began (a turn the+ # kill switch stopped ends "cancelled"): their turn comes next.+ self._wake_lead(goal_id)+ return+ if not ok:+ await self._park(goal, f"error:{error}")+ return+ tasks = await self.tasks(goal_id)+ if any(t.state in TASK_FINISHED and not t.reviewed for t in tasks):+ self._wake_lead(goal_id)+ return+ if any(t.state in TASK_OPEN for t in tasks):+ return+ if goal_id not in self._nudged:+ # Nothing is running and nothing was reported. A plain answer may be+ # the result or a question; the lead says which, once, in a typed+ # report. Its answer stays visible on the board meanwhile.+ self._nudged.add(goal_id)+ if final:+ await self._rt.store.update_team_goal(goal_id, {"report": final})+ self._wake_lead(goal_id)+ return+ # Asked and still no report: the lead's answer is the result.+ await self._finish(goal, TeamGoalState.DONE, report=final or goal.report)++ # ----------------------------------------------------- the lead's tools++ async def _goal_for_lead(self, lead_id: str, *, create_title: str = "") -> TeamGoal:+ """The goal a lead's tool call belongs to; a lead working from its own+ chat with no goal open starts one."""+ group_id = self._leads.get(lead_id)+ if group_id is None:+ raise TeamLeadError("You do not lead a team.")+ goal_id = self._lead_goal.get(lead_id)+ goal = await self.get_goal(goal_id) if goal_id else None+ if goal is not None and goal.state is TeamGoalState.RUNNING:+ return goal+ if goal_id:+ # This is a managing turn whose goal was closed, stopped or handed to+ # the person meanwhile. It must not adopt or start another goal.+ raise TeamLeadError(+ "This goal is no longer in progress. End your turn; you are woken "+ "when there is something to do."+ )+ active = await self._active_goal(group_id)+ if active is not None:+ if active.state is not TeamGoalState.RUNNING:+ raise TeamLeadError(+ f'The goal "{active.title}" is {active.state}; the person continues it '+ "from the team board."+ )+ return active+ if not create_title:+ raise TeamLeadError("Your team has no goal in progress.")+ new_id = uuid7_str()+ stamp = now_ms()+ await self._rt.store.insert_team_goal(+ {+ "goal_id": new_id,+ "group_id": group_id,+ "lead_agent_id": lead_id,+ "title": goal_title(create_title),+ "text": create_title,+ "state": str(TeamGoalState.RUNNING),+ "lead_turns": 1,+ "origin_json": json.dumps({"kind": "lead"}),+ "created_ms": stamp,+ "updated_ms": stamp,+ }+ )+ await self._announce(group_id, goal_id=new_id, state=TeamGoalState.RUNNING)+ created = await self.get_goal(new_id)+ assert created is not None+ return created++ def _resolve_member(self, group: Mapping[str, Any], lead_id: str, wanted: str) -> AgentRecord:+ by_id = {a.agent_id: a for a in self._rt.roster.snapshot()}+ members = [+ by_id[m]+ for m in group.get("members", [])+ if m in by_id and m not in (lead_id, LEAD_AGENT_ID)+ ]+ key = wanted.strip()+ fold = key.casefold()+ for agent in members:+ if key == agent.agent_id or fold == agent.name.casefold():+ return agent+ slug = slugify(key)+ for agent in members:+ if slug in (agent.agent_id, slugify(agent.name)):+ return agent+ names = ", ".join(a.name for a in members) or "nobody yet"+ raise TeamLeadError(f"{key!r} is not a member of your team. Members: {names}.")++ async def assign(+ self, lead_id: str, *, member: str, title: str, brief: str, goal_title_hint: str = ""+ ) -> dict[str, Any]:+ """A lead hands one task to a member: a task row and its ``ASSIGN``."""+ if await self._rt.store.kill_switch():+ raise TeamLeadError("The society is paused.")+ if not title.strip() or not brief.strip():+ raise TeamLeadError("A task needs a title and a brief.")+ await self.refresh()+ group_id = self._leads.get(lead_id)+ if group_id is None:+ raise TeamLeadError("You do not lead a team.")+ await self._rt.roster.refresh()+ group = self._groups[group_id]+ target = self._resolve_member(group, lead_id, member)+ if target.state is not AgentState.ACTIVE:+ raise TeamLeadError(f"{target.name} is {target.state} and cannot take work.")+ goal = await self._goal_for_lead(lead_id, create_title=goal_title_hint or title)+ tasks = await self.tasks(goal.goal_id)+ if len(tasks) >= MAX_TASKS_PER_GOAL:+ raise TeamLeadError("This goal reached its task limit; report to the person.")+ task_id = uuid7_str()+ stamp = now_ms()+ env = self._assign_envelope(goal, lead_id, target.agent_id, task_id, title, brief)+ await self._rt.store.insert_team_task(+ {+ "task_id": task_id,+ "goal_id": goal.goal_id,+ "agent_id": target.agent_id,+ "title": " ".join(title.split())[:160],+ "brief": brief.strip(),+ "state": str(TeamTaskState.ASSIGNED),+ "trace_id": env.trace_id,+ "assign_event_id": env.event_id,+ "created_ms": stamp,+ "updated_ms": stamp,+ }+ )+ await self._rt.store.append_and_publish(env)+ row = await self._rt.store.get_team_task_row(task_id)+ task = TeamTask.from_row(row or {"task_id": task_id, "goal_id": goal.goal_id,+ "agent_id": target.agent_id, "trace_id": env.trace_id})+ await self._announce(group_id, goal_id=goal.goal_id, state=goal.state, reason="task")+ return {+ "task_id": task_id,+ "goal_id": goal.goal_id,+ "member": target.name,+ "state": str(task.state),+ "note": {+ TeamTaskState.RUNNING: f"{target.name} started.",+ TeamTaskState.WAITING: f"{target.name} is busy; the task starts by itself "+ "when they are free.",+ TeamTaskState.BLOCKED: task.result or "The task could not start.",+ }.get(task.state, "Recorded; the start is not confirmed yet."),+ }++ def _assign_envelope(+ self,+ goal: TeamGoal,+ lead_id: str,+ member_id: str,+ task_id: str,+ title: str,+ brief: str,+ attempt: int = 0,+ ) -> SocietyEnvelope:+ # Every knock gets its own trace: the scheduler caps the messages of+ # one trace, and a long wait on a busy member must not hit that cap.+ trace = f"{TRACE_PREFIX}{goal.goal_id}:{task_id}"+ if attempt:+ trace += f":{attempt}"+ text = f"{' '.join(title.split())}\n\n{brief.strip()}"+ payload: dict[str, Any] = {+ "text": text,+ "title": title,+ "reply_policy": "always",+ "team_goal_id": goal.goal_id,+ "team_task_id": task_id,+ }+ if goal.lang:+ payload["lang"] = goal.lang+ return SocietyEnvelope(+ msg_type=MsgType.ASSIGN,+ from_agent=lead_id,+ to_agent=member_id,+ trace_id=trace,+ payload=payload,+ )++ async def board(self, lead_id: str) -> dict[str, Any]:+ """What a lead sees of its team: mission, members and its goals."""+ await self.refresh()+ group_id = self._leads.get(lead_id)+ if group_id is None:+ raise TeamLeadError("You do not lead a team.")+ group = self._groups[group_id]+ await self._rt.roster.refresh()+ goals = [g for g in await self.goals(group_id, limit=30) if g.state not in GOAL_TERMINAL]+ rows = []+ for goal in sorted(goals, key=lambda g: g.created_ms):+ tasks = await self.tasks(goal.goal_id)+ rows.append(+ {+ "goal_id": goal.goal_id,+ "title": goal.title,+ "goal": goal.text[:2000],+ "state": str(goal.state),+ "tasks": [+ {+ "member": self._name(t.agent_id),+ "title": t.title,+ "state": str(t.state),+ "result": t.result[:RESULT_CHARS],+ }+ for t in tasks+ ],+ }+ )+ return {+ "team": group.get("name"),+ "mission": group.get("mission") or "",+ "members": self._roster_lines(group, lead_id),+ "goals": rows,+ }++ async def report(self, lead_id: str, *, status: str, summary: str) -> dict[str, Any]:+ """A lead reports on its goal: progress, a question, the result or a failure."""+ text = summary.strip()+ if not text:+ raise TeamLeadError("A report needs a summary.")+ goal = await self._goal_for_lead(lead_id)+ if status == "progress":+ await self._rt.store.update_team_goal(+ goal.goal_id, {"report": text, "updated_ms": now_ms()}+ )+ await self._announce(goal.group_id, goal_id=goal.goal_id, state=goal.state)+ elif status == "needs_input":+ if not await self._move(+ goal,+ TeamGoalState.NEEDS_INPUT,+ (TeamGoalState.RUNNING,),+ report=text,+ note="question",+ ):+ raise TeamLeadError("This goal is no longer in progress.")+ elif status in ("done", "failed"):+ closed = (+ await self._finish(goal, TeamGoalState.DONE, report=text)+ if status == "done"+ else await self._finish(+ goal, TeamGoalState.FAILED, report=text, note="reported_failed"+ )+ )+ if not closed:+ raise TeamLeadError("This goal is no longer in progress.")+ else:+ raise TeamLeadError("status must be progress, needs_input, done or failed")+ return {"goal_id": goal.goal_id, "title": goal.title, "recorded": status}++ # --------------------------------------------------------- the board++ async def _on_envelope(self, env: SocietyEnvelope) -> None:+ if not env.trace_id.startswith(TRACE_PREFIX):+ run_id = str(env.payload.get("run_id") or "")+ if env.msg_type is MsgType.CLAIM and run_id.startswith(GOAL_RUN_PREFIX):+ # A goal is not a run: it may queue, wait for the person or pause+ # for days. Holding one of the lead's run slots that long would+ # refuse every later assignment; the team's own queue bounds it.+ self._rt.scheduler.note_run_ended(run_id)+ return+ if env.msg_type not in (MsgType.CLAIM, MsgType.RESULT, MsgType.VETO):+ return+ row = await self._rt.store.get_team_task_row_by_trace(env.trace_id)+ if row is None:+ return+ task = TeamTask.from_row(row)+ if task.state not in TASK_OPEN or env.parent_event_id != task.assign_event_id:+ return+ stamp = now_ms()+ if env.msg_type is MsgType.CLAIM:+ await self._rt.store.update_team_task(+ task.task_id,+ {+ "state": str(TeamTaskState.RUNNING),+ "run_id": str(env.payload.get("run_id") or ""),+ "updated_ms": stamp,+ },+ )+ await self._task_changed(task, news=False)+ return+ if env.msg_type is MsgType.RESULT:+ if env.from_agent != task.agent_id:+ return+ blocked = str(env.payload.get("status") or "done") == "blocked"+ result = str(env.payload.get("done") or env.text or "").strip()+ await self._close_task(+ task, TeamTaskState.BLOCKED if blocked else TeamTaskState.DONE, result+ )+ return+ reason = str(env.payload.get("reason") or "")+ if reason in WAIT_REASONS and task.attempts < MAX_WAIT_ATTEMPTS:+ # Not now, not never: the task waits and knocks again by itself.+ await self._rt.store.update_team_task(+ task.task_id,+ {+ "state": str(TeamTaskState.WAITING),+ "attempts": task.attempts + 1,+ "updated_ms": stamp,+ },+ )+ self._arm(+ f"task:{task.task_id}", self._retry_delay, lambda: self._reassign(task.task_id)+ )+ await self._task_changed(task, news=False)+ return+ await self._close_task(+ task, TeamTaskState.BLOCKED, f"Could not start: {env.text or reason or 'refused'}"+ )++ async def _close_task(self, task: TeamTask, state: TeamTaskState, result: str) -> None:+ stamp = now_ms()+ self._disarm(f"task:{task.task_id}")+ await self._rt.store.update_team_task(+ task.task_id,+ {+ "state": str(state),+ "result": result[:20_000],+ "reviewed": 0,+ "updated_ms": stamp,+ "done_ms": stamp,+ },+ )+ await self._task_changed(task, news=True)++ async def _task_changed(self, task: TeamTask, *, news: bool) -> None:+ goal = await self.get_goal(task.goal_id)+ if goal is None:+ return+ await self._announce(goal.group_id, goal_id=goal.goal_id, state=goal.state, reason="task")+ if not news or goal.state is not TeamGoalState.RUNNING:+ return+ self._wake_lead(goal.goal_id, self._review_delay)++ async def _reassign(self, task_id: str) -> None:+ """A waiting task knocks again: a fresh ``ASSIGN`` on a fresh trace."""+ row = await self._rt.store.get_team_task_row(task_id)+ if row is None:+ return+ task = TeamTask.from_row(row)+ goal = await self.get_goal(task.goal_id)+ if task.state is not TeamTaskState.WAITING or goal is None:+ return+ if goal.state in GOAL_TERMINAL:+ return+ if await self._rt.store.kill_switch():+ return+ env = self._assign_envelope(+ goal,+ goal.lead_agent_id,+ task.agent_id,+ task_id,+ task.title,+ task.brief,+ attempt=task.attempts,+ )+ await self._rt.store.update_team_task(+ task_id,+ {+ "state": str(TeamTaskState.ASSIGNED),+ "trace_id": env.trace_id,+ "assign_event_id": env.event_id,+ "updated_ms": now_ms(),+ },+ )+ await self._rt.store.append_and_publish(env)++ # ----------------------------------------------------- recovery, sweep++ async def _recover(self) -> None:+ """Goals that were running when the app closed come back paused: their+ turns died with the process, and nothing resumes paid work on boot."""+ for row in await self._rt.store.list_team_goal_rows(limit=1000):+ goal = TeamGoal.from_row(row)+ if goal.state is not TeamGoalState.RUNNING:+ continue+ for task in await self.tasks(goal.goal_id):+ if task.state in TASK_OPEN:+ stamp = now_ms()+ await self._rt.store.update_team_task(+ task.task_id,+ {+ "state": str(TeamTaskState.BLOCKED),+ "result": "Interrupted when the app closed.",+ "reviewed": 0,+ "updated_ms": stamp,+ "done_ms": stamp,+ },+ )+ await self._rt.store.update_team_goal(+ goal.goal_id,+ {"state": str(TeamGoalState.PAUSED), "note": "interrupted", "updated_ms": now_ms()},+ )++ async def _sweep_loop(self) -> None:+ while True:+ await asyncio.sleep(self._sweep_s)+ try:+ await self.sweep()+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — one failed pass; the next one runs in a minute+ log.warning("society team lead: sweep failed", exc_info=True)++ async def sweep(self) -> None:+ """Find work that died without a word (AP-19: judged per task, by its+ own last sign of life) so the lead hears about it instead of waiting."""+ stamp = now_ms()+ running = self._rt.scheduler.running+ for row in await self._rt.store.list_team_goal_rows(limit=1000):+ goal = TeamGoal.from_row(row)+ if goal.state is not TeamGoalState.RUNNING:+ continue+ tasks = await self.tasks(goal.goal_id)+ for task in tasks:+ if task.state not in TASK_OPEN or stamp - task.updated_ms < STALL_MS:+ continue+ if task.state is TeamTaskState.WAITING:+ if f"task:{task.task_id}" not in self._timers:+ self._arm(+ f"task:{task.task_id}", 0.0, partial(self._reassign, task.task_id)+ )+ continue+ if task.state is TeamTaskState.RUNNING and task.run_id in running:+ continue+ await self._close_task(+ task,+ TeamTaskState.BLOCKED,+ "The run ended without a result."+ if task.state is TeamTaskState.RUNNING+ else "The assignment was never picked up.",+ )+ idle = goal.goal_id not in self._turns and f"lead:{goal.goal_id}" not in self._timers+ if not idle or stamp - goal.updated_ms < STALL_MS:+ continue+ fresh = await self.tasks(goal.goal_id)+ if any(t.state in TASK_OPEN for t in fresh):+ continue+ if any(t.state in TASK_FINISHED and not t.reviewed for t in fresh):+ self._wake_lead(goal.goal_id)+ else:+ await self._park(goal, "stalled")++ # ------------------------------------------------------------ pushes++ async def _announce(+ self,+ group_id: str,+ *,+ goal_id: str = "",+ state: TeamGoalState | str = "",+ reason: str = "goal",+ ) -> None:+ """``SocietyTeamChanged`` on the app bus; the team board re-reads at once."""+ try:+ from jarvis.core.events import SocietyTeamChanged++ event = SocietyTeamChanged(+ source_layer="society",+ group_id=group_id,+ goal_id=goal_id,+ state=str(state),+ reason=reason,+ )+ if self._publish is not None:+ maybe = self._publish(event)+ else:+ from jarvis.core.bus import get_default_bus++ maybe = get_default_bus().publish(event)+ if hasattr(maybe, "__await__"):+ await maybe+ except Exception: # noqa: BLE001 — a window that misses the push falls back to its poll+ log.debug("society team lead: change not pushed", exc_info=True)++ # --------------------------------------------------------- briefings++ def briefing(self, agent_id: str) -> str:+ """The standing part of an agent's prompt about its team. Byte-stable+ between team edits (no goal or run state), so the prompt cache holds."""+ parts: list[str] = []+ by_id = {a.agent_id: a for a in self._rt.roster.snapshot()}+ group_id = self._leads.get(agent_id)+ if group_id is not None:+ group = self._groups.get(group_id) or {}+ lines = [f'## You lead the team "{group.get("name") or group_id}"']+ members = []+ for member_id in group.get("members", []):+ mate = by_id.get(member_id)+ if mate is None or member_id in (agent_id, LEAD_AGENT_ID):+ continue+ members.append(mate.name + (f" — {mate.title}" if mate.title.strip() else ""))+ lines.append("Members you manage: " + ("; ".join(members) or "nobody yet") + ".")+ if str(group.get("mission") or "").strip():+ lines.append("Team mission: " + str(group["mission"]).strip())+ lines.append(_LEAD_RULES)+ parts.append("\n".join(lines))+ for group in self._groups.values():+ lead_id = group.get("lead_agent_id")+ if not lead_id or lead_id == agent_id or agent_id not in group.get("members", []):+ continue+ lead = by_id.get(str(lead_id))+ if lead is None:+ continue+ parts.append(+ f'## Your team\nYou are a member of the team "{group["name"]}", led by '+ f"{lead.name}. Tasks from {lead.name} are your team's work: report the "+ "actual outcome and evidence in your final answer, and put a blocker or an "+ f"open question there too, so {lead.name} can act on it."+ )+ return "\n\n".join(parts)diff --git a/jarvis/society/team_tools.py b/jarvis/society/team_tools.pynew file mode 100644index 0000000000..2991080c75--- /dev/null+++ b/jarvis/society/team_tools.py@@ -0,0 +1,201 @@+"""The three tools of a team lead: assign, board, report.++Offered only in the chats of an agent that currently leads a team+(``surface.society_tools``). None of them starts work by itself:+``society_team_assign`` appends ONE ``ASSIGN`` to the board on the lead's+behalf, and the scheduler — trusted Python — decides whether the member+starts (tier wall, depth, budgets, concurrency). The lifecycle is then read+off the board by ``team_lead.TeamLeads``, which also wakes the lead when a+result arrives, so a lead never waits or polls inside a turn.+"""++from __future__ import annotations++from typing import Any, Final++from jarvis.core.protocols import ToolResult++from .team_lead import TeamLeadError++__all__ = [+ "TEAM_ASSIGN_TOOL_NAME",+ "TEAM_BOARD_TOOL_NAME",+ "TEAM_REPORT_TOOL_NAME",+ "TeamAssignTool",+ "TeamBoardTool",+ "TeamReportTool",+ "team_lead_tools",+]++TEAM_ASSIGN_TOOL_NAME: Final[str] = "society_team_assign"+TEAM_BOARD_TOOL_NAME: Final[str] = "society_team_board"+TEAM_REPORT_TOOL_NAME: Final[str] = "society_team_report"++_MAX_BRIEF: Final[int] = 20_000+_REPORT_STATUSES: Final[tuple[str, ...]] = ("progress", "needs_input", "done", "failed")+++def _refused(exc: TeamLeadError) -> ToolResult:+ return ToolResult(success=False, output={"refused": str(exc)}, error=str(exc))+++class TeamAssignTool:+ """Hand one task to one member of the team the caller leads."""++ name: str = TEAM_ASSIGN_TOOL_NAME+ # Internal coordination, like a message to a teammate: the scheduler's+ # budgets and caps gate the work, not a card in a chat nobody is watching.+ risk_tier: str = "safe"+ description: str = (+ "Hand ONE task to ONE member of the team you lead. The member works on it in their "+ "own chat, in the background; this call returns at once with the task's state. You "+ "are woken automatically with the result, so never wait or poll after assigning. "+ "Call it once per task, and give every task that can start now in the same turn: "+ "members work in parallel. A busy member is fine: the task starts by itself when "+ "they are free. Write an independently actionable brief, not a paraphrase of the "+ "goal: the objective, what you already know, the scope, and what output proves the "+ "task is done. Never invent URLs, paths, credentials or decisions."+ )+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "member": {+ "type": "string",+ "description": "The member's name as listed for your team.",+ },+ "title": {+ "type": "string",+ "description": "A short name for the task, shown on the team board.",+ },+ "task": {+ "type": "string",+ "description": "The objective and scope of the task, self-contained.",+ },+ "context": {+ "type": "string",+ "description": "Known facts, earlier results and constraints the member needs.",+ },+ "completion_criteria": {+ "type": "string",+ "description": "The output and evidence that establish the task is done.",+ },+ },+ "required": ["member", "title", "task"],+ }+ is_action_tool: bool = True++ def __init__(self, runtime: Any, agent_id: str) -> None:+ self._runtime = runtime+ self._agent_id = agent_id++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ title = str(args.get("title") or "").strip()+ brief = str(args.get("task") or "").strip()+ context = str(args.get("context") or "").strip()+ criteria = str(args.get("completion_criteria") or "").strip()+ if context:+ brief += "\n\nRelevant context:\n" + context+ if criteria:+ brief += "\n\nCompletion criteria:\n" + criteria+ if len(brief) > _MAX_BRIEF:+ return ToolResult(success=False, output=None, error="the task brief exceeds its limit")+ try:+ outcome = await self._runtime.team_leads.assign(+ self._agent_id,+ member=str(args.get("member") or ""),+ title=title,+ brief=brief,+ )+ except TeamLeadError as exc: # The refusal is the tool's answer; the lead reads why.+ return _refused(exc)+ return ToolResult(+ success=outcome["state"] != "blocked",+ output={+ **outcome,+ "next": "End your turn after assigning; the result wakes you. "+ "This receipt is the start of the task, not its completion.",+ },+ error=outcome["note"] if outcome["state"] == "blocked" else None,+ )+++class TeamBoardTool:+ """The caller's team at a glance: mission, members, goals, tasks, results."""++ name: str = TEAM_BOARD_TOOL_NAME+ risk_tier: str = "safe"+ description: str = (+ "Read the board of the team you lead: its mission, who is on it and whether they are "+ "free, every open goal, and each task with its state and result. Read-only. Use it "+ "to check where a goal stands before deciding, never to wait for a result."+ )+ schema: dict[str, Any] = {"type": "object", "properties": {}}++ def __init__(self, runtime: Any, agent_id: str) -> None:+ self._runtime = runtime+ self._agent_id = agent_id++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ try:+ return ToolResult(+ success=True, output=await self._runtime.team_leads.board(self._agent_id)+ )+ except TeamLeadError as exc: # The refusal is the tool's answer; the lead reads why.+ return _refused(exc)+++class TeamReportTool:+ """Report on the team's goal to the person: progress, a question, the result."""++ name: str = TEAM_REPORT_TOOL_NAME+ risk_tier: str = "safe"+ description: str = (+ "Report to the person on the goal your team is working on. status=done closes the "+ "goal: give the complete result, where the output is and what remains open. "+ "status=needs_input pauses the goal on ONE precise question only the person can "+ "answer. status=progress is an interim update on long work; the goal keeps running. "+ "status=failed closes a goal that cannot be reached, with the reason. Write the "+ "summary for the person, in the language they used."+ )+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "status": {"type": "string", "enum": list(_REPORT_STATUSES)},+ "summary": {+ "type": "string",+ "description": "What the person should read: the result, the question or why.",+ },+ },+ "required": ["status", "summary"],+ }+ is_action_tool: bool = True++ def __init__(self, runtime: Any, agent_id: str) -> None:+ self._runtime = runtime+ self._agent_id = agent_id++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ status = str(args.get("status") or "").strip().lower()+ if status not in _REPORT_STATUSES:+ return ToolResult(+ success=False, output=None, error="status must be " + " | ".join(_REPORT_STATUSES)+ )+ try:+ outcome = await self._runtime.team_leads.report(+ self._agent_id, status=status, summary=str(args.get("summary") or "")+ )+ except TeamLeadError as exc: # The refusal is the tool's answer; the lead reads why.+ return _refused(exc)+ return ToolResult(success=True, output=outcome)+++def team_lead_tools(runtime: Any, agent_id: str) -> dict[str, Any]:+ """The lead's tools for ``agent_id``; empty unless it leads a team right now."""+ leads = getattr(runtime, "team_leads", None)+ if leads is None or leads.group_led_by(agent_id) is None:+ return {}+ return {+ TeamAssignTool.name: TeamAssignTool(runtime, agent_id),+ TeamBoardTool.name: TeamBoardTool(runtime, agent_id),+ TeamReportTool.name: TeamReportTool(runtime, agent_id),+ }diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupDialog.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupDialog.tsxindex 33805cb526..0320bdc9e6 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupDialog.tsx@@ -61,7 +61,8 @@ export function ChatGroupDialog({ group, agents, onClose, onSaved }: Props) {{choices.map((agent) => <label key={agent.agentId} className="flex cursor-pointer items-center gap-3 rounded-md px-2 py-1.5 hover:bg-secondary"><input type="checkbox" checked={members.includes(agent.agentId)} onChange={() => setMembers((current) => current.includes(agent.agentId) ? current.filter((id) => id !== agent.agentId) : [...current, agent.agentId])} /><AgentSwatch agent={agent} size={28} />- <span className="min-w-0 truncate text-sm">{societyDisplayName(agent, assistantName)}</span>+ <span className="min-w-0 flex-1 truncate text-sm">{societyDisplayName(agent, assistantName)}</span>+ {group?.lead_agent_id === agent.agentId && <span className="shrink-0 rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">{t("society.lead.role")}</span>}</label>)}</div>{error && <p role="alert" className="text-sm text-destructive">{error}</p>}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsxindex 7d926899ed..ab7c5bafbb 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsx@@ -20,6 +20,7 @@ vi.mock("./AgentChatPanel", () => ({},}));vi.mock("./MeetingChat", () => ({ MeetingChat: () => <div data-testid="meeting" /> }));+vi.mock("./TeamLeadBoard", () => ({ TeamLeadBoard: () => <div data-testid="lead-board" /> }));afterEach(() => { cleanup(); groupApi.remove.mockClear(); });@@ -83,3 +84,25 @@ it("shows an explicit ungroup confirmation and restores individual chats on confawait waitFor(() => expect(groupApi.remove).toHaveBeenCalledWith("team"));await waitFor(() => expect(onDeleted).toHaveBeenCalledOnce());});++it("opens a team that has a lead on the lead's board, and a team without one on its meeting", () => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const scout = { agentId: "scout", name: "Scout", tier: "orchestrator", chatSessionId: "society:scout" } as SocietyAgent;+ const writer = { agentId: "writer", name: "Writer", tier: "specialist", chatSessionId: "society:writer" } as SocietyAgent;+ render(<QueryClientProvider client={client}><ChatGroupPanel+ group={{ group_id: "team", name: "Team", members: ["scout", "writer"], created_ms: 1, updated_ms: 1, lead_agent_id: "scout" }}+ groups={[]} roster={[scout, writer]} onOpenAgent={() => undefined} onOpenGroup={() => undefined}+ onCreateAgent={() => undefined} onDeleted={() => undefined}+ onGroupAgents={() => undefined} onAddAgentToGroup={() => undefined}+ /></QueryClientProvider>);++ const leadView = screen.getByRole("button", { name: "society.lead.tab" });+ expect(leadView.getAttribute("aria-pressed")).toBe("true");+ expect(screen.getByTestId("lead-board")).toBeTruthy();+ expect(screen.queryByTestId("meeting")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "society.meeting.title" }));+ expect(screen.getByTestId("meeting")).toBeTruthy();+ expect(screen.queryByTestId("lead-board")).toBeNull();+ fireEvent.click(leadView);+ expect(screen.getByTestId("lead-board")).toBeTruthy();+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsxindex fd09292657..6e3f7454f9 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsx@@ -14,6 +14,10 @@ import { RosterRail } from "../roster/RosterRail";import { AgentChatPanel } from "./AgentChatPanel";import { ChatGroupDialog } from "./ChatGroupDialog";import { MeetingChat } from "./MeetingChat";+import { TeamLeadBoard } from "./TeamLeadBoard";++/** What the team's main column shows. */+type GroupView = "lead" | "meeting" | "individual";/** The active view reads as selected; both states keep the same box size. */function viewToggle(active: boolean): string {@@ -47,7 +51,8 @@ export function ChatGroupPanel({const [leftId, setLeftId] = useState(group.members[0] ?? "");const [rightId, setRightId] = useState(group.members[1] ?? "");const [editing, setEditing] = useState(false);- const [shared, setShared] = useState(true);+ // A team that has a lead opens on the lead's board; the others on their meeting.+ const [view, setView] = useState<GroupView>(group.lead_agent_id ? "lead" : "meeting");const [confirmUngroup, setConfirmUngroup] = useState(false);const [removing, setRemoving] = useState(false);const [error, setError] = useState("");@@ -152,16 +157,20 @@ export function ChatGroupPanel({footer={teamFooter} /><div className="flex min-h-0 min-w-0 flex-col border-l border-border"><div className="flex shrink-0 gap-2 border-b border-border p-2">- <button type="button" aria-pressed={shared} onClick={() => setShared(true)}- className={viewToggle(shared)}>{t("society.meeting.title")}</button>- <button type="button" aria-pressed={!shared} onClick={() => setShared(false)}- className={viewToggle(!shared)}>{t("society.meeting.individual")}</button>+ <button type="button" aria-pressed={view === "lead"} onClick={() => setView("lead")}+ className={viewToggle(view === "lead")}>{t("society.lead.tab")}</button>+ <button type="button" aria-pressed={view === "meeting"} onClick={() => setView("meeting")}+ className={viewToggle(view === "meeting")}>{t("society.meeting.title")}</button>+ <button type="button" aria-pressed={view === "individual"} onClick={() => setView("individual")}+ className={viewToggle(view === "individual")}>{t("society.meeting.individual")}</button></div>- {shared ? <MeetingChat key={group.group_id} group={group} roster={roster} /> : <div className="grid min-h-0 min-w-0 flex-1 grid-cols-2 divide-x-2 divide-border-strong overflow-hidden bg-background"- data-testid="society-group-split">- {pane("left", left)}- {pane("right", right)}- </div>}+ {view === "lead" ? <TeamLeadBoard key={group.group_id} group={group} roster={roster} onOpenAgent={onOpenAgent} />+ : view === "meeting" ? <MeetingChat key={group.group_id} group={group} roster={roster} />+ : <div className="grid min-h-0 min-w-0 flex-1 grid-cols-2 divide-x-2 divide-border-strong overflow-hidden bg-background"+ data-testid="society-group-split">+ {pane("left", left)}+ {pane("right", right)}+ </div>}</div>{editing && <ChatGroupDialog group={group} agents={roster} onClose={() => setEditing(false)} onSaved={onOpenGroup} />}</div>;diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.test.tsxnew file mode 100644index 0000000000..c469265f91--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.test.tsx@@ -0,0 +1,201 @@+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { SocietyChatGroup, SocietyTeam, SocietyTeamGoal } from "@/lib/societyChatGroups";+import type { SocietyAgent } from "../data";+import { TeamLeadBoard } from "./TeamLeadBoard";++const api = vi.hoisted(() => ({+ team: null as unknown,+ setLead: vi.fn(),+ createLead: vi.fn(),+ setMission: vi.fn(),+ setCheckin: vi.fn(),+ startGoal: vi.fn(),+ message: vi.fn(),+ resume: vi.fn(),+ cancel: vi.fn(),+}));++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("../AgentSwatch", () => ({ AgentSwatch: () => <i data-testid="swatch" /> }));+vi.mock("./AgentChatPanel", () => ({ Prose: ({ text }: { text: string }) => <p>{text}</p> }));+vi.mock("@/components/ui/select", () => ({+ BrandedSelect: ({ options, onValueChange, testId, value }: {+ options: { value: string; label: string }[]; onValueChange: (value: string) => void; testId: string; value: string;+ }) => <div data-testid={testId} data-value={value}>+ {options.map((option) => <button key={option.value} type="button" onClick={() => onValueChange(option.value)}>{option.label}</button>)}+ </div>,+}));+vi.mock("@/lib/societyChatGroups", () => ({+ TEAM_GOAL_OPEN: ["queued", "running", "needs_input", "paused"],+ useSocietyTeam: () => ({ data: api.team, isLoading: false, isError: false, error: null }),+ setSocietyTeamLead: api.setLead,+ createSocietyTeamLead: api.createLead,+ setSocietyTeamMission: api.setMission,+ setSocietyTeamCheckin: api.setCheckin,+ startSocietyTeamGoal: api.startGoal,+ messageSocietyTeamGoal: api.message,+ resumeSocietyTeamGoal: api.resume,+ cancelSocietyTeamGoal: api.cancel,+}));++const agent = (agentId: string, name: string, tier = "specialist") => ({+ agentId, name, tier, title: `${name} title`, lifecycle: "active", chatSessionId: `society:${agentId}`,+}) as unknown as SocietyAgent;+const roster = [agent("jarvis", "Jarvis", "lead"), agent("boss", "Boss", "orchestrator"), agent("scout", "Scout"), agent("writer", "Writer")];+const group: SocietyChatGroup = {+ group_id: "team", name: "Launch", members: ["jarvis", "boss", "scout", "writer"], created_ms: 1, updated_ms: 1, lead_agent_id: "boss",+};++function team(over: Partial<SocietyTeam> = {}): SocietyTeam {+ return {+ group_id: "team", lead_agent_id: "boss", lead_available: true, mission: "", checkin_minutes: 0,+ goals: [], working: false, max_lead_turns: 24, ...over,+ };+}++function goal(over: Partial<SocietyTeamGoal> = {}): SocietyTeamGoal {+ return {+ goal_id: "g1", group_id: "team", lead_agent_id: "boss", title: "Launch the page", text: "Launch the page",+ state: "running", report: "", note: "", lead_turns: 1, source: "board", created_ms: 1, updated_ms: 1, done_ms: null,+ tasks: [], ...over,+ };+}++function mount(onOpenAgent = vi.fn()) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(<QueryClientProvider client={client}><TeamLeadBoard group={group} roster={roster} onOpenAgent={onOpenAgent} /></QueryClientProvider>);+ return onOpenAgent;+}++beforeEach(() => {+ for (const fn of [api.setLead, api.createLead, api.setMission, api.setCheckin, api.startGoal, api.message, api.resume, api.cancel]) {+ fn.mockReset();+ fn.mockImplementation(async () => api.team);+ }+});+afterEach(cleanup);++it("offers to create a lead or promote a member, never the assistant or nobody", async () => {+ api.team = team({ lead_agent_id: null, lead_available: false });+ mount();+ expect(screen.getByText("society.lead.none_title")).toBeTruthy();+ const pick = screen.getByTestId("team-lead-pick");+ expect(within(pick).getAllByRole("button").map((button) => button.textContent)).toEqual(["Boss", "Scout", "Writer"]);+ expect(screen.getByRole("button", { name: "society.lead.make" }).hasAttribute("disabled")).toBe(true);+ fireEvent.click(within(pick).getByRole("button", { name: "Scout" }));+ fireEvent.click(screen.getByRole("button", { name: "society.lead.make" }));+ await waitFor(() => expect(api.setLead).toHaveBeenCalledWith("team", "scout"));+ fireEvent.click(screen.getByTestId("team-lead-create"));+ await waitFor(() => expect(api.createLead).toHaveBeenCalledWith("team"));+});++it("gives the team a goal and clears the field once the lead has it", async () => {+ api.team = team();+ const onOpenAgent = mount();+ expect(screen.getByRole("heading", { name: "Boss" })).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "society.lead.open_chat" }));+ expect(onOpenAgent).toHaveBeenCalledWith("boss");++ const send = screen.getByRole("button", { name: "society.lead.goal_send" });+ expect(send.hasAttribute("disabled")).toBe(true);+ const field = screen.getByLabelText("society.lead.goal_label") as HTMLTextAreaElement;+ fireEvent.change(field, { target: { value: " Launch the page " } });+ fireEvent.click(send);+ await waitFor(() => expect(api.startGoal).toHaveBeenCalledWith("team", "Launch the page"));+ await waitFor(() => expect(field.value).toBe(""));+});++it("keeps the goal text and shows the reason when the team refuses it", async () => {+ api.team = team();+ api.startGoal.mockImplementation(async () => { throw new Error("The society is paused."); });+ mount();+ const field = screen.getByLabelText("society.lead.goal_label") as HTMLTextAreaElement;+ fireEvent.change(field, { target: { value: "Launch" } });+ fireEvent.click(screen.getByRole("button", { name: "society.lead.goal_send" }));+ expect((await screen.findByRole("alert")).textContent).toBe("The society is paused.");+ expect(field.value).toBe("Launch");+});++it("shows each task with its member, state and result", () => {+ api.team = team({+ working: true,+ goals: [goal({+ tasks: [+ { task_id: "t1", goal_id: "g1", agent_id: "scout", title: "Research", brief: "", state: "done", result: "Three found.", reviewed: true, created_ms: 1, updated_ms: 2, done_ms: 2 },+ { task_id: "t2", goal_id: "g1", agent_id: "writer", title: "Draft", brief: "", state: "running", result: "", reviewed: false, created_ms: 2, updated_ms: 2, done_ms: null },+ ],+ })],+ });+ mount();+ expect(screen.getByRole("status").textContent).toBe("society.lead.working");+ const card = screen.getByTestId("team-goal-g1");+ expect(card.getAttribute("data-state")).toBe("running");+ const research = within(card).getByTestId("team-task-t1");+ expect(research.textContent).toContain("Scout");+ expect(research.textContent).toContain("society.lead.task_state_done");+ expect(within(research).queryByText("Three found.")).toBeNull();+ fireEvent.click(within(research).getByRole("button", { name: "society.lead.show_result" }));+ expect(within(research).getByText("Three found.")).toBeTruthy();+ const draft = within(card).getByTestId("team-task-t2");+ expect(draft.textContent).toContain("society.lead.task_state_running");+ expect(within(draft).queryByRole("button")).toBeNull();+});++it("answers the lead's question and stops a goal", async () => {+ api.team = team({ goals: [goal({ state: "needs_input", report: "Which market?", note: "question" })] });+ mount();+ const card = screen.getByTestId("team-goal-g1");+ expect(within(card).getByText("society.lead.question")).toBeTruthy();+ expect(within(card).getByText("Which market?")).toBeTruthy();+ fireEvent.change(within(card).getByLabelText("society.lead.answer_placeholder"), { target: { value: "Germany" } });+ fireEvent.click(within(card).getByRole("button", { name: "society.lead.send" }));+ await waitFor(() => expect(api.message).toHaveBeenCalledWith("team", "g1", "Germany"));+ fireEvent.click(within(card).getByRole("button", { name: "society.lead.stop" }));+ await waitFor(() => expect(api.cancel).toHaveBeenCalledWith("team", "g1"));+});++it("explains why a goal is paused and continues it", async () => {+ api.team = team({+ goals: [+ goal({ state: "paused", note: "turn_budget" }),+ goal({ goal_id: "g2", state: "paused", note: "error:provider unavailable" }),+ goal({ goal_id: "g3", state: "queued" }),+ goal({ goal_id: "g4", state: "done", report: "All shipped." }),+ ],+ });+ mount();+ expect(within(screen.getByTestId("team-goal-g1")).getByText("society.lead.note_turn_budget")).toBeTruthy();+ expect(within(screen.getByTestId("team-goal-g2")).getByText("society.lead.note_error")).toBeTruthy();+ fireEvent.click(within(screen.getByTestId("team-goal-g1")).getByRole("button", { name: "society.lead.resume" }));+ await waitFor(() => expect(api.resume).toHaveBeenCalledWith("team", "g1"));+ const queued = screen.getByTestId("team-goal-g3");+ expect(within(queued).getByRole("button", { name: "society.lead.start_now" })).toBeTruthy();+ expect(within(queued).getByRole("button", { name: "society.lead.remove_goal" })).toBeTruthy();+ // A finished goal keeps its report and offers nothing to do.+ const done = screen.getByTestId("team-goal-g4");+ expect(within(done).getByText("All shipped.")).toBeTruthy();+ expect(within(done).queryByRole("button")).toBeNull();+ expect(screen.getByText("society.lead.finished")).toBeTruthy();+});++it("saves the mission, switches check-ins and changes the lead", async () => {+ api.team = team({ mission: "Ship the launch." });+ mount();+ const mission = screen.getByLabelText("society.lead.mission") as HTMLTextAreaElement;+ await waitFor(() => expect(mission.value).toBe("Ship the launch."));+ expect(screen.queryByRole("button", { name: "society.lead.mission_save" })).toBeNull();+ fireEvent.change(mission, { target: { value: "Ship it by Friday." } });+ fireEvent.click(screen.getByRole("button", { name: "society.lead.mission_save" }));+ await waitFor(() => expect(api.setMission).toHaveBeenCalledWith("team", "Ship it by Friday."));++ fireEvent.click(within(screen.getByTestId("team-lead-checkin")).getByRole("button", { name: "society.lead.checkin_60" }));+ await waitFor(() => expect(api.setCheckin).toHaveBeenCalledWith("team", 60));++ fireEvent.click(screen.getByRole("button", { name: "society.lead.change" }));+ // The current lead is not offered as its own replacement.+ expect(within(screen.getByTestId("team-lead-pick")).getAllByRole("button").map((button) => button.textContent)).toEqual(["Scout", "Writer"]);+ fireEvent.click(screen.getByRole("button", { name: "society.lead.remove" }));+ await waitFor(() => expect(api.setLead).toHaveBeenCalledWith("team", null));+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.tsxnew file mode 100644index 0000000000..4c0c0d6a92--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.tsx@@ -0,0 +1,414 @@+/**+ * The team's lead and its work: who manages the team, what the team is for,+ * the goals the person gave it, and every task the lead handed out.+ *+ * The person only sets a goal. The lead plans it, hands tasks to the members,+ * is woken with each result and reports back; this board follows that live+ * (`useSocietyTeam`) and offers the few moments that are the person's: answer+ * the lead's question, continue a paused goal, stop one.+ */+import { useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { ChevronDown, Crown, Loader2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import { BrandedSelect } from "@/components/ui/select";+import { Textarea } from "@/components/ui/textarea";+import { useT } from "@/i18n";+import {+ TEAM_GOAL_OPEN,+ cancelSocietyTeamGoal,+ createSocietyTeamLead,+ messageSocietyTeamGoal,+ resumeSocietyTeamGoal,+ setSocietyTeamCheckin,+ setSocietyTeamLead,+ setSocietyTeamMission,+ startSocietyTeamGoal,+ useSocietyTeam,+ type SocietyChatGroup,+ type SocietyTeam,+ type SocietyTeamGoal,+ type SocietyTeamTask,+} from "@/lib/societyChatGroups";+import { societyDisplayName } from "@/lib/societyDisplayName";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import type { SocietyAgent } from "../data";+import { AgentSwatch } from "../AgentSwatch";+import { Prose } from "./AgentChatPanel";++/** The server's check-in intervals (jarvis/society/team_lead.py CHECKIN_MINUTES). */+const CHECKIN_CHOICES = [0, 60, 240, 1440] as const;+/** Reasons a goal waits that have their own sentence; anything else shows as written. */+const NOTE_KEYS = new Set([+ "society_paused", "interrupted", "turn_budget", "lead_busy", "lead_unavailable", "stalled",+]);++const DOT: Record<string, string> = {+ running: "bg-success",+ assigned: "bg-success",+ needs_input: "bg-warning",+ waiting: "bg-warning",+ paused: "bg-warning",+ queued: "bg-muted-foreground",+ done: "bg-foreground",+ blocked: "bg-destructive",+ failed: "bg-destructive",+ cancelled: "bg-muted-foreground",+};++function StateChip({ state, label }: { state: string; label: string }) {+ return (+ <span data-state={state}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">+ <i className={cn("h-1.5 w-1.5 rounded-full", DOT[state] ?? "bg-muted-foreground")} aria-hidden />+ {label}+ </span>+ );+}++function Section({ title, children }: { title: string; children: ReactNode }) {+ return (+ <section className="flex flex-col gap-2">+ <h3 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{title}</h3>+ {children}+ </section>+ );+}++interface Props {+ group: SocietyChatGroup;+ roster: SocietyAgent[];+ onOpenAgent: (id: string) => void;+}++export function TeamLeadBoard({ group, roster, onOpenAgent }: Props) {+ const t = useT();+ const client = useQueryClient();+ const assistantName = useEventStore((s) => s.assistantName);+ const query = useSocietyTeam(group.group_id);+ const team = query.data;+ const [busy, setBusy] = useState("");+ const [problem, setProblem] = useState("");+ const [picked, setPicked] = useState("");+ const [changing, setChanging] = useState(false);+ const [goalText, setGoalText] = useState("");+ const [mission, setMission] = useState("");+ const savedMission = useRef("");+ const serverMission = team?.mission;++ // The saved mission fills the field until the person starts editing it.+ useEffect(() => {+ if (serverMission === undefined) return;+ const previous = savedMission.current;+ savedMission.current = serverMission;+ setMission((current) => (current === previous ? serverMission : current));+ }, [serverMission]);++ const agentOf = (id: string | null | undefined) => roster.find((agent) => agent.agentId === id);+ const nameOf = (id: string | null | undefined) => {+ const agent = agentOf(id);+ return agent ? societyDisplayName(agent, assistantName) : (id ?? "");+ };+ const lead = agentOf(team?.lead_agent_id);+ const leadName = nameOf(team?.lead_agent_id);+ const members = group.members.map(agentOf).filter((agent): agent is SocietyAgent => Boolean(agent));+ // Jarvis already leads every agent; a team lead is one of the others.+ const candidates = members.filter((agent) => agent.tier !== "lead" && agent.lifecycle !== "archived"+ && agent.agentId !== team?.lead_agent_id);++ /** Run one board action: the answer replaces the board, a refusal shows as written. */+ const run = async (key: string, action: () => Promise<SocietyTeam>): Promise<boolean> => {+ if (busy) return false;+ setBusy(key);+ setProblem("");+ try {+ client.setQueryData(["society", "team", group.group_id], await action());+ return true;+ } catch (cause) {+ setProblem(cause instanceof Error ? cause.message : String(cause));+ return false;+ } finally {+ setBusy("");+ }+ };+ /** A lead change also changes the roster (tier) and the group (members). */+ const leadChanged = async (key: string, action: () => Promise<SocietyTeam>) => {+ if (!(await run(key, action))) return;+ setChanging(false);+ setPicked("");+ await Promise.all([+ client.invalidateQueries({ queryKey: ["society", "chat-groups"] }),+ client.invalidateQueries({ queryKey: ["society", "roster"] }),+ ]);+ };++ const submitGoal = async (event: FormEvent) => {+ event.preventDefault();+ const text = goalText.trim();+ if (!text) return;+ if (await run("goal", () => startSocietyTeamGoal(group.group_id, text))) setGoalText("");+ };++ if (query.isLoading) {+ return <p className="m-auto p-6 text-sm text-muted-foreground" role="status">{t("society.lead.loading")}</p>;+ }+ if (query.isError || !team) {+ return <p className="m-auto p-6 text-sm text-destructive" role="alert">{String(query.error ?? "")}</p>;+ }++ const picker = (+ <div className="flex flex-wrap items-center gap-2">+ <BrandedSelect+ ariaLabel={t("society.lead.pick")}+ testId="team-lead-pick"+ value={picked}+ onValueChange={setPicked}+ placeholder={t("society.lead.pick_placeholder")}+ className="min-w-[12rem] flex-1"+ options={candidates.map((agent) => ({ value: agent.agentId, label: societyDisplayName(agent, assistantName) }))}+ />+ <Button size="sm" variant="secondary" disabled={!picked || Boolean(busy)}+ onClick={() => void leadChanged("pick", () => setSocietyTeamLead(group.group_id, picked))}>+ {t("society.lead.make")}+ </Button>+ </div>+ );++ const createButton = (variant: "default" | "secondary") => (+ <Button size="sm" variant={variant} disabled={Boolean(busy)} data-testid="team-lead-create"+ onClick={() => void leadChanged("create", () => createSocietyTeamLead(group.group_id))}>+ {busy === "create" ? <Loader2 className="animate-spin" aria-hidden /> : <Crown aria-hidden />}+ {t("society.lead.create")}+ </Button>+ );++ if (!team.lead_agent_id) {+ return (+ <section className="flex min-h-0 flex-1 flex-col overflow-y-auto bg-background" data-testid="team-lead-board">+ <div className="mx-auto flex w-full max-w-[36rem] flex-col gap-4 px-6 py-12">+ <span className="grid h-11 w-11 place-items-center rounded-xl bg-secondary text-foreground"><Crown className="h-5 w-5" aria-hidden /></span>+ <h2 className="text-lg font-semibold text-foreground">{t("society.lead.none_title")}</h2>+ <p className="text-sm text-muted-foreground">{t("society.lead.none_body")}</p>+ <div>{createButton("default")}</div>+ {candidates.length > 0 && <>+ <p className="pt-2 text-sm font-medium text-foreground">{t("society.lead.pick")}</p>+ {picker}+ </>}+ {problem && <p role="alert" className="text-sm text-destructive">{problem}</p>}+ </div>+ </section>+ );+ }++ const open = team.goals.filter((goal) => TEAM_GOAL_OPEN.includes(goal.state))+ .sort((a, b) => Number(b.state !== "queued") - Number(a.state !== "queued") || a.created_ms - b.created_ms);+ const finished = team.goals.filter((goal) => !TEAM_GOAL_OPEN.includes(goal.state));++ return (+ <section className="flex min-h-0 flex-1 flex-col overflow-y-auto bg-background" data-testid="team-lead-board">+ <div className="mx-auto flex w-full max-w-[52rem] flex-col gap-6 px-4 py-5 sm:px-6">+ <header className="flex flex-wrap items-center gap-3 rounded-xl border border-border bg-card p-3">+ <span className="grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-secondary">+ {lead ? <AgentSwatch agent={lead} size={38} /> : <Crown className="h-5 w-5" aria-hidden />}+ </span>+ <div className="min-w-0 flex-1">+ <p className="flex items-center gap-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">+ <Crown className="h-3 w-3" aria-hidden />{t("society.lead.role")}+ </p>+ <h2 className="truncate text-base font-semibold text-foreground">{leadName}</h2>+ <p className="truncate text-xs text-muted-foreground" role="status">+ {!team.lead_available ? t("society.lead.unavailable")+ : team.working ? t("society.lead.working").replace("{0}", leadName)+ : (lead?.title ?? "")}+ </p>+ </div>+ {lead && <Button size="sm" variant="secondary" onClick={() => onOpenAgent(lead.agentId)}>{t("society.lead.open_chat")}</Button>}+ <Button size="sm" variant="ghost" aria-expanded={changing} onClick={() => setChanging((value) => !value)}>+ {t("society.lead.change")}<ChevronDown className={cn("transition-transform", changing && "rotate-180")} aria-hidden />+ </Button>+ {changing && <div className="flex w-full flex-col gap-2 border-t border-border pt-3">+ {candidates.length > 0 && picker}+ <div className="flex flex-wrap gap-2">+ {createButton("secondary")}+ <Button size="sm" variant="ghost" disabled={Boolean(busy)}+ onClick={() => void leadChanged("remove", () => setSocietyTeamLead(group.group_id, null))}>+ {t("society.lead.remove")}+ </Button>+ </div>+ </div>}+ </header>++ {problem && <p role="alert" className="text-sm text-destructive">{problem}</p>}++ <form onSubmit={(event) => void submitGoal(event)} className="flex flex-col gap-2">+ <label htmlFor="team-goal" className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{t("society.lead.goal_label")}</label>+ <Textarea id="team-goal" value={goalText} maxLength={20000} rows={3}+ placeholder={t("society.lead.goal_placeholder")}+ onChange={(event) => setGoalText(event.target.value)}+ onKeyDown={(event) => { if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) void submitGoal(event); }} />+ <div className="flex items-center justify-between gap-3">+ <p className="text-xs text-muted-foreground">{t("society.lead.goal_hint").replace("{0}", leadName)}</p>+ <Button type="submit" size="sm" disabled={!goalText.trim() || Boolean(busy) || !team.lead_available}>+ {busy === "goal" && <Loader2 className="animate-spin" aria-hidden />}{t("society.lead.goal_send")}+ </Button>+ </div>+ </form>++ <Section title={t("society.lead.goals")}>+ {open.length === 0 && <p className="rounded-xl border border-dashed border-border px-4 py-6 text-center text-sm text-muted-foreground">+ {t("society.lead.goals_empty").replace("{0}", leadName)}+ </p>}+ {open.map((goal) => <GoalCard key={goal.goal_id} goal={goal} leadName={leadName} assistantName={assistantName}+ agentOf={agentOf} nameOf={nameOf} busy={busy}+ onMessage={(text) => run(`message:${goal.goal_id}`, () => messageSocietyTeamGoal(group.group_id, goal.goal_id, text))}+ onResume={() => void run(`resume:${goal.goal_id}`, () => resumeSocietyTeamGoal(group.group_id, goal.goal_id))}+ onCancel={() => void run(`cancel:${goal.goal_id}`, () => cancelSocietyTeamGoal(group.group_id, goal.goal_id))} />)}+ </Section>++ {finished.length > 0 && <details className="group/finished">+ <summary className="cursor-pointer list-none text-xs font-medium uppercase tracking-wide text-muted-foreground hover:text-foreground">+ <ChevronDown className="mr-1 inline h-3.5 w-3.5 -rotate-90 transition-transform group-open/finished:rotate-0" aria-hidden />+ {t("society.lead.finished").replace("{0}", String(finished.length))}+ </summary>+ <div className="mt-2 flex flex-col gap-2">+ {finished.map((goal) => <GoalCard key={goal.goal_id} goal={goal} leadName={leadName} assistantName={assistantName}+ agentOf={agentOf} nameOf={nameOf} busy={busy}+ onMessage={async () => false}+ onResume={() => void run(`resume:${goal.goal_id}`, () => resumeSocietyTeamGoal(group.group_id, goal.goal_id))}+ onCancel={() => undefined} />)}+ </div>+ </details>}++ <Section title={t("society.lead.mission")}>+ <Textarea value={mission} maxLength={4000} rows={2} aria-label={t("society.lead.mission")}+ placeholder={t("society.lead.mission_placeholder")} onChange={(event) => setMission(event.target.value)} />+ {mission.trim() !== team.mission && <div>+ <Button size="sm" variant="secondary" disabled={Boolean(busy)}+ onClick={() => void run("mission", () => setSocietyTeamMission(group.group_id, mission))}>+ {t("society.lead.mission_save")}+ </Button>+ </div>}+ </Section>++ <Section title={t("society.lead.checkin")}>+ <div className="flex flex-wrap items-center gap-3">+ <BrandedSelect+ ariaLabel={t("society.lead.checkin")}+ testId="team-lead-checkin"+ value={String(team.checkin_minutes)}+ disabled={Boolean(busy)}+ onValueChange={(value) => void run("checkin", () => setSocietyTeamCheckin(group.group_id, Number(value)))}+ className="w-[12rem]"+ options={CHECKIN_CHOICES.map((minutes) => ({ value: String(minutes), label: t(`society.lead.checkin_${minutes}`) }))}+ />+ <p className="min-w-[14rem] flex-1 text-xs text-muted-foreground">{t("society.lead.checkin_hint").replace("{0}", leadName)}</p>+ </div>+ </Section>+ </div>+ </section>+ );+}++function TaskRow({ task, agent, name }: { task: SocietyTeamTask; agent: SocietyAgent | undefined; name: string }) {+ const t = useT();+ const [shown, setShown] = useState(false);+ return (+ <li className="flex flex-col gap-1.5 py-2" data-testid={`team-task-${task.task_id}`}>+ <div className="flex items-center gap-2">+ {agent ? <AgentSwatch agent={agent} size={22} /> : null}+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">+ <span className="font-medium">{name}</span>+ <span className="text-muted-foreground"> · {task.title}</span>+ </span>+ {task.result && <button type="button" aria-expanded={shown} onClick={() => setShown((value) => !value)}+ className="shrink-0 rounded-md px-1.5 py-0.5 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground">+ {t(shown ? "society.lead.hide_result" : "society.lead.show_result")}+ </button>}+ <StateChip state={task.state} label={t(`society.lead.task_state_${task.state}`)} />+ </div>+ {shown && <div className="ml-7 rounded-lg bg-secondary/50 px-3 py-2 text-sm"><Prose text={task.result} /></div>}+ </li>+ );+}++function GoalCard({ goal, leadName, assistantName, agentOf, nameOf, busy, onMessage, onResume, onCancel }: {+ goal: SocietyTeamGoal;+ leadName: string;+ assistantName: string;+ agentOf: (id: string) => SocietyAgent | undefined;+ nameOf: (id: string) => string;+ busy: string;+ onMessage: (text: string) => Promise<boolean>;+ onResume: () => void;+ onCancel: () => void;+}) {+ const t = useT();+ const [reply, setReply] = useState("");+ const waiting = goal.state === "needs_input";+ const live = goal.state === "running" || waiting;+ const source = goal.source === "jarvis" ? t("society.lead.source_jarvis").replace("{0}", assistantName)+ : goal.source === "lead" ? t("society.lead.source_lead").replace("{0}", leadName)+ : goal.source === "assignment" ? t("society.lead.source_assignment") : "";+ // The title is the goal's first line; show only what the text adds to it.+ const text = goal.text.trim();+ const detailText = text.startsWith(goal.title) ? text.slice(goal.title.length).trim() : text;+ const detail = goal.note.startsWith("error:") ? goal.note.slice(6) : "";+ const note = goal.state !== "paused" && goal.state !== "failed" ? ""+ : detail ? t("society.lead.note_error").replace("{0}", detail)+ : NOTE_KEYS.has(goal.note) ? t(`society.lead.note_${goal.note}`) : "";++ const send = async (event: FormEvent) => {+ event.preventDefault();+ const text = reply.trim();+ if (text && await onMessage(text)) setReply("");+ };++ return (+ <article className={cn("flex flex-col gap-3 rounded-xl border bg-card p-4", waiting ? "border-warning/50" : "border-border")}+ data-testid={`team-goal-${goal.goal_id}`} data-state={goal.state}>+ <header className="flex items-start gap-3">+ <div className="min-w-0 flex-1">+ <h4 className="text-sm font-semibold text-foreground">{goal.title}</h4>+ {detailText && <p className="mt-1 whitespace-pre-wrap text-sm text-muted-foreground">{detailText}</p>}+ {source && <p className="mt-1 text-xs text-muted-foreground">{source}</p>}+ </div>+ <StateChip state={goal.state} label={t(`society.lead.state_${goal.state}`)} />+ </header>++ {note && <p className="text-sm text-muted-foreground">{note}</p>}++ {goal.tasks.length > 0 && <ul className="divide-y divide-border border-y border-border">+ {goal.tasks.map((task) => <TaskRow key={task.task_id} task={task} agent={agentOf(task.agent_id)} name={nameOf(task.agent_id)} />)}+ </ul>}+ {goal.tasks.length === 0 && goal.state === "running" && <p className="text-xs text-muted-foreground">{t("society.lead.tasks_none").replace("{0}", leadName)}</p>}++ {goal.report && <div className="flex flex-col gap-1">+ <p className="text-xs font-medium text-muted-foreground">+ {t(waiting ? "society.lead.question" : "society.lead.report").replace("{0}", leadName)}+ </p>+ <div className="rounded-lg bg-secondary/50 px-3 py-2 text-sm"><Prose text={goal.report} /></div>+ </div>}++ {live && <form onSubmit={(event) => void send(event)} className="flex items-end gap-2">+ <Textarea value={reply} rows={1} maxLength={20000} className="min-h-[36px] flex-1"+ aria-label={t(waiting ? "society.lead.answer_placeholder" : "society.lead.message_placeholder").replace("{0}", leadName)}+ placeholder={t(waiting ? "society.lead.answer_placeholder" : "society.lead.message_placeholder").replace("{0}", leadName)}+ onChange={(event) => setReply(event.target.value)}+ onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey) void send(event); }} />+ <Button type="submit" size="sm" variant={waiting ? "default" : "secondary"} disabled={!reply.trim() || Boolean(busy)}>+ {t("society.lead.send")}+ </Button>+ </form>}++ {goal.state !== "done" && goal.state !== "cancelled" && <div className="flex flex-wrap justify-end gap-2">+ {goal.state === "paused" && <Button size="sm" disabled={Boolean(busy)} onClick={onResume}>{t("society.lead.resume")}</Button>}+ {goal.state === "failed" && <Button size="sm" variant="secondary" disabled={Boolean(busy)} onClick={onResume}>{t("society.lead.retry")}</Button>}+ {goal.state === "queued" && <Button size="sm" variant="secondary" disabled={Boolean(busy)} onClick={onResume}>{t("society.lead.start_now")}</Button>}+ {goal.state !== "failed" && <Button size="sm" variant="ghost" disabled={Boolean(busy)} onClick={onCancel}>+ {t(goal.state === "queued" ? "society.lead.remove_goal" : "society.lead.stop")}+ </Button>}+ </div>}+ </article>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsx b/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsxindex c0f1a2c80a..fafe81a10f 100644--- a/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsx@@ -159,6 +159,7 @@ function TeamCard({ group, agents, layout, sample, actions }: {const [error, setError] = useState("");const present = group.members.map((id) => agents.find((a) => a.agentId === id)).filter((a): a is SocietyAgent => !!a);const working = present.filter((a) => a.state === "working").length;+ const lead = present.find((a) => a.agentId === group.lead_agent_id);const inMeeting = !!meeting && meeting.groupId === group.group_id && meeting.untilMs > Date.now();const meet = () => {@@ -199,6 +200,7 @@ function TeamCard({ group, agents, layout, sample, actions }: {<span className="office-hint">{t("society.office.team_members").replace("{0}", String(present.length))}{working > 0 ? ` · ${t("society.office.team_working").replace("{0}", String(working))}` : ""}+ {lead ? ` · ${t("society.office.team_lead").replace("{0}", lead.name)}` : ""}</span></div><div className="team-badges">diff --git a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsxindex d313571675..185709cf77 100644--- a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx+++ b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx@@ -592,7 +592,9 @@ export function RosterRail({<span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-foreground">{group.name}</span><span className="block truncate text-xs text-muted-foreground">{groupHover?.kind === "group" && groupHover.id === group.group_id? t(groupReady ? "society.groups.release_to_group" : "society.groups.hold_to_group")- : group.members.map(memberName).join(", ")}</span>+ : group.lead_agent_id+ ? `${t("society.lead.rail").replace("{0}", memberName(group.lead_agent_id))} · ${group.members.filter((id) => id !== group.lead_agent_id).map(memberName).join(", ")}`+ : group.members.map(memberName).join(", ")}</span></span></button></li>)}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 251a553ea0..0fd804ca38 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -5690,6 +5690,75 @@"mode_pipeline": "Stimme rein und raus"},"society": {+ "lead": {+ "tab": "Leitung",+ "loading": "Team wird geladen…",+ "none_title": "Dieses Team hat noch keine Leitung",+ "none_body": "Eine Leitung ist ein Agent, der das Team für dich managt. Du gibst dem Team ein Ziel; die Leitung zerlegt es in Aufgaben, verteilt sie an die Mitglieder, prüft die Ergebnisse und meldet sich bei dir, wenn alles erledigt ist.",+ "create": "Leitung erstellen",+ "pick": "Oder ein Mitglied zur Leitung machen",+ "pick_placeholder": "Mitglied auswählen",+ "make": "Zur Leitung machen",+ "role": "Teamleitung",+ "rail": "Leitung: {0}",+ "open_chat": "Chat öffnen",+ "change": "Ändern",+ "remove": "Leitung entfernen",+ "unavailable": "Diese Leitung ist pausiert oder wurde gelöscht. Wähle eine andere.",+ "working": "{0} arbeitet gerade daran…",+ "goal_label": "Neues Ziel für das Team",+ "goal_placeholder": "Was soll das Team erreichen?",+ "goal_hint": "{0} plant es, verteilt die Aufgaben und meldet sich mit dem Ergebnis.",+ "goal_send": "Ziel übergeben",+ "goals": "Ziele",+ "goals_empty": "Kein offenes Ziel. Gib dem Team eines, {0} übernimmt ab da.",+ "finished": "Abgeschlossen ({0})",+ "tasks_none": "{0} plant gerade die Arbeit.",+ "report": "Bericht von {0}",+ "question": "{0} fragt",+ "answer_placeholder": "Deine Antwort für {0}",+ "message_placeholder": "Sag {0} etwas zu diesem Ziel",+ "send": "Senden",+ "stop": "Ziel stoppen",+ "resume": "Fortsetzen",+ "retry": "Erneut versuchen",+ "start_now": "Jetzt starten",+ "remove_goal": "Entfernen",+ "show_result": "Ergebnis anzeigen",+ "hide_result": "Ergebnis ausblenden",+ "mission": "Auftrag des Teams",+ "mission_placeholder": "Wofür ist dieses Team da? Die Leitung liest das bei jedem Schritt.",+ "mission_save": "Auftrag speichern",+ "checkin": "Check-ins",+ "checkin_hint": "{0} schaut von sich aus nach dem Team und handelt, wenn etwas ansteht. Jeder Check-in ist ein Durchlauf auf dem Modell der Leitung.",+ "checkin_0": "Aus",+ "checkin_60": "Jede Stunde",+ "checkin_240": "Alle 4 Stunden",+ "checkin_1440": "Einmal am Tag",+ "source_jarvis": "Übergeben von {0}",+ "source_lead": "Gestartet von {0}",+ "source_assignment": "Vom Board",+ "state_queued": "Wartet",+ "state_running": "In Arbeit",+ "state_needs_input": "Braucht deine Antwort",+ "state_paused": "Pausiert",+ "state_done": "Erledigt",+ "state_failed": "Fehlgeschlagen",+ "state_cancelled": "Gestoppt",+ "task_state_waiting": "Wartet",+ "task_state_assigned": "Zugewiesen",+ "task_state_running": "Arbeitet",+ "task_state_done": "Erledigt",+ "task_state_blocked": "Blockiert",+ "task_state_cancelled": "Gestoppt",+ "note_society_paused": "Pausiert, weil alle Agenten gestoppt wurden.",+ "note_interrupted": "Unterbrochen, als die App geschlossen wurde. Mit Fortsetzen geht es weiter.",+ "note_turn_budget": "Die Leitung hat alle Durchläufe für dieses Ziel verbraucht. Mit Fortsetzen bekommt sie neue.",+ "note_lead_busy": "Die Leitung war zu lange in einem anderen Gespräch beschäftigt.",+ "note_lead_unavailable": "Die Leitung ist gerade nicht verfügbar.",+ "note_stalled": "Bei diesem Ziel hat sich nichts mehr bewegt.",+ "note_error": "Der Durchlauf der Leitung ist fehlgeschlagen: {0}"+ },"groups": {"create": "Neues Agent-Team","edit": "Agent-Team bearbeiten",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 39e76b3eba..9d73c71aea 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -5690,6 +5690,75 @@"mode_pipeline": "voice in and out"},"society": {+ "lead": {+ "tab": "Lead",+ "loading": "Loading the team…",+ "none_title": "This team has no lead yet",+ "none_body": "A lead is an agent that manages the team for you. You give the team a goal; the lead breaks it into tasks, hands them to the members, checks what comes back and reports to you when it is done.",+ "create": "Create a lead",+ "pick": "Or make a member the lead",+ "pick_placeholder": "Choose a member",+ "make": "Make lead",+ "role": "Team lead",+ "rail": "Lead: {0}",+ "open_chat": "Open chat",+ "change": "Change",+ "remove": "Remove lead",+ "unavailable": "This lead is paused or was deleted. Choose another one.",+ "working": "{0} is working on it…",+ "goal_label": "New goal for the team",+ "goal_placeholder": "What should the team achieve?",+ "goal_hint": "{0} plans it, hands out the tasks and reports back.",+ "goal_send": "Give goal",+ "goals": "Goals",+ "goals_empty": "No open goal. Give the team one and {0} takes it from there.",+ "finished": "Finished ({0})",+ "tasks_none": "{0} is planning the work.",+ "report": "Report from {0}",+ "question": "{0} asks",+ "answer_placeholder": "Your answer for {0}",+ "message_placeholder": "Tell {0} something about this goal",+ "send": "Send",+ "stop": "Stop goal",+ "resume": "Continue",+ "retry": "Try again",+ "start_now": "Start now",+ "remove_goal": "Remove",+ "show_result": "Show result",+ "hide_result": "Hide result",+ "mission": "Team mission",+ "mission_placeholder": "What is this team for? The lead reads this on every turn.",+ "mission_save": "Save mission",+ "checkin": "Check-ins",+ "checkin_hint": "{0} looks at the team unprompted and acts when something needs it. Every check-in is one turn on the lead's model.",+ "checkin_0": "Off",+ "checkin_60": "Every hour",+ "checkin_240": "Every 4 hours",+ "checkin_1440": "Once a day",+ "source_jarvis": "Handed over by {0}",+ "source_lead": "Started by {0}",+ "source_assignment": "From the board",+ "state_queued": "Queued",+ "state_running": "In progress",+ "state_needs_input": "Needs your answer",+ "state_paused": "Paused",+ "state_done": "Done",+ "state_failed": "Failed",+ "state_cancelled": "Stopped",+ "task_state_waiting": "Waiting",+ "task_state_assigned": "Assigned",+ "task_state_running": "Working",+ "task_state_done": "Done",+ "task_state_blocked": "Blocked",+ "task_state_cancelled": "Stopped",+ "note_society_paused": "Paused because all agents were stopped.",+ "note_interrupted": "Interrupted when the app closed. Continue to pick it up again.",+ "note_turn_budget": "The lead used all its turns for this goal. Continue to give it more.",+ "note_lead_busy": "The lead was busy in another conversation for too long.",+ "note_lead_unavailable": "The lead is not available right now.",+ "note_stalled": "Nothing was moving on this goal any more.",+ "note_error": "The lead's turn failed: {0}"+ },"groups": {"create": "New agent team","edit": "Edit agent team",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 6e7510bf35..0cb6ab7375 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -5690,6 +5690,75 @@"mode_pipeline": "voz de entrada y salida"},"society": {+ "lead": {+ "tab": "Líder",+ "loading": "Cargando el equipo…",+ "none_title": "Este equipo aún no tiene líder",+ "none_body": "Un líder es un agente que dirige el equipo por ti. Tú le das un objetivo al equipo; el líder lo divide en tareas, las reparte entre los miembros, revisa lo que vuelve y te informa cuando está hecho.",+ "create": "Crear un líder",+ "pick": "O convertir a un miembro en líder",+ "pick_placeholder": "Elige un miembro",+ "make": "Hacer líder",+ "role": "Líder del equipo",+ "rail": "Líder: {0}",+ "open_chat": "Abrir chat",+ "change": "Cambiar",+ "remove": "Quitar líder",+ "unavailable": "Este líder está en pausa o fue eliminado. Elige otro.",+ "working": "{0} está trabajando en ello…",+ "goal_label": "Nuevo objetivo para el equipo",+ "goal_placeholder": "¿Qué debe lograr el equipo?",+ "goal_hint": "{0} lo planifica, reparte las tareas y te informa.",+ "goal_send": "Dar objetivo",+ "goals": "Objetivos",+ "goals_empty": "Ningún objetivo abierto. Dale uno al equipo y {0} se encarga.",+ "finished": "Terminados ({0})",+ "tasks_none": "{0} está planificando el trabajo.",+ "report": "Informe de {0}",+ "question": "{0} pregunta",+ "answer_placeholder": "Tu respuesta para {0}",+ "message_placeholder": "Dile algo a {0} sobre este objetivo",+ "send": "Enviar",+ "stop": "Detener objetivo",+ "resume": "Continuar",+ "retry": "Reintentar",+ "start_now": "Empezar ahora",+ "remove_goal": "Quitar",+ "show_result": "Ver resultado",+ "hide_result": "Ocultar resultado",+ "mission": "Misión del equipo",+ "mission_placeholder": "¿Para qué es este equipo? El líder lo lee en cada turno.",+ "mission_save": "Guardar misión",+ "checkin": "Revisiones",+ "checkin_hint": "{0} revisa el equipo por su cuenta y actúa cuando algo lo necesita. Cada revisión es un turno en el modelo del líder.",+ "checkin_0": "Desactivado",+ "checkin_60": "Cada hora",+ "checkin_240": "Cada 4 horas",+ "checkin_1440": "Una vez al día",+ "source_jarvis": "Encargado por {0}",+ "source_lead": "Iniciado por {0}",+ "source_assignment": "Desde el tablero",+ "state_queued": "En cola",+ "state_running": "En curso",+ "state_needs_input": "Necesita tu respuesta",+ "state_paused": "En pausa",+ "state_done": "Hecho",+ "state_failed": "Fallido",+ "state_cancelled": "Detenido",+ "task_state_waiting": "Esperando",+ "task_state_assigned": "Asignada",+ "task_state_running": "Trabajando",+ "task_state_done": "Hecha",+ "task_state_blocked": "Bloqueada",+ "task_state_cancelled": "Detenida",+ "note_society_paused": "En pausa porque se detuvieron todos los agentes.",+ "note_interrupted": "Interrumpido al cerrar la aplicación. Continúa para retomarlo.",+ "note_turn_budget": "El líder usó todos sus turnos para este objetivo. Continúa para darle más.",+ "note_lead_busy": "El líder estuvo ocupado demasiado tiempo en otra conversación.",+ "note_lead_unavailable": "El líder no está disponible ahora.",+ "note_stalled": "Ya no avanzaba nada en este objetivo.",+ "note_error": "El turno del líder falló: {0}"+ },"groups": {"create": "Nuevo equipo de agentes","edit": "Editar equipo de agentes",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex d4339e34ad..8045525110 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -1008,6 +1008,7 @@"team_yours": "Deine Teams","team_none": "Noch keine Teams. Stell unten eins zusammen.","team_members": "{0} Mitglieder",+ "team_lead": "Leitung: {0}","team_working": "{0} arbeiten","team_meet": "Am Tisch treffen","team_meeting_now": "Im Meeting",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex e558db5d53..bd5d4e8ef2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -1008,6 +1008,7 @@"team_yours": "Your teams","team_none": "No teams yet. Put one together below.","team_members": "{0} members",+ "team_lead": "Lead: {0}","team_working": "{0} working","team_meet": "Meet at the table","team_meeting_now": "In the meeting",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 07696aa07a..6fbe6803ee 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -1008,6 +1008,7 @@"team_yours": "Tus equipos","team_none": "Aún no hay equipos. Forma uno abajo.","team_members": "{0} miembros",+ "team_lead": "Líder: {0}","team_working": "{0} trabajando","team_meet": "Reunirse en la mesa","team_meeting_now": "En la reunión",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/society/zh.jsonindex e902301c87..fe5c880eb4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/zh.json@@ -1008,6 +1008,7 @@"team_yours": "你的团队","team_none": "还没有团队。在下方组建一个吧。","team_members": "{0} 名成员",+ "team_lead": "负责人:{0}","team_working": "{0} 个工作中","team_meet": "在桌边集合","team_meeting_now": "会议中",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.jsonindex ef12d78505..248e167f30 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json@@ -5696,6 +5696,75 @@"mode_pipeline": "语音输入和输出"},"society": {+ "lead": {+ "tab": "负责人",+ "loading": "正在加载团队…",+ "none_title": "这个团队还没有负责人",+ "none_body": "负责人是替你管理团队的智能体。你给团队一个目标,负责人把它拆成任务、分配给成员、检查结果,并在完成后向你汇报。",+ "create": "创建负责人",+ "pick": "或让一名成员担任负责人",+ "pick_placeholder": "选择成员",+ "make": "设为负责人",+ "role": "团队负责人",+ "rail": "负责人:{0}",+ "open_chat": "打开对话",+ "change": "更换",+ "remove": "移除负责人",+ "unavailable": "这位负责人已暂停或被删除,请另选一位。",+ "working": "{0} 正在处理…",+ "goal_label": "给团队的新目标",+ "goal_placeholder": "团队要达成什么?",+ "goal_hint": "{0} 会规划、分配任务并向你汇报。",+ "goal_send": "下达目标",+ "goals": "目标",+ "goals_empty": "没有进行中的目标。给团队一个目标,{0} 会接手。",+ "finished": "已结束({0})",+ "tasks_none": "{0} 正在规划工作。",+ "report": "{0} 的汇报",+ "question": "{0} 提问",+ "answer_placeholder": "你给 {0} 的回答",+ "message_placeholder": "就这个目标对 {0} 说点什么",+ "send": "发送",+ "stop": "停止目标",+ "resume": "继续",+ "retry": "重试",+ "start_now": "立即开始",+ "remove_goal": "移除",+ "show_result": "显示结果",+ "hide_result": "隐藏结果",+ "mission": "团队使命",+ "mission_placeholder": "这个团队是做什么的?负责人每一轮都会读到。",+ "mission_save": "保存使命",+ "checkin": "例行检查",+ "checkin_hint": "{0} 会主动查看团队,并在需要时采取行动。每次检查都是负责人模型的一轮。",+ "checkin_0": "关闭",+ "checkin_60": "每小时",+ "checkin_240": "每 4 小时",+ "checkin_1440": "每天一次",+ "source_jarvis": "由 {0} 交办",+ "source_lead": "由 {0} 发起",+ "source_assignment": "来自任务板",+ "state_queued": "排队中",+ "state_running": "进行中",+ "state_needs_input": "需要你的回答",+ "state_paused": "已暂停",+ "state_done": "已完成",+ "state_failed": "失败",+ "state_cancelled": "已停止",+ "task_state_waiting": "等待中",+ "task_state_assigned": "已分配",+ "task_state_running": "处理中",+ "task_state_done": "已完成",+ "task_state_blocked": "受阻",+ "task_state_cancelled": "已停止",+ "note_society_paused": "因所有智能体被停止而暂停。",+ "note_interrupted": "应用关闭时被中断。点击继续即可接着做。",+ "note_turn_budget": "负责人已用完这个目标的全部轮次。点击继续可再给一些。",+ "note_lead_busy": "负责人在另一段对话中忙碌太久。",+ "note_lead_unavailable": "负责人目前不可用。",+ "note_stalled": "这个目标已经没有任何进展。",+ "note_error": "负责人的这一轮失败了:{0}"+ },"groups": {"create": "新建智能体团队","edit": "编辑智能体团队",diff --git a/jarvis/ui/web/frontend/src/lib/societyApi.ts b/jarvis/ui/web/frontend/src/lib/societyApi.tsindex b82fe07960..bee93aa314 100644--- a/jarvis/ui/web/frontend/src/lib/societyApi.ts+++ b/jarvis/ui/web/frontend/src/lib/societyApi.ts@@ -79,6 +79,18 @@ export type ApprovalState = (typeof APPROVAL_STATES)[number];export const QUEST_STATES = ["open", "assigned", "running", "done", "failed", "cancelled"] as const;export type QuestState = (typeof QUEST_STATES)[number];+/** A goal the person gave a team; its lead plans, assigns and reports. */+export const TEAM_GOAL_STATES = [+ "queued", "running", "needs_input", "paused", "done", "failed", "cancelled",+] as const;+export type TeamGoalState = (typeof TEAM_GOAL_STATES)[number];++/** One task a team lead handed to a member. */+export const TEAM_TASK_STATES = [+ "waiting", "assigned", "running", "done", "blocked", "cancelled",+] as const;+export type TeamTaskState = (typeof TEAM_TASK_STATES)[number];+/** One row of the board, as GET /api/society/events returns it. */export interface SocietyEnvelope {seq: number;diff --git a/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts b/jarvis/ui/web/frontend/src/lib/societyChatGroups.tsindex 76624c9c3d..37c897a347 100644--- a/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts+++ b/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts@@ -1,4 +1,7 @@-import { useQuery } from "@tanstack/react-query";+import { useEffect } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useEventStore } from "@/store/events";+import type { TeamGoalState, TeamTaskState } from "@/lib/societyApi";export interface SocietyChatGroup {group_id: string;@@ -6,6 +9,10 @@ export interface SocietyChatGroup {members: string[];created_ms: number;updated_ms: number;+ /** The member that manages the team; absent or null = no lead. */+ lead_agent_id?: string | null;+ /** The team's standing purpose, read by its lead. */+ mission?: string;}async function json<T>(url: string, init?: RequestInit): Promise<T> {@@ -70,3 +77,133 @@ export async function sendSocietyMeeting(groupId: string, text: string) {export async function stopSocietyMeeting(groupId: string) {return json<SocietyMeeting>(`${meetingUrl(groupId)}/stop`, { method: "POST" });}++/** One task a team lead handed to a member. */+export interface SocietyTeamTask {+ task_id: string;+ goal_id: string;+ agent_id: string;+ title: string;+ brief: string;+ state: TeamTaskState;+ result: string;+ reviewed: boolean;+ created_ms: number;+ updated_ms: number;+ done_ms: number | null;+}++/** A goal the person gave a team, with the tasks its lead handed out. */+export interface SocietyTeamGoal {+ goal_id: string;+ group_id: string;+ lead_agent_id: string;+ title: string;+ text: string;+ state: TeamGoalState;+ /** The lead's latest report: an update, its question, or the result. */+ report: string;+ /** Why the goal waits: a code (`turn_budget`), or `error:<detail>`. */+ note: string;+ lead_turns: number;+ /** Where it came from: the team board, the assistant, the lead's own chat. */+ source: string;+ created_ms: number;+ updated_ms: number;+ done_ms: number | null;+ tasks: SocietyTeamTask[];+}++/** A team as its board shows it. Reading it never starts a turn. */+export interface SocietyTeam {+ group_id: string;+ lead_agent_id: string | null;+ lead_available: boolean;+ mission: string;+ /** Minutes between the lead's unprompted looks at the team; 0 = off. */+ checkin_minutes: number;+ goals: SocietyTeamGoal[];+ /** Whether the lead is in a managing turn right now. */+ working: boolean;+ max_lead_turns: number;+}++/** Goal states in which the lead or a member may still act. */+export const TEAM_GOAL_OPEN: readonly TeamGoalState[] = ["queued", "running", "needs_input", "paused"];++const teamUrl = (groupId: string) => `/api/society/chat-groups/${encodeURIComponent(groupId)}`;+const teamKey = (groupId: string) => ["society", "team", groupId] as const;++/** Bus event names that mean "a team board changed" (jarvis/core/events.py). */+const TEAM_EVENTS = new Set(["SocietyTeamChanged"]);++/**+ * A team's lead, mission, goals and tasks, kept live by the `SocietyTeamChanged`+ * push the WebSocket forwards, with a slow poll as the safety net while a goal+ * is open.+ */+export function useSocietyTeam(groupId: string, enabled = true) {+ const client = useQueryClient();+ const query = useQuery({+ queryKey: teamKey(groupId),+ queryFn: () => json<SocietyTeam>(`${teamUrl(groupId)}/team`),+ enabled,+ staleTime: 1_000,+ refetchInterval: (current) =>+ current.state.data?.goals.some((goal) => TEAM_GOAL_OPEN.includes(goal.state)) ? 5_000 : false,+ });+ useEffect(() => {+ if (!enabled) return;+ let lastId: string | null = useEventStore.getState().events[0]?.id ?? null;+ return useEventStore.subscribe((state) => {+ const top = state.events[0];+ if (!top || top.id === lastId) return;+ lastId = top.id;+ if (!TEAM_EVENTS.has(top.name)) return;+ const payload = top.payload as { group_id?: string; reason?: string } | undefined;+ if (payload?.group_id && payload.group_id !== groupId) return;+ void client.invalidateQueries({ queryKey: teamKey(groupId) });+ // A new lead is a roster change and a group change too.+ if (payload?.reason === "lead") {+ void client.invalidateQueries({ queryKey: ["society", "chat-groups"] });+ void client.invalidateQueries({ queryKey: ["society", "roster"] });+ }+ });+ }, [client, enabled, groupId]);+ return query;+}++export function setSocietyTeamLead(groupId: string, agentId: string | null) {+ return json<SocietyTeam>(`${teamUrl(groupId)}/lead`, { ...body({ agent_id: agentId }), method: "PUT" });+}++/** Create a new agent whose job is managing this team, and make it the lead. */+export function createSocietyTeamLead(groupId: string) {+ return json<SocietyTeam>(`${teamUrl(groupId)}/lead`, body({}));+}++export function setSocietyTeamMission(groupId: string, mission: string) {+ return json<SocietyTeam>(`${teamUrl(groupId)}/mission`, { ...body({ mission }), method: "PUT" });+}++export function setSocietyTeamCheckin(groupId: string, minutes: number) {+ return json<SocietyTeam>(`${teamUrl(groupId)}/checkin`, { ...body({ minutes }), method: "PUT" });+}++export function startSocietyTeamGoal(groupId: string, text: string) {+ return json<SocietyTeam>(`${teamUrl(groupId)}/goals`, body({ text }));+}++const goalUrl = (groupId: string, goalId: string) => `${teamUrl(groupId)}/goals/${encodeURIComponent(goalId)}`;++export function messageSocietyTeamGoal(groupId: string, goalId: string, text: string) {+ return json<SocietyTeam>(`${goalUrl(groupId, goalId)}/message`, body({ text }));+}++export function resumeSocietyTeamGoal(groupId: string, goalId: string) {+ return json<SocietyTeam>(`${goalUrl(groupId, goalId)}/resume`, { method: "POST" });+}++export function cancelSocietyTeamGoal(groupId: string, goalId: string) {+ return json<SocietyTeam>(`${goalUrl(groupId, goalId)}/cancel`, { method: "POST" });+}diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex 0856c6c035..56b860a576 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -31,6 +31,7 @@ from jarvis.society.memory import MEMORY_SHARE_CAPABILITY, MemoryRefusedfrom jarvis.society.rooms import RoomErrorfrom jarvis.society.roster import AgentRecord, RosterErrorfrom jarvis.society.runtime import SocietyRuntime, SocietyRuntimeClosed+from jarvis.society.team_lead import TeamLeadErrorlog = logging.getLogger(__name__)@@ -684,7 +685,14 @@ async def update_chat_group(group_id: str, body: ChatGroupBody, request: Requestasync with rt.meetings.group_mutation():if rt.meetings.is_running(group_id):raise HTTPException(409, "Stop the meeting before changing its members.")- return {"group": await rt.store.update_chat_group(group_id, body.name.strip(), members)}+ try:+ # A lead that is no longer on the team stops leading it.+ await rt.team_leads.members_changed(group_id, members)+ except TeamLeadError as exc:+ raise HTTPException(exc.status, str(exc)) from exc+ group = await rt.store.update_chat_group(group_id, body.name.strip(), members)+ await rt.team_leads.refresh()+ return {"group": group}@router.delete("/chat-groups/{group_id}", openapi_extra={"x-jarvis-dangerous": True})@@ -698,10 +706,190 @@ async def delete_chat_group(group_id: str, request: Request) -> dict[str, bool]:await rt.meetings.stop(group_id)except ValueError as exc:raise HTTPException(409, str(exc)) from exc+ await rt.team_leads.group_deleted(group_id)await rt.store.delete_chat_group(group_id)+ await rt.team_leads.refresh()return {"deleted": True}+# ---------------------------------------------------------------- team leads+++class TeamLeadBody(BaseModel):+ #: The member that manages the team; ``None`` removes the lead.+ agent_id: str | None = Field(default=None, max_length=80)+++class TeamLeadCreateBody(BaseModel):+ name: str = Field(default="", max_length=40)+++class TeamMissionBody(BaseModel):+ mission: str = Field(default="", max_length=4_000)+++class TeamCheckinBody(BaseModel):+ #: Minutes between the lead's unprompted looks at its team; 0 = off.+ minutes: int = Field(default=0, ge=0, le=1_440)+++class TeamGoalBody(BaseModel):+ text: str = Field(min_length=1, max_length=20_000)+ title: str = Field(default="", max_length=120)+ lang: str | None = None+++class TeamGoalMessageBody(BaseModel):+ text: str = Field(min_length=1, max_length=20_000)+++def _team_error(exc: TeamLeadError) -> HTTPException:+ return HTTPException(exc.status, str(exc))+++async def _team_goal(rt: SocietyRuntime, group_id: str, goal_id: str) -> None:+ goal = await rt.team_leads.get_goal(goal_id)+ if goal is None or goal.group_id != group_id:+ raise HTTPException(404, "goal not found")++[email protected]("/chat-groups/{group_id}/team", openapi_extra={"x-jarvis-readonly": True})+async def get_team(group_id: str, request: Request) -> dict[str, Any]:+ """Read a team's lead, mission, goals and tasks without starting a turn."""+ rt = await _runtime(request)+ try:+ return await rt.team_leads.snapshot(group_id)+ except TeamLeadError as exc:+ raise _team_error(exc) from exc++[email protected]("/chat-groups/{group_id}/lead")+async def set_team_lead(group_id: str, body: TeamLeadBody, request: Request) -> dict[str, Any]:+ """Name the member that manages the team, or remove the lead."""+ rt = await _runtime(request)+ try:+ await rt.team_leads.set_lead(group_id, body.agent_id)+ return await rt.team_leads.snapshot(group_id)+ except TeamLeadError as exc:+ raise _team_error(exc) from exc+ except RosterError as exc:+ raise _typed_error(exc) from exc++[email protected]("/chat-groups/{group_id}/lead")+async def create_team_lead(+ group_id: str, body: TeamLeadCreateBody, request: Request+) -> dict[str, Any]:+ """Create a new agent whose job is managing this team, and make it the lead."""+ rt = await _runtime(request)+ fields: dict[str, Any] = {}+ from .agent_chat_routes import _service_from_state++ # A new lead runs on the seat the person last picked for a chat, as every+ # agent created from the app does; without one it uses the Agents tier.+ svc = _service_from_state(request.app.state)+ selection = svc.store.chat_selection() if svc is not None else None+ if selection is not None:+ fields = {key: value for key, value in selection.to_dict().items() if value}+ try:+ _, agent = await rt.team_leads.create_lead(group_id, name=body.name, fields=fields)+ except TeamLeadError as exc:+ raise _team_error(exc) from exc+ except RosterError as exc:+ raise _typed_error(exc) from exc+ progression = getattr(request.app.state, "progression", None)+ if progression is not None:+ await progression.note_agent_hired(agent.agent_id)+ return {**await rt.team_leads.snapshot(group_id), "agent": agent.to_dict()}++[email protected]("/chat-groups/{group_id}/mission")+async def set_team_mission(+ group_id: str, body: TeamMissionBody, request: Request+) -> dict[str, Any]:+ """Save the team's standing purpose; its lead reads it on every managing turn."""+ rt = await _runtime(request)+ try:+ await rt.team_leads.set_mission(group_id, body.mission)+ return await rt.team_leads.snapshot(group_id)+ except TeamLeadError as exc:+ raise _team_error(exc) from exc++[email protected]("/chat-groups/{group_id}/checkin", openapi_extra={"x-jarvis-dangerous": True})+async def set_team_checkin(+ group_id: str, body: TeamCheckinBody, request: Request+) -> dict[str, Any]:+ """Switch the lead's unprompted team check-in on (0 = off). Each check-in is a turn."""+ rt = await _runtime(request)+ try:+ await rt.team_leads.set_checkin(group_id, body.minutes)+ return await rt.team_leads.snapshot(group_id)+ except TeamLeadError as exc:+ raise _team_error(exc) from exc++[email protected]("/chat-groups/{group_id}/goals", openapi_extra={"x-jarvis-dangerous": True})+async def start_team_goal(group_id: str, body: TeamGoalBody, request: Request) -> dict[str, Any]:+ """Give the team a goal; its lead plans it, hands out tasks and reports back."""+ rt = await _runtime(request)+ try:+ goal = await rt.team_leads.start_goal(+ group_id, body.text, title=body.title, lang=body.lang, origin={"kind": "board"}+ )+ return {**await rt.team_leads.snapshot(group_id), "goal_id": goal.goal_id}+ except TeamLeadError as exc:+ raise _team_error(exc) from exc+++ "/chat-groups/{group_id}/goals/{goal_id}/message",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def message_team_goal(+ group_id: str, goal_id: str, body: TeamGoalMessageBody, request: Request+) -> dict[str, Any]:+ """Answer the lead's question or steer a goal in progress."""+ rt = await _runtime(request)+ await _team_goal(rt, group_id, goal_id)+ try:+ await rt.team_leads.tell(goal_id, body.text)+ return await rt.team_leads.snapshot(group_id)+ except TeamLeadError as exc:+ raise _team_error(exc) from exc+++ "/chat-groups/{group_id}/goals/{goal_id}/resume",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def resume_team_goal(group_id: str, goal_id: str, request: Request) -> dict[str, Any]:+ """Continue a paused goal, retry a failed one, or start a queued one."""+ rt = await _runtime(request)+ await _team_goal(rt, group_id, goal_id)+ try:+ await rt.team_leads.resume(goal_id)+ return await rt.team_leads.snapshot(group_id)+ except TeamLeadError as exc:+ raise _team_error(exc) from exc+++ "/chat-groups/{group_id}/goals/{goal_id}/cancel",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def cancel_team_goal(group_id: str, goal_id: str, request: Request) -> dict[str, Any]:+ """Stop a goal: the lead's turn and every member task that still runs."""+ rt = await _runtime(request)+ await _team_goal(rt, group_id, goal_id)+ try:+ await rt.team_leads.cancel(goal_id)+ return await rt.team_leads.snapshot(group_id)+ except TeamLeadError as exc:+ raise _team_error(exc) from exc+++@router.post("/agents/{agent_id}/message", openapi_extra={"x-jarvis-dangerous": True})async def message_agent(agent_id: str, body: MessageBody, request: Request) -> dict[str, Any]:"""Append a message to the agent (user → agent by default). May start a turn."""diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.pyindex 8b45b2b2d0..7388460133 100644--- a/tests/contract/test_agent_mcp_harmony.py+++ b/tests/contract/test_agent_mcp_harmony.py@@ -229,6 +229,40 @@ WITHHELD: Final[dict[str, str]] = {"POST /api/society/chat-groups/{group_id}/meeting/stop": ("stops the owner's meeting round, which only the app can start"),+ "GET /api/society/chat-groups/{group_id}/team": (+ "the team board (lead, mission, goals, tasks) is the owner's view of a "+ "group in the app; a remote client reads each agent's own chat"+ ),+ "PUT /api/society/chat-groups/{group_id}/lead": (+ "naming a team's lead changes an agent's tier and is the owner's "+ "decision in the app"+ ),+ "POST /api/society/chat-groups/{group_id}/lead": (+ "creates a new agent as the team's lead; staffing a team is the "+ "owner's decision in the app"+ ),+ "PUT /api/society/chat-groups/{group_id}/mission": (+ "the team's standing mission is the owner's own instruction, set in the app"+ ),+ "PUT /api/society/chat-groups/{group_id}/checkin": (+ "switches on recurring unprompted turns on the lead's seat; only the "+ "owner starts work that bills by itself"+ ),+ "POST /api/society/chat-groups/{group_id}/goals": (+ "a remote client gives a team a goal by assigning work to its lead "+ "(agent_assign), which becomes the team's goal"+ ),+ "POST /api/society/chat-groups/{group_id}/goals/{goal_id}/message": (+ "answering the lead's question on a goal is the owner's reply on the "+ "team board in the app"+ ),+ "POST /api/society/chat-groups/{group_id}/goals/{goal_id}/resume": (+ "continuing a paused goal restarts paid turns and is the owner's "+ "decision on the team board"+ ),+ "POST /api/society/chat-groups/{group_id}/goals/{goal_id}/cancel": (+ "stopping a team's goal is the owner's decision on the team board in the app"+ ),}diff --git a/tests/fakes/team_chat.py b/tests/fakes/team_chat.pynew file mode 100644index 0000000000..5b284e1e4c--- /dev/null+++ b/tests/fakes/team_chat.py@@ -0,0 +1,127 @@+"""Deterministic chat turns for team-lead tests; no provider calls.++Every ``send`` starts a turn as its own task, like the real service: the+session is busy until the turn ends, subscribers receive its events, and+``wait_turn`` joins it. ``scripts[session_id]`` decides what a turn does (a+lead's script calls the engine's tools); a session without one answers with+``replies[session_id]``. ``gates[session_id]`` holds a turn open until set.+"""++from __future__ import annotations++import asyncio+from collections.abc import Awaitable, Callable+from typing import Any++from jarvis.agent_chat.events import make_event+from jarvis.agent_chat.service import SessionBusy+from jarvis.agent_chat.store import AgentChatStore++Script = Callable[[str, dict[str, Any]], Awaitable[str]]+++class TeamChatFake:+ supports_turn_completion = True++ def __init__(self, store: AgentChatStore) -> None:+ self.store = store+ self.sent: list[tuple[str, str, dict[str, Any], str]] = []+ self.scripts: dict[str, Script] = {}+ self.replies: dict[str, str] = {}+ self.gates: dict[str, asyncio.Event] = {}+ self.failing: set[str] = set()+ self.cancelled: list[tuple[str, str | None]] = []+ self.busy: set[str] = set()+ self._turns: dict[str, asyncio.Task[None]] = {}+ self._subscribers: dict[str, set[asyncio.Queue[dict[str, Any]]]] = {}++ # ------------------------------------------------------------- reads++ def is_running(self, session_id: str) -> bool:+ return session_id in self.busy++ def running_session_ids(self) -> list[str]:+ return list(self.busy)++ def prompts(self, session_id: str) -> list[str]:+ return [text for sid, text, _, _ in self.sent if sid == session_id]++ def idle(self) -> bool:+ return not self.busy++ # --------------------------------------------------------- subscribe++ def subscribe(self, session_id: str) -> asyncio.Queue[dict[str, Any]]:+ queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue()+ self._subscribers.setdefault(session_id, set()).add(queue)+ return queue++ def unsubscribe(self, session_id: str, queue: asyncio.Queue[dict[str, Any]]) -> None:+ self._subscribers.get(session_id, set()).discard(queue)++ def _emit(self, session_id: str, kind: str, payload: dict[str, Any]) -> None:+ event = self.store.append_event(session_id, make_event(kind, payload))+ for queue in list(self._subscribers.get(session_id, ())):+ queue.put_nowait(event)++ # -------------------------------------------------------------- turns++ async def send(self, session_id: str, text: str, **kwargs: Any) -> str:+ if session_id in self.busy:+ raise SessionBusy(session_id)+ turn_id = f"turn-{len(self.sent)}"+ self.sent.append((session_id, text, kwargs, turn_id))+ self.busy.add(session_id)+ self._turns[session_id] = asyncio.create_task(+ self._run(session_id, turn_id, text, kwargs)+ )+ return turn_id++ async def _run(self, session_id: str, turn_id: str, text: str, kwargs: dict[str, Any]) -> None:+ status, reply, error = "done", "", ""+ try:+ gate = self.gates.get(session_id)+ if gate is not None:+ await gate.wait()+ if session_id in self.failing:+ raise RuntimeError("provider unavailable")+ script = self.scripts.get(session_id)+ if script is not None:+ reply = await script(text, kwargs)+ else:+ reply = self.replies.get(session_id, f"Done by {session_id}")+ except asyncio.CancelledError:+ status = "cancelled"+ except Exception as exc: # noqa: BLE001 — a failing turn ends as an error event+ status, error = "error", str(exc)+ if reply:+ self._emit(session_id, "assistant_text", {"turn_id": turn_id, "text": reply})+ payload = {"turn_id": turn_id, "status": status}+ if error:+ payload["error"] = error+ # Free the session before the terminal is seen, as the service does.+ self.busy.discard(session_id)+ self._emit(session_id, "turn_finished", payload)++ async def wait_turn(self, session_id: str) -> None:+ task = self._turns.get(session_id)+ if task is not None:+ await asyncio.shield(task)++ async def cancel(self, session_id: str, *, expected_turn_id: str | None = None) -> bool:+ self.cancelled.append((session_id, expected_turn_id))+ task = self._turns.get(session_id)+ if task is None or task.done():+ return False+ task.cancel()+ await asyncio.wait({task})+ return True++ async def post_notice(self, session_id: str, payload: dict[str, Any]) -> None:+ self._emit(session_id, "notice", payload)++ async def close(self) -> None:+ for task in self._turns.values():+ task.cancel()+ if self._turns:+ await asyncio.wait(set(self._turns.values()))diff --git a/tests/unit/society/test_society_enum_parity.py b/tests/unit/society/test_society_enum_parity.pyindex 82c2a27825..63d6fd1049 100644--- a/tests/unit/society/test_society_enum_parity.py+++ b/tests/unit/society/test_society_enum_parity.py@@ -34,6 +34,8 @@ _PINS = [(events.RoomState, None, "ROOM_STATES"),(events.ApprovalState, None, "APPROVAL_STATES"),(events.QuestState, "society_quests.state", "QUEST_STATES"),+ (events.TeamGoalState, "society_team_goals.state", "TEAM_GOAL_STATES"),+ (events.TeamTaskState, "society_team_tasks.state", "TEAM_TASK_STATES"),(events.RunState, None, "RUN_STATES"),]diff --git a/tests/unit/society/test_team_lead.py b/tests/unit/society/test_team_lead.pynew file mode 100644index 0000000000..f1c7b91305--- /dev/null+++ b/tests/unit/society/test_team_lead.py@@ -0,0 +1,838 @@+"""Team leads: leadership, the goal loop, waiting, stopping, recovery, the tools."""++from __future__ import annotations++import asyncio+from collections.abc import Callable+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import aiosqlite+import pytest++from jarvis.agent_chat.store import AgentChatStore+from jarvis.society.events import MsgType, SocietyEnvelope, TeamGoalState, TeamTaskState, Tier+from jarvis.society.lead_card import render_lead_card+from jarvis.society.runtime import SocietyRuntime+from jarvis.society.store import SocietyStore+from jarvis.society.team_lead import (+ MAX_LEAD_TURNS,+ TRACE_PREFIX,+ TeamLeadError,+ goal_title,+)+from jarvis.society.team_tools import (+ TEAM_ASSIGN_TOOL_NAME,+ TEAM_BOARD_TOOL_NAME,+ TEAM_REPORT_TOOL_NAME,+ TeamAssignTool,+ TeamReportTool,+ team_lead_tools,+)+from tests.fakes.team_chat import TeamChatFake++LEAD = "society:boss"+SCOUT = "society:scout"+WRITER = "society:writer"+++async def until(predicate: Callable[[], Any], *, within: float = 5.0) -> None:+ """Poll an awaitable-or-plain predicate until it holds."""+ loop = asyncio.get_running_loop()+ deadline = loop.time() + within+ while True:+ value = predicate()+ if asyncio.iscoroutine(value):+ value = await value+ if value:+ return+ if loop.time() > deadline:+ raise AssertionError("condition was not reached in time")+ await asyncio.sleep(0.01)+++def _runtime(tmp_path: Path, svc: TeamChatFake) -> SocietyRuntime:+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path)))+ rt = SocietyRuntime(tmp_path, chat_service=lambda: svc, cfg=lambda: cfg)+ leads = rt.team_leads+ leads._retry_delay = 0.02 # noqa: SLF001 — tests do not wait fifteen seconds+ leads._review_delay = 0.0 # noqa: SLF001+ leads._lead_retry = 0.02 # noqa: SLF001+ return rt+++async def team(tmp_path: Path):+ svc = TeamChatFake(AgentChatStore(tmp_path / "chat.db"))+ rt = _runtime(tmp_path, svc)+ await rt.ensure_started()+ for name in ("Boss", "Scout", "Writer"):+ await rt.roster.create(name=name, provider="ollama", model="fake")+ await rt.store.create_chat_group("team", "Launch", ["boss", "scout", "writer"])+ await rt.team_leads.set_lead("team", "boss")+ try:+ yield rt, svc+ finally:+ await svc.close()+ await rt.close()+ svc.store.close()+++async def _goal(rt: SocietyRuntime, goal_id: str):+ goal = await rt.team_leads.get_goal(goal_id)+ assert goal is not None+ return goal+++def _state_is(rt: SocietyRuntime, goal_id: str, state: TeamGoalState) -> Callable[[], Any]:+ async def check() -> bool:+ return (await _goal(rt, goal_id)).state is state++ return check+++# ------------------------------------------------------------- leadership+++def test_goal_title_is_the_first_line_trimmed():+ assert goal_title("Launch the page\nby Friday") == "Launch the page"+ assert goal_title("x" * 200).endswith("…")+ assert goal_title("anything", "Given") == "Given"+ assert goal_title(" ") == "Goal"+++async def test_naming_a_lead_promotes_it_and_clearing_restores_it(team):+ rt, _ = team+ boss = await rt.roster.get("boss")+ assert boss.tier is Tier.ORCHESTRATOR and boss.may_assign+ assert boss.max_concurrent_runs == 3+ assert rt.team_leads.group_led_by("boss") == "team"+ snapshot = await rt.team_leads.snapshot("team")+ assert snapshot["lead_agent_id"] == "boss" and snapshot["lead_available"]++ await rt.team_leads.set_lead("team", None)+ boss = await rt.roster.get("boss")+ assert boss.tier is Tier.SPECIALIST and boss.max_concurrent_runs == 1+ assert rt.team_leads.group_led_by("boss") is None+++async def test_an_agent_that_was_an_orchestrator_before_stays_one(team):+ rt, _ = team+ await rt.roster.create(name="Chief", tier=Tier.ORCHESTRATOR, provider="ollama", model="fake")+ await rt.team_leads.set_lead("team", None)+ await rt.team_leads.set_lead("team", "chief")+ assert "chief" in (await rt.store.get_chat_group("team"))["members"]+ await rt.team_leads.set_lead("team", None)+ assert (await rt.roster.get("chief")).tier is Tier.ORCHESTRATOR+++async def test_jarvis_and_a_lead_of_another_team_are_refused(team):+ rt, _ = team+ with pytest.raises(TeamLeadError, match="Jarvis"):+ await rt.team_leads.set_lead("team", "jarvis")+ await rt.store.create_chat_group("other", "Other", ["boss", "scout"])+ with pytest.raises(TeamLeadError, match="another team"):+ await rt.team_leads.set_lead("other", "boss")+ with pytest.raises(TeamLeadError) as missing:+ await rt.team_leads.set_lead("nope", "scout")+ assert missing.value.status == 404+++async def test_create_lead_makes_a_new_orchestrator_with_a_free_name(team):+ rt, _ = team+ await rt.store.create_chat_group("ops", "Ops", ["scout", "writer"])+ group, agent = await rt.team_leads.create_lead(+ "ops", fields={"provider": "ollama", "model": "fake"}+ )+ assert agent.name == "Ops Lead" and agent.tier is Tier.ORCHESTRATOR+ assert group["lead_agent_id"] == agent.agent_id and agent.agent_id in group["members"]+ assert "manage a team" in agent.description+ await rt.store.create_chat_group("ops2", "Ops", ["scout", "writer"])+ _, second = await rt.team_leads.create_lead("ops2")+ assert second.name == "Ops Lead 2"+++async def test_a_lead_leaving_the_team_stops_leading_it(team):+ rt, _ = team+ await rt.team_leads.members_changed("team", ["scout", "writer"])+ assert (await rt.store.get_chat_group("team"))["lead_agent_id"] is None+ assert rt.team_leads.group_led_by("boss") is None+++# ------------------------------------------------------------ the goal loop+++async def test_a_goal_is_planned_worked_reviewed_and_reported(team):+ rt, svc = team+ leads = rt.team_leads+ svc.replies[SCOUT] = "Three competitors found: A, B, C."+ svc.replies[WRITER] = "Draft is in draft.md."+ seen: list[str] = []++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ seen.append(text)+ if text.startswith("[team goal for"):+ await leads.assign("boss", member="Scout", title="Research", brief="Find competitors.")+ await leads.assign("boss", member="writer", title="Draft", brief="Write the page.")+ return "Two tasks are running."+ board = await leads.board("boss")+ tasks = board["goals"][0]["tasks"]+ if all(task["state"] == "done" for task in tasks):+ await leads.report("boss", status="done", summary="Launch page is ready.")+ return "Reviewed."++ svc.scripts[LEAD] = boss+ await rt.store.set_chat_group_mission("team", "Ship the launch.")+ goal = await leads.start_goal("team", "Launch the page\nby Friday", lang="en")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))++ done = await _goal(rt, goal.goal_id)+ assert done.report == "Launch page is ready." and done.title == "Launch the page"+ tasks = await leads.tasks(goal.goal_id)+ assert [(t.agent_id, t.state) for t in tasks] == [+ ("scout", TeamTaskState.DONE),+ ("writer", TeamTaskState.DONE),+ ]+ assert all(t.reviewed and t.trace_id.startswith(TRACE_PREFIX) for t in tasks)+ assert tasks[0].result == "Three competitors found: A, B, C."++ assert "Team mission: Ship the launch." in seen[0]+ assert "- Scout" in seen[0] and "- Writer" in seen[0] and "Boss" not in seen[0]+ reviews = "\n".join(seen[1:])+ assert "[team update for team Launch]" in reviews+ assert "Three competitors found" in reviews and "Draft is in draft.md." in reviews+ # The lead's turns are not messages the person typed into its chat.+ lead_calls = [call for call in svc.sent if call[0] == LEAD]+ assert all(call[2]["direct_user"] is False for call in lead_calls)+ assert lead_calls[0][2]["output_language"] == "en"+ assert lead_calls[0][2]["display_text"] == "Launch the page\nby Friday"+ # Members got a framed assignment from the lead, on the board.+ assert svc.prompts(SCOUT)[0].startswith("[assignment from boss]")+ assert not rt.scheduler.running+++async def test_an_answer_without_open_work_is_the_report(team):+ rt, svc = team+ svc.replies[LEAD] = "It is 42."+ goal = await rt.team_leads.start_goal("team", "What is the answer?")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ assert (await _goal(rt, goal.goal_id)).report == "It is 42."+ # A plain answer may be a result or a question: the lead is asked once for+ # a typed report, and only then is its answer taken as the result.+ prompts = svc.prompts(LEAD)+ assert len(prompts) == 2 and prompts[1].startswith("[team goal check for team Launch]")+ assert "society_team_report" in prompts[1]+++async def test_results_arriving_during_a_lead_turn_reach_the_next_one(team):+ rt, svc = team+ leads = rt.team_leads+ release = asyncio.Event()+ seen: list[str] = []++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ seen.append(text)+ if len(seen) == 1:+ await leads.assign("boss", member="scout", title="Research", brief="Look it up.")+ await release.wait() # the member finishes while this turn is still open+ return "Assigned."+ await leads.report("boss", status="done", summary="All in.")+ return "Closed."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Find it")++ async def scout_done() -> bool:+ tasks = await leads.tasks(goal.goal_id)+ return bool(tasks) and tasks[0].state is TeamTaskState.DONE++ await until(scout_done)+ assert len(seen) == 1+ release.set()+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ assert len(seen) == 2 and "New results:" in seen[1]+++async def test_a_busy_member_is_knocked_on_again_instead_of_failing(team):+ rt, svc = team+ leads = rt.team_leads+ svc.busy.add(SCOUT)+ receipts: list[dict[str, Any]] = []++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ if text.startswith("[team goal for"):+ receipts.append(+ await leads.assign("boss", member="scout", title="Research", brief="Go.")+ )+ return "Waiting on Scout."+ await leads.report("boss", status="done", summary="Done.")+ return "Closed."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Research it")++ async def waiting() -> bool:+ tasks = await leads.tasks(goal.goal_id)+ return bool(tasks) and tasks[0].state is TeamTaskState.WAITING and tasks[0].attempts >= 2++ await until(waiting)+ assert (await _goal(rt, goal.goal_id)).state is TeamGoalState.RUNNING++ # A long wait outlives the scheduler's per-trace message cap: every knock+ # is on its own trace.+ async def knocked_often() -> bool:+ return (await leads.tasks(goal.goal_id))[0].attempts >= 16++ await until(knocked_often)+ task = (await leads.tasks(goal.goal_id))[0]+ assert task.state in (TeamTaskState.WAITING, TeamTaskState.ASSIGNED)+ assert task.trace_id.count(":") == 3+ svc.busy.discard(SCOUT)+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ assert (await leads.tasks(goal.goal_id))[0].state is TeamTaskState.DONE+++async def test_a_blocked_member_reaches_the_lead_as_blocked(team):+ rt, svc = team+ leads = rt.team_leads+ svc.failing.add(SCOUT)+ seen: list[str] = []++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ seen.append(text)+ if len(seen) == 1:+ await leads.assign("boss", member="scout", title="Research", brief="Go.")+ return "Assigned."+ await leads.report("boss", status="failed", summary="Scout cannot reach the source.")+ return "Closed."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Research it")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.FAILED))+ assert '"Research": blocked' in seen[1]+ assert (await _goal(rt, goal.goal_id)).report == "Scout cannot reach the source."+++async def test_a_question_waits_for_the_person_and_their_answer_continues(team):+ rt, svc = team+ leads = rt.team_leads+ seen: list[str] = []++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ seen.append(text)+ if len(seen) == 1:+ await leads.report("boss", status="needs_input", summary="Which market?")+ return "I need one answer."+ await leads.report("boss", status="done", summary="Planned for Germany.")+ return "Closed."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Plan the launch")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.NEEDS_INPUT))+ await until(svc.idle)+ waiting = await _goal(rt, goal.goal_id)+ assert waiting.report == "Which market?" and waiting.note == "question"+ assert len(seen) == 1++ await leads.tell(goal.goal_id, "Germany")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ assert "The person says about this goal:" in seen[1] and "Germany" in seen[1]+ with pytest.raises(TeamLeadError, match="not in progress"):+ await leads.tell(goal.goal_id, "More")+++async def test_a_managing_turn_is_marked_so_no_review_follows_it(team):+ rt, svc = team+ leads = rt.team_leads+ svc.gates[LEAD] = asyncio.Event()+ queued: list[str] = []+ rt.conversations.queue_review = lambda session_id, *a, **k: queued.append(session_id) # type: ignore[method-assign]+ goal = await leads.start_goal("team", "Do it")+ await until(lambda: LEAD in svc.busy)+ assert leads.is_managing(LEAD) and not leads.is_managing(SCOUT)+ turn = SimpleNamespace(turn_id="t", direct_user=False)+ done = '[{"kind": "turn_finished", "payload": {"status": "done"}}]'+ completion = SimpleNamespace(events_json=done, turn=turn)+ await rt.turn_completed(SimpleNamespace(session_id=LEAD), completion)+ assert queued == []+ # The same agent's own work is still reviewed.+ await rt.turn_completed(SimpleNamespace(session_id=SCOUT), completion)+ assert queued == [SCOUT]+ svc.gates[LEAD].set()+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ assert not leads.is_managing(LEAD)+++async def test_goals_queue_and_start_one_after_another(team):+ rt, svc = team+ leads = rt.team_leads+ gate = asyncio.Event()+ svc.gates[LEAD] = gate+ first = await leads.start_goal("team", "First")+ second = await leads.start_goal("team", "Second")+ await until(lambda: len(svc.prompts(LEAD)) == 1)+ assert (await _goal(rt, second.goal_id)).state is TeamGoalState.QUEUED+ gate.set()+ await until(_state_is(rt, second.goal_id, TeamGoalState.DONE))+ assert (await _goal(rt, first.goal_id)).state is TeamGoalState.DONE+ plans = [text for text in svc.prompts(LEAD) if text.startswith("[team goal for")]+ assert len(plans) == 2 and "First" in plans[0] and "Second" in plans[1]+++async def test_the_lead_busy_in_its_own_chat_is_retried(team):+ rt, svc = team+ svc.busy.add(LEAD)+ goal = await rt.team_leads.start_goal("team", "Do it")+ await asyncio.sleep(0.1)+ assert svc.prompts(LEAD) == []+ assert (await _goal(rt, goal.goal_id)).state is TeamGoalState.RUNNING+ svc.busy.discard(LEAD)+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+++# ------------------------------------------------------ stopping and bounds+++async def test_cancel_stops_the_member_turn_and_closes_the_tasks(team):+ rt, svc = team+ leads = rt.team_leads+ svc.gates[SCOUT] = asyncio.Event()++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ await leads.assign("boss", member="scout", title="Research", brief="Go.")+ return "Assigned."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Research it")++ async def running() -> bool:+ tasks = await leads.tasks(goal.goal_id)+ return bool(tasks) and tasks[0].state is TeamTaskState.RUNNING and svc.idle() is False++ await until(running)+ await until(lambda: LEAD not in svc.busy)+ cancelled = await leads.cancel(goal.goal_id)+ assert cancelled.state is TeamGoalState.CANCELLED+ assert (await leads.tasks(goal.goal_id))[0].state is TeamTaskState.CANCELLED+ assert (SCOUT, svc.sent[-1][3]) in svc.cancelled+ assert not rt.scheduler.running+ await until(svc.idle)+ # The stopped turn's late RESULT changes nothing.+ await asyncio.sleep(0.05)+ assert (await _goal(rt, goal.goal_id)).state is TeamGoalState.CANCELLED+++async def test_the_kill_switch_pauses_goals_and_resume_continues(team):+ rt, svc = team+ leads = rt.team_leads+ svc.gates[SCOUT] = asyncio.Event()+ seen: list[str] = []++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ seen.append(text)+ if len(seen) == 1:+ await leads.assign("boss", member="scout", title="Research", brief="Go.")+ return "Assigned."+ await leads.report("boss", status="done", summary="Finished after the pause.")+ return "Closed."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Research it")+ await until(lambda: SCOUT in svc.busy and LEAD not in svc.busy)+ result = await rt.engage_kill_switch()+ assert result["team_goals_paused"] == 1+ paused = await _goal(rt, goal.goal_id)+ assert paused.state is TeamGoalState.PAUSED and paused.note == "society_paused"+ with pytest.raises(TeamLeadError, match="paused"):+ await leads.start_goal("team", "Another")+ with pytest.raises(TeamLeadError, match="paused"):+ await leads.resume(goal.goal_id)++ # The real switch stops every society chat; the stopped task is on the board.+ await svc.cancel(SCOUT)+ await until(lambda: not rt.scheduler.running)+ assert len(seen) == 1 # a paused goal does not wake its lead++ await rt.release_kill_switch()+ await leads.resume(goal.goal_id)+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ assert "[team goal resumed for team Launch]" in seen[1]+ assert '"Research": blocked' in seen[1]+++async def test_the_turn_budget_pauses_a_goal_until_the_person_resumes(team):+ rt, svc = team+ leads = rt.team_leads+ goal = await leads.start_goal("team", "Endless")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ await rt.store.update_team_goal(+ goal.goal_id, {"state": "running", "lead_turns": MAX_LEAD_TURNS, "done_ms": None}+ )+ leads._resumed.add(goal.goal_id) # noqa: SLF001 — something to say, so the budget is what stops it+ await leads._lead_turn(goal.goal_id) # noqa: SLF001+ parked = await _goal(rt, goal.goal_id)+ assert parked.state is TeamGoalState.PAUSED and parked.note == "turn_budget"+ await leads.resume(goal.goal_id)+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+++async def test_a_failed_lead_turn_pauses_the_goal_with_the_reason(team):+ rt, svc = team+ svc.failing.add(LEAD)+ goal = await rt.team_leads.start_goal("team", "Do it")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.PAUSED))+ assert (await _goal(rt, goal.goal_id)).note == "error:provider unavailable"+++async def test_a_running_goal_comes_back_paused_after_a_restart(tmp_path: Path):+ svc = TeamChatFake(AgentChatStore(tmp_path / "chat.db"))+ rt = _runtime(tmp_path, svc)+ await rt.ensure_started()+ for name in ("Boss", "Scout"):+ await rt.roster.create(name=name, provider="ollama", model="fake")+ await rt.store.create_chat_group("team", "Launch", ["boss", "scout"])+ await rt.team_leads.set_lead("team", "boss")+ svc.gates[SCOUT] = asyncio.Event()++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ await rt.team_leads.assign("boss", member="scout", title="Research", brief="Go.")+ return "Assigned."++ svc.scripts[LEAD] = boss+ goal = await rt.team_leads.start_goal("team", "Research it")+ await until(lambda: SCOUT in svc.busy and LEAD not in svc.busy)+ await rt.close() # the app closes mid-task; the member's turn dies with it+ await svc.close()++ again = _runtime(tmp_path, svc)+ await again.ensure_started()+ try:+ back = await again.team_leads.get_goal(goal.goal_id)+ assert back.state is TeamGoalState.PAUSED and back.note == "interrupted"+ task = (await again.team_leads.tasks(goal.goal_id))[0]+ assert task.state is TeamTaskState.BLOCKED and "Interrupted" in task.result+ assert not task.reviewed+ assert again.team_leads.group_led_by("boss") == "team"+ # Reading the board resumes nothing.+ await again.team_leads.snapshot("team")+ assert len(svc.prompts(LEAD)) == 1+ finally:+ await again.close()+ svc.store.close()+++async def test_the_sweep_reports_a_run_that_died_silently(team):+ rt, svc = team+ leads = rt.team_leads+ svc.gates[SCOUT] = asyncio.Event()+ seen: list[str] = []++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ seen.append(text)+ if len(seen) == 1:+ await leads.assign("boss", member="scout", title="Research", brief="Go.")+ return "Assigned."+ await leads.report("boss", status="failed", summary="Scout went silent.")+ return "Closed."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Research it")+ await until(lambda: SCOUT in svc.busy and LEAD not in svc.busy)+ task = (await leads.tasks(goal.goal_id))[0]+ await leads.sweep() # fresh work is left alone+ assert (await leads.tasks(goal.goal_id))[0].state is TeamTaskState.RUNNING+ # The run vanished from the scheduler and the task shows no sign of life.+ rt.scheduler.note_run_ended(task.run_id)+ await rt.store.update_team_task(task.task_id, {"updated_ms": 1})+ await leads.sweep()+ await until(_state_is(rt, goal.goal_id, TeamGoalState.FAILED))+ assert "The run ended without a result." in seen[1]+++async def test_a_closed_goal_starts_nothing_more_from_its_open_turn(team):+ rt, svc = team+ leads = rt.team_leads+ svc.gates[LEAD] = asyncio.Event()+ goal = await leads.start_goal("team", "Research it")+ await until(lambda: LEAD in svc.busy)+ # The goal closes while its lead's turn is still open (the lead reported,+ # or the person stopped it and the turn has not ended yet).+ await rt.store.update_team_goal(goal.goal_id, {"state": "cancelled"})+ with pytest.raises(TeamLeadError, match="no longer in progress"):+ await leads.assign("boss", member="scout", title="Research", brief="Go.")+ with pytest.raises(TeamLeadError, match="no longer in progress"):+ await leads.report("boss", status="done", summary="Too late.")+ assert await leads.tasks(goal.goal_id) == []+ assert [g.goal_id for g in await leads.goals("team")] == [goal.goal_id]+ assert svc.prompts(SCOUT) == []+ with pytest.raises(TeamLeadError, match="not in progress"):+ await leads.tell(goal.goal_id, "Still there?")+ with pytest.raises(TeamLeadError, match="not paused"):+ await leads.resume(goal.goal_id)+ assert (await _goal(rt, goal.goal_id)).state is TeamGoalState.CANCELLED+ svc.gates[LEAD].set()+ await until(svc.idle)+++async def test_a_stop_wins_over_a_stale_pause_or_resume(team):+ rt, svc = team+ leads = rt.team_leads+ svc.gates[LEAD] = asyncio.Event()+ goal = await leads.start_goal("team", "Do it")+ await until(lambda: LEAD in svc.busy)+ stale = await _goal(rt, goal.goal_id) # read while the goal was running+ await leads.cancel(goal.goal_id)+ await leads._park(stale, "error:late") # noqa: SLF001 — a late pause from the stale read+ assert (await _goal(rt, goal.goal_id)).state is TeamGoalState.CANCELLED+ assert not await leads._finish(stale, TeamGoalState.DONE, report="late") # noqa: SLF001+ assert (await _goal(rt, goal.goal_id)).report == ""+++async def test_a_resume_during_a_turn_that_is_winding_down_is_not_lost(team):+ rt, svc = team+ leads = rt.team_leads+ svc.gates[LEAD] = asyncio.Event()+ goal = await leads.start_goal("team", "Do it")+ await until(lambda: LEAD in svc.busy)+ await rt.engage_kill_switch()+ await rt.release_kill_switch()+ # The person continues before the stopped turn has fully ended.+ await leads.resume(goal.goal_id)+ assert (await _goal(rt, goal.goal_id)).state is TeamGoalState.RUNNING+ await svc.cancel(LEAD) # the stopped turn ends "cancelled"+ svc.gates.pop(LEAD)+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ assert any(text.startswith("[team goal resumed") for text in svc.prompts(LEAD))+++# ------------------------------------------------- assignments from the board+++async def test_work_handed_to_a_lead_becomes_a_goal_and_answers_its_origin(team):+ rt, svc = team+ leads = rt.team_leads++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ if text.startswith("[team goal for"):+ await leads.assign("boss", member="scout", title="Research", brief="Go.")+ return "Assigned."+ await leads.report("boss", status="done", summary="Researched and summarized.")+ return "Closed."++ svc.scripts[LEAD] = boss+ env = await rt.store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.ASSIGN,+ from_agent="jarvis",+ to_agent="boss",+ trace_id="voice:abc",+ payload={"text": "Research the market", "reply_policy": "always", "lang": "de"},+ )+ )+ events = await rt.store.events_for_trace("voice:abc")+ claim = next(e for e in events if e.msg_type is MsgType.CLAIM)+ run_id = claim.payload["run_id"]+ # A goal may wait for days; it never holds one of the lead's run slots.+ assert run_id.startswith("goal:") and run_id not in rt.scheduler.running+ goal_id = run_id.removeprefix("goal:")+ assert (await _goal(rt, goal_id)).lang == "de"++ await until(_state_is(rt, goal_id, TeamGoalState.DONE))++ async def answered() -> list[SocietyEnvelope]:+ events = await rt.store.events_for_trace("voice:abc")+ return [e for e in events if e.msg_type is MsgType.RESULT]++ await until(answered)+ (result,) = await answered()+ assert result.parent_event_id == env.event_id and result.from_agent == "boss"+ assert result.payload["status"] == "done"+ assert result.payload["done"] == "Researched and summarized."+ assert not rt.scheduler.running+ # The lead's own chat never ran the raw assignment as a second turn.+ assert all(not text.startswith("[assignment from") for text in svc.prompts(LEAD))+++async def test_a_lead_assigning_from_its_own_chat_opens_a_goal(team):+ rt, svc = team+ leads = rt.team_leads+ receipt = await leads.assign("boss", member="scout", title="Check the logs", brief="Go.")+ goal = await _goal(rt, receipt["goal_id"])+ assert goal.title == "Check the logs" and goal.origin == {"kind": "lead"}+ svc.replies[LEAD] = "Logs are clean."+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ assert "[team update for team Launch]" in svc.prompts(LEAD)[0]+++# ---------------------------------------------------------------- the tools+++async def test_only_a_lead_holds_the_team_tools(team):+ rt, _ = team+ assert set(team_lead_tools(rt, "boss")) == {+ TEAM_ASSIGN_TOOL_NAME,+ TEAM_BOARD_TOOL_NAME,+ TEAM_REPORT_TOOL_NAME,+ }+ assert team_lead_tools(rt, "scout") == {}++ from jarvis.society.surface import society_tools++ lead_session = SimpleNamespace(session_id=LEAD, cwd="", permission_mode="")+ member_session = SimpleNamespace(session_id=SCOUT, cwd="", permission_mode="")+ cfg = rt.config()+ assert TEAM_ASSIGN_TOOL_NAME in society_tools(cfg, None, lead_session)+ assert TEAM_ASSIGN_TOOL_NAME not in society_tools(cfg, None, member_session)+++async def test_the_assign_tool_composes_a_brief_and_refuses_strangers(team):+ rt, svc = team+ svc.gates[SCOUT] = asyncio.Event()+ tool = TeamAssignTool(rt, "boss")+ await rt.roster.create(name="Outsider", provider="ollama", model="fake")+ refused = await tool.execute({"member": "Outsider", "title": "X", "task": "Y"}, None)+ assert not refused.success and "not a member of your team" in refused.error+ assert "Scout" in refused.error and "Boss" not in refused.error+ own = await tool.execute({"member": "Boss", "title": "X", "task": "Y"}, None)+ assert not own.success++ ok = await tool.execute(+ {+ "member": "Scout",+ "title": "Research",+ "task": "Find three competitors.",+ "context": "We sell bikes.",+ "completion_criteria": "A list with links.",+ },+ None,+ )+ assert ok.success and ok.output["state"] == "running" and ok.output["member"] == "Scout"+ task = (await rt.team_leads.tasks(ok.output["goal_id"]))[0]+ assert "Relevant context:\nWe sell bikes." in task.brief+ assert "Completion criteria:\nA list with links." in task.brief+ prompt = svc.prompts(SCOUT)[0]+ assert "Research\n\nFind three competitors." in prompt+ svc.gates[SCOUT].set()++ report = TeamReportTool(rt, "boss")+ bad = await report.execute({"status": "maybe", "summary": "x"}, None)+ assert not bad.success+ stranger = await TeamReportTool(rt, "scout").execute(+ {"status": "done", "summary": "x"}, None+ )+ assert not stranger.success and "do not lead" in stranger.error+++async def test_briefings_tell_the_lead_and_its_members_about_the_team(team):+ rt, _ = team+ await rt.team_leads.set_mission("team", "Ship the launch.")+ lead = rt.team_leads.briefing("boss")+ assert '## You lead the team "Launch"' in lead+ assert "Members you manage: Scout; Writer." in lead+ assert "Team mission: Ship the launch." in lead and "society_team_assign" in lead+ member = rt.team_leads.briefing("scout")+ assert 'member of the team "Launch", led by Boss' in member+ assert rt.team_leads.briefing("jarvis") == ""+ # Stable between team edits: the provider prompt cache holds.+ assert rt.team_leads.briefing("boss") == lead+++async def test_jarvis_card_names_the_teams_that_have_a_lead(team):+ rt, _ = team+ card = render_lead_card(+ rt.roster.snapshot(), rt.catalog(), teams=rt.team_leads.teams_snapshot()+ )+ assert "- Launch — lead: Boss · members: Scout, Writer" in card+ assert "goes to its LEAD with delegate_to_agent" in card+ assert "Teams with their own lead" not in render_lead_card(rt.roster.snapshot(), rt.catalog())+++# ------------------------------------------------------- check-ins, storage+++class FakeTasks:+ """The slice of the task store and scheduler a routine needs."""++ def __init__(self) -> None:+ self.specs: dict[str, Any] = {}+ self.cancelled: list[str] = []++ async def schedule(self, spec: Any, **_: Any) -> str:+ self.specs[str(spec.id)] = spec+ return str(spec.id)++ async def cancel_task(self, task_id: str) -> None:+ self.cancelled.append(task_id)++ async def delete(self, task_id: str) -> None:+ self.specs.pop(task_id, None)++ async def list(self, limit: int = 1000) -> list[dict[str, Any]]:+ return [+ {"id": task_id, "title": spec.title, "state": "scheduled",+ "spec_json": spec.model_dump_json()}+ for task_id, spec in self.specs.items()+ ]+++async def test_a_check_in_is_an_agent_routine_the_person_switches_on(team):+ rt, _ = team+ fake = FakeTasks()+ rt.task_services = lambda: (fake, fake)+ leads = rt.team_leads+ assert (await leads.snapshot("team"))["checkin_minutes"] == 0+ with pytest.raises(TeamLeadError):+ await leads.set_checkin("team", 7)++ assert await leads.set_checkin("team", 60) == 60+ (spec,) = fake.specs.values()+ assert "team-checkin:team" in spec.tags and "agent:boss" in spec.tags+ assert spec.trigger.interval_seconds == 3600+ assert "society_team_board" in spec.action.prompt+ assert (await leads.snapshot("team"))["checkin_minutes"] == 60++ await leads.set_checkin("team", 240)+ assert len(fake.specs) == 1 and len(fake.cancelled) == 1+ await leads.set_lead("team", None)+ assert fake.specs == {}+++async def test_an_older_database_gains_the_lead_columns(tmp_path: Path):+ path = tmp_path / "society.db"+ conn = await aiosqlite.connect(path)+ await conn.execute(+ "CREATE TABLE society_chat_groups (group_id TEXT PRIMARY KEY, name TEXT NOT NULL, "+ "members_json TEXT NOT NULL, created_ms INTEGER NOT NULL, updated_ms INTEGER NOT NULL)"+ )+ await conn.execute(+ "INSERT INTO society_chat_groups VALUES (?, ?, ?, 1, 1)", ("old", "Old team", '["a", "b"]')+ )+ await conn.commit()+ await conn.close()++ store = SocietyStore(path)+ await store.open()+ try:+ group = await store.get_chat_group("old")+ assert group["members"] == ["a", "b"]+ assert group["lead_agent_id"] is None and group["mission"] == ""+ assert (await store.set_chat_group_lead("old", "a"))["lead_agent_id"] == "a"+ created = await store.create_chat_group("new", "New", ["a", "b"])+ assert created["lead_agent_id"] is None+ finally:+ await store.close()+++async def test_deleting_a_team_stops_its_goals_and_frees_its_lead(team):+ rt, svc = team+ svc.gates[LEAD] = asyncio.Event()+ goal = await rt.team_leads.start_goal("team", "Do it")+ await until(lambda: LEAD in svc.busy)+ await rt.team_leads.group_deleted("team")+ await rt.store.delete_chat_group("team")+ await rt.team_leads.refresh()+ assert await rt.team_leads.get_goal(goal.goal_id) is None+ assert (await rt.roster.get("boss")).tier is Tier.SPECIALIST+ assert rt.team_leads.group_led_by("boss") is None+ assert (LEAD, svc.sent[0][3]) in svc.cancelleddiff --git a/tests/unit/ui/web/test_society_team_routes.py b/tests/unit/ui/web/test_society_team_routes.pynew file mode 100644index 0000000000..0d2ca6c216--- /dev/null+++ b/tests/unit/ui/web/test_society_team_routes.py@@ -0,0 +1,204 @@+"""/api/society/chat-groups/{id}/team…: a team's lead, mission, goals and tasks."""++from __future__ import annotations++import time+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agent_chat.store import AgentChatStore+from jarvis.society.runtime import SocietyRuntime+from jarvis.ui.web.society_routes import router+from tests.fakes.team_chat import TeamChatFake+++def client(tmp_path: Path):+ svc = TeamChatFake(AgentChatStore(tmp_path / "chat.db"))+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path)))+ runtime = SocietyRuntime(+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg+ )+ runtime.team_leads._review_delay = 0.0 # noqa: SLF001 — no debounce wait in tests+ app = FastAPI()+ app.include_router(router)+ app.state.society = None+ app.state.society_factory = lambda: runtime+ with TestClient(app) as c:+ try:+ yield c, runtime, svc+ finally:+ assert c.portal is not None+ c.portal.call(svc.close)+ c.portal.call(runtime.close)+ svc.store.close()+++def _team(c: TestClient) -> str:+ for name in ("Scout", "Writer"):+ created = c.post(+ "/api/society/agents", json={"name": name, "provider": "ollama", "model": "fake"}+ )+ assert created.status_code == 200, created.text+ group = c.post(+ "/api/society/chat-groups", json={"name": "Launch", "members": ["scout", "writer"]}+ ).json()["group"]+ assert group["lead_agent_id"] is None and group["mission"] == ""+ return str(group["group_id"])+++def _wait(c: TestClient, url: str, done: Any, *, seconds: float = 5.0) -> dict[str, Any]:+ deadline = time.monotonic() + seconds+ while True:+ body = c.get(url).json()+ if done(body):+ return body+ assert time.monotonic() < deadline, body+ time.sleep(0.02)+++def test_a_team_without_a_lead_reads_empty_and_refuses_goals(client):+ c, _, _ = client+ group_id = _team(c)+ url = f"/api/society/chat-groups/{group_id}"+ team = c.get(f"{url}/team").json()+ assert team["lead_agent_id"] is None and team["goals"] == []+ assert team["checkin_minutes"] == 0 and not team["working"]+ refused = c.post(f"{url}/goals", json={"text": "Launch it"})+ assert refused.status_code == 409 and "no lead" in refused.json()["detail"]+ assert c.get("/api/society/chat-groups/nope/team").status_code == 404+ missing = c.put("/api/society/chat-groups/nope/lead", json={"agent_id": "scout"})+ assert missing.status_code == 404+++def test_naming_and_creating_a_lead(client):+ c, _, _ = client+ group_id = _team(c)+ url = f"/api/society/chat-groups/{group_id}"++ named = c.put(f"{url}/lead", json={"agent_id": "scout"})+ assert named.status_code == 200, named.text+ assert named.json()["lead_agent_id"] == "scout" and named.json()["lead_available"]+ agents = {a["agent_id"]: a for a in c.get("/api/society/agents").json()["agents"]}+ assert agents["scout"]["tier"] == "orchestrator"+ assert c.get("/api/society/chat-groups").json()["groups"][0]["lead_agent_id"] == "scout"+ assert c.put(f"{url}/lead", json={"agent_id": "jarvis"}).status_code == 422+ assert c.put(f"{url}/lead", json={"agent_id": "ghost"}).status_code == 404++ cleared = c.put(f"{url}/lead", json={"agent_id": None})+ assert cleared.status_code == 200 and cleared.json()["lead_agent_id"] is None+ agents = {a["agent_id"]: a for a in c.get("/api/society/agents").json()["agents"]}+ assert agents["scout"]["tier"] == "specialist"++ created = c.post(f"{url}/lead", json={})+ assert created.status_code == 200, created.text+ body = created.json()+ assert body["agent"]["name"] == "Launch Lead" and body["agent"]["tier"] == "orchestrator"+ assert body["lead_agent_id"] == body["agent"]["agent_id"]+ members = c.get("/api/society/chat-groups").json()["groups"][0]["members"]+ assert body["agent"]["agent_id"] in members+++def test_mission_is_saved_and_shown(client):+ c, _, _ = client+ group_id = _team(c)+ url = f"/api/society/chat-groups/{group_id}"+ saved = c.put(f"{url}/mission", json={"mission": " Ship the launch. "})+ assert saved.status_code == 200 and saved.json()["mission"] == "Ship the launch."+ assert c.get("/api/society/chat-groups").json()["groups"][0]["mission"] == "Ship the launch."+ assert c.put(f"{url}/mission", json={"mission": "x" * 4001}).status_code == 422+++def test_a_goal_runs_from_the_board_to_its_report(client):+ c, rt, svc = client+ group_id = _team(c)+ url = f"/api/society/chat-groups/{group_id}"+ assert c.put(f"{url}/lead", json={"agent_id": "scout"}).status_code == 200+ svc.replies["society:writer"] = "Draft is in draft.md."++ async def lead(text: str, kwargs: dict[str, Any]) -> str:+ if text.startswith("[team goal for"):+ await rt.team_leads.assign("scout", member="Writer", title="Draft", brief="Write it.")+ return "Writer is on it."+ await rt.team_leads.report("scout", status="done", summary="The page is written.")+ return "Closed."++ svc.scripts["society:scout"] = lead+ started = c.post(f"{url}/goals", json={"text": "Write the launch page", "lang": "en"})+ assert started.status_code == 200, started.text+ goal_id = started.json()["goal_id"]++ team = _wait(c, f"{url}/team", lambda body: body["goals"][0]["state"] == "done")+ goal = team["goals"][0]+ assert goal["goal_id"] == goal_id and goal["report"] == "The page is written."+ assert goal["source"] == "board" and goal["title"] == "Write the launch page"+ assert [(t["agent_id"], t["state"]) for t in goal["tasks"]] == [("writer", "done")]+ assert goal["tasks"][0]["result"] == "Draft is in draft.md."++ # A finished goal takes no message, and another team's goal id is unknown here.+ assert c.post(f"{url}/goals/{goal_id}/message", json={"text": "More"}).status_code == 409+ assert c.post(f"{url}/goals/unknown/cancel").status_code == 404+ assert c.post(f"{url}/goals/{goal_id}/cancel").json()["goals"][0]["state"] == "done"+++def test_a_question_is_answered_and_a_goal_is_stopped_over_http(client):+ c, rt, svc = client+ group_id = _team(c)+ url = f"/api/society/chat-groups/{group_id}"+ c.put(f"{url}/lead", json={"agent_id": "scout"})+ turns: list[str] = []++ async def lead(text: str, kwargs: dict[str, Any]) -> str:+ turns.append(text)+ if len(turns) == 1:+ await rt.team_leads.report("scout", status="needs_input", summary="Which market?")+ return "One question."+ await rt.team_leads.report("scout", status="done", summary="Planned for Germany.")+ return "Closed."++ svc.scripts["society:scout"] = lead+ goal_id = c.post(f"{url}/goals", json={"text": "Plan the launch"}).json()["goal_id"]+ team = _wait(c, f"{url}/team", lambda body: body["goals"][0]["state"] == "needs_input")+ assert team["goals"][0]["report"] == "Which market?"+ assert c.post(f"{url}/goals/{goal_id}/message", json={"text": "Germany"}).status_code == 200+ _wait(c, f"{url}/team", lambda body: body["goals"][0]["state"] == "done")+ assert "Germany" in turns[1]++ svc.scripts.pop("society:scout")+ import asyncio++ gate = asyncio.Event()+ svc.gates["society:scout"] = gate+ second = c.post(f"{url}/goals", json={"text": "Second goal"}).json()["goal_id"]+ _wait(c, f"{url}/team", lambda body: body["working"])+ # A lead cannot be swapped out under a goal it is running.+ busy = c.put(f"{url}/lead", json={"agent_id": "writer"})+ assert busy.status_code == 409 and "current goal" in busy.json()["detail"]+ stopped = c.post(f"{url}/goals/{second}/cancel")+ assert stopped.status_code == 200+ states = {g["goal_id"]: g["state"] for g in stopped.json()["goals"]}+ assert states[second] == "cancelled"+ assert c.post(f"{url}/goals/{second}/resume").status_code == 409+++def test_editing_and_deleting_the_group_keeps_leadership_consistent(client):+ c, _, _ = client+ group_id = _team(c)+ c.post("/api/society/agents", json={"name": "Planner", "provider": "ollama", "model": "fake"})+ url = f"/api/society/chat-groups/{group_id}"+ c.put(f"{url}/lead", json={"agent_id": "scout"})+ edited = c.patch(url, json={"name": "Launch", "members": ["writer", "planner"]})+ assert edited.status_code == 200 and edited.json()["group"]["lead_agent_id"] is None+ agents = {a["agent_id"]: a for a in c.get("/api/society/agents").json()["agents"]}+ assert agents["scout"]["tier"] == "specialist"++ c.put(f"{url}/lead", json={"agent_id": "writer"})+ assert c.delete(url).status_code == 200+ agents = {a["agent_id"]: a for a in c.get("/api/society/agents").json()["agents"]}+ assert agents["writer"]["tier"] == "specialist"+ assert c.get(f"{url}/team").status_code == 404