Skip to content
Python

Add structured outcome and staffing proposals

Rohit C Prasad4099fee5bca8
diff --git a/coworker/agent.py b/coworker/agent.py
index 6e6606f1..aeedf892 100644
--- a/coworker/agent.py
+++ b/coworker/agent.py
@@ -445,6 +445,9 @@ def build_engine(
registry.register_all(clock_tools())
instructions = f"{agent.system_prompt}\n\n{_NARRATION_GUIDANCE}\n\n{_FIRST_CONTACT_GUIDANCE}"
+ if agent.team == "lead":
+ from .teams.proposals import PROPOSAL_GUIDANCE
+ instructions += "\n\n" + PROPOSAL_GUIDANCE
if ws is not None:
instructions = f"{instructions}\n\n{environment_context(ws)}"
conventions = load_agents_md(ws)
diff --git a/coworker/engine.py b/coworker/engine.py
index a973e970..82ad0acf 100644
--- a/coworker/engine.py
+++ b/coworker/engine.py
@@ -1912,19 +1912,17 @@ class TurnEngine:
"""The decomposition gate: emit the proposed items, await the user's decision.
Approval creates them on the board (server-side, inside the approver) and the
result carries their ids; rejection returns feedback for a revised split."""
+ from .teams.proposals import validate_work_proposal
args = tool_call.arguments or {}
- items = args.get("items") or []
- valid = [
- i
- for i in items
- if isinstance(i, dict)
- and str(i.get("title", "")).strip()
- and str(i.get("criteria", "")).strip()
- ]
- if not valid or len(valid) != len(items):
+ problem = None
+ try:
+ args = validate_work_proposal(args)
+ except ValueError as error:
+ problem = str(error)
+ if problem:
result: dict[str, Any] = {
"approved": False,
- "error": "every proposed item needs a title and acceptance criteria",
+ "error": problem,
}
elif self.items_approver is None:
result = {
@@ -1934,7 +1932,7 @@ class TurnEngine:
else:
yield Event(
EventType.ITEMS_PROPOSED,
- {"items": valid, "note": str(args.get("note", "")), "tool_call_id": tool_call.id},
+ {**args, "tool_call_id": tool_call.id},
)
self._audit(tool_call, stage="items_proposed")
result = await self._wait_tool(tool_call,
@@ -2007,12 +2005,22 @@ class TurnEngine:
decision. Approval PRE-SPAWNS the worker sessions (server-side, inside the
approver) and the result carries the roster with actor ids so the lead can
assign; rejection returns the user's feedback for a revised proposal."""
+ from .teams.proposals import validate_team_proposal
+ from .teams.model import BoardError
args = tool_call.arguments or {}
- members = args.get("members") or []
- if not isinstance(members, list) or not members:
+ problem = None
+ try:
+ args = validate_team_proposal(args)
+ validator = getattr(self.team_approver, "validate", None)
+ if validator:
+ validator(args)
+ except (ValueError, BoardError) as error:
+ problem = str(error)
+ members = args.get("members", []) if isinstance(args, dict) else []
+ if problem:
result: dict[str, Any] = {
"approved": False,
- "error": "propose at least one member ({persona, model?, reason?})",
+ "error": problem,
}
elif self.team_approver is None:
result = {
@@ -2023,10 +2031,10 @@ class TurnEngine:
yield Event(
EventType.TEAM_PROPOSED,
{
+ **args,
"tool_call_id": tool_call.id,
"members": members,
"enable_chat": bool(args.get("enable_chat", False)),
- "note": str(args.get("note", "")),
},
)
self._audit(tool_call, stage="team_proposed")
diff --git a/coworker/personas/builtin/swe-lead/manifest.md b/coworker/personas/builtin/swe-lead/manifest.md
index 60f86af3..aab7f5d0 100644
--- a/coworker/personas/builtin/swe-lead/manifest.md
+++ b/coworker/personas/builtin/swe-lead/manifest.md
@@ -25,7 +25,7 @@ How you run a piece of work:
board is per-PROJECT and outlives sessions — before proposing anything, read it
(list_items) and triage leftovers from earlier efforts: reassign or cancel stale
in-progress items, never stack duplicates of existing open ones.
-2. PLAN: split the work into items with crisp acceptance criteria — "Done when:" that a
+2. PLAN: split the work into items with crisp acceptance criteria that a
verifier can actually check. Acceptance criteria are the single biggest quality lever
you own; vague criteria produce vague work. Criteria are 1–3 SHORT, independently
checkable statements — mechanics (setup commands, file paths, how-to) belong in the
diff --git a/coworker/server/manager.py b/coworker/server/manager.py
index c5b4fcb7..19a4476b 100644
--- a/coworker/server/manager.py
+++ b/coworker/server/manager.py
@@ -1554,6 +1554,12 @@ class SessionManager:
the item takes the queue's default like every other background prompt."""
async def approve(args, tool_call_id=None):
+ from ..teams.proposals import validate_team_proposal
+ try:
+ args = validate_team_proposal(args)
+ self.team_planned_items(session_id, args["members"])
+ except (ValueError, TeamsBoardError) as error:
+ return {"approved": False, "error": str(error)}
members = [dict(m) for m in (args.get("members") or []) if isinstance(m, dict)]
# The lead's connector suggestions (worker-connector-grants spec §2-4): inside a
# worker's default set on its own judgment; outside it ONLY on the human's words,
@@ -1597,6 +1603,7 @@ class SessionManager:
inbox=self.inbox_routing.route_for(session_id, agent),
tool_call_id=tool_call_id,
data={
+ "title": args["title"], "summary": args["summary"], "groups": args["groups"],
"gate": "team",
"enable_chat": bool(args.get("enable_chat", False)),
"note": str(args.get("note") or ""),
@@ -1622,24 +1629,36 @@ class SessionManager:
merged.append(
{
**{k: v for k, v in m.items() if k != "connectors"},
+ "name": str(d.get("name", m.get("name", ""))).strip(),
"connectors": list(d.get("connectors") or []),
"model_by_human": str(d.get("model") or "").strip(),
}
)
resolved = self.inbox.get(item.id)
+ try:
+ self.team_planned_items(session_id, merged)
+ except (ValueError, TeamsBoardError) as error:
+ return {"approved": False, "error": str(error)}
return self.create_team(
session_id, merged, enable_chat=enable_chat,
approved_by=str(getattr(resolved, "resolved_by", "") or ""),
)
+ # The engine checks board references before broadcasting the live card.
+ approve.validate = lambda args: self.team_planned_items(session_id, args["members"])
return approve
def inbox_items_approver(self, session_id: str, agent: str, *, visibility=None):
"""The decomposition gate for any turn (see inbox_team_approver)."""
async def approve(args, tool_call_id=None):
+ from ..teams.proposals import validate_work_proposal
+ try:
+ args = validate_work_proposal(args)
+ except ValueError as error:
+ return {"approved": False, "error": str(error)}
items = [i for i in (args.get("items") or []) if isinstance(i, dict)]
- body = "\n".join(f"- {i.get('title', '?')} — Done when: {i.get('criteria', '?')}" for i in items)
+ body = "\n".join(f"- {i.get('title', '?')} — Acceptance criteria: {i.get('criteria', '?')}" for i in items)
item = self.inbox.add_plan(
session_id,
"Approve the proposed work items?",
@@ -1647,7 +1666,7 @@ class SessionManager:
inbox=self.inbox_routing.route_for(session_id, agent),
tool_call_id=tool_call_id,
# Same fields as the inline `items_proposed` event, note included.
- data={"gate": "items", "items": items, "note": str(args.get("note") or "")},
+ data={"gate": "items", **args},
**({"visibility": visibility()} if visibility else {}),
)
if item.state == "pending":
@@ -1657,7 +1676,7 @@ class SessionManager:
resp = _parse_inbox_json(await self.inbox.wait(item.id))
if not resp.get("approved"):
return {"approved": False, "feedback": resp.get("feedback") or "the user declined the split"}
- return self.board_create_items(session_id, items)
+ return self.board_create_items(session_id, items, proposal=args)
return approve
@@ -2507,7 +2526,7 @@ class SessionManager:
return {"error": str(error)}
def board_create_items(
- self, session_id: str, items: list[dict[str, Any]]
+ self, session_id: str, items: list[dict[str, Any]], *, proposal: dict | None = None
) -> dict[str, Any]:
"""The decomposition gate's approved action: create the proposed items as
the LEAD (its identity is the creator; the user's approval is the gate that
@@ -2522,6 +2541,8 @@ class SessionManager:
persona=record.agent,
session_id=session_id,
)
+ if proposal is not None:
+ return self.team_store.create_proposal(space, actor, proposal)
for entry in items:
if not str((entry or {}).get("title", "")).strip() or not str(
(entry or {}).get("criteria", "")
@@ -3310,8 +3331,10 @@ class SessionManager:
continue
lines.append(
f"You've been assigned work item {title}.\n"
- f" Done when: {item['criteria']}"
+ f" Acceptance criteria: {item['criteria']}"
+ (f"\n Details: {item['description']}" if item["description"] else "")
+ + ("\n Approved proposal context (intent, not access grants): "
+ + json.dumps(item["proposal"], ensure_ascii=False) if item.get("proposal") else "")
)
rows.append({**row, "kind": "assigned", "assignee": assignee})
elif event["kind"] == "item_transitioned":
@@ -4219,6 +4242,32 @@ class SessionManager:
record = self.session_store.load(session_id)
return str(getattr(record, "model", "") or self.model)
+ def team_planned_items(self, session_id: str, members: list) -> list[dict]:
+ """Resolve declared responsibilities only within the lead's actual board."""
+ ids = list(dict.fromkeys(i for m in members for i in m.get("item_ids", [])))
+ if not ids:
+ return []
+ record = self.session_store.load(session_id)
+ if record is None or not record.workspace:
+ raise ValueError("planned responsibilities need a session workspace")
+ space = self._space_for(record, record.workspace)
+ actor = TeamActor(id=f"{record.agent}:{session_id[:8]}", role=TeamRole.LEAD,
+ persona=record.agent, session_id=session_id)
+ result = []
+ for item_id in ids:
+ item = self.team_store.get_item(space, item_id, actor=actor)
+ if item["state"] == "canceled":
+ raise ValueError(f"item {item_id} is canceled; revise planned responsibilities")
+ row = {"id": item_id, "title": item["title"]}
+ context = item.get("proposal")
+ if context:
+ final_id = context["item_ids"][context["final_acceptance"]["item_key"]]
+ final = self.team_store.get_item(space, final_id, actor=actor)
+ row["final_acceptance"] = {"id": final_id, "title": final["title"],
+ "owner": "lead" if final["assignee"] == actor.id else "assigned_worker"}
+ result.append(row)
+ return result
+
def team_card_extras(self, session_id: str, members: list) -> dict[str, Any]:
"""Everything the staffing card needs beyond the lead's raw proposal, computed on
THIS machine (where the workers will run): the connector offer, the other connected
@@ -4246,6 +4295,7 @@ class SessionManager:
runnable = [m for m in self._curated_models() if self.model_selectable(m)]
return {
"members": decorated,
+ "planned_items": self.team_planned_items(session_id, members),
"offer": {pid: self.connector_offer(pid) for pid in dict.fromkeys(personas)},
"other_connected": self.other_connected(),
"lead_mode": self.session_mode_value(session_id),
diff --git a/coworker/teams/proposals.py b/coworker/teams/proposals.py
new file mode 100644
index 00000000..82d01f90
--- /dev/null
+++ b/coworker/teams/proposals.py
@@ -0,0 +1,167 @@
+"""Structured proposal intent. Declarations never grant execution authority."""
+from __future__ import annotations
+
+import re
+from copy import deepcopy
+
+
+def obj(properties, required=None):
+ return {"type": "object", "properties": properties, "required": required or list(properties), "additionalProperties": False}
+
+
+TEXT = {"type": "string", "minLength": 1, "maxLength": 600}
+KEY = {"type": "string", "pattern": "^[a-z][a-z0-9_-]{0,47}$"}
+
+
+def array(item, minimum=0, maximum=100):
+ return {"type": "array", "items": item, "minItems": minimum, "maxItems": maximum}
+
+
+GROUP = obj({"id": KEY, "title": TEXT, "summary": TEXT})
+EXTERNAL_ACTIONS = obj({
+ "status": {"type": "string", "enum": ["none", "planned", "undetermined"]},
+ "actions": array(TEXT, maximum=20),
+ "exclusions": array(TEXT, maximum=20),
+ "explanation": TEXT,
+})
+WORK_PROPOSAL_SCHEMA = obj({
+ "title": TEXT, "summary": TEXT,
+ "targets": array(TEXT, 1, 20),
+ "external_actions": EXTERNAL_ACTIONS,
+ "activities": array(GROUP, 1, 12),
+ "workstreams": array(GROUP, 1, 24),
+ "items": array(obj({
+ "key": KEY, "title": TEXT, "criteria": TEXT,
+ "description": {"type": "string", "maxLength": 8000},
+ "case": {"type": "string", "maxLength": 200},
+ "activity": KEY, "workstream": KEY,
+ "depends_on": array(KEY), "verifies": array(KEY),
+ }, ["key", "title", "criteria", "activity", "workstream", "depends_on", "verifies"]), 1),
+ "final_acceptance": obj({"item_key": KEY, "owner": {"type": "string", "enum": ["lead", "assigned_worker"]}}),
+})
+TEAM_PROPOSAL_SCHEMA = obj({
+ "title": TEXT, "summary": TEXT, "groups": array(GROUP, 1, 24),
+ "members": array(obj({
+ "persona": TEXT, "name": TEXT, "model": TEXT, "reason": TEXT,
+ "group": KEY, "item_ids": array({"type": "integer", "minimum": 1}),
+ "connectors": array(TEXT, maximum=30),
+ "connector_reasons": {"type": "object", "additionalProperties": TEXT},
+ }, ["persona", "name", "reason", "group", "item_ids"]), 1),
+ "enable_chat": {"type": "boolean"},
+})
+
+
+def _check(value, schema, path):
+ kind = schema["type"]
+ types = {"object": dict, "array": list, "string": str, "integer": int, "boolean": bool}
+ if not isinstance(value, types[kind]) or (kind == "integer" and isinstance(value, bool)):
+ raise ValueError(f"{path} must be {kind}")
+ if "enum" in schema and value not in schema["enum"]:
+ raise ValueError(f"{path} must be one of {schema['enum']}")
+ if kind == "object":
+ props = schema.get("properties", {})
+ for key in schema.get("required", []):
+ if key not in value:
+ raise ValueError(f"{path}.{key} is required; supply explicit proposal information")
+ for key, child in value.items():
+ rule = props.get(key, schema.get("additionalProperties", False))
+ if not rule:
+ raise ValueError(f"{path}.{key} is not a supported proposal field")
+ _check(child, rule, f"{path}.{key}")
+ elif kind == "array":
+ if not schema.get("minItems", 0) <= len(value) <= schema.get("maxItems", 100):
+ raise ValueError(f"{path} has an invalid number of entries")
+ for i, child in enumerate(value):
+ _check(child, schema["items"], f"{path}[{i}]")
+ elif kind == "string":
+ if not schema.get("minLength", 0) <= len(value.strip()) <= schema.get("maxLength", 10000):
+ raise ValueError(f"{path} must be concise and nonempty")
+ if "pattern" in schema and not re.fullmatch(schema["pattern"], value):
+ raise ValueError(f"{path} must be a short lowercase identifier")
+ elif kind == "integer" and value < schema.get("minimum", 0):
+ raise ValueError(f"{path} must be positive")
+
+
+def _unique(rows, key, label):
+ ids = [r[key] for r in rows]
+ if len(set(ids)) != len(ids):
+ raise ValueError(f"{label} must have unique {key} values")
+ return set(ids)
+
+
+def validate_work_proposal(args):
+ _check(args, WORK_PROPOSAL_SCHEMA, "proposal")
+ acts = _unique(args["activities"], "id", "activities")
+ streams = _unique(args["workstreams"], "id", "workstreams")
+ keys = _unique(args["items"], "key", "items")
+ external = args["external_actions"]
+ if bool(external["actions"]) != (external["status"] == "planned"):
+ raise ValueError("external_actions.actions must list actions only when status is planned; use explanation for uncertainty")
+ if args["final_acceptance"]["item_key"] not in keys:
+ raise ValueError("final_acceptance.item_key must reference a proposed task")
+ for item in args["items"]:
+ if item["activity"] not in acts or item["workstream"] not in streams:
+ raise ValueError(f"{item['key']}: unknown activity or workstream")
+ for field in ("depends_on", "verifies"):
+ refs = item[field]
+ if len(refs) != len(set(refs)) or any(r not in keys or r == item["key"] for r in refs):
+ raise ValueError(f"{item['key']}.{field}: use unique, existing, other task keys")
+ graph = {i["key"]: i["depends_on"] for i in args["items"]}
+ visited, active = set(), set()
+ def visit(key):
+ if key in active:
+ raise ValueError("depends_on contains a cycle; grouping is not sequencing")
+ if key not in visited:
+ active.add(key)
+ for ref in graph[key]:
+ visit(ref)
+ active.remove(key)
+ visited.add(key)
+ for key in graph:
+ visit(key)
+ if acts != {i["activity"] for i in args["items"]} or streams != {i["workstream"] for i in args["items"]}:
+ raise ValueError("every activity and workstream must contain at least one task")
+ return deepcopy(args)
+
+
+def validate_team_proposal(args):
+ _check(args, TEAM_PROPOSAL_SCHEMA, "proposal")
+ groups = _unique(args["groups"], "id", "groups")
+ _unique(args["members"], "name", "members")
+ names = [m["name"].strip().lower() for m in args["members"]]
+ if len(set(names)) != len(names) or any(not re.fullmatch(r"[a-z0-9][a-z0-9._-]{0,23}", name)
+ or name in {"lead", "user", "board"} for name in names):
+ raise ValueError("worker names must be unique mention-safe callnames, max 24 characters; lead/user/board are reserved")
+ for member in args["members"]:
+ if member["group"] not in groups:
+ raise ValueError("each member must reference a declared group")
+ if len(member["item_ids"]) != len(set(member["item_ids"])):
+ raise ValueError("item_ids must be unique per worker")
+ if groups != {m["group"] for m in args["members"]}:
+ raise ValueError("every staffing group must contain a worker")
+ return deepcopy(args)
+
+
+PROPOSAL_GUIDANCE = """Proposal cards are structured decisions, not essays. Use propose_work_items with a short
+customer outcome (title, summary), explicit targets, domain-appropriate activities and
+workstreams (id/title/summary), and tasks keyed within this proposal. Categories do not
+imply sequencing: depends_on names actual prerequisite keys; verifies names tasks being
+independently checked. Criteria are 1–3 concise, testable statements, without a label.
+Name a real final_acceptance item and its owner (lead or assigned_worker).
+Declare external_actions explicitly: status none, planned, or undetermined; actions lists
+only concrete planned external actions, exclusions lists only explicit exclusions, and
+explanation states the basis or uncertainty. Never infer local-only from missing connectors.
+Active scans contact external systems. Clarify uncertain security targets/authorization
+before scanning. These declarations describe intent, never grant execution permission.
+Surface changes to external-action intent to the user before acting beyond the approved plan.
+For staffing, propose_team supplies title, summary, groups and each member's group, reason,
+and item_ids (approved board IDs, not proposal keys). These are planned responsibilities,
+not assignments. Use an empty item_ids list for standing workers with no current task.
+Call team_options first. Suggest only connected, policy-allowed connectors in members[].
+connectors; connector_reasons gives one short reason per suggestion. Outside the worker's
+usual set, quote the user's request. Suggestions only pre-tick the card; the human decides.
+Group labels fit the domain: engineering Build/Verify, security Assess/Remediate/Validate,
+marketing Research/Create/Review. Name staffing groups for their actual responsibilities,
+not their implementation persona: a swe-worker doing security belongs in Assessment &
+remediation, not automatically Build. Do not invent isolation, machine placement, or access.
+"""
diff --git a/coworker/teams/store.py b/coworker/teams/store.py
index d881917e..809530b9 100644
--- a/coworker/teams/store.py
+++ b/coworker/teams/store.py
@@ -168,7 +168,7 @@ class TeamStore:
);
""")
columns = {row[1] for row in self._conn.execute("PRAGMA table_info(team_items)")}
- for column in ("status", "status_ts"):
+ for column in ("status", "status_ts", "proposal"):
if column not in columns:
self._conn.execute(f"ALTER TABLE team_items ADD COLUMN {column} TEXT NOT NULL DEFAULT ''")
self._conn.commit()
@@ -232,6 +232,7 @@ class TeamStore:
recipient: Optional[str],
payload: dict[str, Any],
taint: bool,
+ commit: bool = True,
) -> dict[str, Any]:
prev = self._head_hash(space)
record = {
@@ -282,7 +283,8 @@ class TeamStore:
""",
(space, record["hash"], seq, record["hash"], seq),
)
- self._conn.commit()
+ if commit:
+ self._conn.commit()
return {**record, "seq": seq, "payload": payload}
def events(
@@ -486,6 +488,45 @@ class TeamStore:
# ------------------------------------------------------------------ board verbs
+ def create_proposal(self, space: str, actor: Actor, proposal: dict) -> dict:
+ """Atomically materialize an accepted plan, its intent and dependency links."""
+ from .proposals import validate_work_proposal
+ proposal = validate_work_proposal(proposal)
+ self._require(actor, {Role.USER, Role.LEAD}, "create_proposal")
+ # Journal failures must not leave committed board items followed by an error
+ # that encourages the lead to retry the whole proposal.
+ if self.journal is not None:
+ for case in {i.get("case") for i in proposal["items"]} - {None, ""}:
+ self.journal.ensure_case(case, actor.id)
+ common = {k: v for k, v in proposal.items() if k != "items"}
+ with self._lock:
+ first = self._next_item_id(space)
+ ids = {item["key"]: first + i for i, item in enumerate(proposal["items"])}
+ def append(kind, item_id, payload, case=None):
+ return self._append_locked(space, kind, actor, item_id=item_id,
+ case_id=case, recipient=None, payload=payload, taint=False, commit=False)
+ try:
+ for item in proposal["items"]:
+ metadata = {**common, "key": item["key"], "activity": item["activity"],
+ "workstream": item["workstream"], "item_ids": ids,
+ "verifies": [ids[k] for k in item["verifies"]]}
+ append(ITEM_CREATED, ids[item["key"]], {**item, "proposal": metadata}, item.get("case"))
+ for item in proposal["items"]:
+ for prerequisite in item["depends_on"]:
+ append(ITEM_LINKED, ids[prerequisite], {"src": ids[prerequisite],
+ "kind": "blocks", "dst": ids[item["key"]]})
+ # Reserving the explicit lead-owned acceptance item does not execute it.
+ final = proposal["final_acceptance"]
+ if final["owner"] == "lead":
+ append(ITEM_ASSIGNED, ids[final["item_key"]], {"assignee": actor.id, "previous": ""})
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
+ return {"approved": True, "items": [{"id": ids[i["key"]], "key": i["key"],
+ "title": i["title"]} for i in proposal["items"]],
+ "note": "Items and dependency links created. Staff and assign to start work; declared external actions are not permission grants."}
+
def create_item(
self,
space: str,
@@ -979,6 +1020,9 @@ class TeamStore:
seq,
),
)
+ if payload.get("proposal"):
+ self._conn.execute("UPDATE team_items SET proposal = ? WHERE space = ? AND id = ?",
+ (_canonical(payload["proposal"]), space, item_id))
if payload.get("parent") is not None:
self._conn.execute(
"INSERT OR IGNORE INTO team_links (space, src, kind, dst)"
@@ -1323,6 +1367,7 @@ def _hash(record: dict[str, Any], *, fields: tuple[str, ...] = _HASHED_FIELDS) -
def _row_to_item(row: sqlite3.Row) -> dict[str, Any]:
item = dict(row)
+ item["proposal"] = json.loads(item.get("proposal") or "null")
try:
item["refs"] = json.loads(item.get("refs") or "[]")
except json.JSONDecodeError:
diff --git a/coworker/teams/tools.py b/coworker/teams/tools.py
index ce3e4594..96bfcac9 100644
--- a/coworker/teams/tools.py
+++ b/coworker/teams/tools.py
@@ -17,6 +17,7 @@ import aisuite as ai
from .journal import JournalStore
from .model import Actor, BoardError, Role
+from .proposals import WORK_PROPOSAL_SCHEMA, TEAM_PROPOSAL_SCHEMA, PROPOSAL_GUIDANCE
from .store import TeamStore
LEAD_VERBS = ("create_item", "list_items", "get_item", "transition", "comment", "assign", "link")
@@ -288,37 +289,7 @@ _PROPOSE_TEAM_SCHEMA = {
" approval creates the worker sessions and returns the handles. Only"
" team-capable worker coworkers may be proposed."
),
- "parameters": {
- "type": "object",
- "properties": {
- "members": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "persona": {"type": "string"},
- "name": {"type": "string"},
- "model": {"type": "string"},
- "reason": {"type": "string"},
- "connectors": {
- "type": "array",
- "items": {"type": "string"},
- "description": "Connectors THIS worker needs (from team_options). They arrive pre-ticked for the user, who decides.",
- },
- "connector_reasons": {
- "type": "object",
- "additionalProperties": {"type": "string"},
- "description": "One short reason per suggested connector. Outside the worker's usual set, quote the user's own request.",
- },
- },
- "required": ["persona", "name"],
- },
- },
- "enable_chat": {"type": "boolean"},
- "note": {"type": "string"},
- },
- "required": ["members"],
- },
+ "parameters": TEAM_PROPOSAL_SCHEMA,
},
}
@@ -340,34 +311,19 @@ _PROPOSE_ITEMS_SCHEMA = {
" and works in any mode — it is how a lead plans and coordinates via"
" the board."
),
- "parameters": {
- "type": "object",
- "properties": {
- "items": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "title": {"type": "string"},
- "criteria": {"type": "string"},
- "description": {"type": "string"},
- "case": {"type": "string"},
- },
- "required": ["title", "criteria"],
- },
- },
- "note": {"type": "string"},
- },
- "required": ["items"],
- },
+ "parameters": WORK_PROPOSAL_SCHEMA,
},
}
+_PROPOSE_ITEMS_SCHEMA["function"]["description"] += "\n" + PROPOSAL_GUIDANCE
+_PROPOSE_TEAM_SCHEMA["function"]["description"] += "\n" + PROPOSAL_GUIDANCE
+
+
def propose_work_items_tool() -> object:
- def propose_work_items(items: Optional[list] = None, note: str = "") -> dict:
- """Present proposed work items ({title, criteria, description?, case?})
- for the user's approval; approval creates them on the board."""
+ def propose_work_items(**proposal) -> dict:
+ """Present a structured outcome, workstreams, criteria and declared actions.
+ Approval materializes the plan and dependency links on the board."""
return {
"approved": False,
"error": "item proposals aren't available in this surface",
@@ -386,11 +342,8 @@ def propose_work_items_tool() -> object:
def propose_team_tool() -> object:
- def propose_team(
- members: Optional[list] = None, enable_chat: bool = False, note: str = ""
- ) -> dict:
- """Propose the worker roster for this board (the staffing gate). Each member
- is {persona, name, model?, reason?, connectors?, connector_reasons?}. Call
+ def propose_team(**proposal) -> dict:
+ """Propose grouped workers with planned responsibilities (the staffing gate). Call
team_options first: it says which connectors each worker can be given here. The
user approves and has the final say on connectors; approval creates the worker
sessions and returns their actor ids for assignment."""
diff --git a/surfaces/gui/e2e/card-gallery.spec.ts b/surfaces/gui/e2e/card-gallery.spec.ts
index 1468ab90..b9968687 100644
--- a/surfaces/gui/e2e/card-gallery.spec.ts
+++ b/surfaces/gui/e2e/card-gallery.spec.ts
@@ -36,7 +36,7 @@ test("the same state renders as the parked Inbox item and resolves with the full
test("the rail switches cards and lands on the card's first state", async ({ page }) => {
await page.goto("/#/gallery");
await page.getByTestId("gallery-card-work-items").click();
- await expect(page).toHaveURL(/#\/gallery\/work-items\/three-items$/);
+ await expect(page).toHaveURL(/#\/gallery\/work-items\/launch-plan$/);
await expect(page.getByTestId("itemsreq-card")).toBeVisible();
});
diff --git a/surfaces/gui/e2e/fixtures.ts b/surfaces/gui/e2e/fixtures.ts
index ecafc674..6c831705 100644
--- a/surfaces/gui/e2e/fixtures.ts
+++ b/surfaces/gui/e2e/fixtures.ts
@@ -755,8 +755,8 @@ export async function mockApi(page: import("@playwright/test").Page) {
send("turn_done");
return;
}
- if (/propose the split/i.test(msg.text)) {
- sendState("items_proposed", "work-items", "statements-split");
+ if (/propose the split|propose security split/i.test(msg.text)) {
+ sendState("items_proposed", "work-items", /security/.test(msg.text) ? "security-plan" : "statements-split");
return; // suspended on the items decision
}
// Agent teams (OPE-97): the staffing gate — the lead proposes a roster and
diff --git a/surfaces/gui/e2e/proposal-cards.spec.ts b/surfaces/gui/e2e/proposal-cards.spec.ts
new file mode 100644
index 00000000..ea9cec39
--- /dev/null
+++ b/surfaces/gui/e2e/proposal-cards.spec.ts
@@ -0,0 +1,61 @@
+import { test, expect } from "@playwright/test";
+
+for (const theme of ["light", "dark"]) {
+ for (const width of ["wide", "narrow"]) {
+ test(`proposal cards: ${theme}, ${width}`, async ({ page }) => {
+ await page.goto("/#/gallery/work-items/security-plan");
+ await page.getByTestId(`gallery-theme-${theme}`).click();
+ if (width === "narrow")
+ await page.getByTestId("gallery-width-narrow").click();
+ const card = page.getByTestId("itemsreq-card");
+ await expect(card).toContainText("sandbox-1");
+ await expect(card.getByTestId("proposal-external-actions")).toContainText(
+ "Planned actions",
+ );
+ await card.locator("summary").first().click();
+ await expect(card.getByText("Acceptance criteria").first()).toBeVisible();
+ await expect(
+ card.getByText(
+ "Findings identify affected code and include reproducible evidence.",
+ ),
+ ).toBeVisible();
+ expect(
+ await card.evaluate((el) => el.scrollWidth <= el.clientWidth + 1),
+ ).toBe(true);
+ await card.getByRole("button", { name: "Request changes" }).click();
+ await card
+ .getByLabel("What should change?")
+ .fill("Keep scans in staging");
+ await card.getByRole("button", { name: "Send feedback" }).click();
+ await expect(page.getByTestId("gallery-response")).toContainText(
+ '"approved": false',
+ );
+ await expect(page.getByTestId("gallery-response")).toContainText(
+ "Keep scans in staging",
+ );
+
+ await page.goto("/#/gallery/team-request/launch-team?place=inbox");
+ if (theme === "dark")
+ await page.getByTestId("gallery-theme-dark").click();
+ if (width === "narrow")
+ await page.getByTestId("gallery-width-narrow").click();
+ const team = page.getByTestId("teamreq-card");
+ await team.locator("summary").first().click();
+ await expect(team.getByTestId("teamreq-row-0")).toContainText(
+ "Launch plan data & API",
+ );
+ await team.getByLabel("Worker name").first().fill("sam-custom");
+ await team.getByTestId("teamreq-chat-toggle").uncheck();
+ expect(
+ await team.evaluate((el) => el.scrollWidth <= el.clientWidth + 1),
+ ).toBe(true);
+ await team.getByTestId("teamreq-approve").click();
+ await expect(page.getByTestId("gallery-response")).toContainText(
+ "sam-custom",
+ );
+ await expect(page.getByTestId("gallery-response")).toContainText(
+ '"enable_chat": false',
+ );
+ });
+ }
+}
diff --git a/surfaces/gui/e2e/team.spec.ts b/surfaces/gui/e2e/team.spec.ts
index e323a7c8..80c59032 100644
--- a/surfaces/gui/e2e/team.spec.ts
+++ b/surfaces/gui/e2e/team.spec.ts
@@ -13,6 +13,22 @@ async function proposeTeam(page: import("@playwright/test").Page) {
await expect(page.getByTestId("teamreq-card")).toBeVisible();
}
+test("a rich proposal keeps its actions and composer reachable in a short window", async ({ page }) => {
+ await page.setViewportSize({ width: 1000, height: 700 });
+ await page.goto("/");
+ await page.getByPlaceholder(/Ask the coworker/).fill("propose security split");
+ await page.getByRole("button", { name: "Send" }).click();
+ const card = page.getByTestId("itemsreq-card");
+ await card.locator("summary").first().click();
+ const approve = page.getByTestId("itemsreq-approve");
+ await expect(approve).toBeInViewport();
+ await expect(page.getByPlaceholder(/Reply to adjust the proposal/)).toBeInViewport();
+ const bounds = await card.boundingBox();
+ expect(bounds!.y).toBeGreaterThanOrEqual(0);
+ await approve.click();
+ await expect(card).toHaveCount(0);
+});
+
test("the decomposition gate shows items with criteria; approval lands them on the board", async ({
page,
}) => {
@@ -22,17 +38,11 @@ test("the decomposition gate shows items with criteria; approval lands them on t
const card = page.getByTestId("itemsreq-card");
await expect(card).toBeVisible();
await expect(card).toContainText("Proposed work items — 4");
- await expect(card).toContainText("Done when:");
- // 3 visible + expander with the true remainder
- await expect(card.getByText("Verification pass")).toHaveCount(0);
- await card.getByRole("button", { name: /1 more item/ }).click();
+ await expect(card).toContainText("Acceptance criteria");
await expect(card.getByText("Verification pass")).toBeVisible();
// essay-length criteria clamp behind a per-item expander (owner-hit 2026-08-16)
- const acToggle = page.getByTestId("itemsreq-ac-toggle-0");
- await expect(acToggle).toHaveText("Show full criteria");
- await acToggle.click();
- await expect(acToggle).toHaveText("Show less");
+ await expect(card).toContainText("inclusive boundaries verified end to end");
// the short-criteria items get no toggle
await expect(page.getByTestId("itemsreq-ac-toggle-1")).toHaveCount(0);
@@ -83,7 +93,9 @@ test("declining the split returns feedback to the lead", async ({ page }) => {
await page.getByPlaceholder(/Ask the coworker/).fill("propose the split");
await page.getByRole("button", { name: "Send" }).click();
await page.getByTestId("itemsreq-card").waitFor();
- await page.getByRole("button", { name: "Not now" }).click();
+ await page.getByRole("button", { name: "Request changes" }).click();
+ await page.getByLabel("What should change?").fill("Revise the task split");
+ await page.getByRole("button", { name: "Send feedback" }).click();
await expect(page.getByText(/reworking the split/)).toBeVisible();
});
@@ -104,11 +116,8 @@ test("the staffing gate shows named workers, the chat toggle, and one-line butto
await expect(card).not.toContainText("Approving grants the lead");
const approve = card.getByTestId("teamreq-approve");
await expect(approve).toHaveText("Create team");
- await expect(approve).toHaveAttribute(
- "title",
- /Approving grants the lead create, assign & steer — this team only, revocable\./,
- );
- await expect(card.getByRole("button", { name: "Not now" })).toBeVisible();
+ await expect(card).toContainText("does not start these tasks");
+ await expect(card.getByRole("button", { name: "Request changes" })).toBeVisible();
});
test("enabling chat at the gate adds the # team chat row; posting works with mentions", async ({
@@ -166,7 +175,9 @@ test("with chat declined at the gate, no chat row renders", async ({ page }) =>
test("declining the roster returns the turn to the lead", async ({ page }) => {
await proposeTeam(page);
- await page.getByRole("button", { name: "Not now" }).click();
+ await page.getByRole("button", { name: "Request changes" }).click();
+ await page.getByLabel("What should change?").fill("Revise the roster");
+ await page.getByRole("button", { name: "Send feedback" }).click();
await expect(page.getByText(/tell me how to change the roster/)).toBeVisible();
await expect(page.getByTestId("teamreq-card")).toHaveCount(0);
});
@@ -255,10 +266,7 @@ test("the staffing card carries connector checkboxes and states that approvals f
await card.getByTestId("teamreq-connector-1-linear").check();
await expect(card.getByTestId("teamreq-beyond-1")).toContainText("Beyond this worker's usual set");
await expect(card.getByTestId("teamreq-connector-1-linear")).toBeChecked();
- await expect(card.getByTestId("teamreq-approve")).toHaveAttribute(
- "title",
- /Workers get only the connectors you tick\./,
- );
+ await expect(card.getByTestId("proposal-connector-summary")).toContainText("GitHub");
// the approvals line reads the composer's mode…
await expect(card.getByTestId("teamreq-approvals")).toContainText("Approvals follow the lead's mode: Ask for approval");
// …and follows it live when the mode changes in the composer
diff --git a/surfaces/gui/e2e/union-v15.spec.ts b/surfaces/gui/e2e/union-v15.spec.ts
index f168209b..3112e3d9 100644
--- a/surfaces/gui/e2e/union-v15.spec.ts
+++ b/surfaces/gui/e2e/union-v15.spec.ts
@@ -184,7 +184,7 @@ test("team chat and journal of a cloud lead session route via the proxy", async
await expect(page.getByTestId("rail-toggle-team")).toBeVisible({ timeout: 12_000 });
await page.getByTestId("rail-toggle-team").click();
- await page.getByTestId("team-chat-row").click();
+ await page.getByTestId("team-chat-action").click();
await expect(page.getByTestId("teamchat-view")).toBeVisible();
await expect
diff --git a/surfaces/gui/src/cardPayloads.ts b/surfaces/gui/src/cardPayloads.ts
index c36533b9..84f91725 100644
--- a/surfaces/gui/src/cardPayloads.ts
+++ b/surfaces/gui/src/cardPayloads.ts
@@ -46,6 +46,7 @@ export function planItemFromPayload(d: any): PlanItem {
export function teamItemFromPayload(d: any): TeamRequestItem {
return {
kind: "teamreq",
+ title: d.title, summary: d.summary, groups: d.groups, planned_items: d.planned_items,
toolCallId: typeof d.tool_call_id === "string" ? d.tool_call_id : undefined,
members: Array.isArray(d.members) ? d.members : [],
enable_chat: !!d.enable_chat,
@@ -73,6 +74,8 @@ export function connectorItemFromPayload(d: any): ConnectorRequestItem {
/** `items_proposed`, or a parked `gate: "items"` item. */
export function workItemsItemFromPayload(d: any): WorkItemsItem {
return { kind: "itemsreq", toolCallId: typeof d.tool_call_id === "string" ? d.tool_call_id : undefined,
+ title: d.title, summary: d.summary, targets: d.targets, external_actions: d.external_actions,
+ activities: d.activities, workstreams: d.workstreams, final_acceptance: d.final_acceptance,
items: Array.isArray(d.items) ? d.items : [], note: d.note || "" };
}
diff --git a/surfaces/gui/src/components/Icon.tsx b/surfaces/gui/src/components/Icon.tsx
index 231f6a84..0e17504c 100644
--- a/surfaces/gui/src/components/Icon.tsx
+++ b/surfaces/gui/src/components/Icon.tsx
@@ -26,6 +26,8 @@ export type IconName =
| "pencil"
| "branch"
| "arrowLeft"
+ | "arrowRight"
+ | "team"
| "copy"
| "refresh"
| "panelClose"
@@ -114,6 +116,10 @@ export function Icon({
<path d="M15 4.5v15" />
</svg>
);
+ case "team":
+ return <svg {...s}><circle cx="9" cy="7" r="3" /><path d="M3 21v-3a6 6 0 0 1 12 0v3M16 4a3 3 0 0 1 0 6M18 13a5 5 0 0 1 3 5v3" /></svg>;
+ case "arrowRight":
+ return <svg {...s}><path d="M5 12h14M13 6l6 6-6 6" /></svg>;
case "user":
return (
<svg {...s}>
diff --git a/surfaces/gui/src/components/ProposalCards.test.tsx b/surfaces/gui/src/components/ProposalCards.test.tsx
new file mode 100644
index 00000000..e5533cd3
--- /dev/null
+++ b/surfaces/gui/src/components/ProposalCards.test.tsx
@@ -0,0 +1,114 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { WorkItemsCard } from "./WorkItemsCard";
+import { TeamRequestCard } from "./TeamRequestCard";
+import { workItemsItemFromPayload, teamItemFromPayload } from "../cardPayloads";
+import {
+ launchProposal,
+ securityProposal,
+ marketingProposal,
+ launchTeam,
+} from "../gallery/states/proposal-examples";
+
+afterEach(cleanup);
+describe("structured proposal cards", () => {
+ it("renders declared activities and references without inferring sequence", () => {
+ render(
+ <WorkItemsCard
+ item={workItemsItemFromPayload(launchProposal)}
+ onRespond={vi.fn()}
+ />,
+ );
+ expect(screen.getByTestId("itemsreq-card").textContent).toContain(
+ "7 Build",
+ );
+ expect(screen.getAllByText("Acceptance criteria")).toHaveLength(11);
+ expect(
+ screen.getByTestId("proposal-external-actions").textContent,
+ ).toContain("None planned");
+ expect(screen.getByText("Owner: Lead")).toBeTruthy();
+ expect(screen.queryByText(/can start now/i)).toBeNull();
+ });
+
+ it("renders security targets, scans, exclusions and actual declaration", () => {
+ render(
+ <WorkItemsCard
+ item={workItemsItemFromPayload(securityProposal)}
+ onRespond={vi.fn()}
+ />,
+ );
+ expect(
+ screen.getByTestId("proposal-external-actions").textContent,
+ ).toContain("Run authenticated checks against sandbox-1");
+ expect(screen.getByText("2 Assess")).toBeTruthy();
+ expect(screen.queryByText("None planned")).toBeNull();
+ });
+
+ it("does not mistake missing decisions for no external actions", () => {
+ render(
+ <WorkItemsCard
+ item={workItemsItemFromPayload(marketingProposal)}
+ onRespond={vi.fn()}
+ />,
+ );
+ expect(screen.getByText("Not yet determined")).toBeTruthy();
+ expect(screen.queryByText("None planned")).toBeNull();
+ });
+
+ it("preserves feedback without granting approval", () => {
+ const respond = vi.fn();
+ render(
+ <WorkItemsCard
+ item={workItemsItemFromPayload(securityProposal)}
+ onRespond={respond}
+ />,
+ );
+ fireEvent.click(screen.getByText("Request changes"));
+ fireEvent.change(screen.getByRole("textbox"), {
+ target: { value: "No active scans" },
+ });
+ fireEvent.click(screen.getByText("Send feedback"));
+ expect(respond).toHaveBeenCalledWith(false, "No active scans");
+ });
+
+ it("uses declared worker groups and sends the edited name and chosen grants", () => {
+ const respond = vi.fn();
+ render(
+ <TeamRequestCard
+ item={teamItemFromPayload(launchTeam)}
+ onRespond={respond}
+ />,
+ );
+ expect(screen.getByText("Builders")).toBeTruthy();
+ expect(screen.getByText("Verifiers")).toBeTruthy();
+ expect(screen.getByText("Owner: Lead")).toBeTruthy();
+ expect(screen.getAllByText("Planned responsibilities")).toHaveLength(10);
+ fireEvent.change(screen.getAllByLabelText("Worker name")[0], {
+ target: { value: "sam-custom" },
+ });
+ fireEvent.click(screen.getByTestId("teamreq-approve"));
+ expect(respond.mock.calls[0][3][0]).toMatchObject({
+ name: "sam-custom",
+ connectors: [],
+ });
+ });
+
+ it("prevents duplicate or reserved worker names", () => {
+ const respond = vi.fn();
+ render(
+ <TeamRequestCard
+ item={teamItemFromPayload(launchTeam)}
+ onRespond={respond}
+ />,
+ );
+ fireEvent.change(screen.getAllByLabelText("Worker name")[0], {
+ target: { value: "lead" },
+ });
+ expect(
+ (screen.getByTestId("teamreq-approve") as HTMLButtonElement).disabled,
+ ).toBe(true);
+ expect(screen.getByRole("alert")).toBeTruthy();
+ fireEvent.click(screen.getByTestId("teamreq-approve"));
+ expect(respond).not.toHaveBeenCalled();
+ });
+});
diff --git a/surfaces/gui/src/components/ProposalParts.tsx b/surfaces/gui/src/components/ProposalParts.tsx
new file mode 100644
index 00000000..f0be6bed
--- /dev/null
+++ b/surfaces/gui/src/components/ProposalParts.tsx
@@ -0,0 +1,129 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { ExternalActions } from "../proposals";
+import { Icon } from "./Icon";
+
+export function ProposalActions({
+ approveLabel,
+ testId,
+ onApprove,
+ onReject,
+ disabled = false,
+}: {
+ approveLabel: string;
+ testId: string;
+ onApprove: () => void;
+ onReject: (feedback?: string) => void;
+ disabled?: boolean;
+}) {
+ const { t } = useTranslation();
+ const [editing, setEditing] = useState(false);
+ const [feedback, setFeedback] = useState("");
+ return (
+ <>
+ {editing && (
+ <form
+ className="proposal-feedback"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (feedback.trim()) onReject(feedback.trim());
+ }}
+ >
+ <label>
+ {t("proposal.what_changes")}
+ <textarea
+ autoFocus
+ required
+ value={feedback}
+ onChange={(e) => setFeedback(e.target.value)}
+ rows={3}
+ />
+ </label>
+ <button className="btn" type="submit" disabled={!feedback.trim()}>
+ {t("proposal.send_feedback")}
+ </button>
+ <button
+ className="btn"
+ type="button"
+ onClick={() => setEditing(false)}
+ >
+ {t("proposal.cancel")}
+ </button>
+ </form>
+ )}
+ <div className="proposal-actions">
+ <button
+ className="btn primary"
+ disabled={disabled}
+ data-testid={testId}
+ onClick={onApprove}
+ >
+ {approveLabel}
+ <Icon name="arrowRight" size={14} />
+ </button>
+ <button
+ className="btn proposal-change"
+ aria-expanded={editing}
+ onClick={() => setEditing(!editing)}
+ >
+ {t("proposal.request_changes")}
+ </button>
+ </div>
+ </>
+ );
+}
+
+export function ExternalActionsSection({
+ declaration,
+ targets,
+}: {
+ declaration?: ExternalActions;
+ targets?: string[];
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="proposal-boundaries">
+ {!!targets?.length && (
+ <div>
+ <span className="proposal-label">{t("proposal.targets")}</span>
+ <ul>
+ {targets.map((target) => (
+ <li key={target}>{target}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+ {declaration && (
+ <div data-testid="proposal-external-actions">
+ <span className="proposal-label">
+ {t("proposal.external_actions")}
+ </span>
+ <p>{t(`proposal.external_${declaration.status}`)}</p>
+ {!!declaration.actions.length && (
+ <ul>
+ {declaration.actions.map((action) => (
+ <li key={action}>{action}</li>
+ ))}
+ </ul>
+ )}
+ <p className="proposal-muted">{declaration.explanation}</p>
+ {!!declaration.exclusions.length && (
+ <>
+ <span className="proposal-label">
+ {t("proposal.not_planned")}
+ </span>
+ <ul>
+ {declaration.exclusions.map((action) => (
+ <li key={action}>{action}</li>
+ ))}
+ </ul>
+ </>
+ )}
+ <p className="proposal-muted proposal-permission-note">
+ {t("proposal.intent_not_permission")}
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/surfaces/gui/src/components/TeamRequestCard.test.tsx b/surfaces/gui/src/components/TeamRequestCard.test.tsx
index 4a2d9452..951556ee 100644
--- a/surfaces/gui/src/components/TeamRequestCard.test.tsx
+++ b/surfaces/gui/src/components/TeamRequestCard.test.tsx
@@ -27,16 +27,16 @@ describe("TeamRequestCard", () => {
expect(who?.contains(reason as Node)).toBe(false);
});
- it("labels the buttons Not now / Create team and moves the grant sentence into the title", () => {
+ it("requests actionable changes and makes staffing distinct from assignment", () => {
const onRespond = vi.fn();
render(<TeamRequestCard item={base} onRespond={onRespond} />);
const approve = screen.getByTestId("teamreq-approve");
expect(approve.textContent).toBe("Create team");
- expect(approve.getAttribute("title")).toContain("Approving grants the lead create, assign & steer");
- expect(approve.getAttribute("title")).toContain("Workers get only the connectors you tick.");
- expect(screen.getByTestId("teamreq-card").textContent).not.toContain("Approving grants the lead");
- fireEvent.click(screen.getByText("Not now"));
- expect(onRespond).toHaveBeenCalledWith(false);
+ expect(screen.getByTestId("teamreq-card").textContent).toContain("does not start these tasks");
+ fireEvent.click(screen.getByText("Request changes"));
+ fireEvent.change(screen.getByRole("textbox"), { target: { value: "Add independent verification" } });
+ fireEvent.click(screen.getByText("Send feedback"));
+ expect(onRespond).toHaveBeenCalledWith(false, "Add independent verification");
});
it("an unsuggested default connector starts unticked, with no reason; ticks ride the approval", () => {
diff --git a/surfaces/gui/src/components/TeamRequestCard.tsx b/surfaces/gui/src/components/TeamRequestCard.tsx
index 8b77cd79..fcb7d019 100644
--- a/surfaces/gui/src/components/TeamRequestCard.tsx
+++ b/surfaces/gui/src/components/TeamRequestCard.tsx
@@ -28,6 +28,7 @@ import { modeLabel } from "./Composer";
import { connectorLabel } from "./ConnectorRequestCard";
import { Icon } from "./Icon";
import { modelHover, modelName } from "../modelNames";
+import { ProposalActions } from "./ProposalParts";
// Past this length the lead's note clamps to two lines with More/Less — the roster and
// the connector decisions are the card's subject, not the note.
@@ -37,8 +38,19 @@ const MIXED = "__mixed__";
const WarnGlyph = () => (
<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">
- <path d="M8 2.2 14.2 13H1.8Z" fill="var(--warn-soft)" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" />
- <path d="M8 6.3v3.4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
+ <path
+ d="M8 2.2 14.2 13H1.8Z"
+ fill="var(--warn-soft)"
+ stroke="currentColor"
+ strokeWidth="1.4"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M8 6.3v3.4"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ />
<circle cx="8" cy="11.4" r="0.85" fill="currentColor" />
</svg>
);
@@ -64,6 +76,18 @@ export function TeamRequestCard({
const { t } = useTranslation();
const [chat, setChat] = useState(!!item.enable_chat);
const [noteOpen, setNoteOpen] = useState(false);
+ const [names, setNames] = useState(() =>
+ item.members.map((m) => m.name || ""),
+ );
+ const normalizedNames = names.map((name) => name.trim().toLowerCase());
+ const invalidNames =
+ !!item.groups?.length &&
+ (normalizedNames.some(
+ (name) =>
+ !/^[a-z0-9][a-z0-9._-]{0,23}$/.test(name) ||
+ ["lead", "user", "board"].includes(name),
+ ) ||
+ new Set(normalizedNames).size !== names.length);
const [adding, setAdding] = useState<Record<number, boolean>>({});
const other = item.other_connected ?? [];
const offerFor = (persona: string) => item.offer?.[persona] ?? [];
@@ -77,7 +101,10 @@ export function TeamRequestCard({
Object.fromEntries(
item.members.map((m, i) => {
const allowed = allowedFor(m.persona);
- return [i, [...new Set(m.connectors ?? [])].filter((c) => allowed.includes(c))];
+ return [
+ i,
+ [...new Set(m.connectors ?? [])].filter((c) => allowed.includes(c)),
+ ];
}),
),
);
@@ -89,7 +116,9 @@ export function TeamRequestCard({
const offer = offerFor(m.persona);
return [
i,
- [...new Set(m.connectors ?? [])].filter((c) => !offer.includes(c) && other.includes(c)),
+ [...new Set(m.connectors ?? [])].filter(
+ (c) => !offer.includes(c) && other.includes(c),
+ ),
];
}),
),
@@ -97,11 +126,17 @@ export function TeamRequestCard({
const toggle = (i: number, c: string) =>
setTicked((cur) => {
const have = cur[i] ?? [];
- return { ...cur, [i]: have.includes(c) ? have.filter((x) => x !== c) : [...have, c] };
+ return {
+ ...cur,
+ [i]: have.includes(c) ? have.filter((x) => x !== c) : [...have, c],
+ };
});
const addBeyond = (i: number, c: string) => {
setBeyond((cur) => ({ ...cur, [i]: [...(cur[i] ?? []), c] }));
- setTicked((cur) => ({ ...cur, [i]: [...(cur[i] ?? []).filter((x) => x !== c), c] }));
+ setTicked((cur) => ({
+ ...cur,
+ [i]: [...(cur[i] ?? []).filter((x) => x !== c), c],
+ }));
};
// Set one connector for several workers at once (a role line). Turning on a connector
// outside a worker's usual set lists it in that worker's "beyond" group too.
@@ -118,7 +153,10 @@ export function TeamRequestCard({
setBeyond((cur) => {
const next = { ...cur };
for (const i of idxs)
- if (!offerFor(item.members[i].persona).includes(c) && !(next[i] ?? []).includes(c))
+ if (
+ !offerFor(item.members[i].persona).includes(c) &&
+ !(next[i] ?? []).includes(c)
+ )
next[i] = [...(next[i] ?? []), c];
return next;
});
@@ -132,19 +170,26 @@ export function TeamRequestCard({
});
const [open, setOpen] = useState<Record<string, boolean>>({});
const [groupAdding, setGroupAdding] = useState<Record<string, boolean>>({});
- const runnable = Array.isArray(item.runnable_models) ? item.runnable_models : null;
+ const runnable = Array.isArray(item.runnable_models)
+ ? item.runnable_models
+ : null;
const recommendedFor = (persona: string) => {
const rec = item.model_options?.[persona];
return Array.isArray(rec) ? rec : [];
};
// The model's NAME only; provider and raw id go in the hover text.
- const serverLabels = Object.fromEntries((runnable ?? []).map((r) => [r.id, r.label]));
+ const serverLabels = Object.fromEntries(
+ (runnable ?? []).map((r) => [r.id, r.label]),
+ );
const labels = { ...serverLabels, ...(modelLabels ?? {}) };
const modelLabelOf = (id: string) => modelName(id, labels);
// Each worker's current model pick — starts on what the server resolved for it.
const [picked, setPicked] = useState<Record<number, string>>(() =>
Object.fromEntries(
- item.members.map((m, i) => [i, m.resolved_model || m.model || item.lead_model || ""]),
+ item.members.map((m, i) => [
+ i,
+ m.resolved_model || m.model || item.lead_model || "",
+ ]),
),
);
const decisions = (): TeamMemberDecision[] =>
@@ -152,7 +197,7 @@ export function TeamRequestCard({
const allowed = allowedFor(m.persona);
return {
persona: m.persona,
- ...(m.name ? { name: m.name } : {}),
+ ...(names[i] ? { name: names[i].trim() } : {}),
connectors: (ticked[i] ?? []).filter((c) => allowed.includes(c)),
...(runnable && picked[i] ? { model: picked[i] } : {}),
};
@@ -174,12 +219,18 @@ export function TeamRequestCard({
);
const modelOptions = (persona: string, current: string) => {
const recommended = runnable ? recommendedFor(persona) : [];
- const others = (runnable ?? []).map((r) => r.id).filter((id) => !recommended.includes(id));
+ const others = (runnable ?? [])
+ .map((r) => r.id)
+ .filter((id) => !recommended.includes(id));
return (
<>
- {current !== MIXED && !recommended.includes(current) && !others.includes(current) && (
- <option value={current}>{current ? modelLabelOf(current) : t("team.default_model")}</option>
- )}
+ {current !== MIXED &&
+ !recommended.includes(current) &&
+ !others.includes(current) && (
+ <option value={current}>
+ {current ? modelLabelOf(current) : t("team.default_model")}
+ </option>
+ )}
{recommended.length > 0 && (
<optgroup label={t("team.models_recommended")}>
{recommended.map((id) => (
@@ -203,18 +254,25 @@ export function TeamRequestCard({
};
const warningOf = (i: number) => {
const m = item.members[i];
- return runnable && m.model_warning && (picked[i] ?? "") === (m.resolved_model ?? "") ? m.model_warning : "";
+ return runnable &&
+ m.model_warning &&
+ (picked[i] ?? "") === (m.resolved_model ?? "")
+ ? m.model_warning
+ : "";
};
const memberRow = (i: number): ReactNode => {
const m = item.members[i];
const offer = offerFor(m.persona);
const extra = beyond[i] ?? [];
- const addable = other.filter((c) => !offer.includes(c) && !extra.includes(c));
+ const addable = other.filter(
+ (c) => !offer.includes(c) && !extra.includes(c),
+ );
const reasons = m.connector_reasons ?? {};
const current = picked[i] ?? "";
const recommended = runnable ? recommendedFor(m.persona) : [];
const warn = warningOf(i);
- const offList = !!runnable && recommended.length > 0 && !recommended.includes(current);
+ const offList =
+ !!runnable && recommended.length > 0 && !recommended.includes(current);
return (
<div className="teamreq-row" key={i} data-testid={`teamreq-row-${i}`}>
<span className="teamreq-diamond">◆</span>
@@ -230,10 +288,14 @@ export function TeamRequestCard({
<select
className="teamreq-model-select"
data-testid={`teamreq-model-${i}`}
- aria-label={t("team.model_for", { who: m.name || m.persona })}
+ aria-label={t("team.model_for", {
+ who: m.name || m.persona,
+ })}
title={modelHover(current, labels)}
value={current}
- onChange={(e) => setPicked((cur) => ({ ...cur, [i]: e.target.value }))}
+ onChange={(e) =>
+ setPicked((cur) => ({ ...cur, [i]: e.target.value }))
+ }
>
{modelOptions(m.persona, current)}
</select>
@@ -252,7 +314,10 @@ export function TeamRequestCard({
</>
) : (
m.model && (
- <span className="teamreq-model" title={modelHover(m.model, labels)}>
+ <span
+ className="teamreq-model"
+ title={modelHover(m.model, labels)}
+ >
{" "}
· {modelLabelOf(m.model)}
</span>
@@ -260,26 +325,66 @@ export function TeamRequestCard({
)}
</span>
{offList && (
- <span className="teamreq-model-note" data-testid={`teamreq-model-note-${i}`}>
+ <span
+ className="teamreq-model-note"
+ data-testid={`teamreq-model-note-${i}`}
+ >
{t("team.model_off_list_worker")}
</span>
)}
{m.reason && <span className="teamreq-reason">{m.reason}</span>}
+ {!!item.groups?.length && (
+ <label className="proposal-name">
+ {t("proposal.worker_name")}
+ <input
+ value={names[i]}
+ onChange={(e) =>
+ setNames((cur) =>
+ cur.map((name, index) =>
+ index === i ? e.target.value : name,
+ ),
+ )
+ }
+ />
+ </label>
+ )}
+ {!!m.item_ids?.length && (
+ <span className="proposal-responsibilities">
+ <span className="proposal-label">
+ {t("proposal.planned_responsibilities")}
+ </span>
+ {m.item_ids.map((id) => (
+ <span key={id}>
+ {item.planned_items?.find((task) => task.id === id)?.title ||
+ `#${id}`}
+ </span>
+ ))}
+ </span>
+ )}
<span className="teamreq-dials">
{offer.length > 0 ? (
<span className="teamreq-connectors">
- <span className="teamreq-dial-label">{t("persona.connectors")}</span>
+ <span className="teamreq-dial-label">
+ {t("persona.connectors")}
+ </span>
{offer.map((c) => connectorBox(i, c, reasons[c]))}
</span>
) : extra.length === 0 && other.length === 0 ? (
<span className="teamreq-connectors">
- <span className="teamreq-dial-label">{t("persona.connectors")}</span>
+ <span className="teamreq-dial-label">
+ {t("persona.connectors")}
+ </span>
<span className="teamreq-none">{t("team.none_available")}</span>
</span>
) : null}
{extra.length > 0 && (
- <span className="teamreq-connectors teamreq-beyond" data-testid={`teamreq-beyond-${i}`}>
- <span className="teamreq-dial-label">{t("team.beyond_worker")}</span>
+ <span
+ className="teamreq-connectors teamreq-beyond"
+ data-testid={`teamreq-beyond-${i}`}
+ >
+ <span className="teamreq-dial-label">
+ {t("team.beyond_worker")}
+ </span>
{extra.map((c) => connectorBox(i, c, reasons[c]))}
</span>
)}
@@ -294,7 +399,10 @@ export function TeamRequestCard({
</button>
)}
{adding[i] && addable.length > 0 && (
- <span className="teamreq-connectors" data-testid={`teamreq-addlist-${i}`}>
+ <span
+ className="teamreq-connectors"
+ data-testid={`teamreq-addlist-${i}`}
+ >
{addable.map((c) => (
<label key={c} className="teamreq-connector">
<input
@@ -328,23 +436,38 @@ export function TeamRequestCard({
const tally = [...new Set(models)].map((id) => {
const count = models.filter((x) => x === id).length;
const model = modelLabelOf(id);
- return model ? t("team.tally_model", { n: count, model }) : t("team.tally_default", { n: count });
+ return model
+ ? t("team.tally_model", { n: count, model })
+ : t("team.tally_default", { n: count });
});
const tallyText = tally.join(t("team.list_separator"));
const recommended = runnable ? recommendedFor(persona) : [];
- const offList = !!runnable && uniform && recommended.length > 0 && !recommended.includes(models[0]);
+ const offList =
+ !!runnable &&
+ uniform &&
+ recommended.length > 0 &&
+ !recommended.includes(models[0]);
const warned = idxs.filter((i) => warningOf(i));
const warn = warned.length
? warned.length < n
- ? t("team.warning_partial", { warning: warningOf(warned[0]), have: warned.length, n })
+ ? t("team.warning_partial", {
+ warning: warningOf(warned[0]),
+ have: warned.length,
+ n,
+ })
: warningOf(warned[0])
: "";
// Connectors: the role's usual set, then anything beyond it that any worker holds.
const extra = [...new Set(idxs.flatMap((i) => beyond[i] ?? []))];
- const addable = other.filter((c) => !offer.includes(c) && !extra.includes(c));
- const holders = (c: string) => idxs.filter((i) => (ticked[i] ?? []).includes(c));
+ const addable = other.filter(
+ (c) => !offer.includes(c) && !extra.includes(c),
+ );
+ const holders = (c: string) =>
+ idxs.filter((i) => (ticked[i] ?? []).includes(c));
const sharedConnectorReason = (c: string) => {
- const rs = new Set(holders(c).map((i) => item.members[i].connector_reasons?.[c] || ""));
+ const rs = new Set(
+ holders(c).map((i) => item.members[i].connector_reasons?.[c] || ""),
+ );
return rs.size === 1 ? [...rs][0] : "";
};
const groupBox = (c: string) => {
@@ -363,7 +486,10 @@ export function TeamRequestCard({
/>
<span>{connectorLabel(c)}</span>
{have > 0 && have < n && (
- <span className="teamreq-partial" data-testid={`teamreq-group-partial-${persona}-${c}`}>
+ <span
+ className="teamreq-partial"
+ data-testid={`teamreq-group-partial-${persona}-${c}`}
+ >
{t("team.partial", { have, n })}
</span>
)}
@@ -377,13 +503,19 @@ export function TeamRequestCard({
className="teamreq-add teamreq-add-inline"
data-testid={`teamreq-group-add-${persona}`}
aria-expanded={!!groupAdding[persona]}
- onClick={() => setGroupAdding((cur) => ({ ...cur, [persona]: !cur[persona] }))}
+ onClick={() =>
+ setGroupAdding((cur) => ({ ...cur, [persona]: !cur[persona] }))
+ }
>
{t("team.add_another")}
</button>
);
return (
- <div className="teamreq-group" key={persona} data-testid={`teamreq-group-${persona}`}>
+ <div
+ className="teamreq-group"
+ key={persona}
+ data-testid={`teamreq-group-${persona}`}
+ >
<div className="teamreq-row teamreq-group-row">
<span className="teamreq-diamond">◆</span>
<span className="teamreq-body">
@@ -398,11 +530,17 @@ export function TeamRequestCard({
className="teamreq-model-select"
data-testid={`teamreq-group-model-${persona}`}
aria-label={t("team.model_for_role", { n, persona })}
- title={uniform ? modelHover(models[0], labels) : tallyText}
+ title={
+ uniform ? modelHover(models[0], labels) : tallyText
+ }
value={uniform ? models[0] : MIXED}
onChange={(e) => {
const v = e.target.value;
- if (v !== MIXED) setPicked((cur) => ({ ...cur, ...Object.fromEntries(idxs.map((i) => [i, v])) }));
+ if (v !== MIXED)
+ setPicked((cur) => ({
+ ...cur,
+ ...Object.fromEntries(idxs.map((i) => [i, v])),
+ }));
}}
>
{!uniform && (
@@ -431,14 +569,23 @@ export function TeamRequestCard({
className="teamreq-add teamreq-group-toggle"
data-testid={`teamreq-group-toggle-${persona}`}
aria-expanded={isOpen}
- onClick={() => setOpen((cur) => ({ ...cur, [persona]: !cur[persona] }))}
+ onClick={() =>
+ setOpen((cur) => ({ ...cur, [persona]: !cur[persona] }))
+ }
>
{isOpen ? t("team.hide_workers") : t("team.show_workers")}
</button>
</span>
- {offList && <span className="teamreq-model-note">{t("team.model_off_list_role")}</span>}
+ {offList && (
+ <span className="teamreq-model-note">
+ {t("team.model_off_list_role")}
+ </span>
+ )}
{!uniform && (
- <span className="teamreq-model-note" data-testid={`teamreq-group-tally-${persona}`}>
+ <span
+ className="teamreq-model-note"
+ data-testid={`teamreq-group-tally-${persona}`}
+ >
{tallyText}
</span>
)}
@@ -454,19 +601,27 @@ export function TeamRequestCard({
<span className="teamreq-dials">
{offer.length > 0 ? (
<span className="teamreq-connectors">
- <span className="teamreq-dial-label">{t("team.connectors_for_all", { n })}</span>
+ <span className="teamreq-dial-label">
+ {t("team.connectors_for_all", { n })}
+ </span>
{offer.map(groupBox)}
{extra.length === 0 && addButton}
</span>
) : extra.length === 0 && other.length === 0 ? (
<span className="teamreq-connectors">
- <span className="teamreq-dial-label">{t("persona.connectors")}</span>
- <span className="teamreq-none">{t("team.none_available")}</span>
+ <span className="teamreq-dial-label">
+ {t("persona.connectors")}
+ </span>
+ <span className="teamreq-none">
+ {t("team.none_available")}
+ </span>
</span>
) : null}
{extra.length > 0 && (
<span className="teamreq-connectors teamreq-beyond">
- <span className="teamreq-dial-label">{t("team.beyond_role")}</span>
+ <span className="teamreq-dial-label">
+ {t("team.beyond_role")}
+ </span>
{extra.map(groupBox)}
{addButton}
</span>
@@ -491,7 +646,10 @@ export function TeamRequestCard({
</span>
</div>
{isOpen && (
- <div className="teamreq-group-members" data-testid={`teamreq-group-members-${persona}`}>
+ <div
+ className="teamreq-group-members"
+ data-testid={`teamreq-group-members-${persona}`}
+ >
{idxs.map(memberRow)}
</div>
)}
@@ -499,72 +657,166 @@ export function TeamRequestCard({
);
};
return (
- <div className="dirreq-card teamreq-card" data-testid="teamreq-card">
- <div className="teamreq-head">
- <Icon name="diamond" size={15} />
- <span className="teamreq-title">
- {/* Roles show only when some role has 2+ workers, so that sentence is always "N workers". */}
- {groups.length < item.members.length
- ? t("team.creating_roles", { workers: item.members.length, count: groups.length })
- : t("team.creating", { count: item.members.length })}
- </span>
- </div>
- {note && (
- <div className="teamreq-note-wrap">
- <div className={"teamreq-note" + (noteLong && !noteOpen ? " clamped" : "")}>{note}</div>
- {noteLong && (
- <button
- className="teamreq-note-toggle"
- data-testid="teamreq-note-toggle"
- onClick={() => setNoteOpen((o) => !o)}
- >
- {noteOpen ? t("team.less") : t("team.more")}
- </button>
- )}
+ <div
+ className="dirreq-card teamreq-card proposal-card"
+ data-testid="teamreq-card"
+ >
+ <div className="proposal-content">
+ <header className="proposal-heading">
+ <span className="proposal-mark">
+ <Icon name="team" size={20} />
+ </span>
+ <div>
+ <span className="proposal-label">
+ {t("proposal.proposed_team")}
+ </span>
+ <h3>
+ {item.title || t("team.creating", { count: item.members.length })}
+ </h3>
+ </div>
+ </header>
+ {item.summary && <p className="proposal-summary">{item.summary}</p>}
+ <div className="teamreq-head">
+ <span className="teamreq-title">
+ {/* Roles show only when some role has 2+ workers, so that sentence is always "N workers". */}
+ {groups.length < item.members.length
+ ? t("team.creating_roles", {
+ workers: item.members.length,
+ count: groups.length,
+ })
+ : t("team.creating", { count: item.members.length })}
+ </span>
</div>
- )}
- {/* The roster scrolls inside the card; the header above and the decision below stay
+ {note && (
+ <div className="teamreq-note-wrap">
+ <div
+ className={
+ "teamreq-note" + (noteLong && !noteOpen ? " clamped" : "")
+ }
+ >
+ {note}
+ </div>
+ {noteLong && (
+ <button
+ className="teamreq-note-toggle"
+ data-testid="teamreq-note-toggle"
+ onClick={() => setNoteOpen((o) => !o)}
+ >
+ {noteOpen ? t("team.less") : t("team.more")}
+ </button>
+ )}
+ </div>
+ )}
+ {/* The roster scrolls inside the card; the header above and the decision below stay
in view however many workers the lead proposes. */}
- <div className="teamreq-roster" data-testid="teamreq-roster">
- {groups.map((g) => (g.idxs.length === 1 ? memberRow(g.idxs[0]) : groupRow(g)))}
- </div>
- {mode && (
- <div className="teamreq-approvals" data-testid="teamreq-approvals">
- <Trans
- i18nKey="team.approvals_follow"
- values={{ mode: modeLabel(mode) }}
- components={{ b: <b /> }}
- />
+ <div className="teamreq-roster" data-testid="teamreq-roster">
+ {item.groups?.length
+ ? item.groups.map((group) => {
+ const idxs = item.members
+ .map((_, i) => i)
+ .filter((i) => item.members[i].group === group.id);
+ return (
+ <details className="proposal-group" key={group.id}>
+ <summary>
+ <Icon name="chevronRight" size={14} />
+ <span className="proposal-group-title">
+ {group.title}
+ <small>{group.summary}</small>
+ </span>
+ <span className="proposal-muted">
+ {t("proposal.workers", { count: idxs.length })}
+ </span>
+ </summary>
+ <div className="proposal-group-content">
+ {idxs.map(memberRow)}
+ </div>
+ </details>
+ );
+ })
+ : groups.map((g) =>
+ g.idxs.length === 1 ? memberRow(g.idxs[0]) : groupRow(g),
+ )}
</div>
- )}
- <label className="teamreq-chat">
- <input
- type="checkbox"
- data-testid="teamreq-chat-toggle"
- checked={chat}
- onChange={(e) => setChat(e.target.checked)}
- />
- <span>
- <Trans i18nKey="team.enable_chat" components={{ b: <b /> }} />
- </span>
- <span className="teamreq-info" title={t("team.chat_info")}>
- i
- </span>
- </label>
- <div className="dirreq-actions teamreq-actions">
- <span className="spacer" />
- <button className="btn" onClick={() => onRespond(false)}>
- {t("team.not_now")}
- </button>
- <button
- className="btn primary"
- data-testid="teamreq-approve"
- title={t("team.grant_title")}
- onClick={() => onRespond(true, undefined, chat, decisions())}
+ {[
+ ...new Map(
+ (item.planned_items || []).flatMap((task) =>
+ task.final_acceptance
+ ? [[task.final_acceptance.id, task.final_acceptance] as const]
+ : [],
+ ),
+ ).values(),
+ ].map((final) => (
+ <div className="proposal-final" key={final.id}>
+ <span className="proposal-label">
+ {t("proposal.final_acceptance")}
+ </span>
+ <p>{final.title}</p>
+ <p className="proposal-muted">
+ {t(
+ final.owner === "lead"
+ ? "proposal.owner_lead"
+ : "proposal.owner_assigned_worker",
+ )}
+ </p>
+ </div>
+ ))}
+ <div
+ className="proposal-access"
+ data-testid="proposal-connector-summary"
>
- {t("team.create_team")}
- </button>
+ <span className="proposal-label">
+ {t("proposal.connector_access")}
+ </span>
+ {[...new Set(Object.values(ticked).flat())].length ? (
+ [...new Set(Object.values(ticked).flat())].map((connector) => (
+ <span key={connector}>
+ {connectorLabel(connector)} ·{" "}
+ {t("proposal.workers", {
+ count: Object.values(ticked).filter((list) =>
+ list.includes(connector),
+ ).length,
+ })}
+ </span>
+ ))
+ ) : (
+ <span>{t("proposal.no_connectors")}</span>
+ )}
+ </div>
+ {mode && (
+ <div className="teamreq-approvals" data-testid="teamreq-approvals">
+ <Trans
+ i18nKey="team.approvals_follow"
+ values={{ mode: modeLabel(mode) }}
+ components={{ b: <b /> }}
+ />
+ </div>
+ )}
+ <label className="teamreq-chat">
+ <input
+ type="checkbox"
+ data-testid="teamreq-chat-toggle"
+ checked={chat}
+ onChange={(e) => setChat(e.target.checked)}
+ />
+ <span>
+ <Trans i18nKey="team.enable_chat" components={{ b: <b /> }} />
+ </span>
+ <span className="teamreq-info" title={t("team.chat_info")}>
+ i
+ </span>
+ </label>
+ <p className="proposal-muted proposal-permission-note">
+ {t("proposal.staffing_not_assignment")}
+ </p>
+ {invalidNames && <p role="alert">{t("proposal.invalid_names")}</p>}
</div>
+ <ProposalActions
+ approveLabel={t("team.create_team")}
+ testId="teamreq-approve"
+ disabled={invalidNames}
+ onApprove={() => onRespond(true, undefined, chat, decisions())}
+ onReject={(feedback) => onRespond(false, feedback)}
+ />
</div>
);
}
diff --git a/surfaces/gui/src/components/WorkItemsCard.test.tsx b/surfaces/gui/src/components/WorkItemsCard.test.tsx
index ca3ffd5d..3f16942d 100644
--- a/surfaces/gui/src/components/WorkItemsCard.test.tsx
+++ b/surfaces/gui/src/components/WorkItemsCard.test.tsx
@@ -26,8 +26,9 @@ describe("WorkItemsCard — criteria", () => {
/>,
);
const text = screen.getByTestId("itemsreq-card").textContent || "";
- expect(text.match(/Done when:/g)).toHaveLength(1);
- expect(text).toContain("Done when: no wait exceeds maxDelayMs");
+ expect(text.match(/Acceptance criteria/g)).toHaveLength(1);
+ expect(text).not.toContain("Done when:");
+ expect(text).toContain("no wait exceeds maxDelayMs");
});
it("measures the clamp on the stripped text", () => {
diff --git a/surfaces/gui/src/components/WorkItemsCard.tsx b/surfaces/gui/src/components/WorkItemsCard.tsx
index b71d1419..d2f95d82 100644
--- a/surfaces/gui/src/components/WorkItemsCard.tsx
+++ b/surfaces/gui/src/components/WorkItemsCard.tsx
@@ -1,22 +1,14 @@
-// The decomposition gate (agent teams): a lead proposes work items; approval
-// creates them on the board. The board-flavored sibling of PlanCard — items with
-// acceptance criteria as the primary text, 3 visible + expander with the true
-// count in the header, no in-card reply surface (editing happens by replying).
-import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { Item } from "../types";
+import type { ProposalTask } from "../proposals";
import { Icon } from "./Icon";
+import { ExternalActionsSection, ProposalActions } from "./ProposalParts";
-// Past this length, "Done when" clamps to two lines with a per-item expander —
-// a model that writes essay criteria must not occupy two screens of gate card
-// (owner-hit 2026-08-16). The full text is one click away; the lead's prompt
-// separately pushes criteria back toward 1–3 crisp checks.
-const CRITERIA_CLAMP_CHARS = 160;
-
-// The card prints its own "Done when:" label — a lead that writes the label into the
-// criteria text (sometimes twice) must not produce "Done when: Done when: …".
export function stripDoneWhen(criteria: string | undefined): string {
- return (criteria || "").replace(/^(\s*done\s+when\s*:\s*)+/i, "");
+ return (criteria || "").replace(
+ /^(\s*(done\s+when|acceptance\s+criteria)\s*:\s*)+/i,
+ "",
+ );
}
export function WorkItemsCard({
@@ -27,66 +19,116 @@ export function WorkItemsCard({
onRespond: (approved: boolean, feedback?: string) => void;
}) {
const { t } = useTranslation();
- const [expanded, setExpanded] = useState(false);
- const [openCriteria, setOpenCriteria] = useState<Record<number, boolean>>({});
- const visible = expanded ? item.items : item.items.slice(0, 3);
- const hidden = item.items.length - visible.length;
+ const titles = new Map(item.items.map((entry) => [entry.key, entry.title]));
+ const final = item.items.find(
+ (entry) => entry.key && entry.key === item.final_acceptance?.item_key,
+ );
+ const task = (entry: ProposalTask, i: number) => (
+ <div className="proposal-task" key={entry.key || i}>
+ <div className="proposal-task-title">{entry.title}</div>
+ <span className="proposal-label">
+ {t("proposal.acceptance_criteria")}
+ </span>
+ <p className="proposal-criteria">{stripDoneWhen(entry.criteria)}</p>
+ {entry.description && (
+ <p className="proposal-muted">{entry.description}</p>
+ )}
+ {!!entry.depends_on?.length && (
+ <p className="proposal-muted">
+ {t("proposal.depends_on")}:{" "}
+ {entry.depends_on.map((key) => titles.get(key)).join(" · ")}
+ </p>
+ )}
+ {!!entry.verifies?.length && (
+ <p className="proposal-muted">
+ {t("proposal.verifies")}:{" "}
+ {entry.verifies.map((key) => titles.get(key)).join(" · ")}
+ </p>
+ )}
+ </div>
+ );
return (
- <div className="dirreq-card itemsreq-card" data-testid="itemsreq-card">
- <div className="itemsreq-head">
- <Icon name="table" size={15} />
- <span className="itemsreq-title">
- {t("team.proposed_items", { count: item.items.length })}
- </span>
- </div>
- {item.note && <div className="itemsreq-note">{item.note}</div>}
- <div className="itemsreq-list">
- {visible.map((entry, i) => {
- const criteria = stripDoneWhen(entry.criteria);
- const long = criteria.length > CRITERIA_CLAMP_CHARS;
- const open = !!openCriteria[i];
- return (
- <div className="itemsreq-item" key={i}>
- <span className="itemsreq-num">{i + 1}.</span>
- <span className="itemsreq-body">
- <span className="itemsreq-item-title">{entry.title}</span>
- <span className={"itemsreq-ac" + (long && !open ? " clamped" : "")}>
- <b>{t("team.items_done_when")}</b> {criteria}
- </span>
- {long && (
- <button
- className="itemsreq-ac-toggle"
- data-testid={`itemsreq-ac-toggle-${i}`}
- onClick={() => setOpenCriteria((s) => ({ ...s, [i]: !s[i] }))}
- >
- {open ? t("team.show_less") : t("team.show_full_criteria")}
- </button>
- )}
- </span>
- </div>
- );
- })}
- {hidden > 0 && (
- <button className="itemsreq-more" onClick={() => setExpanded(true)}>
- {t("team.more_items", { count: hidden })}
- <Icon name="chevronDown" size={12} />
- </button>
+ <div
+ className="dirreq-card itemsreq-card proposal-card"
+ data-testid="itemsreq-card"
+ >
+ <div className="proposal-content">
+ <header className="proposal-heading">
+ <span className="proposal-mark">
+ <Icon name="workList" size={20} />
+ </span>
+ <div>
+ <span className="proposal-label">
+ {t("proposal.proposed_work")}
+ </span>
+ <h3>
+ {item.title ||
+ t("team.proposed_items", { count: item.items.length })}
+ </h3>
+ </div>
+ </header>
+ {item.summary && <p className="proposal-summary">{item.summary}</p>}
+ <div className="proposal-meta">
+ <span>{t("proposal.tasks", { count: item.items.length })}</span>
+ {item.activities?.map((activity) => (
+ <span key={activity.id}>
+ {
+ item.items.filter((task) => task.activity === activity.id)
+ .length
+ }{" "}
+ {activity.title}
+ </span>
+ ))}
+ </div>
+ <div className="proposal-workstreams">
+ {item.workstreams?.map((group) => {
+ const tasks = item.items.filter(
+ (entry) => entry.workstream === group.id,
+ );
+ return (
+ <details className="proposal-group" key={group.id}>
+ <summary>
+ <Icon name="chevronRight" size={14} />
+ <span className="proposal-group-title">
+ {group.title}
+ <small>{group.summary}</small>
+ </span>
+ <span className="proposal-muted">
+ {t("proposal.tasks", { count: tasks.length })}
+ </span>
+ </summary>
+ <div className="proposal-group-content">{tasks.map(task)}</div>
+ </details>
+ );
+ })}
+ </div>
+ {!item.workstreams?.length && item.items.map(task)}
+ {final && (
+ <div className="proposal-final">
+ <span className="proposal-label">
+ {t("proposal.final_acceptance")}
+ </span>
+ <p>{final.title}</p>
+ <p className="proposal-muted">
+ {t(
+ item.final_acceptance?.owner === "lead"
+ ? "proposal.owner_lead"
+ : "proposal.owner_assigned_worker",
+ )}
+ </p>
+ </div>
)}
+ <ExternalActionsSection
+ declaration={item.external_actions}
+ targets={item.targets}
+ />
</div>
- <div className="dirreq-actions">
- <span className="itemsreq-grant">{t("team.items_grant")}</span>
- <span className="spacer" />
- <button className="btn" onClick={() => onRespond(false)}>
- {t("team.not_now")}
- </button>
- <button
- className="btn primary"
- data-testid="itemsreq-approve"
- onClick={() => onRespond(true)}
- >
- {t("team.approve_items")}
- </button>
- </div>
+ <ProposalActions
+ approveLabel={t("proposal.approve_plan")}
+ testId="itemsreq-approve"
+ onApprove={() => onRespond(true)}
+ onReject={(feedback) => onRespond(false, feedback)}
+ />
</div>
);
}
diff --git a/surfaces/gui/src/gallery/inboxItems.ts b/surfaces/gui/src/gallery/inboxItems.ts
index 886a4d96..ddcbf5fe 100644
--- a/surfaces/gui/src/gallery/inboxItems.ts
+++ b/surfaces/gui/src/gallery/inboxItems.ts
@@ -39,7 +39,7 @@ export const inboxItemBuilders: Partial<Record<string, (s: CardState<any>) => In
"plan",
"Approve the proposed work items?",
(p.items || []).map((i: any) => `- ${i.title}`).join("\n"),
- { gate: "items", items: p.items || [], note: p.note || "" },
+ { gate: "items", ...p },
),
approval: ({ payload: p, context }) =>
parked("approval", `Run \`${p.name}\`?`, p.reason || "", {
diff --git a/surfaces/gui/src/gallery/states.contract.json b/surfaces/gui/src/gallery/states.contract.json
index 03a5b52f..3a00d1b9 100644
--- a/surfaces/gui/src/gallery/states.contract.json
+++ b/surfaces/gui/src/gallery/states.contract.json
@@ -8923,8 +8923,249 @@
},
"team-request": {
"event": "team_proposed",
- "canonical": "lead-suggested-github",
+ "canonical": "launch-team",
"states": {
+ "launch-team": {
+ "title": "The customer launch team",
+ "summary": "Seven builders own separate workstreams. Three verifiers independently check their results.",
+ "groups": [
+ {
+ "id": "builders",
+ "title": "Builders",
+ "summary": "One owner per implementation workstream"
+ },
+ {
+ "id": "verifiers",
+ "title": "Verifiers",
+ "summary": "Independent checks and board evidence"
+ }
+ ],
+ "members": [
+ {
+ "persona": "swe-worker",
+ "name": "sam-1",
+ "reason": "Launch plan data & API",
+ "group": "builders",
+ "item_ids": [
+ 1
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-2",
+ "reason": "Dependencies & impact preview",
+ "group": "builders",
+ "item_ids": [
+ 2
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-3",
+ "reason": "Launch workspace",
+ "group": "builders",
+ "item_ids": [
+ 3
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-4",
+ "reason": "Interactive timeline",
+ "group": "builders",
+ "item_ids": [
+ 4
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-5",
+ "reason": "Portfolio attention",
+ "group": "builders",
+ "item_ids": [
+ 5
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-6",
+ "reason": "Versioned launch templates",
+ "group": "builders",
+ "item_ids": [
+ 6
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-7",
+ "reason": "Local reminders",
+ "group": "builders",
+ "item_ids": [
+ 7
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "test-worker",
+ "name": "maya-8",
+ "reason": "API & permissions",
+ "group": "verifiers",
+ "item_ids": [
+ 8
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "test-worker",
+ "name": "maya-9",
+ "reason": "Browser journey & evidence",
+ "group": "verifiers",
+ "item_ids": [
+ 9
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "test-worker",
+ "name": "maya-10",
+ "reason": "Upgrade & regression",
+ "group": "verifiers",
+ "item_ids": [
+ 10
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ }
+ ],
+ "enable_chat": true,
+ "planned_items": [
+ {
+ "id": 1,
+ "title": "Launch plan data & API",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 2,
+ "title": "Dependencies & impact preview",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 3,
+ "title": "Launch workspace",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 4,
+ "title": "Interactive timeline",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 5,
+ "title": "Portfolio attention",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 6,
+ "title": "Versioned launch templates",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 7,
+ "title": "Local reminders",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 8,
+ "title": "API & permissions",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 9,
+ "title": "Browser journey & evidence",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 10,
+ "title": "Upgrade & regression",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ }
+ ],
+ "lead_mode": "interactive",
+ "offer": {},
+ "other_connected": [],
+ "runnable_models": [
+ {
+ "id": "anthropic:claude-sonnet-4-8",
+ "label": "Claude Sonnet 4.8"
+ }
+ ],
+ "lead_model": "anthropic:claude-sonnet-4-8",
+ "model_options": {}
+ },
"lead-suggested-github": {
"lead_mode": "auto-approve",
"lead_model": "anthropic:claude-sonnet-4-8",
@@ -10298,6 +10539,264 @@
}
},
"inbox": {
+ "launch-team": {
+ "id": "gallery-item",
+ "session_id": "gallery-session",
+ "kind": "plan",
+ "title": "Create this team?",
+ "body": "- swe-worker (sam-1)\n- swe-worker (sam-2)\n- swe-worker (sam-3)\n- swe-worker (sam-4)\n- swe-worker (sam-5)\n- swe-worker (sam-6)\n- swe-worker (sam-7)\n- test-worker (maya-8)\n- test-worker (maya-9)\n- test-worker (maya-10)",
+ "state": "pending",
+ "resolution": null,
+ "inbox": "default",
+ "created_at": "2026-09-17T09:30:00Z",
+ "resolved_at": null,
+ "visibility": "inbox",
+ "session_title": "Mention #3 · Invoice PDF download",
+ "session_agent": "swe-lead",
+ "session_exists": true,
+ "data": {
+ "gate": "team",
+ "title": "The customer launch team",
+ "summary": "Seven builders own separate workstreams. Three verifiers independently check their results.",
+ "groups": [
+ {
+ "id": "builders",
+ "title": "Builders",
+ "summary": "One owner per implementation workstream"
+ },
+ {
+ "id": "verifiers",
+ "title": "Verifiers",
+ "summary": "Independent checks and board evidence"
+ }
+ ],
+ "members": [
+ {
+ "persona": "swe-worker",
+ "name": "sam-1",
+ "reason": "Launch plan data & API",
+ "group": "builders",
+ "item_ids": [
+ 1
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-2",
+ "reason": "Dependencies & impact preview",
+ "group": "builders",
+ "item_ids": [
+ 2
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-3",
+ "reason": "Launch workspace",
+ "group": "builders",
+ "item_ids": [
+ 3
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-4",
+ "reason": "Interactive timeline",
+ "group": "builders",
+ "item_ids": [
+ 4
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-5",
+ "reason": "Portfolio attention",
+ "group": "builders",
+ "item_ids": [
+ 5
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-6",
+ "reason": "Versioned launch templates",
+ "group": "builders",
+ "item_ids": [
+ 6
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "swe-worker",
+ "name": "sam-7",
+ "reason": "Local reminders",
+ "group": "builders",
+ "item_ids": [
+ 7
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "test-worker",
+ "name": "maya-8",
+ "reason": "API & permissions",
+ "group": "verifiers",
+ "item_ids": [
+ 8
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "test-worker",
+ "name": "maya-9",
+ "reason": "Browser journey & evidence",
+ "group": "verifiers",
+ "item_ids": [
+ 9
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ },
+ {
+ "persona": "test-worker",
+ "name": "maya-10",
+ "reason": "Upgrade & regression",
+ "group": "verifiers",
+ "item_ids": [
+ 10
+ ],
+ "connectors": [],
+ "resolved_model": "anthropic:claude-sonnet-4-8"
+ }
+ ],
+ "enable_chat": true,
+ "planned_items": [
+ {
+ "id": 1,
+ "title": "Launch plan data & API",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 2,
+ "title": "Dependencies & impact preview",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 3,
+ "title": "Launch workspace",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 4,
+ "title": "Interactive timeline",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 5,
+ "title": "Portfolio attention",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 6,
+ "title": "Versioned launch templates",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 7,
+ "title": "Local reminders",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 8,
+ "title": "API & permissions",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 9,
+ "title": "Browser journey & evidence",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 10,
+ "title": "Upgrade & regression",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ },
+ {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "final_acceptance": {
+ "id": 11,
+ "title": "Accept the complete journey",
+ "owner": "lead"
+ }
+ }
+ ],
+ "lead_mode": "interactive",
+ "offer": {},
+ "other_connected": [],
+ "runnable_models": [
+ {
+ "id": "anthropic:claude-sonnet-4-8",
+ "label": "Claude Sonnet 4.8"
+ }
+ ],
+ "lead_model": "anthropic:claude-sonnet-4-8",
+ "model_options": {}
+ }
+ },
"lead-suggested-github": {
"id": "gallery-item",
"session_id": "gallery-session",
@@ -12247,8 +12746,372 @@
},
"work-items": {
"event": "items_proposed",
- "canonical": "three-items",
+ "canonical": "launch-plan",
"states": {
+ "launch-plan": {
+ "title": "Give every customer a launch plan",
+ "summary": "Turn a won deal into an owned, dated plan—and show what changes when a milestone slips.",
+ "targets": [
+ "acme/billing-service · local workspace"
+ ],
+ "external_actions": {
+ "status": "none",
+ "actions": [],
+ "exclusions": [
+ "Pushes, deployments, and outbound messages"
+ ],
+ "explanation": "This rehearsal is limited to local changes and verification."
+ },
+ "activities": [
+ {
+ "id": "build",
+ "title": "Build",
+ "summary": "Implement the customer journey"
+ },
+ {
+ "id": "verify",
+ "title": "Verify",
+ "summary": "Independently check the results"
+ },
+ {
+ "id": "accept",
+ "title": "Accept",
+ "summary": "Review the complete outcome"
+ }
+ ],
+ "workstreams": [
+ {
+ "id": "foundation",
+ "title": "Plan, schedule & dependencies",
+ "summary": "Shared data and scheduling foundation"
+ },
+ {
+ "id": "experience",
+ "title": "Workspace, timeline & portfolio",
+ "summary": "Independent customer-facing surfaces"
+ },
+ {
+ "id": "followthrough",
+ "title": "Templates & reminders",
+ "summary": "Reusable plans and local follow-through"
+ },
+ {
+ "id": "quality",
+ "title": "Verification & acceptance",
+ "summary": "Independent evidence and final judgment"
+ }
+ ],
+ "items": [
+ {
+ "key": "plan",
+ "title": "Launch plan data & API",
+ "activity": "build",
+ "workstream": "foundation",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "A won deal creates an owned plan; existing accounts remain intact."
+ },
+ {
+ "key": "graph",
+ "title": "Dependencies & impact preview",
+ "activity": "build",
+ "workstream": "foundation",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "A three-day slip previews affected successors before applying changes; dependency cycles are rejected."
+ },
+ {
+ "key": "workspace",
+ "title": "Launch workspace",
+ "activity": "build",
+ "workstream": "experience",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Owners can manage tasks without bypassing required work."
+ },
+ {
+ "key": "timeline",
+ "title": "Interactive timeline",
+ "activity": "build",
+ "workstream": "experience",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Dates match the workspace after a schedule change."
+ },
+ {
+ "key": "portfolio",
+ "title": "Portfolio attention",
+ "activity": "build",
+ "workstream": "experience",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Teams can find overdue launches with correct access boundaries."
+ },
+ {
+ "key": "templates",
+ "title": "Versioned launch templates",
+ "activity": "build",
+ "workstream": "followthrough",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "New launches use the chosen version; existing plans are unchanged."
+ },
+ {
+ "key": "reminders",
+ "title": "Local reminders",
+ "activity": "build",
+ "workstream": "followthrough",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Due-date changes update in-app reminders without duplicates."
+ },
+ {
+ "key": "api-check",
+ "title": "API & permissions",
+ "activity": "verify",
+ "workstream": "quality",
+ "depends_on": [
+ "plan",
+ "graph"
+ ],
+ "verifies": [
+ "plan",
+ "graph"
+ ],
+ "criteria": "Tests cover tenant boundaries, roles, completion rules, and scheduling."
+ },
+ {
+ "key": "browser-check",
+ "title": "Browser journey & evidence",
+ "activity": "verify",
+ "workstream": "quality",
+ "depends_on": [
+ "workspace",
+ "timeline",
+ "portfolio"
+ ],
+ "verifies": [
+ "workspace",
+ "timeline",
+ "portfolio"
+ ],
+ "criteria": "The full journey passes with screenshots attached to board items."
+ },
+ {
+ "key": "upgrade-check",
+ "title": "Upgrade & regression",
+ "activity": "verify",
+ "workstream": "quality",
+ "depends_on": [
+ "templates",
+ "reminders"
+ ],
+ "verifies": [
+ "templates",
+ "reminders"
+ ],
+ "criteria": "Existing data survives and the previous journey still works."
+ },
+ {
+ "key": "accept",
+ "title": "Accept the complete journey",
+ "activity": "accept",
+ "workstream": "quality",
+ "depends_on": [
+ "api-check",
+ "browser-check",
+ "upgrade-check"
+ ],
+ "verifies": [],
+ "criteria": "Win a deal, adjust a milestone, verify affected views, and complete the plan."
+ }
+ ],
+ "final_acceptance": {
+ "item_key": "accept",
+ "owner": "lead"
+ }
+ },
+ "security-plan": {
+ "title": "Close the staging exposure gaps",
+ "summary": "Assess the approved staging targets, prepare fixes, and independently recheck the findings.",
+ "targets": [
+ "acme/billing-service",
+ "sandbox-1 · approved staging environment"
+ ],
+ "external_actions": {
+ "status": "planned",
+ "actions": [
+ "Run authenticated checks against sandbox-1",
+ "Open remediation pull requests in acme/billing-service"
+ ],
+ "exclusions": [
+ "Production scans or infrastructure changes",
+ "Merging remediation pull requests"
+ ],
+ "explanation": "Only the staging targets named in the request are in scope. Active scans contact external systems."
+ },
+ "activities": [
+ {
+ "id": "assess",
+ "title": "Assess",
+ "summary": "Establish exposure"
+ },
+ {
+ "id": "remediate",
+ "title": "Remediate",
+ "summary": "Prepare fixes"
+ },
+ {
+ "id": "validate",
+ "title": "Validate",
+ "summary": "Independently recheck"
+ }
+ ],
+ "workstreams": [
+ {
+ "id": "application",
+ "title": "Application security",
+ "summary": "Repository and dependency findings"
+ },
+ {
+ "id": "cloud",
+ "title": "Staging infrastructure",
+ "summary": "Exposure and configuration checks"
+ },
+ {
+ "id": "review",
+ "title": "Remediation & validation",
+ "summary": "Evidence-backed closure"
+ }
+ ],
+ "items": [
+ {
+ "key": "code",
+ "title": "Assess repository findings",
+ "activity": "assess",
+ "workstream": "application",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Findings identify affected code and include reproducible evidence."
+ },
+ {
+ "key": "infra",
+ "title": "Assess staging exposure",
+ "activity": "assess",
+ "workstream": "cloud",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Checks stay within the approved staging targets and report coverage gaps."
+ },
+ {
+ "key": "fix",
+ "title": "Prepare remediation changes",
+ "activity": "remediate",
+ "workstream": "review",
+ "depends_on": [
+ "code",
+ "infra"
+ ],
+ "verifies": [],
+ "criteria": "Each proposed fix references its finding and includes regression coverage."
+ },
+ {
+ "key": "validate",
+ "title": "Accept independently verified findings",
+ "activity": "validate",
+ "workstream": "review",
+ "depends_on": [
+ "fix"
+ ],
+ "verifies": [
+ "fix"
+ ],
+ "criteria": "Reported vulnerabilities no longer reproduce; unresolved risks remain explicitly documented."
+ }
+ ],
+ "final_acceptance": {
+ "item_key": "validate",
+ "owner": "assigned_worker"
+ }
+ },
+ "marketing-plan": {
+ "title": "Prepare the customer launch campaign",
+ "summary": "Research the audience, create campaign drafts, and review claims before publication is considered.",
+ "targets": [
+ "Acme · customer launch campaign"
+ ],
+ "external_actions": {
+ "status": "undetermined",
+ "actions": [],
+ "exclusions": [
+ "Publishing before the user chooses channels and approves the copy"
+ ],
+ "explanation": "Publication channels and recipients have not been selected. Clarification is needed before any publishing or sending."
+ },
+ "activities": [
+ {
+ "id": "research",
+ "title": "Research",
+ "summary": "Establish the audience"
+ },
+ {
+ "id": "create",
+ "title": "Create",
+ "summary": "Draft assets"
+ },
+ {
+ "id": "review",
+ "title": "Review",
+ "summary": "Verify claims and tone"
+ }
+ ],
+ "workstreams": [
+ {
+ "id": "campaign",
+ "title": "Campaign preparation",
+ "summary": "Audience, drafts, and publication-ready review"
+ }
+ ],
+ "items": [
+ {
+ "key": "research",
+ "title": "Audience and message brief",
+ "activity": "research",
+ "workstream": "campaign",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "The brief identifies the audience and cites sources for factual claims."
+ },
+ {
+ "key": "draft",
+ "title": "Campaign drafts",
+ "activity": "create",
+ "workstream": "campaign",
+ "depends_on": [
+ "research"
+ ],
+ "verifies": [],
+ "criteria": "Drafts match the approved brief and make no unsupported claims."
+ },
+ {
+ "key": "review",
+ "title": "Review campaign assets",
+ "activity": "review",
+ "workstream": "campaign",
+ "depends_on": [
+ "draft"
+ ],
+ "verifies": [
+ "draft"
+ ],
+ "criteria": "Claims, tone, and links are checked; publication requires a separate decision."
+ }
+ ],
+ "final_acceptance": {
+ "item_key": "review",
+ "owner": "lead"
+ }
+ },
"three-items": {
"items": [
{
@@ -12344,6 +13207,421 @@
}
},
"inbox": {
+ "launch-plan": {
+ "id": "gallery-item",
+ "session_id": "gallery-session",
+ "kind": "plan",
+ "title": "Approve the proposed work items?",
+ "body": "- Launch plan data & API\n- Dependencies & impact preview\n- Launch workspace\n- Interactive timeline\n- Portfolio attention\n- Versioned launch templates\n- Local reminders\n- API & permissions\n- Browser journey & evidence\n- Upgrade & regression\n- Accept the complete journey",
+ "state": "pending",
+ "resolution": null,
+ "inbox": "default",
+ "created_at": "2026-09-17T09:30:00Z",
+ "resolved_at": null,
+ "visibility": "inbox",
+ "session_title": "Mention #3 · Invoice PDF download",
+ "session_agent": "swe-lead",
+ "session_exists": true,
+ "data": {
+ "gate": "items",
+ "title": "Give every customer a launch plan",
+ "summary": "Turn a won deal into an owned, dated plan—and show what changes when a milestone slips.",
+ "targets": [
+ "acme/billing-service · local workspace"
+ ],
+ "external_actions": {
+ "status": "none",
+ "actions": [],
+ "exclusions": [
+ "Pushes, deployments, and outbound messages"
+ ],
+ "explanation": "This rehearsal is limited to local changes and verification."
+ },
+ "activities": [
+ {
+ "id": "build",
+ "title": "Build",
+ "summary": "Implement the customer journey"
+ },
+ {
+ "id": "verify",
+ "title": "Verify",
+ "summary": "Independently check the results"
+ },
+ {
+ "id": "accept",
+ "title": "Accept",
+ "summary": "Review the complete outcome"
+ }
+ ],
+ "workstreams": [
+ {
+ "id": "foundation",
+ "title": "Plan, schedule & dependencies",
+ "summary": "Shared data and scheduling foundation"
+ },
+ {
+ "id": "experience",
+ "title": "Workspace, timeline & portfolio",
+ "summary": "Independent customer-facing surfaces"
+ },
+ {
+ "id": "followthrough",
+ "title": "Templates & reminders",
+ "summary": "Reusable plans and local follow-through"
+ },
+ {
+ "id": "quality",
+ "title": "Verification & acceptance",
+ "summary": "Independent evidence and final judgment"
+ }
+ ],
+ "items": [
+ {
+ "key": "plan",
+ "title": "Launch plan data & API",
+ "activity": "build",
+ "workstream": "foundation",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "A won deal creates an owned plan; existing accounts remain intact."
+ },
+ {
+ "key": "graph",
+ "title": "Dependencies & impact preview",
+ "activity": "build",
+ "workstream": "foundation",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "A three-day slip previews affected successors before applying changes; dependency cycles are rejected."
+ },
+ {
+ "key": "workspace",
+ "title": "Launch workspace",
+ "activity": "build",
+ "workstream": "experience",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Owners can manage tasks without bypassing required work."
+ },
+ {
+ "key": "timeline",
+ "title": "Interactive timeline",
+ "activity": "build",
+ "workstream": "experience",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Dates match the workspace after a schedule change."
+ },
+ {
+ "key": "portfolio",
+ "title": "Portfolio attention",
+ "activity": "build",
+ "workstream": "experience",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Teams can find overdue launches with correct access boundaries."
+ },
+ {
+ "key": "templates",
+ "title": "Versioned launch templates",
+ "activity": "build",
+ "workstream": "followthrough",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "New launches use the chosen version; existing plans are unchanged."
+ },
+ {
+ "key": "reminders",
+ "title": "Local reminders",
+ "activity": "build",
+ "workstream": "followthrough",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Due-date changes update in-app reminders without duplicates."
+ },
+ {
+ "key": "api-check",
+ "title": "API & permissions",
+ "activity": "verify",
+ "workstream": "quality",
+ "depends_on": [
+ "plan",
+ "graph"
+ ],
+ "verifies": [
+ "plan",
+ "graph"
+ ],
+ "criteria": "Tests cover tenant boundaries, roles, completion rules, and scheduling."
+ },
+ {
+ "key": "browser-check",
+ "title": "Browser journey & evidence",
+ "activity": "verify",
+ "workstream": "quality",
+ "depends_on": [
+ "workspace",
+ "timeline",
+ "portfolio"
+ ],
+ "verifies": [
+ "workspace",
+ "timeline",
+ "portfolio"
+ ],
+ "criteria": "The full journey passes with screenshots attached to board items."
+ },
+ {
+ "key": "upgrade-check",
+ "title": "Upgrade & regression",
+ "activity": "verify",
+ "workstream": "quality",
+ "depends_on": [
+ "templates",
+ "reminders"
+ ],
+ "verifies": [
+ "templates",
+ "reminders"
+ ],
+ "criteria": "Existing data survives and the previous journey still works."
+ },
+ {
+ "key": "accept",
+ "title": "Accept the complete journey",
+ "activity": "accept",
+ "workstream": "quality",
+ "depends_on": [
+ "api-check",
+ "browser-check",
+ "upgrade-check"
+ ],
+ "verifies": [],
+ "criteria": "Win a deal, adjust a milestone, verify affected views, and complete the plan."
+ }
+ ],
+ "final_acceptance": {
+ "item_key": "accept",
+ "owner": "lead"
+ }
+ }
+ },
+ "security-plan": {
+ "id": "gallery-item",
+ "session_id": "gallery-session",
+ "kind": "plan",
+ "title": "Approve the proposed work items?",
+ "body": "- Assess repository findings\n- Assess staging exposure\n- Prepare remediation changes\n- Accept independently verified findings",
+ "state": "pending",
+ "resolution": null,
+ "inbox": "default",
+ "created_at": "2026-09-17T09:30:00Z",
+ "resolved_at": null,
+ "visibility": "inbox",
+ "session_title": "Mention #3 · Invoice PDF download",
+ "session_agent": "swe-lead",
+ "session_exists": true,
+ "data": {
+ "gate": "items",
+ "title": "Close the staging exposure gaps",
+ "summary": "Assess the approved staging targets, prepare fixes, and independently recheck the findings.",
+ "targets": [
+ "acme/billing-service",
+ "sandbox-1 · approved staging environment"
+ ],
+ "external_actions": {
+ "status": "planned",
+ "actions": [
+ "Run authenticated checks against sandbox-1",
+ "Open remediation pull requests in acme/billing-service"
+ ],
+ "exclusions": [
+ "Production scans or infrastructure changes",
+ "Merging remediation pull requests"
+ ],
+ "explanation": "Only the staging targets named in the request are in scope. Active scans contact external systems."
+ },
+ "activities": [
+ {
+ "id": "assess",
+ "title": "Assess",
+ "summary": "Establish exposure"
+ },
+ {
+ "id": "remediate",
+ "title": "Remediate",
+ "summary": "Prepare fixes"
+ },
+ {
+ "id": "validate",
+ "title": "Validate",
+ "summary": "Independently recheck"
+ }
+ ],
+ "workstreams": [
+ {
+ "id": "application",
+ "title": "Application security",
+ "summary": "Repository and dependency findings"
+ },
+ {
+ "id": "cloud",
+ "title": "Staging infrastructure",
+ "summary": "Exposure and configuration checks"
+ },
+ {
+ "id": "review",
+ "title": "Remediation & validation",
+ "summary": "Evidence-backed closure"
+ }
+ ],
+ "items": [
+ {
+ "key": "code",
+ "title": "Assess repository findings",
+ "activity": "assess",
+ "workstream": "application",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Findings identify affected code and include reproducible evidence."
+ },
+ {
+ "key": "infra",
+ "title": "Assess staging exposure",
+ "activity": "assess",
+ "workstream": "cloud",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "Checks stay within the approved staging targets and report coverage gaps."
+ },
+ {
+ "key": "fix",
+ "title": "Prepare remediation changes",
+ "activity": "remediate",
+ "workstream": "review",
+ "depends_on": [
+ "code",
+ "infra"
+ ],
+ "verifies": [],
+ "criteria": "Each proposed fix references its finding and includes regression coverage."
+ },
+ {
+ "key": "validate",
+ "title": "Accept independently verified findings",
+ "activity": "validate",
+ "workstream": "review",
+ "depends_on": [
+ "fix"
+ ],
+ "verifies": [
+ "fix"
+ ],
+ "criteria": "Reported vulnerabilities no longer reproduce; unresolved risks remain explicitly documented."
+ }
+ ],
+ "final_acceptance": {
+ "item_key": "validate",
+ "owner": "assigned_worker"
+ }
+ }
+ },
+ "marketing-plan": {
+ "id": "gallery-item",
+ "session_id": "gallery-session",
+ "kind": "plan",
+ "title": "Approve the proposed work items?",
+ "body": "- Audience and message brief\n- Campaign drafts\n- Review campaign assets",
+ "state": "pending",
+ "resolution": null,
+ "inbox": "default",
+ "created_at": "2026-09-17T09:30:00Z",
+ "resolved_at": null,
+ "visibility": "inbox",
+ "session_title": "Mention #3 · Invoice PDF download",
+ "session_agent": "swe-lead",
+ "session_exists": true,
+ "data": {
+ "gate": "items",
+ "title": "Prepare the customer launch campaign",
+ "summary": "Research the audience, create campaign drafts, and review claims before publication is considered.",
+ "targets": [
+ "Acme · customer launch campaign"
+ ],
+ "external_actions": {
+ "status": "undetermined",
+ "actions": [],
+ "exclusions": [
+ "Publishing before the user chooses channels and approves the copy"
+ ],
+ "explanation": "Publication channels and recipients have not been selected. Clarification is needed before any publishing or sending."
+ },
+ "activities": [
+ {
+ "id": "research",
+ "title": "Research",
+ "summary": "Establish the audience"
+ },
+ {
+ "id": "create",
+ "title": "Create",
+ "summary": "Draft assets"
+ },
+ {
+ "id": "review",
+ "title": "Review",
+ "summary": "Verify claims and tone"
+ }
+ ],
+ "workstreams": [
+ {
+ "id": "campaign",
+ "title": "Campaign preparation",
+ "summary": "Audience, drafts, and publication-ready review"
+ }
+ ],
+ "items": [
+ {
+ "key": "research",
+ "title": "Audience and message brief",
+ "activity": "research",
+ "workstream": "campaign",
+ "depends_on": [],
+ "verifies": [],
+ "criteria": "The brief identifies the audience and cites sources for factual claims."
+ },
+ {
+ "key": "draft",
+ "title": "Campaign drafts",
+ "activity": "create",
+ "workstream": "campaign",
+ "depends_on": [
+ "research"
+ ],
+ "verifies": [],
+ "criteria": "Drafts match the approved brief and make no unsupported claims."
+ },
+ {
+ "key": "review",
+ "title": "Review campaign assets",
+ "activity": "review",
+ "workstream": "campaign",
+ "depends_on": [
+ "draft"
+ ],
+ "verifies": [
+ "draft"
+ ],
+ "criteria": "Claims, tone, and links are checked; publication requires a separate decision."
+ }
+ ],
+ "final_acceptance": {
+ "item_key": "review",
+ "owner": "lead"
+ }
+ }
+ },
"three-items": {
"id": "gallery-item",
"session_id": "gallery-session",
@@ -12519,8 +13797,7 @@
"title": "Fix the typo in the README",
"criteria": "The heading reads “Billing service”."
}
- ],
- "note": ""
+ ]
}
}
}
diff --git a/surfaces/gui/src/gallery/states/proposal-examples.ts b/surfaces/gui/src/gallery/states/proposal-examples.ts
new file mode 100644
index 00000000..f2646cbe
--- /dev/null
+++ b/surfaces/gui/src/gallery/states/proposal-examples.ts
@@ -0,0 +1,344 @@
+// Synthetic, executable tool payloads. The gallery never classifies tasks from prose.
+export const launchProposal = {
+ title: "Give every customer a launch plan",
+ summary:
+ "Turn a won deal into an owned, dated plan—and show what changes when a milestone slips.",
+ targets: ["acme/billing-service · local workspace"],
+ external_actions: {
+ status: "none",
+ actions: [],
+ exclusions: ["Pushes, deployments, and outbound messages"],
+ explanation: "This rehearsal is limited to local changes and verification.",
+ },
+ activities: [
+ { id: "build", title: "Build", summary: "Implement the customer journey" },
+ {
+ id: "verify",
+ title: "Verify",
+ summary: "Independently check the results",
+ },
+ { id: "accept", title: "Accept", summary: "Review the complete outcome" },
+ ],
+ workstreams: [
+ {
+ id: "foundation",
+ title: "Plan, schedule & dependencies",
+ summary: "Shared data and scheduling foundation",
+ },
+ {
+ id: "experience",
+ title: "Workspace, timeline & portfolio",
+ summary: "Independent customer-facing surfaces",
+ },
+ {
+ id: "followthrough",
+ title: "Templates & reminders",
+ summary: "Reusable plans and local follow-through",
+ },
+ {
+ id: "quality",
+ title: "Verification & acceptance",
+ summary: "Independent evidence and final judgment",
+ },
+ ],
+ items: [
+ {
+ key: "plan",
+ title: "Launch plan data & API",
+ activity: "build",
+ workstream: "foundation",
+ depends_on: [],
+ verifies: [],
+ criteria:
+ "A won deal creates an owned plan; existing accounts remain intact.",
+ },
+ {
+ key: "graph",
+ title: "Dependencies & impact preview",
+ activity: "build",
+ workstream: "foundation",
+ depends_on: [],
+ verifies: [],
+ criteria:
+ "A three-day slip previews affected successors before applying changes; dependency cycles are rejected.",
+ },
+ {
+ key: "workspace",
+ title: "Launch workspace",
+ activity: "build",
+ workstream: "experience",
+ depends_on: [],
+ verifies: [],
+ criteria: "Owners can manage tasks without bypassing required work.",
+ },
+ {
+ key: "timeline",
+ title: "Interactive timeline",
+ activity: "build",
+ workstream: "experience",
+ depends_on: [],
+ verifies: [],
+ criteria: "Dates match the workspace after a schedule change.",
+ },
+ {
+ key: "portfolio",
+ title: "Portfolio attention",
+ activity: "build",
+ workstream: "experience",
+ depends_on: [],
+ verifies: [],
+ criteria:
+ "Teams can find overdue launches with correct access boundaries.",
+ },
+ {
+ key: "templates",
+ title: "Versioned launch templates",
+ activity: "build",
+ workstream: "followthrough",
+ depends_on: [],
+ verifies: [],
+ criteria:
+ "New launches use the chosen version; existing plans are unchanged.",
+ },
+ {
+ key: "reminders",
+ title: "Local reminders",
+ activity: "build",
+ workstream: "followthrough",
+ depends_on: [],
+ verifies: [],
+ criteria: "Due-date changes update in-app reminders without duplicates.",
+ },
+ {
+ key: "api-check",
+ title: "API & permissions",
+ activity: "verify",
+ workstream: "quality",
+ depends_on: ["plan", "graph"],
+ verifies: ["plan", "graph"],
+ criteria:
+ "Tests cover tenant boundaries, roles, completion rules, and scheduling.",
+ },
+ {
+ key: "browser-check",
+ title: "Browser journey & evidence",
+ activity: "verify",
+ workstream: "quality",
+ depends_on: ["workspace", "timeline", "portfolio"],
+ verifies: ["workspace", "timeline", "portfolio"],
+ criteria:
+ "The full journey passes with screenshots attached to board items.",
+ },
+ {
+ key: "upgrade-check",
+ title: "Upgrade & regression",
+ activity: "verify",
+ workstream: "quality",
+ depends_on: ["templates", "reminders"],
+ verifies: ["templates", "reminders"],
+ criteria: "Existing data survives and the previous journey still works.",
+ },
+ {
+ key: "accept",
+ title: "Accept the complete journey",
+ activity: "accept",
+ workstream: "quality",
+ depends_on: ["api-check", "browser-check", "upgrade-check"],
+ verifies: [],
+ criteria:
+ "Win a deal, adjust a milestone, verify affected views, and complete the plan.",
+ },
+ ],
+ final_acceptance: { item_key: "accept", owner: "lead" },
+};
+
+export const securityProposal = {
+ title: "Close the staging exposure gaps",
+ summary:
+ "Assess the approved staging targets, prepare fixes, and independently recheck the findings.",
+ targets: ["acme/billing-service", "sandbox-1 · approved staging environment"],
+ external_actions: {
+ status: "planned",
+ actions: [
+ "Run authenticated checks against sandbox-1",
+ "Open remediation pull requests in acme/billing-service",
+ ],
+ exclusions: [
+ "Production scans or infrastructure changes",
+ "Merging remediation pull requests",
+ ],
+ explanation:
+ "Only the staging targets named in the request are in scope. Active scans contact external systems.",
+ },
+ activities: [
+ { id: "assess", title: "Assess", summary: "Establish exposure" },
+ { id: "remediate", title: "Remediate", summary: "Prepare fixes" },
+ { id: "validate", title: "Validate", summary: "Independently recheck" },
+ ],
+ workstreams: [
+ {
+ id: "application",
+ title: "Application security",
+ summary: "Repository and dependency findings",
+ },
+ {
+ id: "cloud",
+ title: "Staging infrastructure",
+ summary: "Exposure and configuration checks",
+ },
+ {
+ id: "review",
+ title: "Remediation & validation",
+ summary: "Evidence-backed closure",
+ },
+ ],
+ items: [
+ {
+ key: "code",
+ title: "Assess repository findings",
+ activity: "assess",
+ workstream: "application",
+ depends_on: [],
+ verifies: [],
+ criteria:
+ "Findings identify affected code and include reproducible evidence.",
+ },
+ {
+ key: "infra",
+ title: "Assess staging exposure",
+ activity: "assess",
+ workstream: "cloud",
+ depends_on: [],
+ verifies: [],
+ criteria:
+ "Checks stay within the approved staging targets and report coverage gaps.",
+ },
+ {
+ key: "fix",
+ title: "Prepare remediation changes",
+ activity: "remediate",
+ workstream: "review",
+ depends_on: ["code", "infra"],
+ verifies: [],
+ criteria:
+ "Each proposed fix references its finding and includes regression coverage.",
+ },
+ {
+ key: "validate",
+ title: "Accept independently verified findings",
+ activity: "validate",
+ workstream: "review",
+ depends_on: ["fix"],
+ verifies: ["fix"],
+ criteria:
+ "Reported vulnerabilities no longer reproduce; unresolved risks remain explicitly documented.",
+ },
+ ],
+ final_acceptance: { item_key: "validate", owner: "assigned_worker" },
+};
+
+export const marketingProposal = {
+ title: "Prepare the customer launch campaign",
+ summary:
+ "Research the audience, create campaign drafts, and review claims before publication is considered.",
+ targets: ["Acme · customer launch campaign"],
+ external_actions: {
+ status: "undetermined",
+ actions: [],
+ exclusions: [
+ "Publishing before the user chooses channels and approves the copy",
+ ],
+ explanation:
+ "Publication channels and recipients have not been selected. Clarification is needed before any publishing or sending.",
+ },
+ activities: [
+ { id: "research", title: "Research", summary: "Establish the audience" },
+ { id: "create", title: "Create", summary: "Draft assets" },
+ { id: "review", title: "Review", summary: "Verify claims and tone" },
+ ],
+ workstreams: [
+ {
+ id: "campaign",
+ title: "Campaign preparation",
+ summary: "Audience, drafts, and publication-ready review",
+ },
+ ],
+ items: [
+ {
+ key: "research",
+ title: "Audience and message brief",
+ activity: "research",
+ workstream: "campaign",
+ depends_on: [],
+ verifies: [],
+ criteria:
+ "The brief identifies the audience and cites sources for factual claims.",
+ },
+ {
+ key: "draft",
+ title: "Campaign drafts",
+ activity: "create",
+ workstream: "campaign",
+ depends_on: ["research"],
+ verifies: [],
+ criteria:
+ "Drafts match the approved brief and make no unsupported claims.",
+ },
+ {
+ key: "review",
+ title: "Review campaign assets",
+ activity: "review",
+ workstream: "campaign",
+ depends_on: ["draft"],
+ verifies: ["draft"],
+ criteria:
+ "Claims, tone, and links are checked; publication requires a separate decision.",
+ },
+ ],
+ final_acceptance: { item_key: "review", owner: "lead" },
+};
+
+export const launchTeam = {
+ title: "The customer launch team",
+ summary:
+ "Seven builders own separate workstreams. Three verifiers independently check their results.",
+ groups: [
+ {
+ id: "builders",
+ title: "Builders",
+ summary: "One owner per implementation workstream",
+ },
+ {
+ id: "verifiers",
+ title: "Verifiers",
+ summary: "Independent checks and board evidence",
+ },
+ ],
+ members: launchProposal.items.slice(0, 10).map((task, i) => ({
+ persona: i < 7 ? "swe-worker" : "test-worker",
+ name: `${i < 7 ? "sam" : "maya"}-${i + 1}`,
+ reason: task.title,
+ group: i < 7 ? "builders" : "verifiers",
+ item_ids: [i + 1],
+ connectors: [],
+ resolved_model: "anthropic:claude-sonnet-4-8",
+ })),
+ enable_chat: true,
+ planned_items: launchProposal.items.map((task, i) => ({
+ id: i + 1,
+ title: task.title,
+ final_acceptance: {
+ id: 11,
+ title: "Accept the complete journey",
+ owner: "lead",
+ },
+ })),
+ lead_mode: "interactive",
+ offer: {},
+ other_connected: [],
+ runnable_models: [
+ { id: "anthropic:claude-sonnet-4-8", label: "Claude Sonnet 4.8" },
+ ],
+ lead_model: "anthropic:claude-sonnet-4-8",
+ model_options: {},
+};
diff --git a/surfaces/gui/src/gallery/states/team-request.ts b/surfaces/gui/src/gallery/states/team-request.ts
index 03a3d451..fbc55378 100644
--- a/surfaces/gui/src/gallery/states/team-request.ts
+++ b/surfaces/gui/src/gallery/states/team-request.ts
@@ -1,5 +1,6 @@
// `team_proposed` payloads (and the parked `gate: "team"` Inbox item's data — same fields).
import type { CardState } from "../types";
+import { launchTeam } from "./proposal-examples";
const MODELS = [
{ id: "anthropic:claude-opus-4-8", label: "Claude Opus 4.8" },
@@ -57,6 +58,7 @@ function roster(builders: number, testers: number, reviewers: number, docs: numb
const BIG_OFFER = { "swe-worker": ["github"], "test-worker": ["github"], "review-worker": ["github"], "docs-worker": [] };
export const teamRequestStates: CardState[] = [
+ { id: "launch-team", title: "Launch team · ten workers", payload: launchTeam },
{
id: "lead-suggested-github",
title: "Lead suggested GitHub",
diff --git a/surfaces/gui/src/gallery/states/work-items.ts b/surfaces/gui/src/gallery/states/work-items.ts
index e46cc2e0..400e10e7 100644
--- a/surfaces/gui/src/gallery/states/work-items.ts
+++ b/surfaces/gui/src/gallery/states/work-items.ts
@@ -1,7 +1,11 @@
// `items_proposed` payloads (and the parked `gate: "items"` Inbox item's data).
import type { CardState } from "../types";
+import { launchProposal, securityProposal, marketingProposal } from "./proposal-examples";
export const workItemsStates: CardState[] = [
+ { id: "launch-plan", title: "Launch plan · eleven tasks", payload: launchProposal },
+ { id: "security-plan", title: "Security · explicit external actions", payload: securityProposal },
+ { id: "marketing-plan", title: "Marketing · publishing undetermined", payload: marketingProposal },
{
id: "three-items",
title: "Three items",
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index 1fb6bda7..9743bd65 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -1,4 +1,36 @@
{
+ "proposal": {
+ "proposed_work": "Proposed work",
+ "proposed_team": "Proposed team",
+ "acceptance_criteria": "Acceptance criteria",
+ "final_acceptance": "Final acceptance",
+ "owner_lead": "Owner: Lead",
+ "owner_assigned_worker": "Owner: the worker assigned to this task",
+ "tasks_one": "{{count}} task",
+ "tasks_other": "{{count}} tasks",
+ "workers_one": "{{count}} worker",
+ "workers_other": "{{count}} workers",
+ "depends_on": "Depends on",
+ "verifies": "Verifies",
+ "targets": "Targets",
+ "external_actions": "External actions",
+ "external_none": "None planned",
+ "external_planned": "Planned actions",
+ "external_undetermined": "Not yet determined",
+ "not_planned": "Explicitly not planned",
+ "intent_not_permission": "Declared intent, not an access grant. Actions still follow approval settings and permissions.",
+ "approve_plan": "Approve plan",
+ "request_changes": "Request changes",
+ "what_changes": "What should change?",
+ "send_feedback": "Send feedback",
+ "cancel": "Cancel",
+ "worker_name": "Worker name",
+ "invalid_names": "Use unique worker names: 1–24 letters, numbers, dots, underscores, or hyphens. Lead, user, and board are reserved.",
+ "planned_responsibilities": "Planned responsibilities",
+ "connector_access": "Connector access",
+ "no_connectors": "No connectors selected",
+ "staffing_not_assignment": "Creating the team does not start these tasks. Approval lets the lead create, assign, and steer this team. Workers receive only the connectors you select."
+ },
"boot": {
"starting": "Starting OpenWorker…",
"restoring": "Restoring your session…"
@@ -1479,7 +1511,7 @@
"close_board": "Close board",
"open_worker_session": "Open this coworker's session",
"filed_by": "filed by {{creator}}",
- "done_when_line": "<label>Done when</label> — {{criteria}}",
+ "done_when_line": "<label>Acceptance criteria</label> — {{criteria}}",
"add_note_placeholder": "Add a note…",
"add_note_title": "Leaves a note on the item — never changes its state",
"changes_placeholder": "What needs to change?",
@@ -1536,7 +1568,7 @@
"not_now": "Not now",
"create_start": "Create team & start",
"proposed_items": "Proposed work items — {{count}}",
- "items_done_when": "Done when:",
+ "items_done_when": "Acceptance criteria:",
"show_less": "Show less",
"show_full_criteria": "Show full criteria",
"more_items_one": "+ {{count}} more item",
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index 809a26a0..b23abbfe 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -1,4 +1,36 @@
{
+ "proposal": {
+ "proposed_work": "工作提案",
+ "proposed_team": "团队提案",
+ "acceptance_criteria": "验收标准",
+ "final_acceptance": "最终验收",
+ "owner_lead": "负责人:主管",
+ "owner_assigned_worker": "负责人:被分配此任务的工作者",
+ "tasks_one": "{{count}} 个任务",
+ "tasks_other": "{{count}} 个任务",
+ "workers_one": "{{count}} 位工作者",
+ "workers_other": "{{count}} 位工作者",
+ "depends_on": "依赖任务",
+ "verifies": "验证任务",
+ "targets": "目标",
+ "external_actions": "外部操作",
+ "external_none": "未计划外部操作",
+ "external_planned": "计划的操作",
+ "external_undetermined": "尚未确定",
+ "not_planned": "明确不在计划内",
+ "intent_not_permission": "这是意图声明,不是访问授权。操作仍须遵循审批设置和权限。",
+ "approve_plan": "批准计划",
+ "request_changes": "请求修改",
+ "what_changes": "需要修改什么?",
+ "send_feedback": "发送反馈",
+ "cancel": "取消",
+ "worker_name": "工作者名称",
+ "invalid_names": "工作者名称必须唯一,使用 1–24 个字母、数字、点、下划线或连字符。lead、user 和 board 为保留名称。",
+ "planned_responsibilities": "计划职责",
+ "connector_access": "连接器访问权限",
+ "no_connectors": "未选择连接器",
+ "staffing_not_assignment": "创建团队不会启动这些任务。批准后,主管可以创建、分配和指导此团队。工作者仅获得您选择的连接器。"
+ },
"boot": {
"starting": "正在启动 OpenWorker…",
"restoring": "正在恢复你的会话…"
@@ -1459,7 +1491,7 @@
"close_board": "关闭看板",
"open_worker_session": "打开该同事的会话",
"filed_by": "由 {{creator}} 创建",
- "done_when_line": "<label>完成标准</label> —— {{criteria}}",
+ "done_when_line": "<label>验收标准</label> —— {{criteria}}",
"add_note_placeholder": "添加备注…",
"add_note_title": "在条目上留下备注 —— 不会改变其状态",
"changes_placeholder": "需要改什么?",
@@ -1506,7 +1538,7 @@
"not_now": "暂不",
"create_start": "创建团队并开始",
"proposed_items": "提议的工作项 —— {{count}}",
- "items_done_when": "完成标准:",
+ "items_done_when": "验收标准:",
"show_less": "收起",
"show_full_criteria": "显示完整标准",
"more_items_other": "+ 还有 {{count}} 项",
diff --git a/surfaces/gui/src/proposals.ts b/surfaces/gui/src/proposals.ts
new file mode 100644
index 00000000..94a9188a
--- /dev/null
+++ b/surfaces/gui/src/proposals.ts
@@ -0,0 +1,21 @@
+export interface ProposalGroup {
+ id: string;
+ title: string;
+ summary: string;
+}
+export interface ExternalActions {
+ status: "none" | "planned" | "undetermined";
+ actions: string[];
+ exclusions: string[];
+ explanation: string;
+}
+export interface ProposalTask {
+ key?: string;
+ title: string;
+ criteria: string;
+ description?: string;
+ activity?: string;
+ workstream?: string;
+ depends_on?: string[];
+ verifies?: string[];
+}
diff --git a/surfaces/gui/src/styles.css b/surfaces/gui/src/styles.css
index 8bd2bbec..daaafe9a 100644
--- a/surfaces/gui/src/styles.css
+++ b/surfaces/gui/src/styles.css
@@ -2099,6 +2099,48 @@ html[data-platform="linux"] ::-webkit-scrollbar-thumb:hover { background-color:
.team-dot.review { background: var(--warn-ink); }
/* Decomposition gate (proposed work items) */
+.proposal-card { padding: 22px; background: var(--panel); color: var(--ink); border-radius: 16px; overflow-wrap: anywhere; }
+.composer-wrap > .proposal-card { display: flex; flex-direction: column; max-height: min(65dvh, calc(100dvh - 220px)); }
+.composer-wrap > .proposal-card > .proposal-content { min-height: 0; overflow-y: auto; }
+.composer-wrap > .proposal-card > .proposal-actions { flex: none; }
+.proposal-heading { display: flex; gap: 12px; align-items: center; }
+.proposal-heading h3 { margin: 2px 0 0; font-size: var(--fs-heading); font-weight: 500; line-height: 1.3; }
+.proposal-mark { width: 38px; height: 38px; display: grid; place-items: center; background: var(--paper); border-radius: 10px; flex: none; }
+.proposal-label { display: block; font-size: var(--fs-meta); color: var(--muted); }
+.proposal-summary { margin: 16px 0 12px; color: var(--muted); font-size: var(--fs-ui); }
+.proposal-meta { display: flex; flex-wrap: wrap; gap: 6px 15px; color: var(--muted); font-size: var(--fs-meta); margin-bottom: 18px; }
+.proposal-group { border-bottom: 1px solid var(--line); }
+.proposal-group>summary { display: flex; align-items: center; gap: 10px; padding: 13px 0; list-style: none; cursor: pointer; }
+.proposal-group>summary::-webkit-details-marker { display: none; }
+.proposal-group>summary>svg { flex: none; color: var(--muted); }
+.proposal-group[open]>summary>svg { transform: rotate(90deg); }
+.proposal-group>summary>.proposal-muted { flex: none; }
+.proposal-group-title { min-width: 0; flex: 1; font-size: var(--fs-ui); font-weight: 500; }
+.proposal-group-title small { display: block; color: var(--muted); font-size: var(--fs-meta); font-weight: 400; margin-top: 3px; }
+.proposal-group-content { padding: 0 0 12px 24px; }
+.proposal-task { padding: 12px 0; border-top: 1px solid var(--line); }
+.proposal-task-title { font-weight: 500; margin-bottom: 8px; }
+.proposal-card p { margin-top: 4px; margin-bottom: 8px; }
+.proposal-criteria { white-space: pre-wrap; font-size: var(--fs-ui); }
+.proposal-muted { color: var(--muted); font-size: var(--fs-meta); }
+.proposal-final { margin-top: 16px; }
+.proposal-boundaries { display: grid; gap: 14px; margin-top: 16px; font-size: var(--fs-meta); }
+.proposal-boundaries ul { padding-left: 18px; margin: 5px 0 8px; }
+.proposal-permission-note { margin-top: 12px; }
+.proposal-access { display: grid; gap: 4px; border-top: 1px solid var(--line); padding-top: 14px; margin: 14px 0; font-size: var(--fs-meta); }
+.proposal-actions { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-top: 20px; }
+.proposal-actions .btn { display: inline-flex; gap: 8px; align-items: center; }
+.proposal-change { border-color: transparent; color: var(--muted); background: transparent; }
+.proposal-feedback { margin-top: 16px; }
+.proposal-feedback textarea { display: block; width: 100%; resize: vertical; margin: 6px 0 10px; padding: 10px; border: 1px solid var(--line-strong); border-radius: 8px; background: var(--panel); color: var(--ink); font: inherit; }
+.proposal-name { display: block; font-size: var(--fs-meta); color: var(--muted); margin: 8px 0; }
+.proposal-name input { display: block; width: 100%; max-width: 240px; padding: 6px 9px; color: var(--ink); background: var(--panel); border: 1px solid var(--line-strong); border-radius: 6px; font: inherit; }
+.proposal-responsibilities { display: grid; gap: 3px; font-size: var(--fs-meta); margin-bottom: 8px; }
+.proposal-card .teamreq-head { margin: 12px 0; color: var(--muted); }
+.proposal-card .teamreq-title { font-size: var(--fs-meta); font-weight: 400; color: var(--muted); }
+.proposal-card .teamreq-diamond { display: none; }
+.proposal-card .teamreq-roster { max-height: 400px; }
+@media(max-width: 520px) { .proposal-card { padding: 16px; } .proposal-group-content { padding-left: 8px; } }
.itemsreq-head { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; }
.itemsreq-title { font-weight: 600; font-size: var(--fs-ui); color: var(--ink); }
.itemsreq-note { font-size: var(--fs-meta); color: var(--muted); margin-bottom: 4px; }
diff --git a/surfaces/gui/src/types.ts b/surfaces/gui/src/types.ts
index 762c9048..fcda83b0 100644
--- a/surfaces/gui/src/types.ts
+++ b/surfaces/gui/src/types.ts
@@ -217,11 +217,17 @@ export type Item =
| {
// The staffing gate (agent teams): a lead proposes its worker roster.
kind: "teamreq";
+ title?: string;
+ summary?: string;
+ groups?: import("./proposals").ProposalGroup[];
+ planned_items?: { id: number; title: string; final_acceptance?: { id: number; title: string; owner: "lead" | "assigned_worker" } }[];
toolCallId?: string;
// connectors = the LEAD'S SUGGESTION for this worker (arrives ticked on the card);
// connector_reasons = why, per suggested connector.
members: {
persona: string;
+ group?: string;
+ item_ids?: number[];
name?: string;
model?: string;
reason?: string;
@@ -262,8 +268,15 @@ export type Item =
| {
// The decomposition gate: a lead proposes work items; approval creates them.
kind: "itemsreq";
+ title?: string;
+ summary?: string;
+ targets?: string[];
+ external_actions?: import("./proposals").ExternalActions;
+ activities?: import("./proposals").ProposalGroup[];
+ workstreams?: import("./proposals").ProposalGroup[];
+ final_acceptance?: { item_key: string; owner: "lead" | "assigned_worker" };
toolCallId?: string;
- items: { title: string; criteria: string; description?: string }[];
+ items: import("./proposals").ProposalTask[];
note?: string;
resolved?: "approved" | "rejected";
}
diff --git a/tests/proposal_fixtures.py b/tests/proposal_fixtures.py
new file mode 100644
index 00000000..6dfe8136
--- /dev/null
+++ b/tests/proposal_fixtures.py
@@ -0,0 +1,22 @@
+"""Explicit synthetic intent for proposal tests; never used by production code."""
+from copy import deepcopy
+
+
+def work_proposal(items=None):
+ rows = deepcopy(items or [{"title": "Verify invoices", "criteria": "Tests pass"}])
+ rows = [{**row, "key": f"task-{i}", "activity": "review", "workstream": "billing",
+ "depends_on": [], "verifies": []} for i, row in enumerate(rows)]
+ return {"title": "Verify billing", "summary": "Check the Acme billing outcome.",
+ "targets": ["acme/billing-service"],
+ "external_actions": {"status": "none", "actions": [], "exclusions": [], "explanation": "Local test fixture only."},
+ "activities": [{"id": "review", "title": "Review", "summary": "Independent checks"}],
+ "workstreams": [{"id": "billing", "title": "Billing", "summary": "Customer invoices"}],
+ "items": rows, "final_acceptance": {"item_key": rows[-1]["key"], "owner": "lead"}}
+
+
+def team_proposal(members=None):
+ return {"title": "Billing team", "summary": "Independently verify customer invoices.",
+ "groups": [{"id": "review", "title": "Reviewers", "summary": "Check the outcome"}],
+ "enable_chat": False,
+ "members": [{"reason": "Verify the outcome", "group": "review", "item_ids": [], **m}
+ for m in deepcopy(members or [{"persona": "test-worker", "name": "sam"}])]}
diff --git a/tests/test_gallery_contract.py b/tests/test_gallery_contract.py
index e004ef88..73a526c6 100644
--- a/tests/test_gallery_contract.py
+++ b/tests/test_gallery_contract.py
@@ -21,6 +21,7 @@ import pytest
from coworker.server.manager import SessionManager
from coworker.sessions import SessionRecord
+from proposal_fixtures import work_proposal, team_proposal
CONTRACT = Path(__file__).resolve().parents[1] / "surfaces/gui/src/gallery/states.contract.json"
OPUS, SONNET = "anthropic:claude-opus-4-8", "anthropic:claude-sonnet-4-8"
@@ -96,6 +97,7 @@ async def test_staffing_card_payload_matches_the_gallery(manager, contract):
],
"note": "Two workers.",
}
+ args = team_proposal(args["members"])
task, item = await _parked(manager, approve(args, "t1"), "Create this team?")
data = item.data or {}
canonical, states = _inbox_data(card)
@@ -118,6 +120,7 @@ async def test_work_items_payload_matches_the_gallery(manager, contract):
card = contract["work-items"]
approve = manager.inbox_items_approver("lead-sid", "swe-lead")
args = {"items": [{"title": "Cap the backoff", "criteria": "no wait exceeds maxDelayMs", "description": "in retry.ts"}], "note": "one item"}
+ args = work_proposal(args["items"])
task, item = await _parked(manager, approve(args, "t2"), "Approve the proposed")
canonical, states = _inbox_data(card)
problems = _compare("items gate", item.data or {}, canonical, states)
diff --git a/tests/test_gate_sync.py b/tests/test_gate_sync.py
index eed3631e..3242ded7 100644
--- a/tests/test_gate_sync.py
+++ b/tests/test_gate_sync.py
@@ -5,12 +5,13 @@ import pytest
from test_engine import ScriptedProvider, _text_turn, _tool_turn
from test_team_live_gaps import manager
+from proposal_fixtures import work_proposal, team_proposal
@pytest.mark.parametrize("approved", [True, False])
@pytest.mark.parametrize("name,args,event_name", [
- ("propose_team", {"members": [{"persona": "test-worker", "name": "Sam"}]}, "team_proposed"),
- ("propose_work_items", {"items": [{"title": "Verify invoices", "criteria": "Tests pass"}]}, "items_proposed"),
+ ("propose_team", team_proposal(), "team_proposed"),
+ ("propose_work_items", work_proposal(), "items_proposed"),
])
def test_external_gate_answer_broadcasts_matching_completion_to_all_viewers(manager, approved, name, args, event_name):
manager.provider = ScriptedProvider([_tool_turn(name, args, "proposal-id"), _text_turn("Finished")])
diff --git a/tests/test_proposal_contract.py b/tests/test_proposal_contract.py
new file mode 100644
index 00000000..f0255657
--- /dev/null
+++ b/tests/test_proposal_contract.py
@@ -0,0 +1,124 @@
+import copy
+import json
+from pathlib import Path
+
+import pytest
+
+from coworker.teams.model import Actor, Role
+from coworker.teams.proposals import validate_work_proposal, validate_team_proposal
+from coworker.teams.store import TeamStore
+from proposal_fixtures import work_proposal, team_proposal
+from test_gallery_contract import manager, _parked
+
+
+def test_domain_examples_are_valid_tool_arguments():
+ contract = json.loads((Path(__file__).parents[1] / "surfaces/gui/src/gallery/states.contract.json").read_text())
+ for name in ("launch-plan", "security-plan", "marketing-plan"):
+ proposal = contract["cards"]["work-items"]["states"][name]
+ assert validate_work_proposal(proposal) == proposal
+
+
[email protected]("field", ["title", "summary", "targets", "external_actions", "activities", "workstreams", "final_acceptance"])
+def test_new_work_contract_requires_explicit_information(field):
+ proposal = work_proposal()
+ del proposal[field]
+ with pytest.raises(ValueError, match=field):
+ validate_work_proposal(proposal)
+
+
[email protected]("status,actions,valid", [("none", [], True), ("planned", ["Open a PR"], True),
+ ("undetermined", [], True), ("none", ["Deploy"], False), ("planned", [], False), ("undetermined", ["Scan"], False)])
+def test_external_intent_is_not_inferred(status, actions, valid):
+ proposal = work_proposal()
+ proposal["external_actions"].update(status=status, actions=actions)
+ if valid:
+ assert validate_work_proposal(proposal)["external_actions"]["status"] == status
+ else:
+ with pytest.raises(ValueError):
+ validate_work_proposal(proposal)
+
+
+def test_references_and_cycles_are_rejected_before_writing():
+ proposal = work_proposal([{"title": "Assess", "criteria": "Findings have evidence"},
+ {"title": "Verify", "criteria": "Findings are rechecked"}])
+ proposal["items"][0]["depends_on"] = ["task-1"]
+ proposal["items"][1]["depends_on"] = ["task-0"]
+ with pytest.raises(ValueError, match="cycle"):
+ validate_work_proposal(proposal)
+ proposal["items"][0]["depends_on"] = ["missing"]
+ with pytest.raises(ValueError, match="existing"):
+ validate_work_proposal(proposal)
+
+
+def test_accepted_metadata_and_dependencies_survive_rebuild(tmp_path):
+ store = TeamStore(tmp_path / "board.db")
+ actor = Actor("lead", Role.LEAD)
+ proposal = work_proposal([{"title": "Assess", "criteria": "Findings have evidence"},
+ {"title": "Verify", "criteria": "Findings are rechecked"}])
+ proposal["items"][1].update(depends_on=["task-0"], verifies=["task-0"])
+ result = store.create_proposal("acme", actor, proposal)
+ assert [i["key"] for i in result["items"]] == ["task-0", "task-1"]
+ before = store.get_item("acme", 2, actor=actor)
+ assert before["state"] == "open" and before["assignee"] == "lead"
+ assert before["proposal"]["external_actions"] == proposal["external_actions"]
+ assert before["proposal"]["verifies"] == [1]
+ assert store.get_item("acme", 1, actor=actor)["assignee"] == ""
+ store.rebuild("acme")
+ assert store.get_item("acme", 2, actor=actor) == before
+ assert store.verify_chain("acme")
+ store.close()
+
+
+def test_failed_batch_does_not_leave_partial_items_or_events(tmp_path, monkeypatch):
+ store = TeamStore(tmp_path / "board.db")
+ proposal = work_proposal([{"title": "First", "criteria": "Verified"}, {"title": "Second", "criteria": "Verified"}])
+ original = store._apply
+ def fail_second(space, seq, ts, kind, actor, item_id, payload):
+ if item_id == 2:
+ raise RuntimeError("write failure")
+ return original(space, seq, ts, kind, actor, item_id, payload)
+ monkeypatch.setattr(store, "_apply", fail_second)
+ with pytest.raises(RuntimeError):
+ store.create_proposal("acme", Actor("lead", Role.LEAD), proposal)
+ assert store.event_count("acme") == 0
+ assert store.list_items("acme", Actor("lead", Role.LEAD)) == []
+
+
+def test_staffing_requires_declared_groups_and_unique_names():
+ proposal = team_proposal()
+ assert validate_team_proposal(proposal) == proposal
+ proposal["members"][0]["group"] = "unknown"
+ with pytest.raises(ValueError, match="group"):
+ validate_team_proposal(proposal)
+ proposal = team_proposal()
+ proposal["members"].append(copy.deepcopy(proposal["members"][0]))
+ with pytest.raises(ValueError, match="unique"):
+ validate_team_proposal(proposal)
+
+
+async def test_server_resolves_responsibilities_and_preserves_human_name_without_assigning(manager):
+ plan = work_proposal([{"title": "Assess", "criteria": "Evidence exists"}, {"title": "Accept", "criteria": "Evidence checked"}])
+ created = manager.board_create_items("lead-sid", plan["items"], proposal=plan)
+ item_id = created["items"][0]["id"]
+ proposal = team_proposal([{"persona": "test-worker", "name": "maya", "item_ids": [item_id]}])
+ approve = manager.inbox_team_approver("lead-sid", "swe-lead")
+ task, prompt = await _parked(manager, approve(proposal, "staff"), "Create this team?")
+ assert prompt.data["planned_items"][0]["title"] == "Assess"
+ assert prompt.data["planned_items"][0]["final_acceptance"]["owner"] == "lead"
+ manager.inbox.resolve(prompt.id, json.dumps({"approved": True, "members": [{"name": "maya-custom", "connectors": []}]}))
+ result = await task
+ assert result["approved"] is True
+ assert result["workers"][0]["actor"] == "maya-custom"
+ record = manager.session_store.load("lead-sid")
+ space = manager._space_for(record, record.workspace)
+ item = manager.team_store.get_item(space, item_id, actor=Actor("lead", Role.LEAD))
+ assert item["assignee"] == "" and item["state"] == "open"
+
+
+async def test_unknown_board_responsibilities_do_not_park_a_card(manager):
+ proposal = team_proposal([{"persona": "test-worker", "name": "maya", "item_ids": [999]}])
+ result = await manager.inbox_team_approver("lead-sid", "swe-lead")(proposal, "invalid")
+ assert not result["approved"]
+ assert not manager.inbox.pending("lead-sid")
diff --git a/tests/test_worker_connectors.py b/tests/test_worker_connectors.py
index 5f7ebc96..ea29cd47 100644
--- a/tests/test_worker_connectors.py
+++ b/tests/test_worker_connectors.py
@@ -107,7 +107,8 @@ async def test_lead_suggestions_outside_the_default_set_need_the_users_words(man
approve = manager.inbox_team_approver("lead-sid", "swe-lead")
# No reason for Slack (outside swe-worker's default set) and Jira is not connected:
# the proposal bounces back to the lead with what to do, and nothing is parked.
- bounced = await approve({"members": [{"persona": "swe-worker", "name": "nia", "connectors": ["slack", "jira"]}]}, "t0")
+ from proposal_fixtures import team_proposal
+ bounced = await approve(team_proposal([{"persona": "swe-worker", "name": "nia", "connectors": ["slack", "jira"]}]), "t0")
assert bounced["approved"] is False
assert any("slack" in p and "quote" in p for p in bounced["problems"])
assert any("jira" in p and "request_connector" in p for p in bounced["problems"])
@@ -115,7 +116,7 @@ async def test_lead_suggestions_outside_the_default_set_need_the_users_words(man
# With the user's words as the reason it reaches the card, carrying what the card needs.
members = [{"persona": "swe-worker", "name": "nia", "connectors": ["GitHub", "slack"],
"connector_reasons": {"github": "pushes the branch", "slack": 'you asked: "post the summary in Slack"'}}]
- task = asyncio.create_task(approve({"members": members}, "t1"))
+ task = asyncio.create_task(approve(team_proposal(members), "t1"))
for _ in range(50):
await asyncio.sleep(0.02)
pending = manager.inbox.list(session_id="lead-sid", state="pending")
@@ -381,7 +382,8 @@ async def test_staffing_gate_works_without_a_socket(manager):
_lead(manager)
approve = manager.inbox_team_approver("lead-sid", "swe-lead")
- task = asyncio.create_task(approve({"members": [{"persona": "swe-worker", "name": "nia", "connectors": ["github"]}, {"persona": "test-worker", "name": "checks"}]}, "t1"))
+ from proposal_fixtures import team_proposal
+ task = asyncio.create_task(approve(team_proposal([{"persona": "swe-worker", "name": "nia", "connectors": ["github"]}, {"persona": "test-worker", "name": "checks"}]), "t1"))
for _ in range(50):
await asyncio.sleep(0.02)
pending = [i for i in manager.inbox.list(session_id="lead-sid", state="pending") if i.title == "Create this team?"]
@@ -410,16 +412,18 @@ async def test_items_gate_and_connector_ask_work_without_a_socket(manager):
_lead(manager)
approve = manager.inbox_items_approver("lead-sid", "swe-lead")
- task = asyncio.create_task(approve({"items": [{"title": "Cap the backoff", "criteria": "no wait exceeds maxDelayMs"}], "note": "one item is enough"}, "t2"))
+ from proposal_fixtures import work_proposal
+ proposal = work_proposal([{"title": "Cap the backoff", "criteria": "no wait exceeds maxDelayMs"}])
+ task = asyncio.create_task(approve(proposal, "t2"))
for _ in range(50):
await asyncio.sleep(0.02)
pending = [i for i in manager.inbox.list(session_id="lead-sid", state="pending") if i.title.startswith("Approve the proposed")]
if pending:
break
- assert pending and "Done when: no wait exceeds" in pending[0].body
+ assert pending and "Acceptance criteria: no wait exceeds" in pending[0].body
assert (pending[0].data or {}).get("gate") == "items" and (pending[0].data or {})["items"][0]["title"] == "Cap the backoff"
# The lead's note reaches the Inbox card too (it used to be inline only).
- assert pending[0].data["note"] == "one item is enough"
+ assert pending[0].data["summary"] == proposal["summary"]
manager.inbox.resolve(pending[0].id, '{"approved": true}')
result = await task
assert result.get("approved") is True or result.get("ok") is True