Python
Add team progress and usage projections
Rohit C Prasad9e9d7e421e31
diff --git a/coworker/engine.py b/coworker/engine.pyindex 5727972a..fa2cd231 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -168,6 +168,7 @@ class TurnEngine:self.max_iterations = max_iterationsself.model_settings = dict(model_settings or {})self.messages: list[dict[str, Any]] = list(messages or [])+ self._tool_timings: dict[str, dict[str, float]] = {}self.audit_sink = audit_sink# Returns an ephemeral `<system-context>` block appended to the LAST user message at# send-time only (never persisted). We can't reliably inject system messages mid-thread@@ -329,6 +330,19 @@ class TurnEngine:finally:cancel_wait.cancel()+ async def _wait_tool(self, tool_call, coro, interrupted):+ started, clock = time.time(), time.monotonic()+ try:+ return await self._interruptible(coro, interrupted)+ finally:+ self._tool_timings.setdefault(tool_call.id, {}).update(waited_started=started, waited_ms=(time.monotonic() - clock) * 1000)++ def _timed_result(self, tool_call, result):+ message = _tool_result_message(tool_call, result)+ if tool_call.id in self._tool_timings:+ message["timing"] = self._tool_timings.pop(tool_call.id)+ return message+def queue_steering(self, text: str, source: Optional[dict[str, Any]] = None) -> None:@@ -585,6 +599,7 @@ class TurnEngine:reasoning="".join(streamed_reasoning) or None,)+ model_started, model_clock = time.time(), time.monotonic()try:async for chunk in self._astream():if chunk.reasoning_delta:@@ -653,6 +668,7 @@ class TurnEngine:effort_setting=self.model_settings.get("reasoning_effort"),))+ self.messages[-1]["timing"] = {"model_started": model_started, "model_ms": (time.monotonic() - model_clock) * 1000}payload: dict[str, Any] = {"text": turn.text,"tool_calls": [tc.name for tc in turn.tool_calls],@@ -1585,7 +1601,7 @@ class TurnEngine:reason=decision.reason,call_id=tool_call.id,)- outcome = await self._interruptible(+ outcome = await self._wait_tool(tool_call,self.approver(PermissionRequest(tool_name=tool_call.name,@@ -1659,6 +1675,8 @@ class TurnEngine:if spec is None:reason = f"unknown tool: {tool_call.name}"err_msg = _tool_error_message(tool_call, reason)+ if tool_call.id in self._tool_timings:+ err_msg["timing"] = self._tool_timings.pop(tool_call.id)origin = self._approval_origins.pop(tool_call.id, None)if origin:err_msg["_display"] = {@@ -1690,10 +1708,13 @@ class TurnEngine:def _execute_sync(self, tool_call: ToolCall) -> tuple[Any, str]:"""Execute one authorized call (runs in a worker thread)."""+ started, clock = time.time(), time.monotonic()try:return self.registry.execute(tool_call.name, tool_call.arguments), "ok"except Exception as exc:return {"error": str(exc), "error_type": type(exc).__name__}, "error"+ finally:+ self._tool_timings.setdefault(tool_call.id, {}).update(tool_started=started, tool_ms=(time.monotonic() - clock) * 1000)def _record_result(self, tool_call: ToolCall, result: Any, status: str) -> Event:self._step += 1@@ -1731,7 +1752,7 @@ class TurnEngine:step=self._step,tool_name=tool_call.name,)- message = _tool_result_message(tool_call, result)+ message = self._timed_result(tool_call, result)if display:message["_display"] = displayself.messages.append(message)@@ -1865,13 +1886,13 @@ class TurnEngine:{"items": valid, "note": str(args.get("note", ""))},)self._audit(tool_call, stage="items_proposed")- result = await self._interruptible(+ result = await self._wait_tool(tool_call,self.items_approver(dict(args), tool_call.id),interrupted={"approved": False, "error": "interrupted by user"},) or {"approved": False, "error": "no response"}status = "ok" if result.get("approved") else "denied"- self.messages.append(_tool_result_message(tool_call, result))+ self.messages.append(self._timed_result(tool_call, result))self._audit(tool_call,stage="finished",@@ -1912,7 +1933,7 @@ class TurnEngine:{"request": request, "connector": connector, "worker": worker, "reason": reason},)self._audit(tool_call, stage="connector_requested", reason=reason)- result = await self._interruptible(+ result = await self._wait_tool(tool_call,self.connector_requester(dict(args), tool_call.id),interrupted={"approved": False, "error": "interrupted by user"},) or {"approved": False, "error": "no response"}@@ -1922,7 +1943,7 @@ class TurnEngine:"The user declined. Carry on without it and say plainly what you could not do.",)status = "ok" if result.get("approved") else "denied"- self.messages.append(_tool_result_message(tool_call, result))+ self.messages.append(self._timed_result(tool_call, result))self._audit(tool_call, stage="finished", status=status, result=result, result_preview=_preview(result))yield Event(EventType.TOOL_FINISHED,@@ -1956,13 +1977,18 @@ class TurnEngine:},)self._audit(tool_call, stage="team_proposed")- result = await self._interruptible(+ result = await self._wait_tool(tool_call,self.team_approver(dict(args), tool_call.id),interrupted={"approved": False, "error": "interrupted by user"},) or {"approved": False, "error": "no response"}status = "ok" if result.get("approved") else "denied"- self.messages.append(_tool_result_message(tool_call, result))+ message = self._timed_result(tool_call, result)+ created = None+ if result.get("approved") and result.get("team_id"):+ created = {"team_id": result["team_id"], "workers": result.get("workers") or []}+ message["_display"] = {"team_created": created}+ self.messages.append(message)self._audit(tool_call,stage="finished",@@ -1976,6 +2002,7 @@ class TurnEngine:"name": tool_call.name,"status": status,"result_preview": _preview(result),+ "display": {"team_created": created} if created else {},},)@@ -2007,7 +2034,7 @@ class TurnEngine:else:yield Event(EventType.PLAN_PROPOSED, {"plan": plan})self._audit(tool_call, stage="plan_proposed")- result = await self._interruptible(+ result = await self._wait_tool(tool_call,self.plan_approver(dict(args), tool_call.id),interrupted={"approved": False, "error": "interrupted by user"},) or {@@ -2029,7 +2056,7 @@ class TurnEngine:}status = "ok" if result.get("approved") else "denied"- self.messages.append(_tool_result_message(tool_call, result))+ self.messages.append(self._timed_result(tool_call, result))self._audit(tool_call,stage="finished",@@ -2100,7 +2127,7 @@ class TurnEngine:},)self._audit(tool_call, stage="tool_requested", reason=reason)- result = await self._interruptible(+ result = await self._wait_tool(tool_call,self.tool_requester(dict(args), tool_call.id),interrupted={"installed": False, "error": "interrupted by user"},) or {"installed": False, "error": "no response"}@@ -2126,7 +2153,7 @@ class TurnEngine:)status = "ok" if result.get("installed") else "denied"- self.messages.append(_tool_result_message(tool_call, result))+ self.messages.append(self._timed_result(tool_call, result))self._audit(tool_call,stage="finished",@@ -2172,7 +2199,7 @@ class TurnEngine:stage="directory_requested",reason=str(args.get("reason", "")),)- result = await self._interruptible(+ result = await self._wait_tool(tool_call,self.directory_requester(dict(args), tool_call.id),interrupted={"granted": False, "error": "interrupted by user"},) or {@@ -2181,7 +2208,7 @@ class TurnEngine:}status = "ok" if result.get("granted") else "denied"- self.messages.append(_tool_result_message(tool_call, result))+ self.messages.append(self._timed_result(tool_call, result))self._audit(tool_call,stage="finished",@@ -2223,7 +2250,7 @@ class TurnEngine:# The asker is mode-aware (attended → live inline prompt; unattended → Inbox), so it# owns surfacing the question. The engine just awaits the answer.self._audit(tool_call, stage="question_requested", reason=question)- result = await self._interruptible(+ result = await self._wait_tool(tool_call,self.question_asker(dict(args), tool_call.id),interrupted={"answer": "", "error": "interrupted by user"},) or {@@ -2234,7 +2261,7 @@ class TurnEngine:status = "ok" if (result.get("answer") or result.get("answers")) else "denied"if status == "ok":self._note_ask_replies(result, question)- self.messages.append(_tool_result_message(tool_call, result))+ self.messages.append(self._timed_result(tool_call, result))self._audit(tool_call,stage="finished",@@ -2307,6 +2334,7 @@ class TurnEngine:# display-only too: dropped entirely._SIDECARS = ("source",+ "timing","_display","ts","reasoning",diff --git a/coworker/personas/builtin/appsec-worker/manifest.md b/coworker/personas/builtin/appsec-worker/manifest.mdindex 5e740444..befc462b 100644--- a/coworker/personas/builtin/appsec-worker/manifest.md+++ b/coworker/personas/builtin/appsec-worker/manifest.md@@ -52,3 +52,5 @@ Security standards (these outrank speed):- Secrets are radioactive: never print a discovered secret's value anywhere —location and kind only.- NEVER inline multi-line scripts in shell commands: write a file, then run it.++At a meaningful step change, use set_status(item, text) to show one short progress line (at most 80 characters) on your assigned item. Include the explicit item id; this is display-only, never a substitute for blockers, evidence or the review hand-off. Do not post heartbeats.diff --git a/coworker/personas/builtin/change-worker/manifest.md b/coworker/personas/builtin/change-worker/manifest.mdindex 8f2abbab..eccc7f09 100644--- a/coworker/personas/builtin/change-worker/manifest.md+++ b/coworker/personas/builtin/change-worker/manifest.md@@ -44,3 +44,5 @@ How you work:value, escalate to the lead immediately.- You report to the LEAD via the board (post updates on your item; move it to reviewwith your evidence summary). Never use ask_user — the lead owns the user.++At a meaningful step change, use set_status(item, text) to show one short progress line (at most 80 characters) on your assigned item. Include the explicit item id; this is display-only, never a substitute for blockers, evidence or the review hand-off. Do not post heartbeats.diff --git a/coworker/personas/builtin/design-worker/manifest.md b/coworker/personas/builtin/design-worker/manifest.mdindex 25f9f894..ded3a1ff 100644--- a/coworker/personas/builtin/design-worker/manifest.md+++ b/coworker/personas/builtin/design-worker/manifest.md@@ -32,3 +32,5 @@ Design standards: work WITH the app's existing design system — its tokens, spatypography and component idioms; never introduce a parallel style. State assumptions(theme, viewport, empty states) in the hand-off. Keep interaction states (hover,focus, disabled, loading) and both color themes covered; note anything deferred.++At a meaningful step change, use set_status(item, text) to show one short progress line (at most 80 characters) on your assigned item. Include the explicit item id; this is display-only, never a substitute for blockers, evidence or the review hand-off. Do not post heartbeats.diff --git a/coworker/personas/builtin/devops-lead/manifest.md b/coworker/personas/builtin/devops-lead/manifest.mdindex 438f9699..4a89e941 100644--- a/coworker/personas/builtin/devops-lead/manifest.md+++ b/coworker/personas/builtin/devops-lead/manifest.md@@ -78,3 +78,5 @@ RULES OF THE WATCH:- Instructions flow down, evidence flows up; steer workers only for exceptions. Theuser outranks you everywhere.- Report plainly when you do speak: what happened, what you know, what you need.++When mentioning a board task in your reply, write `[title](task:<id>)`; copy the `mention` returned by board tools. Do not use GitHub-style #numbers for task links.diff --git a/coworker/personas/builtin/devsecops-lead/manifest.md b/coworker/personas/builtin/devsecops-lead/manifest.mdindex 8fdd020a..72318f21 100644--- a/coworker/personas/builtin/devsecops-lead/manifest.md+++ b/coworker/personas/builtin/devsecops-lead/manifest.md@@ -93,3 +93,5 @@ Communication doctrine:minutes; when a wake finds nothing changed, double the interval (cap ~20 minutes);tighten back when things get hot.- Report to the user plainly: what was found, what's fixed, what needs their decision.++When mentioning a board task in your reply, write `[title](task:<id>)`; copy the `mention` returned by board tools. Do not use GitHub-style #numbers for task links.diff --git a/coworker/personas/builtin/infra-worker/manifest.md b/coworker/personas/builtin/infra-worker/manifest.mdindex 38890415..9b3cabfe 100644--- a/coworker/personas/builtin/infra-worker/manifest.md+++ b/coworker/personas/builtin/infra-worker/manifest.md@@ -43,3 +43,5 @@ How you work:location only, never the value, escalate to the lead immediately.- You report to the LEAD via the board (post updates on your item; move it to reviewwith your evidence summary). Never use ask_user — the lead owns the user.++At a meaningful step change, use set_status(item, text) to show one short progress line (at most 80 characters) on your assigned item. Include the explicit item id; this is display-only, never a substitute for blockers, evidence or the review hand-off. Do not post heartbeats.diff --git a/coworker/personas/builtin/logs-worker/manifest.md b/coworker/personas/builtin/logs-worker/manifest.mdindex bd2d2577..49b8b1e7 100644--- a/coworker/personas/builtin/logs-worker/manifest.md+++ b/coworker/personas/builtin/logs-worker/manifest.md@@ -41,3 +41,5 @@ How you work:- You report to the LEAD via the board (post updates on your item; move it to reviewwith your evidence summary). Never use ask_user — user-facing questions are thelead's job. Read-only everywhere: you diagnose, you do not restart, patch, or tune.++At a meaningful step change, use set_status(item, text) to show one short progress line (at most 80 characters) on your assigned item. Include the explicit item id; this is display-only, never a substitute for blockers, evidence or the review hand-off. Do not post heartbeats.diff --git a/coworker/personas/builtin/posture-worker/manifest.md b/coworker/personas/builtin/posture-worker/manifest.mdindex ccec0149..961a328a 100644--- a/coworker/personas/builtin/posture-worker/manifest.md+++ b/coworker/personas/builtin/posture-worker/manifest.md@@ -52,3 +52,5 @@ Craft standards (these outrank speed):hand-off includes a Coverage note.- Never print cloud credentials or full account identifiers in output.- NEVER inline multi-line scripts in shell commands: write a file, then run it.++At a meaningful step change, use set_status(item, text) to show one short progress line (at most 80 characters) on your assigned item. Include the explicit item id; this is display-only, never a substitute for blockers, evidence or the review hand-off. Do not post heartbeats.diff --git a/coworker/personas/builtin/secrets-worker/manifest.md b/coworker/personas/builtin/secrets-worker/manifest.mdindex 059098d7..e4aec261 100644--- a/coworker/personas/builtin/secrets-worker/manifest.md+++ b/coworker/personas/builtin/secrets-worker/manifest.md@@ -53,3 +53,5 @@ Craft standards (these outrank speed):or report the check as NOT RUN with the reason. Your hand-off includes a Coveragenote.- NEVER inline multi-line scripts in shell commands: write a file, then run it.++At a meaningful step change, use set_status(item, text) to show one short progress line (at most 80 characters) on your assigned item. Include the explicit item id; this is display-only, never a substitute for blockers, evidence or the review hand-off. Do not post heartbeats.diff --git a/coworker/personas/builtin/swe-lead/manifest.md b/coworker/personas/builtin/swe-lead/manifest.mdindex 67ee1832..60f86af3 100644--- a/coworker/personas/builtin/swe-lead/manifest.md+++ b/coworker/personas/builtin/swe-lead/manifest.md@@ -84,3 +84,5 @@ Communication doctrine:a nothing's-wrong wake costs one glance. (The harness has a backstop if youforget, but relying on it means slower reactions — own your cadence.)- Report to the user plainly: what moved, what's blocked, what needs their decision.++When mentioning a board task in your reply, write `[title](task:<id>)`; copy the `mention` returned by board tools. Do not use GitHub-style #numbers for task links.diff --git a/coworker/personas/builtin/swe-worker/manifest.md b/coworker/personas/builtin/swe-worker/manifest.mdindex 06574571..1931aec9 100644--- a/coworker/personas/builtin/swe-worker/manifest.md+++ b/coworker/personas/builtin/swe-worker/manifest.md@@ -47,3 +47,5 @@ The team contract (this is how you work):Engineering standards: match the codebase's own patterns; keep diffs focused on theitem; add or update tests for what you changed; run the relevant test suite beforehanding off and report the real result.++At a meaningful step change, use set_status(item, text) to show one short progress line (at most 80 characters) on your assigned item. Include the explicit item id; this is display-only, never a substitute for blockers, evidence or the review hand-off. Do not post heartbeats.diff --git a/coworker/personas/builtin/test-worker/manifest.md b/coworker/personas/builtin/test-worker/manifest.mdindex 109a7660..7b0dead0 100644--- a/coworker/personas/builtin/test-worker/manifest.md+++ b/coworker/personas/builtin/test-worker/manifest.md@@ -48,3 +48,5 @@ How you verify:The team contract also binds you: in_progress when you start, blocked with a commentif you can't verify (missing creds, un-runnable app), never mark items done yourself.++At a meaningful step change, use set_status(item, text) to show one short progress line (at most 80 characters) on your assigned item. Include the explicit item id; this is display-only, never a substitute for blockers, evidence or the review hand-off. Do not post heartbeats.diff --git a/coworker/personas/builtin/triage-lead/manifest.md b/coworker/personas/builtin/triage-lead/manifest.mdindex 4887c800..23973126 100644--- a/coworker/personas/builtin/triage-lead/manifest.md+++ b/coworker/personas/builtin/triage-lead/manifest.md@@ -76,3 +76,5 @@ RULES OF THE WATCH:- Staff workers only when a filed item genuinely needs hands (a real investigation, adocument to produce) — this is rare in triage; when in doubt, do not staff.- Instructions flow down, evidence flows up; the user outranks you everywhere.++When mentioning a board task in your reply, write `[title](task:<id>)`; copy the `mention` returned by board tools. Do not use GitHub-style #numbers for task links.diff --git a/coworker/server/app.py b/coworker/server/app.pyindex e0a89c0a..1859a83d 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -839,6 +839,11 @@ def create_app(manager: SessionManager) -> FastAPI:comment=str(body.get("comment", "")),)+ @app.get("/v1/teams/{team_id}/summary")+ def team_summary(team_id: str):+ result = manager.team_summary(team_id)+ return JSONResponse(result, status_code=404 if "error" in result else 200)+@app.get("/v1/teams/{team_id}/chat")def team_chat(team_id: str) -> dict[str, Any]:return manager.team_chat(team_id)diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex 09045eb6..76896541 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -2390,6 +2390,15 @@ class SessionManager:self.kick_team_tick() # the assignee's feed has newsreturn {"ok": True, "seq": event["seq"]}+ def team_summary(self, team_id: str) -> dict[str, Any]:+ from ..teams.summary import make_summary+ team = self.teams.get(team_id)+ if team is None:+ return {"error": "team not found"}+ if self._board_space(team.lead_session) != team.space:+ return {"error": "the lead's board binding has changed"}+ return make_summary(self, team, time.time())+def session_board(self, session_id: str) -> dict[str, Any]:"""The session's board: items grouped by the workspace-keyed space. Empty(space=None) when the workspace has no items — the rail hides itself."""@@ -2413,6 +2422,11 @@ class SessionManager:if payload.get("comment"):item["blocker"] = self._clamp(payload["comment"], 120)break+ from ..teams.summary import all_events, waiting_items+ waits = waiting_items(all_events(self.team_store, space), self.inbox, items)+ for item in items:+ if item["id"] in waits:+ item["waiting"] = waits[item["id"]]return {"space": space, "name": Path(space).name, "items": items}def board_transition(@@ -3070,7 +3084,7 @@ class SessionManager:)lines: list[str] = []rows: list[dict] = []- for event in directs + subs:+ for event in sorted(directs + subs, key=lambda e: e["seq"]):item_id = event.get("item_id")payload = event.get("payload") or {}item = None@@ -3135,6 +3149,8 @@ class SessionManager:{**row,"kind": "moved",+ "from": payload.get("from"),+ "refs": payload.get("refs") or [],"to": to,"note": self._clamp(payload.get("comment") or "", self.DIGEST_CLAMP_UI@@ -5102,7 +5118,20 @@ class SessionManager:if item is None or item.kind != "approval":return Nonedata = item.data or {}+ task_fields = {}+ found = self.teams.for_worker_session(item.session_id)+ if found:+ from ..teams.summary import all_events+ team, _worker = found+ for event in all_events(self.team_store, team.space):+ if event["kind"] == WORKER_WAITING and event["payload"].get("prompt_id") == item.id and event.get("item_id") is not None:+ try:+ task = self.team_store.get_item(team.space, event["item_id"], actor=self._user_actor())+ task_fields = {"item_id": task["id"], "item_title": task["title"]}+ except TeamsBoardError:+ passreturn {+ **task_fields,"worker": str((arguments or {}).get("worker") or ""),"tool": str(data.get("tool") or ""),"arguments": data.get("arguments") or {},diff --git a/coworker/teams/store.py b/coworker/teams/store.pyindex 8f5159cc..f4c69722 100644--- a/coworker/teams/store.py+++ b/coworker/teams/store.py@@ -62,6 +62,7 @@ ITEM_TRANSITIONED = "item_transitioned"ITEM_COMMENTED = "item_commented"ITEM_ASSIGNED = "item_assigned"ITEM_LINKED = "item_linked"+ITEM_STATUS = "item_status"# §11.6: a manual-mode worker parked on a tool approval — the lead cannot approve it# (it holds nothing the human did not grant) but should wait knowingly or reassign.WORKER_WAITING = "worker_waiting"@@ -166,6 +167,11 @@ class TeamStore:name TEXT PRIMARY KEY);""")+ columns = {row[1] for row in self._conn.execute("PRAGMA table_info(team_items)")}+ for column in ("status", "status_ts"):+ if column not in columns:+ self._conn.execute(f"ALTER TABLE team_items ADD COLUMN {column} TEXT NOT NULL DEFAULT ''")+ self._conn.commit()migrated = self._conn.execute("SELECT 1 FROM team_migrations WHERE name = ?",(ATTACHMENT_REFS_MIGRATION,),@@ -288,9 +294,13 @@ class TeamStore:case_id: Optional[str] = None,since_seq: int = 0,limit: int = 500,+ exclude_kinds: Optional[list[str]] = None,) -> list[dict[str, Any]]:where = ["space = ?", "seq > ?"]params: list[Any] = [space, since_seq]+ if exclude_kinds:+ where.append(f"kind NOT IN ({','.join('?' * len(exclude_kinds))})")+ params.extend(exclude_kinds)if kinds:where.append(f"kind IN ({','.join('?' * len(kinds))})")params.extend(kinds)@@ -340,7 +350,7 @@ class TeamStore:assigned to it) or END it (just reassigned away — it hears that, thengoes quiet). Its own events never appear."""key = f"feed:{actor_id}:{space}"- events = self.events(space, since_seq=self._cursor(key), limit=limit)+ events = self.events(space, since_seq=self._cursor(key), limit=limit, exclude_kinds=[ITEM_STATUS])with self._lock:slice_ids = self._worker_slice(space, actor_id)out = []@@ -763,6 +773,24 @@ class TeamStore:taint=taint,)+ def set_status(self, space: str, actor: Actor, item_id: int, text: str) -> dict[str, Any]:+ """Display-only progress. Never an assignment, transition or wake signal."""+ self._require(actor, {Role.WORKER}, "set_status")+ if not isinstance(item_id, int) or isinstance(item_id, bool) or item_id < 1:+ raise BoardError("item must be an explicit positive integer")+ if not isinstance(text, str) or len(text) > 80 or len(text.splitlines()) > 1 or "\n" in text or "\r" in text:+ raise BoardError("status must be one line of at most 80 characters")+ with self._lock:+ item = self.get_item(space, item_id, actor=actor)+ if item["assignee"] != actor.id:+ raise AuthorityError("set_status requires an item currently assigned to you")+ if item["state"] in ("done", "canceled"):+ raise BoardError("cannot update status on a finished item")+ if item["status"] == text.strip():+ return item+ self.append_event(space, ITEM_STATUS, actor, item_id=item_id, payload={"text": text.strip()})+ return self.get_item(space, item_id, actor=actor)+def assign(self, space: str, actor: Actor, item_id: int, assignee: str) -> dict[str, Any]:@@ -956,7 +984,7 @@ class TeamStore:)elif kind == ITEM_TRANSITIONED:self._conn.execute(- "UPDATE team_items SET state = ?, updated_seq = ?"+ "UPDATE team_items SET state = ?, updated_seq = ?, status = '', status_ts = ''"" WHERE space = ? AND id = ?",(payload.get("to"), seq, space, item_id),)@@ -968,10 +996,15 @@ class TeamStore:)elif kind == ITEM_ASSIGNED:self._conn.execute(- "UPDATE team_items SET assignee = ?, updated_seq = ?"+ "UPDATE team_items SET assignee = ?, updated_seq = ?, status = '', status_ts = ''"" WHERE space = ? AND id = ?",(payload.get("assignee") or "", seq, space, item_id),)+ elif kind == ITEM_STATUS:+ self._conn.execute(+ "UPDATE team_items SET status = ?, status_ts = ? WHERE space = ? AND id = ?",+ (payload.get("text") or "", ts, space, item_id),+ )elif kind == ITEM_LINKED:self._conn.execute("INSERT OR IGNORE INTO team_links (space, src, kind, dst)"diff --git a/coworker/teams/summary.py b/coworker/teams/summary.pynew file mode 100644index 00000000..908f4e3d--- /dev/null+++ b/coworker/teams/summary.py@@ -0,0 +1,232 @@+"""Read-only Team View projections. Never a wake source or an agent transcript tool."""+from __future__ import annotations++import json+import math+from datetime import datetime+from statistics import median++from .store import ITEM_STATUS, WORKER_WAITING++KINDS = ("input", "cache_read", "output", "cache_write")+++def stamp(value) -> float:+ try:+ number = float(value) if isinstance(value, (float, int)) else datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp()+ return number if math.isfinite(number) else 0.0+ except (ValueError, TypeError, OverflowError):+ return 0.0+++def tokens(usage) -> dict:+ result = {}+ for key in KINDS:+ try:+ result[key] = max(0, int((usage or {}).get(key) or 0))+ except (ValueError, TypeError, OverflowError):+ result[key] = 0+ return result+++def add_tokens(rows) -> dict:+ return {key: sum(row.get(key, 0) for row in rows) for key in KINDS}+++def all_events(store, space):+ """Read every page, not just the first 500 events of a long-running team."""+ cursor = 0+ while True:+ page = store.events(space, since_seq=cursor, limit=2000)+ if not page:+ return+ yield from page+ cursor = page[-1]["seq"]+++def waiting_items(events, inbox, items):+ current = {i["id"]: i for i in items}+ result = {}+ for event in events:+ if event["kind"] != WORKER_WAITING:+ continue+ p = event.get("payload") or {}+ item = current.get(event.get("item_id"))+ prompt = inbox.get(p.get("prompt_id", ""))+ if (item and prompt and prompt.state == "pending"+ and item["state"] not in ("done", "canceled")+ and item["assignee"] == event["actor"]+ and prompt.session_id == p.get("session_id")):+ result[item["id"]] = {"prompt_id": prompt.id, "tool": p.get("tool", ""),+ "preview": p.get("preview", ""), "session_id": prompt.session_id}+ return result+++def breakdown(intervals, start, end):+ """Partition wall time; overlapping parallel calls count once, not N times."""+ clipped = [(max(start, a), min(end, b), kind) for a, b, kind in intervals if b > start and a < end and b > a]+ edges = sorted({start, end, *(a for a, _, _ in clipped), *(b for _, b, _ in clipped)})+ out = dict(model_ms=0, tool_ms=0, waited_ms=0, queued_ms=0)+ for a, b in zip(edges, edges[1:]):+ active = {kind for x, y, kind in clipped if x < b and y > a}+ kind = next((k for k in ("waited_ms", "tool_ms", "model_ms") if k in active), "queued_ms")+ out[kind] += max(0, (b - a) * 1000)+ return {k: round(v) for k, v in out.items()}+++def active_windows(events, end):+ """Assignment to review/done, including rework; no inference from prose."""+ windows, start, actor = [], None, ""+ for event in events:+ ts = stamp(event["ts"])+ p = event.get("payload") or {}+ if event["kind"] == "item_assigned":+ if start is not None:+ windows.append((start, ts, actor))+ actor, start = p.get("assignee", ""), ts+ elif event["kind"] == "item_transitioned":+ if p.get("to") in ("review", "done", "canceled") and start is not None:+ windows.append((start, ts, actor))+ start = None+ elif p.get("to") == "in_progress" and start is None and actor:+ start = ts+ if start is not None:+ windows.append((start, end, actor))+ return windows+++def make_summary(manager, team, now):+ board = manager.session_board(team.lead_session)+ events = list(all_events(manager.team_store, team.space))+ actors = {team.lead_actor, *(w.actor for w in team.workers)}+ # A project board can be shared. A team view includes its filings/assignments,+ # not another lead's unrelated backlog (the board itself remains unchanged).+ items = [i for i in board["items"] if i["creator"] in actors or i["assignee"] in actors]+ by_item = {i["id"]: [] for i in items}+ for e in events:+ if e.get("item_id") in by_item:+ by_item[e["item_id"]].append(e)+ waits = waiting_items(events, manager.inbox, items)+ session_ids = {team.lead_session, *(w.session_id for w in team.workers)}+ prompts = [p for p in manager.inbox.list() if p.session_id in session_ids and p.kind != "notification"]+ # The lead decision and the original worker approval are one human interruption.+ forwarded = {(p.data.get("arguments") or {}).get("call_id") for p in prompts+ if p.data.get("tool") == "decide_worker_call"}+ asks = []+ for p in prompts:+ if p.id in forwarded:+ continue+ kind = ("staffing" if p.data.get("members") else "reviews" if p.kind == "plan"+ else "questions" if p.kind == "question" else "grants" if p.kind in ("connector", "directory", "tool")+ else "approvals")+ asks.append({"id": p.id, "kind": kind, "state": p.state,+ "waited_s": max(0, (stamp(p.resolved_at) if p.resolved_at else now) - stamp(p.created_at))})+ ask_groups = {k: {"answered": sum(a["kind"] == k and a["state"] == "resolved" for a in asks),+ "waiting": sum(a["kind"] == k and a["state"] == "pending" for a in asks)}+ for k in ("approvals", "questions", "reviews", "staffing", "grants")}+ answered = [a["waited_s"] for a in asks if a["state"] == "resolved"]+ members = [(team.lead_actor, "lead", team.lead_session)] + [(w.actor, w.persona, w.session_id) for w in team.workers]+ workers, usage_points, records = [], [], {}+ for actor, role, sid in members:+ record = manager.session_store.load(sid)+ engine = manager._engines.get(sid)+ messages = list(engine.messages) if engine is not None else (record.messages if record else [])+ records[actor] = messages+ usage = [tokens(m["usage"]) for m in messages if m.get("role") == "assistant" and isinstance(m.get("usage"), dict)]+ # A persisted session's usage may be available before its full transcript.+ total = add_tokens(usage or [tokens(u) for u in (record.usage if record else {}).values()])+ step = None+ for m in messages:+ if m.get("role") == "assistant" and isinstance(m.get("usage"), dict):+ ts = stamp((m.get("timing") or {}).get("model_started") or m.get("ts"))+ if ts:+ usage_points.append({"ts": ts, "role": role, "tokens": sum(tokens(m["usage"]).values())})+ for call in m.get("tool_calls") or []:+ if (call.get("function") or {}).get("name") == "todo_write":+ try:+ a = json.loads(call["function"].get("arguments") or "{}")+ todos = a.get("todos", a.get("items", []))+ if isinstance(todos, list) and todos:+ step = {"done": sum(x.get("status") == "done" for x in todos if isinstance(x, dict)), "total": len(todos)}+ except (TypeError, ValueError):+ pass+ workers.append({"actor": actor, "role": role, "session_id": sid, "model": record.model if record else "",+ "workspace": record.workspace if record else "", "running": manager.is_running(sid),+ "tokens": total, "step": step, "items": [i["id"] for i in items if i["assignee"] == actor]})+ windows = {i["id"]: active_windows(by_item[i["id"]], now) for i in items}+ worker_by_actor = {w["actor"]: w for w in workers}+ all_item_times = []+ for item in items:+ story = by_item[item["id"]]+ activity = [e for e in story if e["kind"] != ITEM_STATUS]+ item["updated"] = stamp(activity[-1]["ts"]) if activity else stamp(item["created_ts"])+ item["last_event"] = activity[-1]["kind"] if activity else "item_created"+ item["waiting"] = waits.get(item["id"])+ blockers = [l for l in item.get("links", []) if l["kind"] == "blocked_by"]+ item["group"] = ("waiting" if item["waiting"] or (item["state"] == "blocked" and not blockers)+ else "review" if item["state"] == "review" else "working" if item["state"] == "in_progress"+ else "done" if item["state"] == "done" else "canceled" if item["state"] == "canceled" else "queued")+ worker = worker_by_actor.get(item["assignee"])+ item["worker_session"] = worker["session_id"] if worker else None+ active_assigned = [i for i in items if i["assignee"] == item["assignee"] and i["state"] not in ("review", "done", "canceled")]+ item["step"] = worker["step"] if worker and len(active_assigned) == 1 and item in active_assigned else None+ item["pr"] = next((ref for ref in item["refs"] if ref.startswith(("https://", "http://")) and "/pull/" in ref), None)+ started = stamp(item["created_ts"])+ closed = next((stamp(e["ts"]) for e in reversed(story) if e["kind"] == "item_transitioned"+ and e["payload"].get("to") in ("done", "canceled")), now)+ item["elapsed_s"] = max(0, closed - started)+ intervals, attributed_usage = [], []+ ambiguous = False+ for a, b, actor in windows[item["id"]]:+ for m in records.get(actor, []):+ ts = stamp((m.get("timing") or {}).get("model_started") or m.get("ts"))+ # Multiple assignments: don't attribute a single call to two tasks.+ overlaps = [(x, y) for other, ws in windows.items() if other != item["id"]+ for x, y, who in ws if who == actor and x < b and y > a]+ if any(x <= ts < y for x, y in overlaps):+ ambiguous = True+ continue+ if a <= ts < b and m.get("role") == "assistant" and m.get("usage"):+ attributed_usage.append(tokens(m["usage"]))+ timing = m.get("timing") or {}+ for kind in ("model_ms", "tool_ms", "waited_ms"):+ start = stamp(timing.get(kind.replace("_ms", "_started")))+ duration = timing.get(kind)+ if start and isinstance(duration, (float, int)) and duration >= 0:+ stop = start + duration / 1000+ if stop <= a or start >= b:+ continue+ cuts = sorted({max(a, start), min(b, stop), *(max(a, start, x) for x, y in overlaps if x < min(b, stop) and y > max(a, start)), *(min(b, stop, y) for x, y in overlaps if x < min(b, stop) and y > max(a, start))})+ for x, y in zip(cuts, cuts[1:]):+ if x < y and not any(ox < y and oy > x for ox, oy in overlaps):+ intervals.append((x, y, kind))+ for event in story:+ if event["kind"] == WORKER_WAITING:+ p = manager.inbox.get(event["payload"].get("prompt_id", ""))+ if p:+ intervals.append((stamp(p.created_at), stamp(p.resolved_at) if p.resolved_at else now, "waited_ms"))+ item["tokens"] = add_tokens(attributed_usage)+ item["usage_partial"] = ambiguous or any(m.get("role") == "assistant" and not m.get("usage")+ for _, _, actor in windows[item["id"]] for m in records.get(actor, []))+ item["timing_partial"] = ambiguous or any(m.get("role") == "assistant" and not m.get("timing")+ for _, _, actor in windows[item["id"]] for m in records.get(actor, []))+ item["timing"] = breakdown(intervals, started, closed) if intervals else None+ if item["timing"]:+ all_item_times.append(item["timing"])+ lead = workers[0]+ workers = workers[1:]+ by_kind = add_tokens([lead["tokens"], *(w["tokens"] for w in workers)])+ counts = {g: sum(i["group"] == g for i in items) for g in ("waiting", "review", "working", "queued", "done")}+ active = [i for i in items if i["group"] != "canceled"]+ end = max((stamp(e["ts"]) for e in events if e.get("item_id") in by_item and e["kind"] != ITEM_STATUS), default=now) if active and all(i["group"] == "done" for i in active) else now+ elapsed = max(0, end - stamp(team.created_at))+ timing = {k: sum(v[k] for v in all_item_times) for k in ("model_ms", "tool_ms", "waited_ms", "queued_ms")}+ return {"team_id": team.team_id, "space": team.space, "lead_session": team.lead_session,+ "items": items, "workers": workers, "lead": lead, "counts": counts,+ "totals": {"done": counts["done"], "total": len(active), "elapsed_s": elapsed,+ "tokens": sum(by_kind.values()), "tokens_by_kind": by_kind,+ "asks_answered": len(answered), "asks_waiting": sum(a["state"] == "pending" for a in asks)},+ "timing": timing if all_item_times else None, "timing_partial": any(i["timing_partial"] for i in items),+ "usage_partial": any(m.get("role") == "assistant" and not m.get("usage") for messages in records.values() for m in messages),+ "asks": ask_groups, "median_answer_s": median(answered) if answered else None,+ "usage_points": sorted(usage_points, key=lambda p: p["ts"]), "generated_at": now}diff --git a/coworker/teams/tools.py b/coworker/teams/tools.pyindex 5e29e011..23416bfb 100644--- a/coworker/teams/tools.py+++ b/coworker/teams/tools.py@@ -25,9 +25,19 @@ LEAD_VERBS = ("create_item", "list_items", "transition", "comment", "assign", "l# self-assignment: on an open-claims board (the default) a worker may pick up an# open, unassigned item — the store arbitrates races, the lead supervises by# exception (every claim lands in its feed; reassign/cancel revokes).-WORKER_VERBS = ("create_item", "list_items", "transition", "comment", "claim")+WORKER_VERBS = ("create_item", "list_items", "transition", "comment", "claim", "set_status")JOURNAL_VERBS = ("journal_append", "journal_read")++def with_mention(item: dict) -> dict:+ """A copyable Markdown mention; user-controlled titles cannot break out of the label."""+ if "id" not in item:+ return item+ title = " ".join(str(item.get("title") or "").split())+ for char in ("\\", "[", "]", "*", "_", "`", "<", ">"):+ title = title.replace(char, "\\" + char)+ return {**item, "mention": f"[{title}](task:{item['id']})"}+# Explicit schema: the auto-generator's normalizer strips every `title` key to drop# pydantic metadata, which also deletes a PARAMETER named `title` from properties.# Registered via `__coworker_schema__` (same escape hatch as todo_write).@@ -84,7 +94,7 @@ def board_tools(before the item can be done; required. `parent` links it under anotheritem; `case` names its journal case (children inherit the parent's caseby default)."""- return _call(+ return with_mention(_call(store.create_item,space,actor,@@ -93,16 +103,22 @@ def board_tools(description=description,parent=parent,case=case or None,- )+ ))def list_items(state: str = "", assignee: str = "") -> dict:"""List work items on the board, optionally filtered by state(open/in_progress/blocked/review/done/canceled) or assignee."""try:- return {"items": store.list_items(space, actor, state=state or None, assignee=assignee or None)}+ return {"items": [with_mention(i) for i in store.list_items(space, actor, state=state or None, assignee=assignee or None)]}except (BoardError, ValueError) as error:return {"error": str(error)}+ def set_status(item: int, text: str) -> dict:+ """Set a one-line progress description (at most 80 characters) on an item+ currently assigned to you. Explicit item id required. Display only: does+ not change state, wake the lead, or replace evidence and review."""+ return _call(store.set_status, space, actor, item, text)+def transition(item: int, to: str, comment: str = "", refs: Optional[list] = None) -> dict:diff --git a/tests/test_team_board.py b/tests/test_team_board.pyindex 66cedcf4..c6b6c745 100644--- a/tests/test_team_board.py+++ b/tests/test_team_board.py@@ -256,7 +256,7 @@ def test_tool_sets_are_role_filtered(store):tool.__name__ for tool in board_tools(store, space=SPACE, actor=WORKER)}assert lead_names == {"create_item", "list_items", "transition", "comment", "assign", "link"}- assert worker_names == {"create_item", "list_items", "transition", "comment", "claim"}+ assert worker_names == {"create_item", "list_items", "transition", "comment", "claim", "set_status"}def test_tools_return_errors_instead_of_raising(store):diff --git a/tests/test_team_view.py b/tests/test_team_view.pynew file mode 100644index 00000000..c425b486--- /dev/null+++ b/tests/test_team_view.py@@ -0,0 +1,187 @@+"""Team View contracts: status ownership, quiet delivery, projections and timing."""+import asyncio+import json+from types import SimpleNamespace++import pytest+from coworker.teams import Actor, AuthorityError, BoardError, Role, TeamStore+from coworker.teams.store import ITEM_STATUS, WORKER_WAITING+from coworker.teams.summary import all_events, breakdown, waiting_items, tokens, make_summary+from coworker.teams.tools import board_tools, with_mention+from coworker.teams.registry import TeamRegistry, TeamWorker+from coworker.inbox import InboxStore+from coworker.sessions import SessionRecord+from coworker.server.manager import SessionManager++LEAD = Actor(id="lead", role=Role.LEAD)+WORKER = Actor(id="sam", role=Role.WORKER)+OTHER = Actor(id="maya", role=Role.WORKER)+++def store(tmp_path):+ store = TeamStore(tmp_path / "teams.db")+ yield store+ store.close()+++def assigned(store):+ item = store.create_item("acme", LEAD, title="Invoice PDF", criteria="Download verified")+ return store.assign("acme", LEAD, item["id"], WORKER.id)+++def test_status_is_owned_and_does_not_change_work_state(store):+ item = assigned(store)+ updated = store.set_status("acme", WORKER, item["id"], "Testing 18 of 24 cases")+ assert updated["state"] == item["state"]+ assert updated["updated_seq"] == item["updated_seq"]+ assert updated["status"] == "Testing 18 of 24 cases"+ with pytest.raises(BoardError):+ store.set_status("acme", OTHER, item["id"], "Wrong item")+ with pytest.raises(AuthorityError):+ store.set_status("acme", LEAD, item["id"], "Wrong role")+++def test_reassignment_revokes_status_and_clears_old_line(store):+ item = assigned(store)+ store.set_status("acme", WORKER, item["id"], "Testing")+ moved = store.assign("acme", LEAD, item["id"], OTHER.id)+ assert moved["status"] == ""+ with pytest.raises(BoardError):+ store.set_status("acme", WORKER, item["id"], "Still testing")+ assert store.set_status("acme", OTHER, item["id"], "Reading hand-off")["status"]++[email protected]("text", ["x" * 81, "two\nlines", "two\rlines", None])+def test_status_validation(store, text):+ item = assigned(store)+ with pytest.raises(BoardError):+ store.set_status("acme", WORKER, item["id"], text)+++def test_status_boundary_empty_and_replay(store):+ item = assigned(store)+ store.set_status("acme", WORKER, item["id"], "x" * 80)+ store.rebuild("acme")+ assert store.get_item("acme", item["id"], actor=LEAD)["status"] == "x" * 80+ assert store.set_status("acme", WORKER, item["id"], "")["status"] == ""+++def test_status_is_excluded_before_feed_pagination(store):+ item = assigned(store)+ store.consume_feed("acme", LEAD.id, 2)+ store.consume_subscription("acme", LEAD.id, 2)+ for n in range(205):+ store.set_status("acme", WORKER, item["id"], f"Testing step {n}")+ assert not store.feed_for("acme", LEAD.id)+ assert not store.subscribed_events("acme", LEAD.id)+ store.transition("acme", WORKER, item["id"], "in_progress")+ store.transition("acme", WORKER, item["id"], "review")+ assert store.subscribed_events("acme", LEAD.id)[0]["payload"]["to"] == "review"+ assert all(e["kind"] != ITEM_STATUS for e in store.feed_for("acme", "observer"))+++def test_worker_with_multiple_items_sets_the_explicit_one(store):+ first, second = assigned(store), assigned(store)+ store.set_status("acme", WORKER, second["id"], "Testing the second task")+ assert store.get_item("acme", first["id"], actor=LEAD)["status"] == ""+++def test_mention_escapes_markdown_and_does_not_mutate():+ item = {"id": 2, "title": "[x](https://example.com) *bold*\nnext"}+ mention = with_mention(item)+ assert mention["mention"].endswith("](task:2)")+ assert "\\[x\\]" in mention["mention"]+ assert "mention" not in item+++def test_role_filtered_tool_surface(store):+ assert "set_status" in {t.__name__ for t in board_tools(store, space="acme", actor=WORKER)}+ assert "set_status" not in {t.__name__ for t in board_tools(store, space="acme", actor=LEAD)}+++def test_waiting_requires_a_current_pending_prompt():+ inbox = InboxStore()+ p = inbox.add_approval("worker-session", "Run tests")+ events = [{"kind": WORKER_WAITING, "item_id": 2, "actor": "sam", "payload": {"prompt_id": p.id, "session_id": "worker-session", "tool": "run_shell"}}]+ items = [{"id": 2, "assignee": "sam", "state": "in_progress"}]+ assert 2 in waiting_items(events, inbox, items)+ inbox.resolve(p.id, "allow")+ assert not waiting_items(events, inbox, items)+++def test_parallel_time_is_wall_clock_union():+ result = breakdown([(0, 5, "tool_ms"), (2, 8, "tool_ms"), (8, 9, "model_ms")], 0, 10)+ assert result == dict(model_ms=1000, tool_ms=8000, waited_ms=0, queued_ms=1000)+ assert sum(result.values()) == 10000+++def test_waiting_has_priority_and_intervals_are_clipped():+ result = breakdown([(-5, 20, "model_ms"), (3, 6, "waited_ms"), (2, 7, "tool_ms")], 0, 10)+ assert result == dict(model_ms=5000, tool_ms=2000, waited_ms=3000, queued_ms=0)+++def test_usage_is_normalized_defensively():+ assert tokens(dict(input=-1, output="12", cache_read=None, cache_write="bad")) == dict(input=0, output=12, cache_read=0, cache_write=0)+++def test_event_reader_paginates(store):+ for _ in range(2005):+ store.append_event("acme", ITEM_STATUS, WORKER, payload={"text": ""})+ assert len(list(all_events(store, "acme"))) == 2005+++def test_real_manager_summary_and_current_wait(tmp_path, monkeypatch):+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))+ manager = SessionManager(workspace=tmp_path / "repo", data_dir=tmp_path / "data")+ manager.session_store.save(SessionRecord(session_id="lead-session", workspace=str(tmp_path / "repo"), model="sample", mode="interactive", agent="swe-lead"))+ team = manager.teams.create(space=manager._board_space("lead-session"), lead_session="lead-session", lead_actor="lead", workers=[TeamWorker(actor="sam", persona="swe-worker", session_id="worker-session")])+ item = manager.team_store.create_item(team.space, LEAD, title="Invoice PDF", criteria="Verified")+ manager.team_store.assign(team.space, LEAD, item["id"], WORKER.id)+ manager.team_store.transition(team.space, WORKER, item["id"], "in_progress")+ manager.team_store.set_status(team.space, WORKER, item["id"], "Running tests")+ manager.session_store.save(SessionRecord(session_id="worker-session", workspace=str(tmp_path / "repo"), model="sample", mode="interactive", agent="swe-worker", messages=[{"role": "assistant", "content": "Testing", "ts": 10, "usage": {"input": 10, "cache_read": 20, "output": 5, "cache_write": 2}}]))+ summary = manager.team_summary(team.team_id)+ assert summary["items"][0]["status"] == "Running tests"+ assert summary["totals"]["tokens"] == 37+ assert summary["counts"]["working"] == 1+ assert summary["items"][0]["timing"] is None+ assert manager.team_summary("missing") == {"error": "team not found"}+ asyncio.run(manager.aclose())+++def test_engine_records_and_strips_timing(tmp_path):+ from test_engine import _engine, _tool_turn, _text_turn, _collect+ (tmp_path / "sample.txt").write_text("sample")+ engine, _ = _engine(tmp_path, [_tool_turn("read_file", {"path": "sample.txt"}), _text_turn("Read")])+ _collect(engine, "read")+ model = next(m for m in engine.messages if m["role"] == "assistant")+ tool = next(m for m in engine.messages if m["role"] == "tool")+ assert model["timing"]["model_ms"] >= 0+ assert tool["timing"]["tool_ms"] >= 0+ assert all("timing" not in m for m in engine._outbound_messages())+++def test_call_after_review_is_not_attributed_to_the_previous_item():+ events = [+ {"seq": 1, "ts": 1, "kind": "item_created", "item_id": 1, "payload": {}},+ {"seq": 2, "ts": 10, "kind": "item_assigned", "item_id": 1, "payload": {"assignee": "sam"}},+ {"seq": 3, "ts": 20, "kind": "item_transitioned", "item_id": 1, "payload": {"to": "review"}},+ {"seq": 4, "ts": 30, "kind": "item_transitioned", "item_id": 1, "payload": {"to": "done"}},+ ]+ item = {"id": 1, "title": "Task", "created_ts": 1, "creator": "lead", "assignee": "sam", "state": "done", "refs": [], "links": []}+ worker = SessionRecord(session_id="worker", workspace="acme", model="sample", mode="interactive", messages=[+ {"role": "assistant", "ts": 29, "usage": {"input": 100}, "timing": {"model_started": 25, "model_ms": 10000}}+ ])+ manager = SimpleNamespace(+ session_board=lambda sid: {"items": [item]},+ team_store=SimpleNamespace(events=lambda space, since_seq, limit: [e for e in events if e["seq"] > since_seq]),+ inbox=InboxStore(), _engines={}, is_running=lambda sid: False,+ session_store=SimpleNamespace(load=lambda sid: worker if sid == "worker" else None),+ )+ team = SimpleNamespace(lead_session="lead", lead_actor="lead", team_id="t", space="acme", created_at=1,+ workers=[TeamWorker(actor="sam", persona="swe-worker", session_id="worker")])+ result = make_summary(manager, team, 40)+ assert result["items"][0]["timing"] is None+ assert sum(result["items"][0]["tokens"].values()) == 0+ assert result["totals"]["tokens"] == 100