Skip to content
Python

Make team coordination event driven and quiet

Rohit C Prasad2e7b734ab20a
diff --git a/coworker/agent.py b/coworker/agent.py
index 1896fd1e..84012ec0 100644
--- a/coworker/agent.py
+++ b/coworker/agent.py
@@ -451,6 +451,15 @@ def build_engine(
instructions += "\n\n" + PROPOSAL_GUIDANCE
if agent.team in ("lead", "worker"):
instructions += (
+ "\n\nTeam coordination is event-driven: finish your turn when there is nothing "
+ "actionable. Do not poll or schedule routine sleeps just to check teammates. "
+ "User-requested schedules and external monitoring cadences still apply. "
+ "Routine notes and intermediate artifact publications remain on the board without "
+ "waking the lead. For a question needing a decision, use comment(needs_attention=True); "
+ "for a blocker transition to blocked. Publish evidence first, then submit ONE concise "
+ "review transition carrying the verdict and exact artifact versions/refs. This is the "
+ "handoff signal: do not send duplicate chat or a second copy of the report. "
+ "Completed workers need not acknowledge acceptance or overall team completion. "
"\n\nBoard efficiency: get_item reads current task details, not its comment history. "
"Read the exact comment sequence cited in a wake with get_item_comment, or new "
"comments with get_item_comments(after_seq); follow pagination. Read get_proposal "
diff --git a/coworker/personas/builtin/devsecops-lead/manifest.md b/coworker/personas/builtin/devsecops-lead/manifest.md
index 72318f21..f830817d 100644
--- a/coworker/personas/builtin/devsecops-lead/manifest.md
+++ b/coworker/personas/builtin/devsecops-lead/manifest.md
@@ -88,10 +88,10 @@ Communication doctrine:
- The user outranks you everywhere; steering attributed [User] wins over yours.
- Journal decisions as you make them (journal_append, kind=decision) — the next lead
reads the case, not your transcript.
-- NEVER end a turn with work in flight and no check-in timer set. After assigning —
- and at the end of every wake while items are active — call sleep_for: start at 3–5
- minutes; when a wake finds nothing changed, double the interval (cap ~20 minutes);
- tighten back when things get hot.
+- Finish your turn when no decision is needed. Review, blockers, explicit questions
+ and approvals wake you automatically; do not poll the team or set routine sleep
+ timers. A watchdog catches idle unfinished work. Explicit timed checks remain
+ available when the task actually requires one.
- 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/swe-lead/manifest.md b/coworker/personas/builtin/swe-lead/manifest.md
index 28aad642..91cb1dce 100644
--- a/coworker/personas/builtin/swe-lead/manifest.md
+++ b/coworker/personas/builtin/swe-lead/manifest.md
@@ -98,12 +98,11 @@ Communication doctrine:
- The user outranks you everywhere; steering attributed [User] wins over yours.
- Journal decisions as you make them (journal_append, kind=decision) — the next lead
reads the journal, not your transcript.
-- NEVER end a turn with work in flight and no check-in timer set. After assigning —
- and at the end of every wake while items are active — call sleep_for: start at 3–5
- minutes; when a wake finds nothing changed, double the interval (cap ~20 minutes);
- tighten back when things get hot. Your timer wakes arrive with a board digest, so
- a nothing's-wrong wake costs one glance. (The harness has a backstop if you
- forget, but relying on it means slower reactions — own your cadence.)
+- After assigning or handling a wake, finish your turn when nothing needs a decision.
+ The board wakes you for review, blockers, explicit questions and approvals; no
+ polling or sleep timer is needed while teammates work. A watchdog catches idle
+ unfinished work. Use sleep_for only for an explicit deadline or a check that has
+ no event signal, never to periodically ask whether the team is finished.
- 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/selfwake.py b/coworker/selfwake.py
index ad9fa0b5..ed5d9cf3 100644
--- a/coworker/selfwake.py
+++ b/coworker/selfwake.py
@@ -236,8 +236,9 @@ def selfwake_tools(store: WakeStore, session_id: str) -> list:
def sleep_for(seconds: int, note: str = "") -> dict:
"""Suspend and wake this session after `seconds` (a relative wait: "check again in
- 5 minutes" is sleep_for(300)). Use it for polling/waiting without burning context
- while idle. Replaces the previous sleep. Earlier board/user activity cancels
+ 5 minutes" is sleep_for(300)). Use for an explicit timed check, not routine
+ team polling: board decisions already wake a lead that finishes its turn.
+ Replaces the previous sleep. Earlier board/user activity cancels
it and carries your optional reminder note forward. No clock arithmetic needed."""
secs = int(seconds)
if secs <= 0:
diff --git a/coworker/server/app.py b/coworker/server/app.py
index 98c1847c..1b7e10c1 100644
--- a/coworker/server/app.py
+++ b/coworker/server/app.py
@@ -972,16 +972,18 @@ def create_app(manager: SessionManager) -> FastAPI:
@app.post("/v1/board/items/comment")
def board_comment_item(request: Request, body: dict):
body = body or {}
- return _board(
- request,
- lambda actor: manager.team_store.comment(
+ def run(actor):
+ result = manager.team_store.comment(
str(body.get("space", "")),
actor,
int(body.get("id", 0)),
str(body.get("body", "")),
refs=[str(ref) for ref in body.get("refs") or []],
- ),
- )
+ needs_attention=body.get("needs_attention", False),
+ )
+ manager.kick_team_tick()
+ return result
+ return _board(request, run)
@app.post("/v1/board/items/assign")
def board_assign_item(request: Request, body: dict):
diff --git a/coworker/server/manager.py b/coworker/server/manager.py
index 5df19902..143ac93c 100644
--- a/coworker/server/manager.py
+++ b/coworker/server/manager.py
@@ -395,6 +395,7 @@ class SessionManager:
# Lead-session last-turn timestamps for the check-in backstop (monotonic-ish
# wall clock; restart resets the clock rather than firing a wake storm).
self._team_last_alive: dict[str, float] = {}
+ self._team_watchdog_alerted: dict[str, tuple] = {}
self._loop: Optional[asyncio.AbstractEventLoop] = None
# Personas: registry + lifecycle state under this manager's data dir. Installed as the
# process singleton so agents.get_agent resolves persona ids (incl. third-party) here.
@@ -2677,6 +2678,7 @@ class SessionManager:
# Resolve live grants at call time, including scratch and directories
# added or revoked since this engine was built. No engine => no access.
roots=lambda: getattr(self._engines.get(session_id), "roots", []),
+ on_change=self.kick_team_tick,
) + journal_tools(
self.journal_store, actor=actor, space=space
)
@@ -3064,15 +3066,16 @@ class SessionManager:
delivered += await self._maybe_backstop_lead(team)
return delivered
- # The lead owns its cadence (sleep_for, stretch-when-quiet); this backstop only
- # exists because prompts aren't guarantees. A forgotten timer must never orphan
- # a running team — and it de-facto covers a worker dying without a transition
- # (its item goes stale; the backstop wake surfaces it in the digest).
+ # Event-driven teams need no polling timer. This optional backstop catches
+ # idle, unfinished work only; healthy busy workers and human waits are quiet.
+ # Set to zero to disable it. Explicit user/connector schedules are unchanged.
TEAM_LEAD_BACKSTOP_SECS = 600
TEAM_BATCH_SECONDS = 2.0
def _lead_backstop_due(self, team) -> bool:
sid = team.lead_session
+ if self.TEAM_LEAD_BACKSTOP_SECS <= 0 or team.paused:
+ return False
if sid in self.wakes.stopped_sessions:
return False
if self.is_running(sid) or sid in self._team_inflight:
@@ -3083,13 +3086,27 @@ class SessionManager:
last = self._team_last_alive.setdefault(sid, time.time())
if time.time() - last < self.TEAM_LEAD_BACKSTOP_SECS:
return False
- try:
- items = self.team_store.list_items(team.space, self._user_actor())
- except Exception:
- return False
- return any(
- i["state"] in ("in_progress", "blocked", "review") for i in items
- )
+ stalled = self._stalled_team_state(team)
+ return bool(stalled) and self._team_watchdog_alerted.get(sid) != stalled
+
+ def _stalled_team_state(self, team) -> tuple:
+ workers = {w.actor: w.session_id for w in team.workers}
+ workers[team.lead_actor] = team.lead_session
+ if self.inbox.list(session_id=team.lead_session, state="pending"):
+ return ()
+ stalled = []
+ for item in self.team_store.list_items(team.space, self._user_actor()):
+ if item["state"] not in ("in_progress", "blocked", "review"):
+ continue
+ sid = workers.get(item["assignee"])
+ if sid and (self.is_running(sid) or sid in self._team_inflight or self.wakes.pending(sid)
+ or sid in self.wakes.stopped_sessions or self.inbox.list(session_id=sid, state="pending")):
+ continue
+ last = self._team_last_alive.get(sid, self._team_last_alive.get(team.lead_session, time.time()))
+ if time.time() - last >= self.TEAM_LEAD_BACKSTOP_SECS:
+ stalled.append((item["id"], item["state"], item["updated_seq"], item["assignee"],
+ self._team_last_alive.get(sid, 0) if sid != team.lead_session else 0))
+ return tuple(stalled)
async def _maybe_backstop_lead(self, team) -> int:
if not self._lead_backstop_due(team):
@@ -3097,21 +3114,23 @@ class SessionManager:
if not self.teams.count_wake(team.team_id, cap=self.TEAM_WAKE_CAP_PER_HOUR):
return 0
sid = team.lead_session
+ stalled = self._stalled_team_state(team)
self._team_last_alive[sid] = time.time()
message = (
- "Check-in — work is in flight but you had no check-in timer"
- " set.\n\n"
+ "Team watchdog — unfinished work has been idle for at least ten minutes.\n\n"
+ (self.team_staleness_digest(sid) or "Board state unavailable.")
- + "\n\nGlance, act only if something needs you, and set your next"
- " check-in with sleep_for (start 3–5 minutes; stretch when quiet)."
+ + "\n\nCheck for a stalled assignment or missing handoff. Act only if needed,"
+ " then finish your turn. Board decisions wake you automatically; do not start polling."
)
self._team_inflight.add(sid)
async def _deliver() -> None:
try:
- await self.deliver_to_session(
+ accepted = await self.deliver_to_session(
sid, message, source=self._board_source(team, message)
)
+ if accepted:
+ self._team_watchdog_alerted[sid] = stalled
finally:
self._team_inflight.discard(sid)
@@ -3127,15 +3146,8 @@ class SessionManager:
# Interest follows the assignment relation: everyone's feed is the events
# on their slice (assigned ∪ filed) — comments, moves, reassignments. The
# lead additionally subscribes to the board-wide decision classes.
- directs = self.team_store.feed_for(team.space, actor)
- if not is_lead and directs and all(e["kind"] == WORKER_WAITING for e in directs):
- # A wait owned by the lead/user is not work for a worker. Advance
- # this informational-only batch so it cannot repeatedly wake them.
- self.team_store.consume_feed(team.space, actor, max(e["seq"] for e in directs))
- directs = []
- subs = (
- self.team_store.subscribed_events(team.space, actor) if is_lead else []
- )
+ page = self.team_store.delivery_page(team.space, actor, is_lead=is_lead)
+ directs, subs = page["directs"], page["subs"]
if subs:
seen = {e["seq"] for e in subs}
directs = [e for e in directs if e["seq"] not in seen]
@@ -3145,13 +3157,17 @@ class SessionManager:
if team.chat_enabled and team.chat_group
else []
)
+ receipt = self._board_receipt(team, actor, directs, subs, chats, chat_handle,
+ through_seq=page["through_seq"], is_lead=is_lead)
+ directs = self._actionable_team_events(team, directs, actor=actor, is_lead=is_lead)
+ subs = self._actionable_team_events(team, subs, actor=actor, is_lead=is_lead)
# Cancel is top-priority: an in-flight worker gets interrupted NOW; the
# queued notice (delivered when the turn dies) tells it why. Only for the
# item's ASSIGNEE — a filer merely hears about it.
def _holds(event) -> bool:
try:
item = self.team_store.get_item(
- team.space, int(event["item_id"]), actor=self._user_actor()
+ team.space, int(event["item_id"]), actor=self._user_actor(), include_comments=False
)
except Exception:
return False
@@ -3164,23 +3180,30 @@ class SessionManager:
and (e.get("payload") or {}).get("to") == "canceled"
and _holds(e)
]
- if cancels and self.is_running(session_id):
+ lost_assignments = [e for e in directs if e["kind"] == "item_assigned"
+ and e["payload"].get("previous") == actor and not _holds(e)]
+ if (cancels or lost_assignments) and self.is_running(session_id):
engine = self._engines.get(session_id)
if engine is not None:
engine.request_interrupt()
- if not directs and not subs and not chats:
- self._clear_team_batch(session_id)
- return 0
message, rows = self._team_digest(
team, directs, subs, chats, is_lead=is_lead, reader=actor
)
if not rows:
- self._consume_board_receipt(self._board_receipt(team, actor, directs, subs, chats, chat_handle))
+ # Quiet events remain in the board/UI, but do not create model turns
+ # or cancel a user-requested timer. Do not leap over queued input.
+ engine = self._engines.get(session_id)
+ if any((activity or {}).get("board") for _, _, activity in (engine._steering if engine else [])):
+ return 0
+ self._consume_board_receipt(receipt)
self._clear_team_batch(session_id)
+ if page["has_more"]:
+ self.kick_team_tick()
return 0
if is_lead:
deadline = self._team_batch_deadlines.setdefault(session_id, time.monotonic() + self.TEAM_BATCH_SECONDS)
- urgent = any(r.get("kind") == "waiting" or (r.get("to") == "blocked" and not r.get("historical")) for r in rows)
+ urgent = any(r.get("needs_attention") or r.get("kind") in ("waiting", "assigned")
+ or (r.get("to") == "blocked" and not r.get("historical")) for r in rows)
timer_due = any(w.session_id == session_id and w.kind == "timer" for w in self.wakes.due())
if not urgent and not timer_due and time.monotonic() < deadline:
if session_id not in self._team_batch_handles:
@@ -3218,10 +3241,10 @@ class SessionManager:
handle.cancel()
@staticmethod
- def _board_receipt(team, actor, directs, subs, chats, chat_handle) -> dict:
+ def _board_receipt(team, actor, directs, subs, chats, chat_handle, *, through_seq=None, is_lead=False) -> dict:
return {"space": team.space, "actor": actor,
- "feed": max([e["seq"] for e in directs + subs], default=0),
- "subscription": max([e["seq"] for e in subs], default=0),
+ "feed": through_seq if through_seq is not None else max([e["seq"] for e in directs + subs], default=0),
+ "subscription": through_seq if through_seq is not None and is_lead else max([e["seq"] for e in subs], default=0),
"chat_group": team.chat_group, "chat_handle": chat_handle,
"chat": max([e["seq"] for e in chats], default=0)}
@@ -3242,26 +3265,69 @@ class SessionManager:
if team is None or team.paused:
return "", [], {}
actor = team.lead_actor if is_lead else worker.actor
- directs = self.team_store.feed_for(team.space, actor)
- subs = self.team_store.subscribed_events(team.space, actor) if is_lead else []
engine = self._engines.get(session_id)
queued = [(a or {}).get("board") or {} for _, _, a in (engine._steering if engine else [])]
feed_through = max([r.get("feed", 0) for r in queued], default=0)
sub_through = max([r.get("subscription", 0) for r in queued], default=0)
- directs = [e for e in directs if e["seq"] > feed_through]
- subs = [e for e in subs if e["seq"] > sub_through]
+ page = self.team_store.delivery_page(team.space, actor, is_lead=is_lead,
+ feed_after=feed_through, subscription_after=sub_through)
+ directs, subs = page["directs"], page["subs"]
seen = {e["seq"] for e in subs}
directs = [e for e in directs if e["seq"] not in seen]
handle = "lead" if is_lead else actor
chats = self.chat_store.unread_for(team.chat_group, handle) if team.chat_enabled and team.chat_group else []
chat_through = max([r.get("chat", 0) for r in queued], default=0)
chats = [e for e in chats if e["seq"] > chat_through]
- receipt = self._board_receipt(team, actor, directs, subs, chats, handle)
- if not is_lead:
- directs = [e for e in directs if e["kind"] != WORKER_WAITING]
+ receipt = self._board_receipt(team, actor, directs, subs, chats, handle,
+ through_seq=page["through_seq"], is_lead=is_lead)
+ directs = self._actionable_team_events(team, directs, actor=actor, is_lead=is_lead)
+ subs = self._actionable_team_events(team, subs, actor=actor, is_lead=is_lead)
text, rows = self._team_digest(team, directs, subs, chats, is_lead=is_lead, reader=actor)
return text if rows else "", rows, receipt
+ def _actionable_team_events(self, team, events, *, actor: str, is_lead: bool) -> list:
+ """Wake policy, not storage/visibility policy. No prose classification.
+
+ Publications/notes are evidence, review is the handoff. Explicit questions
+ use needs_attention; human notes and lead instructions are never muted.
+ A dependency completion wakes only workers with live dependent work.
+ """
+ items = {i["id"]: i for i in self.team_store.list_items(team.space, self._user_actor())}
+ active = [i for i in items.values() if i["assignee"] == actor and i["state"] not in ("done", "canceled")]
+ prerequisites = {link["item"] for i in active for link in i.get("links", []) if link["kind"] == "blocked_by"}
+
+ def actionable(e):
+ kind, p = e["kind"], e.get("payload") or {}
+ item = items.get(e.get("item_id"))
+ if kind == WORKER_WAITING:
+ return is_lead # digest also checks the exact prompt is still pending
+ if kind == "item_commented":
+ if p.get("attachments") or p.get("artifact"):
+ return bool(p.get("needs_attention")) and is_lead
+ if e.get("actor_role") == "user":
+ return True
+ if is_lead:
+ return bool(p.get("needs_attention"))
+ return e.get("actor_role") == "lead" and bool(active or (item and item["assignee"] == actor))
+ if kind == "item_assigned":
+ if is_lead:
+ return bool(p.get("claimed")) or e.get("actor_role") == "user" or actor in (p.get("assignee"), p.get("previous"))
+ return bool(item) and ((p.get("assignee") == actor and item["assignee"] == actor)
+ or (p.get("previous") == actor and item["assignee"] != actor))
+ if kind == "item_created":
+ return is_lead
+ if kind != "item_transitioned" or item is None or item["state"] != p.get("to"):
+ return False
+ if is_lead:
+ return p.get("to") in ("review", "blocked") or e.get("actor_role") == "user"
+ if item["id"] in prerequisites and p.get("to") in ("done", "canceled"):
+ return True # includes a worker's own accepted prerequisite
+ if item["assignee"] == actor:
+ return p.get("to") == "canceled" or (p.get("to") in ("open", "in_progress") and p.get("from") in ("review", "blocked", "canceled"))
+ return False
+
+ return [e for e in events if actionable(e)]
+
def prepare_activity(self, session_id: str, reason: str, *, wake=None, include_board=True) -> dict:
"""Cancel idle sleep and gather context; acknowledgement waits for durable input."""
self.reconcile_activity_receipts(session_id)
@@ -3358,6 +3424,7 @@ class SessionManager:
"title": item["title"] if item else "",
"actor": event.get("actor", ""),
"seq": event["seq"],
+ "needs_attention": bool(payload.get("needs_attention")) or event.get("actor_role") == "user",
}
if event["kind"] == "item_assigned":
if item is None:
@@ -6053,7 +6120,7 @@ class SessionManager:
# Team sessions: a finished turn is the moment new board events exist (an
# assign, a review transition) — kick the queue drain now instead of waiting
# for the next scheduler tick. Cheap no-op for teamless sessions.
- if self.teams.for_lead_session(session_id):
+ if self.teams.for_lead_session(session_id) or self.teams.for_worker_session(session_id):
self._team_last_alive[session_id] = time.time()
if self._loop is not None and (
self.teams.for_lead_session(session_id)
diff --git a/coworker/teams/cli.py b/coworker/teams/cli.py
index 8a3bfbea..7fd7930c 100644
--- a/coworker/teams/cli.py
+++ b/coworker/teams/cli.py
@@ -92,6 +92,7 @@ def _parser() -> argparse.ArgumentParser:
p.add_argument("id", type=int)
p.add_argument("body")
p.add_argument("--ref", action="append", default=[], dest="refs")
+ p.add_argument("--needs-attention", action="store_true", help="ask the lead for a decision")
p = cmd("assign", _cmd_assign, "assign an item (lead/user)")
p.add_argument("id", type=int)
@@ -332,7 +333,7 @@ def _cmd_move(args) -> int:
def _cmd_comment(args) -> int:
- _dialect(args).comment(_space(args), args.id, args.body, refs=args.refs)
+ _dialect(args).comment(_space(args), args.id, args.body, refs=args.refs, needs_attention=args.needs_attention)
print("ok" if not args.json else json.dumps({"ok": True}))
return 0
diff --git a/coworker/teams/dialect.py b/coworker/teams/dialect.py
index 3b4427d6..efbc7519 100644
--- a/coworker/teams/dialect.py
+++ b/coworker/teams/dialect.py
@@ -76,6 +76,7 @@ class BoardDialect(Protocol):
body: str,
*,
refs: Optional[list[str]] = None,
+ needs_attention: bool = False,
) -> dict[str, Any]: ...
def assign(self, space: str, item_id: int, assignee: str) -> dict[str, Any]: ...
def claim(self, space: str, item_id: int) -> dict[str, Any]: ...
@@ -202,8 +203,9 @@ class LocalDialect:
body: str,
*,
refs: Optional[list[str]] = None,
+ needs_attention: bool = False,
) -> dict[str, Any]:
- return self.store.comment(space, self.actor, item_id, body, refs=refs)
+ return self.store.comment(space, self.actor, item_id, body, refs=refs, needs_attention=needs_attention)
def assign(self, space: str, item_id: int, assignee: str) -> dict[str, Any]:
return self.store.assign(space, self.actor, item_id, assignee)
@@ -439,10 +441,11 @@ class RemoteDialect:
body: str,
*,
refs: Optional[list[str]] = None,
+ needs_attention: bool = False,
) -> dict[str, Any]:
return self._post(
"/v1/board/items/comment",
- {"space": space, "id": item_id, "body": body, "refs": refs or []},
+ {"space": space, "id": item_id, "body": body, "refs": refs or [], "needs_attention": needs_attention},
)
def assign(self, space: str, item_id: int, assignee: str) -> dict[str, Any]:
diff --git a/coworker/teams/mcp_server.py b/coworker/teams/mcp_server.py
index 6e5bd02e..da746517 100644
--- a/coworker/teams/mcp_server.py
+++ b/coworker/teams/mcp_server.py
@@ -139,10 +139,12 @@ def build(dialect, *, space: str):
)
@mcp.tool()
- def board_comment(item: int, body: str, refs: list[str] = []) -> Any:
+ def board_comment(item: int, body: str, refs: list[str] = [], needs_attention: bool = False) -> Any:
"""Comment on a work item — durable and attributed; answers that matter
- belong here. `refs` attach artifact pointers."""
- return _safe(dialect.comment, space, item, body, refs=list(refs or []))
+ belong here. Routine notes are quiet; needs_attention=True wakes the lead
+ for an explicit question/decision. Review transitions are the handoff.
+ `refs` attach artifact pointers."""
+ return _safe(dialect.comment, space, item, body, refs=list(refs or []), needs_attention=needs_attention)
@mcp.tool()
def board_attach(item: int, path: str, caption: str = "") -> Any:
diff --git a/coworker/teams/store.py b/coworker/teams/store.py
index 8e56d3a3..7be434fd 100644
--- a/coworker/teams/store.py
+++ b/coworker/teams/store.py
@@ -373,6 +373,41 @@ class TeamStore:
def consume_feed(self, space: str, actor_id: str, upto_seq: int) -> None:
self._set_cursor(f"feed:{actor_id}:{space}", int(upto_seq))
+ @staticmethod
+ def _subscription_event(event: dict, subscriber: str) -> bool:
+ if event["actor"] == subscriber:
+ return False
+ kind, payload = event["kind"], event["payload"]
+ if kind == ITEM_COMMENTED:
+ return bool(payload.get("needs_attention")) or event.get("actor_role") == "user"
+ if kind == ITEM_TRANSITIONED:
+ return payload.get("to") in ("review", "blocked")
+ if kind == ITEM_ASSIGNED:
+ return bool(payload.get("claimed"))
+ return kind in (ITEM_CREATED, WORKER_WAITING)
+
+ def delivery_page(self, space: str, actor: str, *, is_lead: bool,
+ feed_after: int = 0, subscription_after: int = 0, limit: int = 200) -> dict:
+ """Read both delivery projections from ONE scanned log range.
+
+ Even quiet/self/status events advance the scan. Never let a subscription
+ cursor leap over an unscanned direct user instruction on a busy board.
+ The caller acknowledges through_seq only after deciding it is quiet or
+ durably accepting the actionable input.
+ """
+ with self._lock:
+ feed = max(feed_after, self._cursor(f"feed:{actor}:{space}"))
+ sub = max(subscription_after, self._cursor(f"sub:{actor}:{space}")) if is_lead else feed
+ events = self.events(space, since_seq=min(feed, sub), limit=limit + 1)
+ page = events[:limit]
+ visible = self._worker_slice(space, actor)
+ directs = [e for e in page if e["seq"] > feed and e["actor"] != actor and (
+ e.get("item_id") in visible or
+ (e["kind"] == ITEM_ASSIGNED and actor in (e["payload"].get("assignee"), e["payload"].get("previous"))))]
+ subs = [e for e in page if e["seq"] > sub and self._subscription_event(e, actor)] if is_lead else []
+ return {"directs": directs, "subs": subs, "through_seq": page[-1]["seq"] if page else 0,
+ "has_more": len(events) > limit}
+
# Lead subscriptions: an ALLOWLIST of decision-demanding event classes — a
# worker moving its item to review/blocked, or filing a new item. Journal
# appends and routine comments never wake anyone.
@@ -385,12 +420,14 @@ class TeamStore:
key = f"sub:{subscriber}:{space}"
events = self.events(
space,
- kinds=[ITEM_TRANSITIONED, ITEM_CREATED, ITEM_ASSIGNED, WORKER_WAITING],
+ kinds=[ITEM_TRANSITIONED, ITEM_CREATED, ITEM_ASSIGNED, ITEM_COMMENTED, WORKER_WAITING],
since_seq=self._cursor(key),
limit=limit,
)
out = []
for event in events:
+ if event["kind"] == ITEM_COMMENTED and not self._subscription_event(event, subscriber):
+ continue
if event["actor"] == subscriber:
continue # your own verbs never wake you
if (
@@ -873,9 +910,12 @@ class TeamStore:
*,
refs: Optional[list[str]] = None,
taint: bool = False,
+ needs_attention: bool = False,
) -> dict[str, Any]:
if not (body or "").strip():
raise BoardError("comment body is required")
+ if not isinstance(needs_attention, bool):
+ raise BoardError("needs_attention must be a boolean")
with self._lock:
item = self._item(space, item_id)
if actor.role == Role.WORKER and item_id not in self._worker_slice(
@@ -891,7 +931,8 @@ class TeamStore:
actor,
item_id=item_id,
case_id=item["case_id"] or None,
- payload={"body": body, "refs": list(refs or [])},
+ payload={"body": body, "refs": list(refs or []),
+ **({"needs_attention": True} if needs_attention else {})},
taint=taint,
)
diff --git a/coworker/teams/tools.py b/coworker/teams/tools.py
index a01162fc..de2913f8 100644
--- a/coworker/teams/tools.py
+++ b/coworker/teams/tools.py
@@ -97,6 +97,7 @@ def board_tools(
taint: Callable[[], bool] = lambda: False,
attachments=None,
roots: Callable[[], list] = lambda: [],
+ on_change: Callable[[], None] = lambda: None,
) -> list:
"""The board verbs for one agent, pre-bound to its space and identity.
@@ -105,6 +106,11 @@ def board_tools(
the tool layer is convenience, the store is the gate.
"""
+ def receipt(result: dict, *, notify: bool = True) -> dict:
+ if "error" not in result and notify:
+ on_change()
+ return mutation_receipt(result)
+
def create_item(
title: str,
criteria: str,
@@ -117,7 +123,7 @@ def board_tools(
before the item can be done; required. `parent` links it under another
item; `case` names its journal case (children inherit the parent's case
by default)."""
- return item_snapshot(_call(
+ result = _call(
store.create_item,
space,
actor,
@@ -126,7 +132,10 @@ def board_tools(
description=description,
parent=parent,
case=case or None,
- ))
+ )
+ if "error" not in result:
+ on_change()
+ return item_snapshot(result)
def list_items(state: str = "", assignee: str = "", after_item: int = 0, limit: int = 50) -> dict:
"""List work items on the board, optionally filtered by state
@@ -148,7 +157,7 @@ def board_tools(
"""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 mutation_receipt(_call(store.set_status, space, actor, item, text))
+ return receipt(_call(store.set_status, space, actor, item, text), notify=False)
def get_item(item: int) -> dict:
"""Read current task details, acceptance criteria, links and evidence refs,
@@ -189,7 +198,7 @@ def board_tools(
in_progress, blocked, or review (attach the blocker or a hand-off summary
as `comment`, and artifact pointers — branch, report, session — as
`refs`); done requires review verification first."""
- return mutation_receipt(_call(
+ return receipt(_call(
store.transition,
space,
actor,
@@ -200,11 +209,14 @@ def board_tools(
taint=taint(),
))
- def comment(item: int, body: str, refs: Optional[list] = None) -> dict:
+ def comment(item: int, body: str, refs: Optional[list] = None, needs_attention: bool = False) -> dict:
"""Add a comment to a work item. Comments are durable and attributed —
answers that matter belong here, not in chat. `refs` attach artifact
- pointers (branch, PR, report, file:line) to the item."""
- return mutation_receipt(_call(
+ pointers (branch, PR, report, file:line) to the item. Routine notes do NOT
+ wake the lead. Set needs_attention=True for an explicit question/decision;
+ blockers use transition to blocked. Publish evidence first, then one
+ concise transition to review with its artifact refs: that is the handoff."""
+ return receipt(_call(
store.comment,
space,
actor,
@@ -212,23 +224,24 @@ def board_tools(
body,
refs=[str(ref) for ref in refs or []],
taint=taint(),
+ needs_attention=needs_attention,
))
def claim(item: int) -> dict:
"""Claim an open, unassigned work item for yourself. First claim wins;
the item becomes your assignment. Only claim work you can start on —
the lead sees every claim and can reassign."""
- return mutation_receipt(_call(store.claim, space, actor, item))
+ return receipt(_call(store.claim, space, actor, item))
def assign(item: int, assignee: str) -> dict:
"""Assign a work item to a worker coworker. The item itself becomes the
worker's assignment — write the description and criteria accordingly."""
- return mutation_receipt(_call(store.assign, space, actor, item, assignee))
+ return receipt(_call(store.assign, space, actor, item, assignee))
def link(src: int, kind: str, dst: int) -> dict:
"""Link two work items: kind `parent` (dst becomes src's parent) or
`blocks` (src blocks dst)."""
- return mutation_receipt(_call(store.link, space, actor, src, kind, dst))
+ return receipt(_call(store.link, space, actor, src, kind, dst))
def attach_image(item: int, path: str, caption: str = "") -> dict:
"""Attach a screenshot or image file (png/jpg/gif/webp, ≤10MB) to a work
diff --git a/docs/team-board-evidence.md b/docs/team-board-evidence.md
index 295db285..e238440e 100644
--- a/docs/team-board-evidence.md
+++ b/docs/team-board-evidence.md
@@ -34,6 +34,35 @@ compaction or restart, start from zero or re-read a known sequence when evidence
missing. Receiving something earlier does not mean the model still remembers it.
The existing per-item visibility checks still apply to all comment/proposal reads.
+## Quiet coordination
+
+Board storage/visibility and model wake policy are separate. Progress, routine worker
+comments and intermediate attachments remain in the UI/event log without starting a
+lead turn. Publish evidence first, then one `transition(..., to="review", comment=...,
+refs=...)` with the verdict and exact artifact versions: review is the handoff signal.
+Review handoffs use the existing fixed two-second batch, not a sliding debounce.
+
+Blockers and pending approvals/questions wake promptly. `comment(needs_attention=True)`
+is an explicit request for a lead decision; ordinary comments are quiet. CLI users can
+pass `--needs-attention`, and board MCP/HTTP clients have the same boolean field. Human
+notes and lead instructions are not classified by their prose or silently suppressed.
+Cancellation/reassignment can interrupt a busy previous owner; changes requested at
+review wake the assigned worker. A completed prerequisite wakes a worker with live
+dependent work, including when it was that worker's own earlier task.
+
+Acceptance and overall completion do not wake finished workers merely to acknowledge
+them. No board data is deleted. Quiet delivery receipts advance only through a scanned
+log range, never past unseen user instructions; actionable receipts still require
+durable input acceptance, including user-versus-board dispatch and restart races.
+
+Leads finish their turn when waiting for the team. No sleep tool call is required.
+Explicit timers and external monitoring/scheduled-task cadences retain their existing
+semantics. The optional ten-minute watchdog checks for idle unfinished work, not a
+quiet lead with healthy active workers. Pending human decisions, stopped sessions and
+explicit pending wakes suppress it. An unchanged stall is not repeatedly reported in
+the same runtime. Restart starts a fresh observation interval. Set the runtime's
+`TEAM_LEAD_BACKSTOP_SECS` to zero to disable the watchdog; no new GUI setting is added.
+
The board MCP interface provides equivalent `board_comments`, `board_comment_text`
and `board_proposal` tools, compact `board_show`, paged `board_list` and small mutation
receipts. The human CLI/full-detail HTTP views retain their existing full projections.
diff --git a/tests/test_idle_checkins.py b/tests/test_idle_checkins.py
index 8da54352..9deeba7b 100644
--- a/tests/test_idle_checkins.py
+++ b/tests/test_idle_checkins.py
@@ -213,12 +213,12 @@ def test_expiry_records_one_receipt_and_no_second_wake(manager):
assert wake.state == "fired" and wake.context_delivered
-def test_reopened_review_is_marked_historical(manager):
+def test_reopened_review_no_longer_wakes_lead_for_a_stale_decision(manager):
space, item = review(manager)
manager.team_store.transition(space, Actor(id="lead", role=Role.LEAD), item["id"], "in_progress", comment="Needs another test")
text, rows, receipt = manager._pending_board_context("lead")
- assert "historical transition; current state: in_progress" in text
- assert next(r for r in rows if r.get("to") == "review")["historical"] is True
+ assert text == "" and rows == []
+ assert receipt["feed"] > 0 # still acknowledged without deleting audit history
def test_failed_delivery_keeps_due_timer(manager, monkeypatch):
diff --git a/tests/test_team_live_gaps.py b/tests/test_team_live_gaps.py
index 7bd3b924..618e5cd0 100644
--- a/tests/test_team_live_gaps.py
+++ b/tests/test_team_live_gaps.py
@@ -228,7 +228,8 @@ def test_worker_wait_digest_is_informational_and_wait_only_batch_does_not_wake(
assert "decide_worker_call" not in body and "your decision" not in body
assert "lead or user" in body and rows[0]["kind"] == "waiting"
consumed = []
- monkeypatch.setattr(manager.team_store, "feed_for", lambda *a: events)
+ monkeypatch.setattr(manager.team_store, "delivery_page", lambda *a, **kw: {
+ "directs": events, "subs": [], "through_seq": 10, "has_more": False})
monkeypatch.setattr(
manager.team_store, "consume_feed", lambda *a: consumed.append(a)
)
diff --git a/tests/test_team_quiet_coordination.py b/tests/test_team_quiet_coordination.py
new file mode 100644
index 00000000..3637ede8
--- /dev/null
+++ b/tests/test_team_quiet_coordination.py
@@ -0,0 +1,202 @@
+import asyncio
+import time
+from unittest.mock import Mock
+
+from coworker.teams import Actor, Role
+from coworker.teams.store import TeamStore
+from coworker.teams.tools import board_tools
+from test_engine import ScriptedProvider, _text_turn
+from test_team_live_gaps import manager
+from test_team_reader_recovery import create_item
+from test_idle_checkins import timer, drain, finish
+
+SAM = Actor(id="sam", role=Role.WORKER)
+
+
+def test_progress_and_publications_are_quiet_and_do_not_cancel_timer(manager):
+ space, lead, item = create_item(manager)
+ manager.team_store.transition(space, SAM, item["id"], "in_progress")
+ manager.team_store.comment(space, SAM, item["id"], "Halfway through")
+ manager.team_store.attach_ref(space, SAM, item["id"], "Version one", "attachment://" + "a"*64 + ".md#report.md")
+ manager.team_store.attach_ref(space, SAM, item["id"], "Version two", "attachment://" + "b"*64 + ".md#report.md")
+ wake = timer(manager)
+ assert asyncio.run(drain(manager)) == 0
+ assert wake.state == "pending"
+ assert not manager.session_store.load("lead").messages
+ assert len(manager.team_store.get_item(space, item["id"], actor=lead)["comments"]) == 3
+
+
+def test_one_review_handoff_after_publications_and_notes(manager):
+ manager.provider = ScriptedProvider([_text_turn("Reviewing the evidence")])
+ manager.TEAM_BATCH_SECONDS = 0
+ space, _, item = create_item(manager)
+ manager.team_store.transition(space, SAM, item["id"], "in_progress")
+ for n in range(5):
+ manager.team_store.comment(space, SAM, item["id"], f"Evidence detail {n}")
+ handoff = manager.team_store.transition(space, SAM, item["id"], "review", comment="PASS; published versions 1/2", refs=["report.md"])
+ async def run():
+ assert await drain(manager) == 1
+ await finish(manager)
+ asyncio.run(run())
+ msgs = [m for m in manager.session_store.load("lead").messages if m["role"] == "user"]
+ assert len(msgs) == 1
+ rows = msgs[0]["source"]["board"]["rows"]
+ assert len(rows) == 1 and rows[0]["seq"] == handoff["seq"]
+ assert "Evidence detail" not in msgs[0]["content"]
+ assert not manager._pending_board_context("lead")[0]
+
+
+def test_acceptance_keeps_completed_worker_quiet(manager):
+ space, lead, item = create_item(manager)
+ manager.team_store.transition(space, SAM, item["id"], "in_progress")
+ manager.team_store.transition(space, SAM, item["id"], "review", comment="Verified")
+ manager.team_store.consume_feed(space, "sam", manager.team_store.events(space)[-1]["seq"])
+ manager.team_store.transition(space, lead, item["id"], "done", comment="Accepted, thanks")
+ team = manager.teams.for_lead_session("lead")
+ assert asyncio.run(manager._drain_team_member(team, session_id="worker", actor="sam", is_lead=False)) == 0
+ assert not manager.team_store.feed_for(space, "sam")
+ assert not manager.is_running("worker")
+
+
+def test_dependency_completion_only_wakes_live_dependent_worker(manager):
+ space, lead, task = create_item(manager)
+ _, _, prerequisite = create_item(manager, "maya")
+ manager.team_store.link(space, lead, prerequisite["id"], "blocks", task["id"])
+ maya = Actor(id="maya", role=Role.WORKER)
+ manager.team_store.transition(space, maya, prerequisite["id"], "in_progress")
+ manager.team_store.transition(space, maya, prerequisite["id"], "review")
+ manager.team_store.transition(space, lead, prerequisite["id"], "done")
+ event = manager.team_store.events(space)[-1]
+ team = manager.teams.for_lead_session("lead")
+ assert manager._actionable_team_events(team, [event], actor="sam", is_lead=False)
+ manager.team_store.transition(space, lead, task["id"], "canceled")
+ assert not manager._actionable_team_events(team, [event], actor="sam", is_lead=False)
+
+
+def test_explicit_worker_question_wakes_lead_without_batch_delay(manager):
+ manager.provider = ScriptedProvider([_text_turn("Answering the question")])
+ space, _, item = create_item(manager)
+ # Worker-created task: lead is not its creator/assignee. Subscription still works.
+ question = manager.team_store.create_item(space, SAM, title="Question", criteria="Decision")
+ manager.team_store.comment(space, SAM, question["id"], "Which acceptance rule?", needs_attention=True)
+ async def run():
+ assert await drain(manager) == 1
+ await finish(manager)
+ asyncio.run(run())
+ messages = manager.session_store.load("lead").messages
+ assert any("Which acceptance rule?" in m.get("content", "") for m in messages if m["role"] == "user")
+
+
+def test_human_note_and_send_back_are_not_muted(manager):
+ space, lead, item = create_item(manager)
+ manager.team_store.transition(space, SAM, item["id"], "in_progress")
+ manager.team_store.transition(space, SAM, item["id"], "review")
+ manager.team_store.transition(space, lead, item["id"], "in_progress", comment="Fix this acceptance gap")
+ team = manager.teams.for_lead_session("lead")
+ event = manager.team_store.events(space)[-1]
+ assert manager._actionable_team_events(team, [event], actor="sam", is_lead=False)
+ note = manager.team_store.comment(space, Actor(id="user", role=Role.USER), item["id"], "Change the scope")
+ assert manager._actionable_team_events(team, [note], actor="sam", is_lead=False)
+ assert manager._actionable_team_events(team, [note], actor="lead", is_lead=True)
+
+
+def test_reassignment_interrupts_previous_busy_owner(manager):
+ space, lead, item = create_item(manager)
+ manager.team_store.consume_feed(space, "sam", manager.team_store.events(space)[-1]["seq"])
+ manager.team_store.assign(space, lead, item["id"], "maya")
+ engine = manager.get_engine("worker")
+ engine.request_interrupt = Mock()
+ manager.mark_running("worker")
+ team = manager.teams.for_lead_session("lead")
+ assert asyncio.run(manager._drain_team_member(team, session_id="worker", actor="sam", is_lead=False)) == 0
+ engine.request_interrupt.assert_called_once()
+ assert manager.team_store.feed_for(space, "sam") # delivery not acknowledged until accepted
+
+
+def test_cancellation_interrupts_busy_worker_without_acknowledging_early(manager):
+ space, lead, item = create_item(manager)
+ manager.team_store.consume_feed(space, "sam", manager.team_store.events(space)[-1]["seq"])
+ manager.team_store.transition(space, lead, item["id"], "canceled", comment="Stop now")
+ engine = manager.get_engine("worker")
+ engine.request_interrupt = Mock()
+ manager.mark_running("worker")
+ team = manager.teams.for_lead_session("lead")
+ assert asyncio.run(manager._drain_team_member(team, session_id="worker", actor="sam", is_lead=False)) == 0
+ engine.request_interrupt.assert_called_once()
+ assert manager.team_store.feed_for(space, "sam")
+
+
+def test_stale_assignment_does_not_restart_previous_owner(manager):
+ space, lead, item = create_item(manager)
+ manager.team_store.assign(space, lead, item["id"], "maya")
+ team = manager.teams.for_lead_session("lead")
+ events = manager.team_store.feed_for(space, "sam")
+ chosen = manager._actionable_team_events(team, events, actor="sam", is_lead=False)
+ assert len(chosen) == 1 and chosen[0]["payload"]["previous"] == "sam"
+
+
+def test_shared_scan_does_not_skip_human_note_behind_quiet_page(manager):
+ space, _, item = create_item(manager)
+ for _ in range(230):
+ manager.team_store.comment(space, SAM, item["id"], "Routine evidence")
+ note = manager.team_store.comment(space, Actor(id="user", role=Role.USER), item["id"], "Important new restriction")
+ manager.team_store.comment(space, SAM, item["id"], "Question", needs_attention=True)
+ assert asyncio.run(drain(manager)) == 0 # acknowledge first quiet page only
+ text, rows, receipt = manager._pending_board_context("lead")
+ assert "Important new restriction" in text
+ assert any(r["seq"] == note["seq"] for r in rows)
+ assert receipt["feed"] >= note["seq"]
+
+
+def test_watchdog_ignores_busy_workers_and_human_waits(manager):
+ space, _, item = create_item(manager)
+ manager.team_store.transition(space, SAM, item["id"], "in_progress")
+ team = manager.teams.for_lead_session("lead")
+ manager._team_last_alive["lead"] = time.time() - 700
+ manager.mark_running("worker")
+ assert not manager._lead_backstop_due(team)
+ manager._running_sessions.discard("worker")
+ prompt = manager.inbox.add_approval("worker", "Run check")
+ assert not manager._lead_backstop_due(team)
+ manager.inbox.resolve(prompt.id, "deny")
+ assert manager._lead_backstop_due(team)
+ manager._team_watchdog_alerted["lead"] = manager._stalled_team_state(team)
+ assert not manager._lead_backstop_due(team) # unchanged stall is not polling
+ manager.TEAM_LEAD_BACKSTOP_SECS = 0
+ assert not manager._lead_backstop_due(team)
+
+
+def test_native_question_and_transition_kick_delivery(manager):
+ space, lead, item = create_item(manager)
+ notify = Mock()
+ tools = {t.__name__: t for t in board_tools(manager.team_store, space=space, actor=SAM, on_change=notify)}
+ tools["comment"](item["id"], "Question", needs_attention=True)
+ tools["transition"](item["id"], "in_progress")
+ assert notify.call_count == 2
+ tools["set_status"](item["id"], "Reading evidence")
+ assert notify.call_count == 2
+
+
+def test_own_accepted_prerequisite_wakes_worker_with_more_work(manager):
+ space, lead, first = create_item(manager)
+ _, _, second = create_item(manager)
+ manager.team_store.link(space, lead, first["id"], "blocks", second["id"])
+ manager.team_store.transition(space, SAM, first["id"], "in_progress")
+ manager.team_store.transition(space, SAM, first["id"], "review")
+ manager.team_store.transition(space, lead, first["id"], "done")
+ team = manager.teams.for_lead_session("lead")
+ event = manager.team_store.events(space)[-1]
+ assert manager._actionable_team_events(team, [event], actor="sam", is_lead=False)
+
+
+def test_quiet_acknowledgement_survives_store_reopen(manager):
+ space, _, item = create_item(manager)
+ note = manager.team_store.comment(space, SAM, item["id"], "Routine detail")
+ assert asyncio.run(drain(manager)) == 0
+ reopened = TeamStore(manager.team_store.db_path)
+ try:
+ page = reopened.delivery_page(space, "lead", is_lead=True)
+ assert page["directs"] == [] and page["subs"] == []
+ assert reopened._cursor(f"feed:lead:{space}") >= note["seq"]
+ finally:
+ reopened.close()