Python
Board claims: store-stamped self-assignment + claims policy knob (OPE-100)
Rohit C Prasad9f6a3d383350
diff --git a/coworker/personas/builtin/swe-lead/manifest.md b/coworker/personas/builtin/swe-lead/manifest.mdindex 04dddf90..40ba0554 100644--- a/coworker/personas/builtin/swe-lead/manifest.md+++ b/coworker/personas/builtin/swe-lead/manifest.md@@ -33,7 +33,11 @@ How you run a piece of work:isn't: who owns what interface, who to ask about which decision.4. ASSIGN: assign items to actor ids. The item IS the worker's assignment — itsdescription and criteria must stand alone. Respect dependencies (link blocks/parent);- don't assign what's blocked.+ don't assign what's blocked. Workers (including external ones on this board) may+ also CLAIM open unassigned items themselves — a claim shows up in your digest;+ let good claims stand, reassign or cancel bad ones. To hold an item back from+ claiming, assign it to yourself; to turn claiming off board-wide, set the claim+ policy to lead-only.5. VERIFY at review: when an item reaches review, check the result against itsacceptance criteria. Implementation items should be verified by the test worker whenone is on the team — a builder never grades its own work: create a linkeddiff --git a/coworker/personas/builtin/swe-worker/manifest.md b/coworker/personas/builtin/swe-worker/manifest.mdindex 6acb8a0a..f3860ff0 100644--- a/coworker/personas/builtin/swe-worker/manifest.md+++ b/coworker/personas/builtin/swe-worker/manifest.md@@ -20,6 +20,9 @@ The team contract (this is how you work):criteria are the definition of done. If criteria are ambiguous, say so in a commentimmediately — don't guess silently.- Move your item to in_progress when you start.+- Out of assigned work but able to help? You may claim an OPEN, unassigned item+ (claim) — only one you can start on now. The lead sees every claim and may+ reassign; if the board refuses ("lead-only"), wait for assignment instead.- Blocked? Transition to blocked WITH a comment saying exactly what you need. Neverstall silently; never idle-wait. If other assigned items are workable, work them.- Journal as you go (journal_append): findings, evidence, decisions — with file:linediff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex 00f2b6ed..fd76e1fe 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -89,6 +89,7 @@ from ..teams import JournalStore, Role as TeamRole, TeamStore, board_tools, jourfrom ..teams.model import space_for_workspacefrom ..teams.chat import ChatStorefrom ..teams.registry import TeamRegistry, TeamWorker+from ..teams.tokens import BoardTokensfrom ..skills import (SessionSkillStore,SkillLoader,@@ -212,6 +213,9 @@ class SessionManager:self.team_store = TeamStore(base / "teams.db", journal=self.journal_store)self.chat_store = ChatStore(base / "chat.db")self.teams = TeamRegistry(base / "teams.json")+ # External board clients (OPE-100): join tokens bind actor+role; the+ # `/v1/board` API resolves them and the store enforces authority.+ self.board_tokens = BoardTokens(base / "board-tokens.json")self._team_inflight: set[str] = set()# Lead-session last-turn timestamps for the check-in backstop (monotonic-ish# wall clock; restart resets the clock rather than firing a wake storm).@@ -1828,6 +1832,13 @@ class SessionManager:),}+ def kick_team_tick(self) -> None:+ """Nudge the wake plumbing from outside the turn loop — e.g. after an+ external board client writes through the `/v1/board` API, so a review or a+ new filing reaches the lead now, not at the next 30s scheduler tick."""+ if self._loop is not None:+ asyncio.run_coroutine_threadsafe(self.team_tick(), self._loop)+async def team_tick(self) -> int:"""Drain team queues (called each scheduler tick + kicked after team turns).One wake consumes a burst as one digest; durable-until-consumed — the cursor@@ -1985,6 +1996,14 @@ class SessionManager:if event["kind"] == "item_assigned":if item is None:continue+ if payload.get("claimed"):+ # A self-claim surfacing in the lead's subscription feed —+ # supervision by exception, not an assignment to the reader.+ lines.append(+ f"{event['actor']} claimed {title} — it's theirs now;"+ " reassign or cancel if that's wrong."+ )+ continuelines.append(f"You've been assigned work item {title}.\n"f" Done when: {item['criteria']}"diff --git a/coworker/teams/store.py b/coworker/teams/store.pyindex 81871eb4..d8fe935b 100644--- a/coworker/teams/store.py+++ b/coworker/teams/store.py@@ -43,6 +43,12 @@ from .model import (GENESIS = "genesis"+# Board-level claim policy: "open" (default) lets any worker self-assign an open,+# unassigned item — the board works as a pull queue for a fleet of workers, local or+# external. "lead-only" turns claims off; assignment stays with the lead/user. A lead+# on an open board can still reserve individual items by assigning them to itself.+CLAIM_POLICIES = ("open", "lead-only")+# Event kinds. Chat lands later with the chat surface; the record shape already fits.# Journal entries live in their own case-keyed store (teams.journal) — cases outlive# boards, so they don't belong in a board's space-scoped log.@@ -137,6 +143,10 @@ class TeamStore:cursor_key TEXT PRIMARY KEY,consumed_seq INTEGER NOT NULL);+ CREATE TABLE IF NOT EXISTS team_settings (+ space TEXT PRIMARY KEY,+ claims TEXT NOT NULL DEFAULT 'open'+ );""")self._conn.commit()@@ -309,7 +319,7 @@ class TeamStore:key = f"sub:{subscriber}:{space}"events = self.events(space,- kinds=[ITEM_TRANSITIONED, ITEM_CREATED],+ kinds=[ITEM_TRANSITIONED, ITEM_CREATED, ITEM_ASSIGNED],since_seq=self._cursor(key),limit=limit,)@@ -322,6 +332,10 @@ class TeamStore:and event["payload"].get("to") not in self.SUBSCRIBED_TRANSITIONS):continue+ # Assignments only surface when they are CLAIMS — the lead supervises+ # self-service by exception; its own (and the user's) assigns are not news.+ if event["kind"] == ITEM_ASSIGNED and not event["payload"].get("claimed"):+ continueout.append(event)return out@@ -609,6 +623,72 @@ class TeamStore:)return self.get_item(space, item_id, seq=event["seq"])+ def claim(self, space: str, actor: Actor, item_id: int) -> dict[str, Any]:+ """Self-assign an open, unassigned item. Nobody stamps a claim — the store+ arbitrates: the open+unassigned check runs under the write lock, so when two+ workers race for the same item, exactly one wins and the other gets a clean+ error. A claim is a normal assignment event attributed to the claimer —+ visible in the lead's subscription feed and revocable like any assignment+ (reassign or cancel). Gated by the board's claim policy."""+ self._require(actor, {Role.USER, Role.LEAD, Role.WORKER}, "claim")+ with self._lock:+ if actor.role == Role.WORKER and self.policy(space)["claims"] != "open":+ raise AuthorityError(+ "claims are lead-only on this board — ask the lead to assign"+ " the item to you"+ )+ item = self._item(space, item_id)+ if ItemState(item["state"]) is not ItemState.OPEN:+ raise BoardError(+ f"item #{item_id} is {item['state']} — only open items can be"+ " claimed"+ )+ if item["assignee"]:+ raise BoardError(+ f"item #{item_id} is already claimed by {item['assignee']}"+ )+ event = self.append_event(+ space,+ ITEM_ASSIGNED,+ actor,+ item_id=item_id,+ case_id=item["case_id"] or None,+ payload={"assignee": actor.id, "previous": "", "claimed": True},+ )+ if self.journal is not None and item["case_id"]:+ self.journal.sync_assignment(+ item["case_id"],+ space=space,+ item_id=item_id,+ assignee=actor.id,+ previous="",+ )+ return self.get_item(space, item_id, seq=event["seq"])++ def policy(self, space: str) -> dict[str, Any]:+ with self._lock:+ row = self._conn.execute(+ "SELECT claims FROM team_settings WHERE space = ?", (space,)+ ).fetchone()+ return {"claims": row["claims"] if row else "open"}++ def set_policy(self, space: str, actor: Actor, *, claims: str) -> dict[str, Any]:+ """Board-level policy. Settings, not history — like cursors, this is+ infrastructure the log doesn't narrate."""+ self._require(actor, {Role.USER, Role.LEAD}, "set_policy")+ if claims not in CLAIM_POLICIES:+ raise BoardError(+ f"unknown claim policy: {claims} (use one of {CLAIM_POLICIES})"+ )+ with self._lock:+ self._conn.execute(+ "INSERT INTO team_settings (space, claims) VALUES (?, ?)"+ " ON CONFLICT(space) DO UPDATE SET claims = ?",+ (space, claims, claims),+ )+ self._conn.commit()+ return {"claims": claims}+def link(self, space: str, actor: Actor, src: int, kind: str, dst: int) -> dict[str, Any]:diff --git a/coworker/teams/tools.py b/coworker/teams/tools.pyindex 16054b80..fa4f8845 100644--- a/coworker/teams/tools.py+++ b/coworker/teams/tools.py@@ -21,8 +21,11 @@ from .store import TeamStoreLEAD_VERBS = ("create_item", "list_items", "transition", "comment", "assign", "link")# Workers file items too (a bug spotted in passing, a follow-up) — new items land-# `open` and unassigned; nothing runs until the lead/user assigns them.-WORKER_VERBS = ("create_item", "list_items", "transition", "comment")+# `open` and unassigned; nothing runs until the item is assigned. `claim` is+# 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")JOURNAL_VERBS = ("journal_append", "journal_read")# Explicit schema: the auto-generator's normalizer strips every `title` key to drop@@ -131,6 +134,12 @@ def board_tools(taint=taint(),)+ 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 _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 theworker's assignment — write the description and criteria accordingly."""diff --git a/tests/test_team_board.py b/tests/test_team_board.pyindex d9f3d320..abcd1c56 100644--- a/tests/test_team_board.py+++ b/tests/test_team_board.py@@ -203,7 +203,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"}+ assert worker_names == {"create_item", "list_items", "transition", "comment", "claim"}def test_tools_return_errors_instead_of_raising(store):