Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(squads): direct member handoff mode with guardrails and member briefs (MUL-9986) (#11353)
Jiayuan Zhang42fc65ef409c
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex c33848bb0b..27c95cf150 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -556,7 +556,8 @@ Migration depuis l'ancien découpage CSV : remplacez `--attachment a,b` par `--a| | `search <query>` | Rechercher des skills | || | `files list/upsert/delete <skill-id>` | Gérer les fichiers d'un skill | `list` : `--with-content` ; `upsert` / `delete` : `--base-revision` (refuse d'écraser une modification concurrente avec HTTP 409) || | `label list/add/remove <skill-id>` | Gérer les étiquettes d'un skill | `add` / `remove` : `<label-id>` accepte un UUID complet ou un préfixe court |-| `squad` | `list/get/create/update/delete` | Gérer les squads (`delete` archive) | |+| `squad` | `list/get/create/update/delete` | Gérer les squads (`delete` archive) | `update` : `--name`, `--description`, `--instructions`, `--leader`, `--avatar-url`, `--handoff-mode` (`leader` ou `direct` ; voir [Mode de collaboration](/squads#mode-de-collaboration)) |+| | `briefs <squad>` | Afficher le contexte de squad que reçoit chaque agent membre ; nécessite le droit de gérer le squad | `--agent` (nom ou ID) || | `member list/add/set-role/remove` | Gérer les membres d'un squad | || | `activity <issue-id> <outcome>` | Enregistrer une évaluation du chef | || `chat` | `history`, `thread [id]` | Lire la session de messagerie externe qu'un agent traite actuellement | `--limit`, `--before` |diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex 3068579187..5f27b2851d 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -548,7 +548,8 @@ CSV 形式からの移行: 2 つのファイルを添付する場合は `--attac| | `search <query>` | スキルを検索 | || | `files list/upsert/delete <skill-id>` | スキル内のファイルを管理 | `list`: `--with-content`;`upsert` / `delete`: `--base-revision`(更新済みなら HTTP 409 で上書きを拒否) || | `label list/add/remove <skill-id>` | スキルのラベルを管理 | `add` / `remove`: `<label-id>` は完全な UUID または短いプレフィックス |-| `squad` | `list/get/create/update/delete` | スクワッドを管理(`delete` はアーカイブ) | |+| `squad` | `list/get/create/update/delete` | スクワッドを管理(`delete` はアーカイブ) | `update`:`--name`、`--description`、`--instructions`、`--leader`、`--avatar-url`、`--handoff-mode`(`leader` または `direct`。[連携方法](/squads#連携方法)を参照) |+| | `briefs <squad>` | 各エージェントメンバーが受け取るスクワッドの内容を表示。スクワッドを管理できる権限が必要 | `--agent`(名前または ID) || | `member list/add/set-role/remove` | スクワッドのメンバーを管理 | || | `activity <issue-id> <outcome>` | リーダーの評価を記録 | || `chat` | `history`、`thread [id]` | エージェントが現在処理している外部チャットセッションを読み取り | `--limit`、`--before` |diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex 5064467475..d276c45425 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -548,7 +548,8 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| | `search <query>` | 스킬 검색 | || | `files list/upsert/delete <skill-id>` | 스킬 내부 파일 관리 | `list`: `--with-content`; `upsert` / `delete`: `--base-revision`(내용이 변경되었으면 HTTP 409로 덮어쓰기 거부) || | `label list/add/remove <skill-id>` | 스킬 라벨 관리 | `add` / `remove`: `<label-id>`에 전체 UUID 또는 짧은 접두사 사용 가능 |-| `squad` | `list/get/create/update/delete` | 스쿼드 관리(`delete`는 보관) | |+| `squad` | `list/get/create/update/delete` | 스쿼드 관리(`delete`는 보관) | `update`: `--name`, `--description`, `--instructions`, `--leader`, `--avatar-url`, `--handoff-mode`(`leader` 또는 `direct`, [협업 방식](/squads#협업-방식) 참고) |+| | `briefs <squad>` | 각 에이전트 멤버가 받는 스쿼드 내용 보기. 스쿼드를 관리할 권한 필요 | `--agent`(이름 또는 ID) || | `member list/add/set-role/remove` | 스쿼드 멤버 관리 | || | `activity <issue-id> <outcome>` | 리더 평가 기록 | || `chat` | `history`, `thread [id]` | 에이전트가 현재 처리 중인 외부 채팅 대화 읽기 | `--limit`, `--before` |diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex b78f4d5097..300fb39028 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -565,7 +565,8 @@ Migration from CSV parsing: replace `--attachment a,b` with `--attachment a --at| | `search <query>` | Search skills | || | `files list/upsert/delete <skill-id>` | Manage the files inside a skill | `list`: `--with-content`; `upsert` / `delete`: `--base-revision` (rejects stale overwrites with HTTP 409) || | `label list/add/remove <skill-id>` | Manage labels on a skill | `add` / `remove`: `<label-id>` accepts a full UUID or short prefix |-| `squad` | `list/get/create/update/delete` | Manage squads (`delete` archives) | |+| `squad` | `list/get/create/update/delete` | Manage squads (`delete` archives) | `update`: `--name`, `--description`, `--instructions`, `--leader`, `--avatar-url`, `--handoff-mode` (`leader` or `direct`; see [Collaboration mode](/squads#collaboration-mode)) |+| | `briefs <squad>` | Show the squad context each agent member receives; requires permission to manage the squad | `--agent` (name or ID) || | `member list/add/set-role/remove` | Manage squad members | || | `activity <issue-id> <outcome>` | Record a leader evaluation | || `chat` | `history`, `thread [id]` | Read the external chat session an agent is currently handling | `--limit`, `--before` |diff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdxindex b03c99a40d..5774f764e5 100644--- a/apps/docs/content/docs/cli.zh-Hant.mdx+++ b/apps/docs/content/docs/cli.zh-Hant.mdx@@ -539,7 +539,8 @@ CLI 配置檔案包含可代表你訪問 Multica 的令牌。不要提交到倉| | `search <query>` | 搜尋 skill | || | `files list/upsert/delete <skill-id>` | 管理 skill 內的檔案 | `list`:`--with-content`;`upsert` / `delete`:`--base-revision`(內容已變更時回傳 HTTP 409 拒絕覆寫) || | `label list/add/remove <skill-id>` | 管理 skill 上的標籤 | `add` / `remove`:`<label-id>` 可使用完整 UUID 或短字首 |-| `squad` | `list/get/create/update/delete` | 管理小隊(`delete` 為歸檔) | |+| `squad` | `list/get/create/update/delete` | 管理小隊(`delete` 為歸檔) | `update`:`--name`、`--description`、`--instructions`、`--leader`、`--avatar-url`、`--handoff-mode`(`leader` 或 `direct`,見[協作方式](/squads#協作方式)) |+| | `briefs <squad>` | 查看每個 AI 代理成員實際收到的小隊內容;需要有管理該小隊的權限 | `--agent`(名稱或 ID) || | `member list/add/set-role/remove` | 管理小隊成員 | || | `activity <issue-id> <outcome>` | 記錄隊長評價 | || `chat` | `history`、`thread [id]` | 讀取 AI 代理當前正在處理的外部聊天會話 | `--limit`、`--before` |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex b5976b635c..277bb657be 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -548,7 +548,8 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| | `search <query>` | 搜索 skill | || | `files list/upsert/delete <skill-id>` | 管理 skill 内的文件 | `list`:`--with-content`;`upsert` / `delete`:`--base-revision`(内容已变更时返回 HTTP 409 拒绝覆盖) || | `label list/add/remove <skill-id>` | 管理 skill 上的标签 | `add` / `remove`:`<label-id>` 可使用完整 UUID 或短前缀 |-| `squad` | `list/get/create/update/delete` | 管理小队(`delete` 为归档) | |+| `squad` | `list/get/create/update/delete` | 管理小队(`delete` 为归档) | `update`:`--name`、`--description`、`--instructions`、`--leader`、`--avatar-url`、`--handoff-mode`(`leader` 或 `direct`,见[协作方式](/squads#协作方式)) |+| | `briefs <squad>` | 查看每个智能体成员实际收到的小队内容;需要有管理该小队的权限 | `--agent`(名称或 ID) || | `member list/add/set-role/remove` | 管理小队成员 | || | `activity <issue-id> <outcome>` | 记录队长评价 | || `chat` | `history`、`thread [id]` | 读取智能体当前正在处理的外部聊天会话 | `--limit`、`--before` |diff --git a/apps/docs/content/docs/squads.fr.mdx b/apps/docs/content/docs/squads.fr.mdxindex 71d85afcc0..d75da49e1c 100644--- a/apps/docs/content/docs/squads.fr.mdx+++ b/apps/docs/content/docs/squads.fr.mdx@@ -23,7 +23,7 @@ Lorsque le périmètre est clair, assignez directement la tâche à l'[agent](/a| **Chef** | Doit être un agent. Reçoit le travail assigné au squad et décide comment le traiter. || **Membres** | Peuvent être des agents ou des membres humains. Un même membre peut faire partie de plusieurs squads. || **Descriptions de rôle** | Indiquent au chef pour quel travail chaque membre est adapté. Contexte uniquement — elles n'accordent aucune permission et ne déclenchent jamais les membres automatiquement. |-| **Instructions du squad** | Contiennent les règles de routage, les normes de collaboration et le contexte commun au squad. Fournies au chef uniquement. |+| **Instructions du squad** | Contiennent les règles de routage, les normes de collaboration et le contexte commun au squad. Fournies au chef et à chaque agent membre qui travaille sur les tâches du squad. |Pour créer un squad, il faut un nom et un chef. Le chef du squad en devient automatiquement membre ; vous pouvez ensuite ajouter d'autres membres et renseigner les descriptions de rôle et les instructions du squad.@@ -36,7 +36,7 @@ Lorsqu'une tâche qui n'est pas dans À planifier est assignée à un squad, Mul3. **Le chef publie un commentaire de délégation.** Le commentaire mentionne avec `@` le ou les membres choisis, en reprenant exactement le markdown de mention fourni par le roster. Chaque agent mentionné reçoit une nouvelle exécution, et chaque membre humain mentionné reçoit une notification.4. **Le chef consigne son évaluation** via `multica squad activity <issue-id> action --reason "..."`. Cela ajoute une entrée dans la chronologie d'activité de la tâche, afin que les humains voient que le chef a bien évalué le déclencheur.5. **Le tour de répartition laisse la tâche parente en `in_progress`.** Même contrat de statut géré par l'agent que pour une assignation directe à un agent — coordonner le squad revient à traiter la demande de la tâche parente, qui passe donc de `todo` à `in_progress` ; répartir le travail entre les membres n'est pas une livraison, donc elle y reste pendant que le squad travaille.-6. **Le chef s'arrête.** Le chef ne réalise pas lui-même l'implémentation. Lorsque le membre délégué publie un retour — ou lorsqu'une sous-tâche ou une barrière d'étape se ferme — le chef est redéclenché pour lire la mise à jour et, au choix, déléguer l'étape suivante, escalader, passer la tâche parente en `in_review` une fois l'objectif global atteint, ou rester silencieux. `done` est laissé à un relecteur humain ou aux intégrations existantes (par exemple une PR avec intention de fermeture qui est fusionnée).+6. **Le chef s'arrête.** Le chef ne réalise pas lui-même l'implémentation. Lorsque le membre délégué publie un retour — ou lorsqu'une sous-tâche ou une barrière d'étape se ferme — le chef est redéclenché (sauf si le squad laisse [les membres se passer la main](#mode-de-collaboration)) pour lire la mise à jour et, au choix, déléguer l'étape suivante, escalader, passer la tâche parente en `in_review` une fois l'objectif global atteint, ou rester silencieux. `done` est laissé à un relecteur humain ou aux intégrations existantes (par exemple une PR avec intention de fermeture qui est fusionnée).Si la tâche est dans **À planifier**, le chef n'est pas déclenché : À planifier est une zone d'attente, selon la même règle que pour une assignation directe à un agent.@@ -54,6 +54,28 @@ La démo ci-dessous confie une tâche de préparation d'événement au Squad év- **Squad Roster** — la ligne du chef lui-même, plus une ligne par membre non archivé. Chaque ligne contient exactement le markdown de mention (`[@Name](mention://agent/<uuid>)` ou `[@Name](mention://member/<uuid>)`) que le chef doit coller — taper un simple `@name` ne déclenche personne.- **Squad Instructions** — vos consignes personnalisées pour ce squad (définies sur la page de détail du squad ou via `multica squad update --instructions`). Utilisez-les pour les règles de routage (« confier le travail de base de données à Alice, le frontend à Bob »), les politiques d'escalade ou tout ce que le chef doit savoir et qui ne figure pas déjà dans la tâche.+### Ce que voient les membres++Lorsqu'un agent membre récupère une exécution sur une tâche assignée à son squad, un **Squad Member Brief** est ajouté à ses instructions : son rôle, les autres membres avec leur markdown de mention exact, les instructions du squad et la façon de passer la main selon le mode de collaboration du squad. Les personnes qui peuvent gérer le squad peuvent prévisualiser ce que reçoit chaque agent dans **Ce que reçoivent les membres**, sur la page de détail du squad.++## Mode de collaboration++Le réglage **Collaboration** de la page de détail du squad décide qui choisit l'étape suivante quand un membre a terminé. Seules les personnes qui peuvent gérer le squad peuvent le modifier.++| Mode | Effet |+|---|---|+| **Le chef attribue** (par défaut) | Chaque réponse d'un membre revient au chef, qui choisit l'étape suivante. Les squads existants conservent ce mode. |+| **Les membres se passent la main** | Le chef attribue la première étape et gère les exceptions. Un membre mentionne le membre suivant avec `@`, qui s'exécute sans réveiller le chef. Un membre qui mentionne une personne attend sa réponse plutôt que le chef. |++Avec **Les membres se passent la main**, la tâche revient au chef lorsque :++- les deux mêmes membres se la sont déjà renvoyée 3 tours ;+- la tâche a déjà connu 20 passations entre membres sur les dernières 24 heures ;+- l'exécution d'un membre échoue ;+- la réponse d'un membre ne désigne pas le responsable suivant.++Ces limites sont fixes. Chaque passation apparaît dans la chronologie de la tâche, avec son tour et, quand la tâche revient au chef, la raison.+## Règles de redéclenchement du chefAprès la première répartition, le chef est automatiquement réveillé par **la plupart des commentaires suivants** sur la tâche. Les règles exactes :@@ -64,7 +86,7 @@ Après la première répartition, le chef est automatiquement réveillé par **l| Un membre du squad publie un point d'avancement sans `@mention` | Oui | Le chef réévalue si une étape suivante est nécessaire || Un membre ou un agent de travail mentionne explicitement le chef du squad assigné comme agent | Oui | Le chef agit dans son rôle de chef et peut consigner sa décision avec `multica squad activity` || Un membre humain mentionne uniquement d'autres membres ou `@all` | Non | Les personnes reçoivent des notifications ; le routage implicite vers les agents est désactivé |-| Un agent autre que le chef mentionne uniquement des membres ou `@all` | Oui | Le résultat du worker revient au chef ; les personnes reçoivent leurs notifications habituelles |+| Un agent autre que le chef mentionne uniquement des membres ou `@all` | Oui | Le résultat du worker revient au chef ; les personnes reçoivent leurs notifications habituelles. Avec **Les membres se passent la main**, un membre du squad qui mentionne une personne ne réveille pas le chef || Quelqu'un mentionne explicitement un agent ou un squad | Seulement s'il est nommé | Seuls les agents ou chefs de squad nommés sont exécutés ; aucun repli supplémentaire vers le chef || Le propre commentaire du chef | Non | Bloqué pour que le chef ne se déclenche pas lui-même || Un commentaire ne contenant qu'une référence croisée à une tâche (`[MUL-123](mention://issue/...)`) | Oui | Les références à des tâches ne constituent pas un routage |@@ -114,6 +136,8 @@ multica squad member add <squad-id> \--member-id <agent-or-member-id> \--type agent \--role "Responsable de l'implémentation frontend"+multica squad update <squad-id> --handoff-mode direct+multica squad briefs <squad-id> --agent <agent-name-or-id>```Toutes les commandes dans [Utiliser le CLI](/cli).diff --git a/apps/docs/content/docs/squads.ja.mdx b/apps/docs/content/docs/squads.ja.mdxindex a4be587366..bbc851e87e 100644--- a/apps/docs/content/docs/squads.ja.mdx+++ b/apps/docs/content/docs/squads.ja.mdx@@ -23,7 +23,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";| **リーダー** | 必ずエージェントです。スクワッドに割り当てられた仕事を受け取り、どう処理するかを決めます。 || **メンバー** | エージェントでも人間のメンバーでもかまいません。同じメンバーが複数のスクワッドに参加できます。 || **ロールの説明** | 各メンバーがどんな仕事に向いているかをリーダーに伝えます。あくまでコンテキストであり、権限を付与したりメンバーを自動的にトリガーしたりはしません。 |-| **スクワッドの指示** | ルーティングのルール、協働の進め方、スクワッド全体で共有すべき背景を保存します。リーダーにだけ提供されます。 |+| **スクワッドの指示** | ルーティングのルール、協働の進め方、スクワッド全体で共有すべき背景を保存します。リーダーと、スクワッドのタスクに取り組む各エージェントメンバーに提供されます。 |スクワッドの作成には、名前の入力とリーダーの選択が必要です。スクワッドのリーダーは自動的にメンバーになります。その後、メンバーの追加、ロールの説明、スクワッドの指示を続けて設定できます。@@ -36,7 +36,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";3. **リーダーが割り振りのコメントを投稿します。** 名簿に載っているメンション用の markdown をそのまま使って、選んだメンバーを `@` メンションします。メンションされたエージェントには新しい実行がキューに入り、メンションされた人間のメンバーには通知が届きます。4. **リーダーが評価を記録します**:`multica squad activity <issue-id> <outcome> --reason "..."`。この記録はタスクのアクティビティに残るので、リーダーが毎回どう判断したかを人間が後から確認できます。5. **割り振りのターンで親タスクは `in_progress` になります。** エージェントに直接割り当てたときと同じステータスの扱いです。スクワッドの調整は親タスクそのものを進める作業なので、親タスクは `todo` から `in_progress` に移ります。割り振りは納品ではないため、スクワッドが作業している間はそのままです。-6. **リーダーは止まります。** 割り振ったあと、リーダーは自分で実装しません。割り振られたメンバーが返信すると、リーダーが自動的に起こされて次の手を決めます。さらに割り振る、人間にエスカレーションする、全体の目標が達成されたら親タスクを `in_review` に進める、あるいは何もしない、のいずれかです。`done` は人間の確認か既存の連携(たとえば close intent 付きの PR のマージ)に任されます。適したメンバーがいない場合、リーダーは自分で引き受けず、足りない点をタスクのコメントに書き残します。+6. **リーダーは止まります。** 割り振ったあと、リーダーは自分で実装しません。割り振られたメンバーが返信すると、リーダーが自動的に起こされて次の手を決めます(スクワッドで[メンバーが直接引き継ぐ](#連携方法)設定のときを除く)。さらに割り振る、人間にエスカレーションする、全体の目標が達成されたら親タスクを `in_review` に進める、あるいは何もしない、のいずれかです。`done` は人間の確認か既存の連携(たとえば close intent 付きの PR のマージ)に任されます。適したメンバーがいない場合、リーダーは自分で引き受けず、足りない点をタスクのコメントに書き残します。タスクがまだ `backlog` にある間は、割り当てだけではリーダーはトリガーされません。`backlog` を出た時点で実行が始まります。@@ -54,6 +54,28 @@ import { SquadDemo } from "@/components/demos/squad-demo";- **Squad Roster(スクワッドの名簿)**:リーダー自身の行と、アーカイブされていない各メンバーの行です。各行にはそのまま貼り付けられるメンション用の markdown(`[@Name](mention://agent/<uuid>)`)が付いています。プレーンテキストの `@name` では誰もトリガーされません。- **Squad Instructions(スクワッドの指示)**:このスクワッド用に書いたカスタムの内容です。ルーティングのルール(「データベース関連は Alice、フロントエンドは Bob」)、エスカレーションの方針、タスク自体には書かれていない背景などを置きます。+### メンバーが受け取る内容++エージェントメンバーが自分のスクワッドに割り当てられたタスクで実行を受け取ると、指示の末尾に **Squad Member Brief(スクワッドメンバー向けの説明)** が追加されます。スクワッド内での役割、ほかのメンバーとそのまま貼り付けられるメンション用の markdown、スクワッドの指示、そして現在の連携方法での引き継ぎ方です。スクワッドを管理できる人は、スクワッドの詳細ページの **メンバーが受け取る内容** で、エージェントごとに実際の内容をプレビューできます。++## 連携方法++スクワッドの詳細ページの **連携方法** で、メンバーが 1 ステップを終えたあとに誰が次を決めるかを選びます。変更できるのはスクワッドを管理できる人だけです。++| 方法 | 動作 |+|---|---|+| **リーダーが割り振る**(既定) | メンバーの返信はすべてリーダーに戻り、リーダーが次のステップを決めます。既存のスクワッドはこの方法のままです。 |+| **メンバーが直接引き継ぐ** | リーダーは最初のステップと例外対応を受け持ちます。メンバーが次のメンバーを `@` でメンションすると、そのメンバーがリーダーを起こさずに実行します。メンバーが人をメンションした場合は、リーダーではなくその人の返信を待ちます。 |++**メンバーが直接引き継ぐ** では、次の場合にタスクがリーダーに戻ります。++- 同じ 2 人のメンバーの間ですでに 3 回往復した+- 直近 24 時間でこのタスクのメンバー間の引き継ぎが 20 回に達した+- メンバーの実行が失敗した+- メンバーの返信が次の担当を指名していない++これらの上限は固定です。引き継ぎはそれぞれタスクのタイムラインに表示され、何回目の往復か、リーダーに戻った場合はその理由も示されます。+## リーダーが再びトリガーされるタイミング最初の割り振りのあとは、ほとんどの後続コメントでリーダーが自動的に起こされます。@@ -64,7 +86,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";| スクワッドのメンバーが `@` なしで進捗を投稿する | する | リーダーが次の手を評価し直す || メンバーまたは作業エージェントが、担当スクワッドのリーダーをエージェントとして明示的にメンションする | する | リーダーとして実行され、`multica squad activity` で判断を記録できる || 人間のメンバーが他のメンバーまたは `@all` だけをメンションする | しない | 人には通知が届くが、エージェントへの暗黙のルーティングは抑制される |-| リーダー以外のエージェントがメンバーまたは `@all` だけをメンションする | する | ワーカーの結果はリーダーに戻り、人への通知も通常どおり届く |+| リーダー以外のエージェントがメンバーまたは `@all` だけをメンションする | する | ワーカーの結果はリーダーに戻り、人への通知も通常どおり届く。**メンバーが直接引き継ぐ** では、スクワッドのメンバーが人をメンションしてもリーダーは起こされない || 誰かがエージェントまたはスクワッドを明示的にメンションする | 指名された場合のみ | 指名されたエージェントまたはスクワッドのリーダーだけが実行され、リーダーへの追加のフォールバックはない || リーダー自身のコメント | しない | 自分で自分をトリガーしないようにするため || コメントにタスクへの相互リンクしかない | する | タスクの参照はルーティングとはみなさない |@@ -114,6 +136,8 @@ multica squad member add <squad-id> \--member-id <agent-or-member-id> \--type agent \--role "フロントエンド実装を担当"+multica squad update <squad-id> --handoff-mode direct+multica squad briefs <squad-id> --agent <agent-name-or-id>```完全なコマンドは [CLI コマンドリファレンス](/cli)を参照してください。diff --git a/apps/docs/content/docs/squads.ko.mdx b/apps/docs/content/docs/squads.ko.mdxindex 0922510de9..cd0a2bb19b 100644--- a/apps/docs/content/docs/squads.ko.mdx+++ b/apps/docs/content/docs/squads.ko.mdx@@ -23,7 +23,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";| **리더** | 반드시 에이전트여야 합니다. 스쿼드에 할당된 작업을 받고 처리 방법을 결정합니다. || **멤버** | 에이전트 또는 사람 멤버가 될 수 있습니다. 같은 멤버가 여러 스쿼드에 참여할 수 있습니다. || **역할 설명** | 각 멤버에게 적합한 작업을 리더에게 알려 줍니다. 컨텍스트일 뿐 권한을 부여하거나 멤버를 자동으로 트리거하지 않습니다. |-| **스쿼드 지시문** | 라우팅 규칙, 협업 방식, 스쿼드 전체에 적용할 배경을 저장하며 리더에게만 제공됩니다. |+| **스쿼드 지시문** | 라우팅 규칙, 협업 방식, 스쿼드 전체에 적용할 배경을 저장합니다. 리더와, 스쿼드의 태스크를 처리하는 모든 에이전트 멤버에게 제공됩니다. |스쿼드를 만들 때 이름을 입력하고 리더를 선택해야 합니다. 스쿼드 리더는 자동으로 멤버가 됩니다. 이후 멤버를 추가하고 역할 설명과 스쿼드 지시문을 작성할 수 있습니다.@@ -36,7 +36,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";3. **리더가 작업 배정 댓글을 남깁니다.** 명단에 있는 멘션 markdown을 그대로 써서 고른 멤버를 `@`멘션합니다. 멘션된 에이전트에는 새 실행이 큐에 들어가고, 멘션된 사람 멤버는 알림을 받습니다.4. **리더가 평가를 기록합니다**: `multica squad activity <issue-id> <outcome> --reason "..."`. 이 기록은 태스크의 활동 타임라인에 남아, 리더가 매번 어떻게 판단했는지 사람이 나중에 확인할 수 있습니다.5. **배정 턴에서 상위 태스크는 `in_progress`가 됩니다.** 에이전트에 직접 할당할 때와 같은 상태 규칙입니다. 스쿼드를 조율하는 일이 곧 상위 태스크를 진행하는 일이므로 상위 태스크는 `todo`에서 `in_progress`로 바뀝니다. 배정은 납품이 아니므로 스쿼드가 일하는 동안에는 그대로 유지됩니다.-6. **리더는 멈춥니다.** 배정한 뒤 리더는 직접 구현하지 않습니다. 배정받은 멤버가 답하면 리더가 자동으로 깨어나 다음 단계를 정합니다. 더 배정하거나, 사람에게 올리거나, 전체 목표를 달성했으면 상위 태스크를 `in_review`로 옮기거나, 아무것도 하지 않습니다. `done`은 사람의 확인이나 기존 연동(예: close intent가 있는 PR 머지)에 맡깁니다. 적합한 멤버가 없으면 리더는 직접 맡지 않고, 부족한 점을 태스크 댓글로 남깁니다.+6. **리더는 멈춥니다.** 배정한 뒤 리더는 직접 구현하지 않습니다. 배정받은 멤버가 답하면 리더가 자동으로 깨어나 다음 단계를 정합니다(스쿼드가 [멤버가 직접 인계](#협업-방식)하도록 설정된 경우는 제외). 더 배정하거나, 사람에게 올리거나, 전체 목표를 달성했으면 상위 태스크를 `in_review`로 옮기거나, 아무것도 하지 않습니다. `done`은 사람의 확인이나 기존 연동(예: close intent가 있는 PR 머지)에 맡깁니다. 적합한 멤버가 없으면 리더는 직접 맡지 않고, 부족한 점을 태스크 댓글로 남깁니다.태스크가 여전히 `backlog`이면 할당만으로 리더가 트리거되지 않습니다. `backlog`에서 벗어난 뒤에 실행이 시작됩니다.@@ -54,6 +54,28 @@ import { SquadDemo } from "@/components/demos/squad-demo";- **Squad Roster(스쿼드 명단)**: 리더 자신의 행과, 보관되지 않은 멤버마다 한 행씩입니다. 각 행에는 그대로 붙여 넣을 수 있는 멘션 markdown(`[@Name](mention://agent/<uuid>)`)이 들어 있습니다. 일반 텍스트 `@name`으로는 아무도 트리거되지 않습니다.- **Squad Instructions(스쿼드 지시문)**: 이 스쿼드를 위해 직접 쓴 내용입니다. 라우팅 규칙("데이터베이스 관련은 Alice, 프런트엔드는 Bob"), 에스컬레이션 방침, 태스크에는 없는 배경 등을 넣습니다.+### 멤버가 받는 내용++에이전트 멤버가 자기 스쿼드에 할당된 태스크에서 실행을 가져가면, 지침 끝에 **Squad Member Brief(스쿼드 멤버 안내)** 가 덧붙습니다. 스쿼드에서의 역할, 다른 멤버와 그대로 붙여 넣을 수 있는 멘션 markdown, 스쿼드 지시문, 그리고 현재 협업 방식에서 인계하는 방법이 들어 있습니다. 스쿼드를 관리할 수 있는 사람은 스쿼드 상세 페이지의 **멤버가 실제로 받는 내용** 에서 에이전트별로 실제 내용을 미리 볼 수 있습니다.++## 협업 방식++스쿼드 상세 페이지의 **협업 방식** 은 멤버가 한 단계를 마친 뒤 누가 다음 단계를 정할지 결정합니다. 스쿼드를 관리할 수 있는 사람만 바꿀 수 있습니다.++| 방식 | 동작 |+|---|---|+| **리더가 배정** (기본값) | 멤버의 모든 답글이 리더에게 돌아가고, 리더가 다음 단계를 정합니다. 기존 스쿼드는 이 방식을 유지합니다. |+| **멤버가 직접 인계** | 리더는 첫 단계 배정과 예외 처리를 맡습니다. 멤버가 다음 멤버를 `@`로 멘션하면 그 멤버가 리더를 깨우지 않고 실행합니다. 멤버가 사람을 멘션하면 리더 대신 그 사람의 답을 기다립니다. |++**멤버가 직접 인계** 에서는 다음 경우 태스크가 리더에게 돌아갑니다.++- 같은 두 멤버 사이에서 이미 3회 왕복한 경우+- 최근 24시간 동안 이 태스크의 멤버 간 인계가 20회에 이른 경우+- 멤버의 실행이 실패한 경우+- 멤버의 답글이 다음 담당을 지정하지 않은 경우++이 한도는 고정되어 있습니다. 각 인계는 태스크 타임라인에 표시되며, 몇 번째 왕복인지와, 리더에게 돌아간 경우 그 이유가 함께 나옵니다.+## 리더가 다시 트리거되는 경우첫 배정 이후에는 대부분의 후속 댓글이 리더를 자동으로 깨웁니다.@@ -64,7 +86,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";| 스쿼드 멤버가 `@` 없이 진행 상황을 올림 | 예 | 리더가 다음 단계를 다시 평가 || 멤버 또는 작업 에이전트가 담당 스쿼드의 리더를 에이전트로 직접 멘션함 | 예 | 리더 역할로 실행되어 `multica squad activity`로 판단을 기록할 수 있음 || 사람 멤버가 다른 멤버 또는 `@all`만 멘션함 | 아니요 | 사람에게 알림이 전달되지만 암시적 에이전트 라우팅은 억제됨 |-| 리더가 아닌 에이전트가 멤버 또는 `@all`만 멘션함 | 예 | 워커의 결과는 리더에게 돌아가고 사람에게도 평소처럼 알림이 전달됨 |+| 리더가 아닌 에이전트가 멤버 또는 `@all`만 멘션함 | 예 | 워커의 결과는 리더에게 돌아가고 사람에게도 평소처럼 알림이 전달됨. **멤버가 직접 인계** 에서는 스쿼드 멤버가 사람을 멘션해도 리더를 깨우지 않음 || 누구든 에이전트 또는 스쿼드를 명시적으로 멘션함 | 지명된 경우에만 | 지명된 에이전트 또는 스쿼드 리더만 실행되며 리더로의 추가 폴백은 없음 || 리더 자신의 댓글 | 아니요 | 자기 자신을 트리거하지 않도록 막음 || 댓글에 태스크 상호 링크만 있음 | 예 | 태스크 참조는 라우팅으로 보지 않음 |@@ -114,6 +136,8 @@ multica squad member add <squad-id> \--member-id <agent-or-member-id> \--type agent \--role "프런트엔드 구현 담당"+multica squad update <squad-id> --handoff-mode direct+multica squad briefs <squad-id> --agent <agent-name-or-id>```전체 명령은 [CLI 사용](/cli)을 참고하세요.diff --git a/apps/docs/content/docs/squads.mdx b/apps/docs/content/docs/squads.mdxindex c5ab270824..bc25b425e9 100644--- a/apps/docs/content/docs/squads.mdx+++ b/apps/docs/content/docs/squads.mdx@@ -23,7 +23,7 @@ When the scope is clear, assign directly to the matching [agent](/agents).| **Leader** | Must be an agent. Receives work assigned to the squad and decides how to handle it. || **Members** | Can be agents or human members. The same member can join multiple squads. || **Role descriptions** | Tell the leader what work each member is suited for. Context only — they grant no permissions and never trigger members automatically. |-| **Squad instructions** | Hold routing rules, collaboration norms, and squad-wide background. Provided to the leader only. |+| **Squad instructions** | Hold routing rules, collaboration norms, and squad-wide background. Provided to the leader and to every agent member working on the squad's issues. |Creating a squad requires a name and a leader. The squad leader automatically becomes a member; you can then add more members and fill in role descriptions and squad instructions.@@ -36,7 +36,7 @@ When a non-Backlog issue is assigned to a squad, Multica immediately enqueues a3. **Leader posts one delegation comment.** The comment `@`-mentions the chosen member(s) using the exact mention markdown from the roster. Each mentioned agent gets a new run, and each mentioned human member gets a notification.4. **Leader records its evaluation** via `multica squad activity <issue-id> action --reason "..."`. This writes an entry to the issue's activity timeline so humans can see the leader actually evaluated the trigger.5. **The dispatch turn leaves the parent `in_progress`.** Same agent-managed status contract as a direct agent assignment — coordinating the squad is working the parent's ask, so the parent moves from `todo` to `in_progress`, and dispatching members is not delivery, so it stays there while the squad works.-6. **Leader stops.** The leader does not do the implementation itself. When the delegated member posts back — or when a sub-issue / stage barrier closes — the leader is re-triggered to read the update and either delegate the next step, escalate, move the parent to `in_review` once the overall goal is met, or stay silent. `done` is left to a human reviewer or existing integrations (for example a PR with close intent that merges).+6. **Leader stops.** The leader does not do the implementation itself. When the delegated member posts back — or when a sub-issue / stage barrier closes — the leader is re-triggered (unless the squad lets [members hand off directly](#collaboration-mode)) to read the update and either delegate the next step, escalate, move the parent to `in_review` once the overall goal is met, or stay silent. `done` is left to a human reviewer or existing integrations (for example a PR with close intent that merges).If the issue is in **Backlog**, the leader is not triggered: Backlog is a parking lot, same rule as for direct agent assignment.@@ -54,6 +54,28 @@ On each squad-leader run, three blocks are appended to the leader's instructions- **Squad Roster** — the leader's self-row plus one row per non-archived member. Each row carries the exact mention markdown (`[@Name](mention://agent/<uuid>)` or `[@Name](mention://member/<uuid>)`) the leader should paste — typing a plain `@name` won't trigger anyone.- **Squad Instructions** — your custom guidance for this squad (set on the squad detail page or via `multica squad update --instructions`). Use this for routing rules ("send DB work to Alice, frontend to Bob"), escalation policies, or anything else the leader needs to know that isn't already in the issue.+### What members see++When an agent member claims a run on an issue assigned to its squad, a **Squad Member Brief** is appended to its instructions: its role, the other members with their exact mention markdown, the squad instructions, and how to hand off under the squad's collaboration mode. People who can manage the squad can preview what each agent receives under **What members receive** on the squad detail page.++## Collaboration mode++The **Collaboration** setting on the squad detail page decides who picks the next step after a member finishes. Only people who can manage the squad can change it.++| Mode | What happens |+|---|---|+| **Leader assigns** (default) | Every member reply returns to the leader, who picks the next step. Existing squads keep this mode. |+| **Members hand off directly** | The leader assigns the first step and handles exceptions. A member `@`-mentions the next member, who runs without waking the leader. A member that `@`-mentions a person waits for that person instead of the leader. |++With **Members hand off directly**, the issue goes back to the leader when:++- the same two members have already passed it back and forth 3 rounds;+- the issue has taken 20 member handoffs in the past 24 hours;+- a member's run fails;+- a member's reply names no next owner.++These limits are fixed. Each handoff appears on the issue timeline, with its round and, when the issue went back to the leader, the reason.+## Leader re-trigger rulesAfter the first dispatch, the leader is woken up automatically by **most subsequent comments** on the issue. The exact rules:@@ -64,7 +86,7 @@ After the first dispatch, the leader is woken up automatically by **most subsequ| A squad member posts a progress update with no `@mention` | Yes | The leader re-evaluates whether a next step is needed || A member or worker explicitly mentions the assigned squad’s leader as an agent | Yes | Runs as the squad leader, so `multica squad activity` can record its decision || A human member mentions only other members or `@all` | No | People receive notifications; implicit agent routing is suppressed |-| A non-leader agent mentions only members or `@all` | Yes | The worker result still reaches the leader; people receive notifications as usual |+| A non-leader agent mentions only members or `@all` | Yes | The worker result still reaches the leader; people receive notifications as usual. With **Members hand off directly**, a squad member that mentions a person does not wake the leader || Anyone explicitly mentions an agent or squad | Only if named | Only the named agents or squad leaders run; there is no additional leader fallback || The leader's own comment | No | Guarded so the leader can't trigger itself || A comment containing only an issue cross-reference (`[MUL-123](mention://issue/...)`) | Yes | Issue references aren't routing |@@ -114,6 +136,8 @@ multica squad member add <squad-id> \--member-id <agent-or-member-id> \--type agent \--role "Owns frontend implementation"+multica squad update <squad-id> --handoff-mode direct+multica squad briefs <squad-id> --agent <agent-name-or-id>```Full commands in [Using the CLI](/cli).diff --git a/apps/docs/content/docs/squads.zh-Hant.mdx b/apps/docs/content/docs/squads.zh-Hant.mdxindex eb8253e3a1..6b4e6e1144 100644--- a/apps/docs/content/docs/squads.zh-Hant.mdx+++ b/apps/docs/content/docs/squads.zh-Hant.mdx@@ -23,7 +23,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";| **隊長** | 必須是一名 AI 代理。接收分配給小隊的工作,並決定如何處理。 || **成員** | 可以是 AI 代理,也可以是人類成員。同一成員可以加入多個小隊。 || **角色說明** | 告訴隊長每個成員適合處理什麼工作。它只是上下文,不會授予權限或自動觸發成員。 |-| **小隊指令** | 儲存路由規則、協作方式和需要貫穿全隊的背景,只會提供給隊長。 |+| **小隊指令** | 儲存路由規則、協作方式和需要貫穿全隊的背景。會提供給隊長,以及處理本小隊任務的每個 AI 代理成員。 |建立小隊時需要填寫名稱並選擇隊長。隊長會自動成為小隊成員;之後可以繼續新增成員、填寫角色說明和小隊指令。@@ -36,7 +36,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";3. **隊長發一條派活評論。** 評論裡用花名冊給好的 mention markdown `@` 選中的成員。被 `@` 的 AI 代理會入隊一次新執行,被 `@` 的人類成員會收到通知。4. **隊長記錄 evaluation**:`multica squad activity <issue-id> <outcome> --reason "..."`。這一行會寫進任務的 activity 時間線,方便人類回溯隊長的每次評估。5. **派活輪讓父任務處於 `in_progress`。** 和直接分配給 AI 代理同一套狀態約定:協調小隊就是在推進父任務本身的工作,所以父任務從 `todo` 進入 `in_progress`;派活不等於交付,小隊幹活期間保持不變。-6. **隊長停下。** 派完活,隊長不親自動手。被派成員有回覆時,隊長會被自動喚醒,決定下一步:繼續派活、上拋給人類、在整體目標達成後把父任務推到 `in_review`,或保持沉默。`done` 留給人工確認或既有整合(例如帶 close intent 的 PR merge)。+6. **隊長停下。** 派完活,隊長不親自動手。被派成員有回覆時,隊長會被自動喚醒(小隊開啟[成員直接交接](#協作方式)時除外),決定下一步:繼續派活、上拋給人類、在整體目標達成後把父任務推到 `in_review`,或保持沉默。`done` 留給人工確認或既有整合(例如帶 close intent 的 PR merge)。如果任務仍在 `backlog`,分配本身不會觸發隊長。移出 `backlog` 後才會開始執行。@@ -54,6 +54,28 @@ import { SquadDemo } from "@/components/demos/squad-demo";- **Squad Roster(小隊花名冊)**:隊長一行,加上每個未歸檔成員一行,每行帶可直接複製的 mention markdown(`[@Name](mention://agent/<uuid>)` 或 `[@Name](mention://member/<uuid>)`)。純文字 `@name` 不會觸發任何人。- **Squad Instructions(小隊指令)**:你為這個小隊寫的自定義內容,包括路由規則("資料庫相關派給 Alice,前端派給 Bob")、上報策略,或任務本身不會有的背景。+### 成員看到的內容++AI 代理成員在分配給本小隊的任務上領取執行時,Multica 會在它的指令後追加一段 **Squad Member Brief(小隊成員說明)**:它在小隊裡的角色、其他成員及可直接複製的 mention markdown、小隊指令,以及目前協作方式下怎麼交接。能管理小隊的人可以在小隊詳情頁的 **成員實際會收到什麼** 裡,按 AI 代理預覽實際注入的內容。++## 協作方式++小隊詳情頁的 **協作方式** 決定成員做完一步後由誰選下一步。只有能管理小隊的人可以修改。++| 方式 | 效果 |+|---|---|+| **由隊長派工**(預設) | 每則成員回覆都回到隊長,由隊長決定下一步。現有小隊維持這種方式。 |+| **成員直接交接** | 隊長派第一步、處理異常。成員 `@` 下一位成員,對方直接開始執行,不喚醒隊長;成員 `@` 某個人時,等這個人回覆,也不喚醒隊長。 |++開啟 **成員直接交接** 後,以下情況會把任務交回隊長:++- 同兩名成員之間已經來回 3 輪;+- 這條任務在過去 24 小時內已有 20 次成員交接;+- 成員的執行失敗;+- 成員的回覆沒有點名下一位負責人。++這些上限是固定的。每次交接都會出現在任務時間軸上,顯示所在輪次;交回隊長時還會註明原因。+## 隊長的再次觸發時機第一次派活之後,大多數後續評論會自動喚醒隊長:@@ -64,7 +86,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";| 小隊成員發進展更新,不帶任何 `@` | 會 | 隊長重新評估下一步 || 成員或工作 AI 代理顯式提及負責該任務的小隊隊長 AI 代理 | 會 | 以隊長身分執行,可用 `multica squad activity` 記錄決策 || 人類成員的評論只提及其他成員或 `@all` | 不會 | 成員收到通知,隱式 AI 代理路由被抑制 |-| 非隊長 AI 代理的評論只提及成員或 `@all` | 會 | 工作 AI 代理的結果仍會交回隊長,成員照常收到通知 |+| 非隊長 AI 代理的評論只提及成員或 `@all` | 會 | 工作 AI 代理的結果仍會交回隊長,成員照常收到通知。開啟 **成員直接交接** 時,小隊成員提及某個人不會喚醒隊長 || 任何作者顯式提及 AI 代理或小隊 | 僅在被點名時 | 只執行被點名的 AI 代理或小隊隊長,不額外回退到隊長 || 隊長自己發的評論 | 不會 | 防止自己觸發自己 || 評論裡只有任務互鏈(`[MUL-123](mention://issue/...)`) | 會 | 任務引用不算路由 |@@ -114,6 +136,8 @@ multica squad member add <squad-id> \--member-id <agent-or-member-id> \--type agent \--role "負責前端實現"+multica squad update <squad-id> --handoff-mode direct+multica squad briefs <squad-id> --agent <agent-name-or-id>```完整命令見 [使用 CLI](/cli)。diff --git a/apps/docs/content/docs/squads.zh.mdx b/apps/docs/content/docs/squads.zh.mdxindex cfcb3b5627..a22ba435ab 100644--- a/apps/docs/content/docs/squads.zh.mdx+++ b/apps/docs/content/docs/squads.zh.mdx@@ -23,7 +23,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";| **队长** | 必须是一名智能体。接收分配给小队的工作,并决定如何处理。 || **成员** | 可以是智能体,也可以是人类成员。同一成员可以加入多个小队。 || **角色说明** | 告诉队长每个成员适合处理什么工作。它只是上下文,不会授予权限或自动触发成员。 |-| **小队指令** | 保存路由规则、协作方式和需要贯穿全队的背景,只会提供给队长。 |+| **小队指令** | 保存路由规则、协作方式和需要贯穿全队的背景。会提供给队长,以及处理本小队任务的每个智能体成员。 |创建小队时需要填写名称并选择队长。队长会自动成为小队成员;之后可以继续添加成员、填写角色说明和小队指令。@@ -36,7 +36,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";3. **队长发一条派活评论。** 评论里用花名册给好的 mention markdown `@` 选中的成员。被 `@` 的智能体会入队一次新运行,被 `@` 的人类成员会收到通知。4. **队长记录 evaluation**:`multica squad activity <issue-id> <outcome> --reason "..."`。这一行会写进任务的 activity 时间线,方便人类回溯队长的每次评估。5. **派活轮让父任务处于 `in_progress`。** 和直接分配给智能体同一套状态约定:协调小队就是在推进父任务本身的工作,所以父任务从 `todo` 进入 `in_progress`;派活不等于交付,小队干活期间保持不变。-6. **队长停下。** 派完活,队长不亲自动手。被派成员有回复时,队长会被自动唤醒,决定下一步:继续派活、上抛给人类、在整体目标达成后把父任务推到 `in_review`,或保持沉默。`done` 留给人工确认或既有集成(例如带 close intent 的 PR merge)。+6. **队长停下。** 派完活,队长不亲自动手。被派成员有回复时,队长会被自动唤醒(小队开启[成员直接交接](#协作方式)时除外),决定下一步:继续派活、上抛给人类、在整体目标达成后把父任务推到 `in_review`,或保持沉默。`done` 留给人工确认或既有集成(例如带 close intent 的 PR merge)。如果任务仍在 `backlog`,分配本身不会触发队长。移出 `backlog` 后才会开始执行。@@ -54,6 +54,28 @@ import { SquadDemo } from "@/components/demos/squad-demo";- **Squad Roster(小队花名册)**:队长一行,加上每个未归档成员一行,每行带可直接复制的 mention markdown(`[@Name](mention://agent/<uuid>)`)。纯文本 `@name` 不会触发任何人。- **Squad Instructions(小队指令)**:你为这个小队写的自定义内容,包括路由规则("数据库相关派给 Alice,前端派给 Bob")、上报策略,或任务本身不会有的背景。+### 成员看到的内容++智能体成员在分配给本小队的任务上领取运行时,Multica 会在它的指令后追加一段 **Squad Member Brief(小队成员说明)**:它在小队里的角色、其他成员及可直接复制的 mention markdown、小队指令,以及当前协作方式下怎么交接。能管理小队的人可以在小队详情页的 **成员实际会收到什么** 里,按智能体预览实际注入的内容。++## 协作方式++小队详情页的 **协作方式** 决定成员做完一步后由谁选下一步。只有能管理小队的人可以修改。++| 方式 | 效果 |+|---|---|+| **由队长派活**(默认) | 每条成员回复都回到队长,由队长决定下一步。现有小队保持这种方式。 |+| **成员直接交接** | 队长派第一步、处理异常。成员 `@` 下一位成员,对方直接开始运行,不唤醒队长;成员 `@` 某个人时,等这个人回复,也不唤醒队长。 |++开启 **成员直接交接** 后,以下情况会把任务交回队长:++- 同两名成员之间已经来回 3 轮;+- 这条任务在过去 24 小时内已有 20 次成员交接;+- 成员的运行失败;+- 成员的回复没有点名下一位负责人。++这些上限是固定的。每次交接都会出现在任务时间线上,显示所在轮次;交回队长时还会注明原因。+## 队长的再次触发时机第一次派活之后,大多数后续评论会自动唤醒队长:@@ -64,7 +86,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";| 小队成员发进展更新,不带任何 `@` | 会 | 队长重新评估下一步 || 成员或工作智能体显式提及负责该任务的小队队长智能体 | 会 | 以队长身份运行,可用 `multica squad activity` 记录决策 || 人类成员的评论只提及其他成员或 `@all` | 不会 | 成员收到通知,隐式智能体路由被抑制 |-| 非队长智能体的评论只提及成员或 `@all` | 会 | 工作智能体的结果仍会交回队长,成员照常收到通知 |+| 非队长智能体的评论只提及成员或 `@all` | 会 | 工作智能体的结果仍会交回队长,成员照常收到通知。开启 **成员直接交接** 时,小队成员提及某个人不会唤醒队长 || 任何作者显式提及智能体或小队 | 仅在被点名时 | 只运行被点名的智能体或小队队长,不额外回退到队长 || 队长自己发的评论 | 不会 | 防止自己触发自己 || 评论里只有任务互链 | 会 | 任务引用不算路由 |@@ -114,6 +136,8 @@ multica squad member add <squad-id> \--member-id <agent-or-member-id> \--type agent \--role "负责前端实现"+multica squad update <squad-id> --handoff-mode direct+multica squad briefs <squad-id> --agent <agent-name-or-id>```完整命令见 [使用 CLI](/cli)。diff --git a/apps/mobile/lib/format-activity.ts b/apps/mobile/lib/format-activity.tsindex 5c21c46a65..f9d0abf85d 100644--- a/apps/mobile/lib/format-activity.ts+++ b/apps/mobile/lib/format-activity.ts@@ -9,7 +9,7 @@* mobile clients in the wild must render them as a generic fallback, not* crash).*/-import type { IssuePriority, TimelineEntry } from "@multica/core/types";+import { SQUAD_HANDOFF_ROUND_LIMIT, type IssuePriority, type TimelineEntry } from "@multica/core/types";import { formatDateOnly } from "@multica/core/issues/date";import { i18n } from "@/lib/i18n/singleton";import { STATUS_LABEL, isBuiltInIssueStatus } from "@/lib/issue-status";@@ -167,7 +167,38 @@ export function formatActivity(return t("issues:activity.squad_evaluated");}}+ case "squad_handoff": {+ // Mirrors web's formatActivity + squadHandoffNote in+ // packages/views/issues/components/activity-text.ts.+ const name =+ details.to_id && details.to_type+ ? resolveActorName(details.to_type, details.to_id)+ : "?";+ const text =+ details.kind === "human"+ ? t("issues:activity.squad_handoff_human", { name })+ : details.kind === "leader"+ ? t("issues:activity.squad_handoff_leader", { name })+ : t("issues:activity.squad_handoff_to", { name });+ const note = squadHandoffNote(details);+ return note ? `${text} · ${note}` : text;+ }default:return entry.action ?? "";}}++const SQUAD_HANDOFF_REASON: Record<string, string> = {+ round_limit: "issues:activity.squad_handoff_reason_round_limit",+ daily_limit: "issues:activity.squad_handoff_reason_daily_limit",+ run_failed: "issues:activity.squad_handoff_reason_run_failed",+};++function squadHandoffNote(details: Record<string, string>): string | null {+ if (details.kind === "leader") {+ const key = details.reason ? SQUAD_HANDOFF_REASON[details.reason] : undefined;+ return key ? i18n.t(key, { limit: SQUAD_HANDOFF_ROUND_LIMIT }) : null;+ }+ const round = Number(details.round);+ return round >= 2 ? i18n.t("issues:activity.squad_handoff_round", { round }) : null;+}diff --git a/apps/mobile/lib/timeline-coalesce.ts b/apps/mobile/lib/timeline-coalesce.tsindex 59381b2916..41ed80e6b9 100644--- a/apps/mobile/lib/timeline-coalesce.ts+++ b/apps/mobile/lib/timeline-coalesce.ts@@ -24,7 +24,7 @@ import type { TimelineEntry } from "@multica/core/types";const COALESCE_MS = 2 * 60 * 1000;const NO_TIME_LIMIT_ACTIONS = new Set(["task_completed", "task_failed"]);-const NEVER_COALESCE_ACTIONS = new Set(["squad_leader_evaluated"]);+const NEVER_COALESCE_ACTIONS = new Set(["squad_leader_evaluated", "squad_handoff"]);export function coalesceTimeline(entries: TimelineEntry[],diff --git a/apps/mobile/locales/en/issues.json b/apps/mobile/locales/en/issues.jsonindex d3d805fa96..0995953465 100644--- a/apps/mobile/locales/en/issues.json+++ b/apps/mobile/locales/en/issues.json@@ -112,6 +112,13 @@"squad_failed_with_reason": "evaluation failed: {{reason}}","squad_failed": "evaluation failed","squad_evaluated": "evaluated the squad trigger",+ "squad_handoff_to": "handed off to {{name}}",+ "squad_handoff_human": "asked {{name}} to decide",+ "squad_handoff_leader": "handed back to {{name}}",+ "squad_handoff_round": "round {{round}}",+ "squad_handoff_reason_round_limit": "{{limit}}-round limit reached",+ "squad_handoff_reason_daily_limit": "daily handoff limit reached",+ "squad_handoff_reason_run_failed": "run failed","commented": "commented"},"errors": {diff --git a/apps/mobile/locales/zh-Hans/issues.json b/apps/mobile/locales/zh-Hans/issues.jsonindex 4b2329463e..016ab16727 100644--- a/apps/mobile/locales/zh-Hans/issues.json+++ b/apps/mobile/locales/zh-Hans/issues.json@@ -110,6 +110,13 @@"squad_failed_with_reason": "评估失败:{{reason}}","squad_failed": "评估失败","squad_evaluated": "评估了小队触发器",+ "squad_handoff_to": "交给了 {{name}}",+ "squad_handoff_human": "请 {{name}} 决定",+ "squad_handoff_leader": "交回 {{name}}",+ "squad_handoff_round": "第 {{round}} 轮",+ "squad_handoff_reason_round_limit": "已来回 {{limit}} 轮",+ "squad_handoff_reason_daily_limit": "今日交接已达上限",+ "squad_handoff_reason_run_failed": "运行失败","commented": "发表了评论"},"errors": {diff --git a/apps/mobile/locales/zh-Hant/issues.json b/apps/mobile/locales/zh-Hant/issues.jsonindex ee17e85027..e0ad682c3e 100644--- a/apps/mobile/locales/zh-Hant/issues.json+++ b/apps/mobile/locales/zh-Hant/issues.json@@ -110,6 +110,13 @@"squad_failed_with_reason": "評估失敗:{{reason}}","squad_failed": "評估失敗","squad_evaluated": "評估了小隊觸發器",+ "squad_handoff_to": "交給了 {{name}}",+ "squad_handoff_human": "請 {{name}} 決定",+ "squad_handoff_leader": "交回 {{name}}",+ "squad_handoff_round": "第 {{round}} 輪",+ "squad_handoff_reason_round_limit": "已來回 {{limit}} 輪",+ "squad_handoff_reason_daily_limit": "今日交接已達上限",+ "squad_handoff_reason_run_failed": "執行失敗","commented": "發表了評論"},"errors": {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 3cc6757c66..a34b35febb 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -280,6 +280,8 @@ import type {Squad,SquadMember,SquadMemberStatusListResponse,+ SquadBriefsResponse,+ SquadHandoffMode,BillingBalance,BillingTransactionsPage,BillingBatchesPage,@@ -446,6 +448,8 @@ import {SquadSchema,SquadListSchema,SquadMemberStatusListResponseSchema,+ SquadBriefsResponseSchema,+ EMPTY_SQUAD_BRIEFS,SubscribersListSchema,TaskMessageListSchema,TaskContextReceiptResponseSchema,@@ -5621,7 +5625,7 @@ export class ApiClient {}) as Squad;}- async updateSquad(id: string, data: { name?: string; description?: string; instructions?: string; leader_id?: string; avatar_url?: string }): Promise<Squad> {+ async updateSquad(id: string, data: { name?: string; description?: string; instructions?: string; leader_id?: string; avatar_url?: string; handoff_mode?: SquadHandoffMode }): Promise<Squad> {const raw = await this.fetch<unknown>(`/api/squads/${id}`, { method: "PUT", body: JSON.stringify(data) });return parseWithFallback(raw, SquadSchema, EMPTY_SQUAD, {endpoint: "PUT /api/squads/:id",@@ -5659,6 +5663,15 @@ export class ApiClient {}) as SquadMemberStatusListResponse;}+ // What each agent of the squad receives as squad context on its runs.+ // Restricted server-side to the people who can edit the squad.+ async getSquadBriefs(squadId: string): Promise<SquadBriefsResponse> {+ const raw = await this.fetch<unknown>(`/api/squads/${squadId}/briefs`);+ return parseWithFallback(raw, SquadBriefsResponseSchema, EMPTY_SQUAD_BRIEFS, {+ endpoint: "GET /api/squads/:id/briefs",+ }) as SquadBriefsResponse;+ }+// Autopilotsasync listAutopilots(params?: { status?: string }): Promise<ListAutopilotsResponse> {const search = new URLSearchParams();diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 8f6583d117..9166f2b460 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -58,9 +58,11 @@ import {RuntimeUsageByHourListSchema,RuntimeUsageListSchema,SendChatMessageResponseSchema,+ SquadBriefsResponseSchema,SquadListSchema,SquadSchema,SourceContextPreviewSchema,+ EMPTY_SQUAD_BRIEFS,TimelineEntriesSchema,UserSchema,PluginInstallationSchema,@@ -1213,6 +1215,34 @@ describe("SquadListSchema member preview drift", () => {expect(parsed[0]?.member_preview).toHaveLength(2);expect(parsed[0]?.member_preview?.[0]?.role).toBe("leader");});++ it("treats a squad from an older backend as leader handoff", () => {+ expect(SquadSchema.parse(baseSquad).handoff_mode).toBe("leader");+ });++ it("falls back to leader handoff for an unknown mode", () => {+ expect(SquadSchema.parse({ ...baseSquad, handoff_mode: "round_robin" }).handoff_mode).toBe("leader");+ expect(SquadSchema.parse({ ...baseSquad, handoff_mode: "direct" }).handoff_mode).toBe("direct");+ });+});++describe("SquadBriefsResponseSchema drift", () => {+ it("defaults missing fields instead of dropping the briefs", () => {+ const parsed = SquadBriefsResponseSchema.parse({+ briefs: [{ member_type: "agent", member_id: "agent-2" }],+ });+ expect(parsed.handoff_mode).toBe("leader");+ expect(parsed.briefs).toEqual([{ member_type: "agent", member_id: "agent-2", is_leader: false, brief: "" }]);+ });++ it("returns the empty fallback for a malformed body", () => {+ expect(+ parseWithFallback({ briefs: "nope" }, SquadBriefsResponseSchema, EMPTY_SQUAD_BRIEFS, {+ endpoint: "GET /api/squads/:id/briefs",+ }),+ ).toEqual(EMPTY_SQUAD_BRIEFS);+ expect(SquadBriefsResponseSchema.parse({}).briefs).toEqual([]);+ });});// The workspace dashboard and runtime-detail pages were re-pointed at thediff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex bed7d00b42..e950553616 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2978,6 +2978,8 @@ export const SquadSchema = z.object({archived_by: z.string().nullable().optional().transform((v) => v ?? null),member_count: z.number().default(0),member_preview: z.array(SquadMemberPreviewSchema).default([]),+ // Older backends predate handoff modes; they always routed through the leader.+ handoff_mode: z.enum(["leader", "direct"]).catch("leader").default("leader"),}).loose();export const SquadListSchema = z.array(SquadSchema);@@ -2997,6 +2999,7 @@ export const EMPTY_SQUAD: Squad = {archived_by: null,member_count: 0,member_preview: [],+ handoff_mode: "leader",};// Squad member status — backs the Squad detail page's Members tab. status@@ -3024,6 +3027,18 @@ export const SquadMemberStatusListResponseSchema = z.object({export const EMPTY_SQUAD_MEMBER_STATUS_LIST = { members: [] };+export const SquadBriefsResponseSchema = z.object({+ handoff_mode: z.enum(["leader", "direct"]).catch("leader").default("leader"),+ briefs: z.array(z.object({+ member_type: z.string(),+ member_id: z.string(),+ is_leader: z.boolean().default(false),+ brief: z.string().default(""),+ }).loose()).default([]),+}).loose();++export const EMPTY_SQUAD_BRIEFS = { handoff_mode: "leader" as const, briefs: [] };+// Structured error body — POST /api/workspaces/:wsId/issues 409 conflict.//// When the server detects an active issue with the same title in the samediff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 9186ea9d88..37ee938716 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -397,7 +397,11 @@ export type {SquadActiveIssueBrief,SquadMemberStatus,SquadMemberStatusListResponse,+ SquadHandoffMode,+ SquadBrief,+ SquadBriefsResponse,} from "./squad";+export { SQUAD_HANDOFF_ROUND_LIMIT, SQUAD_HANDOFF_DAILY_LIMIT } from "./squad";export type {BillingBalance,BillingTransaction,diff --git a/packages/core/types/squad.ts b/packages/core/types/squad.tsindex 1dab68c7bb..25c62e88d1 100644--- a/packages/core/types/squad.ts+++ b/packages/core/types/squad.ts@@ -2,6 +2,17 @@ export type SquadMemberType = "agent" | "member";export type SquadActivityOutcome = "action" | "no_action" | "failed";+/**+ * How work moves between squad members. "leader" (the default) routes every+ * member reply back through the leader; "direct" lets a member hand the issue+ * to the next member, with fixed guardrails sending it back to the leader.+ */+export type SquadHandoffMode = "leader" | "direct";++/** Fixed guardrails of the direct mode; mirrors the server constants. */+export const SQUAD_HANDOFF_ROUND_LIMIT = 3;+export const SQUAD_HANDOFF_DAILY_LIMIT = 20;+export interface SquadMemberPreview {member_type: SquadMemberType;member_id: string;@@ -23,6 +34,7 @@ export interface Squad {archived_by: string | null;member_count?: number;member_preview?: SquadMemberPreview[];+ handoff_mode?: SquadHandoffMode;}export interface SquadMember {@@ -58,6 +70,7 @@ export interface UpdateSquadRequest {instructions?: string;leader_id?: string;avatar_url?: string;+ handoff_mode?: SquadHandoffMode;}export interface AddSquadMemberRequest {@@ -118,3 +131,16 @@ export interface SquadMemberStatus {export interface SquadMemberStatusListResponse {members: SquadMemberStatus[];}++/** The squad context one agent receives on an issue assigned to the squad. */+export interface SquadBrief {+ member_type: SquadMemberType;+ member_id: string;+ is_leader: boolean;+ brief: string;+}++export interface SquadBriefsResponse {+ handoff_mode: SquadHandoffMode;+ briefs: SquadBrief[];+}diff --git a/packages/core/workspace/queries.ts b/packages/core/workspace/queries.tsindex 43db20abc0..0b5f3de4f9 100644--- a/packages/core/workspace/queries.ts+++ b/packages/core/workspace/queries.ts@@ -20,6 +20,8 @@ export const workspaceKeys = {// `["workspaces", wsId, "squads"]` invalidation covers it.squadMemberStatus: (wsId: string, squadId: string) =>["workspaces", wsId, "squads", squadId, "members-status"] as const,+ squadBriefs: (wsId: string, squadId: string) =>+ ["workspaces", wsId, "squads", squadId, "briefs"] as const,skills: (wsId: string) => ["workspaces", wsId, "skills"] as const,mcpServers: (wsId: string) => ["workspaces", wsId, "mcp-servers"] as const,};@@ -132,6 +134,14 @@ export function squadMemberStatusOptions(wsId: string, squadId: string) {});}+export function squadBriefsOptions(wsId: string, squadId: string) {+ return queryOptions({+ queryKey: workspaceKeys.squadBriefs(wsId, squadId),+ queryFn: () => api.getSquadBriefs(squadId),+ enabled: !!wsId && !!squadId,+ });+}+export function skillListOptions(wsId: string) {return queryOptions({queryKey: workspaceKeys.skills(wsId),diff --git a/packages/views/issues/components/activity-text.test.ts b/packages/views/issues/components/activity-text.test.tsnew file mode 100644index 0000000000..4b41ca9733--- /dev/null+++ b/packages/views/issues/components/activity-text.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from "vitest";+import type { TimelineEntry } from "@multica/core/types";+import {+ formatActivity,+ latestSquadHandoffRound,+ squadHandoffNote,+ type ActivityT,+} from "./activity-text";++// Renders the selected key and its params, so assertions read the copy choice.+const keyPath = (prefix: string): unknown =>+ new Proxy({}, {+ get: (_target, key) =>+ key === "__path" ? prefix : keyPath(prefix ? `${prefix}.${String(key)}` : String(key)),+ });+const t = ((select: (root: unknown) => { __path: string }, params?: object) =>+ `${select(keyPath("")).__path}${params ? JSON.stringify(params) : ""}`) as unknown as ActivityT;++const handoff = (details: Record<string, string>, created_at = "2026-11-24T10:00:00Z") =>+ ({+ type: "activity",+ action: "squad_handoff",+ actor_type: "agent",+ actor_id: "agent-a",+ details,+ created_at,+ }) as unknown as TimelineEntry;++const names = (_type: string, id: string) => ({ "agent-b": "Reviewer", "agent-l": "Leader", "user-1": "Ada" })[id] ?? "?";++describe("squad handoff activity", () => {+ it("names who the issue went to", () => {+ expect(formatActivity(handoff({ kind: "member", to_type: "agent", to_id: "agent-b" }), t, "en", names))+ .toBe('activity.squad_handoff_to{"name":"Reviewer"}');+ expect(formatActivity(handoff({ kind: "human", to_type: "member", to_id: "user-1" }), t, "en", names))+ .toBe('activity.squad_handoff_human{"name":"Ada"}');+ expect(formatActivity(handoff({ kind: "leader", to_type: "agent", to_id: "agent-l" }), t, "en", names))+ .toBe('activity.squad_handoff_leader{"name":"Leader"}');+ });++ it("notes the round from the second pass on, and why the leader took over", () => {+ expect(squadHandoffNote(handoff({ kind: "member" }), t)).toBeNull();+ expect(squadHandoffNote(handoff({ kind: "member", round: "2" }), t)).toBe('activity.squad_handoff_round{"round":2}');+ expect(squadHandoffNote(handoff({ kind: "leader" }), t)).toBeNull();+ expect(squadHandoffNote(handoff({ kind: "leader", reason: "round_limit" }), t))+ .toBe('activity.squad_handoff_reason_round_limit{"limit":3}');+ expect(squadHandoffNote(handoff({ kind: "leader", reason: "run_failed" }), t))+ .toBe("activity.squad_handoff_reason_run_failed");+ });++ it("reads the current round off the newest handoff only", () => {+ const second = handoff({ kind: "member", to_type: "agent", to_id: "agent-b", round: "2" }, "2026-11-24T10:00:00Z");+ expect(latestSquadHandoffRound([second])).toEqual({ agentId: "agent-b", round: 2 });+ expect(latestSquadHandoffRound([handoff({ kind: "member", to_type: "agent", to_id: "agent-b" })])).toBeNull();+ const backToLeader = handoff({ kind: "leader", to_type: "agent", to_id: "agent-l" }, "2026-11-24T11:00:00Z");+ expect(latestSquadHandoffRound([backToLeader, second])).toBeNull();+ });+});diff --git a/packages/views/issues/components/activity-text.ts b/packages/views/issues/components/activity-text.tsindex f7ce9d3ecb..4e766b0c84 100644--- a/packages/views/issues/components/activity-text.ts+++ b/packages/views/issues/components/activity-text.ts@@ -1,6 +1,6 @@import { isBuiltInIssueStatus } from "@multica/core/issue-statuses";import { formatDateOnly } from "@multica/core/issues/date";-import type { TimelineEntry } from "@multica/core/types";+import { SQUAD_HANDOFF_ROUND_LIMIT, type TimelineEntry } from "@multica/core/types";import type { useT } from "../../i18n";import { priorityLabel } from "../utils/priority-label";@@ -152,6 +152,19 @@ export function formatActivity(return t(($) => $.activity.squad_leader_evaluated);}}+ case "squad_handoff": {+ const name = details.to_id && details.to_type && resolveActorName+ ? resolveActorName(details.to_type, details.to_id)+ : "?";+ switch (details.kind) {+ case "human":+ return t(($) => $.activity.squad_handoff_human, { name });+ case "leader":+ return t(($) => $.activity.squad_handoff_leader, { name });+ default:+ return t(($) => $.activity.squad_handoff_to, { name });+ }+ }case "environment_controlled": {const name = details.label || details.name || "?";switch (details.action) {@@ -167,3 +180,46 @@ export function formatActivity(return entry.action ?? "";}}++/**+ * The side note on a squad handoff row: which round a member-to-member+ * handoff is in, or why the issue went back to the leader.+ */+export function squadHandoffNote(entry: ActivityTextEntry, t: ActivityT): string | null {+ const details = (entry.details ?? {}) as Record<string, string>;+ if (details.kind === "leader") {+ switch (details.reason) {+ case "round_limit":+ return t(($) => $.activity.squad_handoff_reason_round_limit, { limit: SQUAD_HANDOFF_ROUND_LIMIT });+ case "daily_limit":+ return t(($) => $.activity.squad_handoff_reason_daily_limit);+ case "run_failed":+ return t(($) => $.activity.squad_handoff_reason_run_failed);+ default:+ return null;+ }+ }+ const round = Number(details.round);+ return round >= 2 ? t(($) => $.activity.squad_handoff_round, { round }) : null;+}++/**+ * The round of the newest squad handoff when it passed the issue between+ * members for the second time or more — the header chip appends it to the+ * running agent. Any newer handoff (to a person, back to the leader) ends it.+ */+export function latestSquadHandoffRound(+ entries: readonly Pick<TimelineEntry, "type" | "action" | "details" | "created_at">[],+): { agentId: string; round: number } | null {+ let latest: (typeof entries)[number] | null = null;+ for (const entry of entries) {+ if (entry.type !== "activity" || entry.action !== "squad_handoff") continue;+ if (!latest || entry.created_at >= latest.created_at) latest = entry;+ }+ const details = (latest?.details ?? {}) as Record<string, string>;+ const round = Number(details.round);+ if (details.kind !== "member" || details.to_type !== "agent" || !details.to_id || !(round >= 2)) {+ return null;+ }+ return { agentId: details.to_id, round };+}diff --git a/packages/views/issues/components/issue-agent-header-chip.tsx b/packages/views/issues/components/issue-agent-header-chip.tsxindex 40fc58b4d6..c8d5726fbc 100644--- a/packages/views/issues/components/issue-agent-header-chip.tsx+++ b/packages/views/issues/components/issue-agent-header-chip.tsx@@ -47,11 +47,14 @@ import { groupExecutionTasksByActor } from "../surface/execution-actors";interface IssueAgentHeaderChipProps {issueId: string;onJumpToRun?: (taskId: string) => void;+ /** Squad handoff round of the agent the issue was last handed to. */+ handoffRound?: { agentId: string; round: number } | null;}export const IssueAgentHeaderChip = memo(function IssueAgentHeaderChip({issueId,onJumpToRun,+ handoffRound,}: IssueAgentHeaderChipProps) {const { t } = useT("issues");// Same query options as ExecutionLogSection so both observe one cache entry.@@ -99,6 +102,7 @@ export const IssueAgentHeaderChip = memo(function IssueAgentHeaderChip({running={running}queued={queued}onJumpToRun={onJumpToRun}+ handoffRound={handoffRound}onTranscriptOpenChange={(task, open, fromKeyboard) => {setOpenedTranscript(open ? { task, fromKeyboard } : null);}}@@ -127,6 +131,7 @@ interface ActiveChipProps {running: AgentTask[];queued: AgentTask[];onJumpToRun?: (taskId: string) => void;+ handoffRound?: { agentId: string; round: number } | null;onTranscriptOpenChange: (task: AgentTask,open: boolean,@@ -139,6 +144,7 @@ function ActiveChip({running,queued,onJumpToRun,+ handoffRound,onTranscriptOpenChange,}: ActiveChipProps) {const { t } = useT("issues");@@ -166,12 +172,22 @@ function ActiveChip({// truly running. With nothing running (queued / dispatched / parked on a// path lock) the chip reads "is queued" so a not-yet-started agent or squad// isn't mislabelled as working.- const label = isSingle && singleActor+ const singleLabel = isSingle && singleActor? t(($) =>anyRunning ? $.agent_live.is_working : $.agent_live.is_queued,{ name: getActorName(singleActor.type, singleActor.id) },)+ : null;+ // A member re-handed the issue by its squad shows which round it is on.+ const round =+ isSingle && anyRunning && handoffRound && agentIds.length === 1 && handoffRound.agentId === agentIds[0]+ ? handoffRound.round+ : null;+ const label = singleLabel !== null+ ? round !== null+ ? t(($) => $.agent_live.is_working_round, { label: singleLabel, round })+ : singleLabel: t(($) =>anyRunning@@ -210,7 +226,8 @@ function ActiveChip({type="button"aria-label={label}className={cn(- "flex h-9 min-w-9 max-w-[11rem] items-center justify-center gap-1.5 rounded-md px-2 text-muted-foreground outline-none transition-colors hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring md:h-7 md:min-w-0 md:justify-start md:px-1.5",+ "flex h-9 min-w-9 items-center justify-center gap-1.5 rounded-md px-2 text-muted-foreground outline-none transition-colors hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring md:h-7 md:min-w-0 md:justify-start md:px-1.5",+ round !== null ? "max-w-[14rem]" : "max-w-[11rem]",anyRunning && "relative bg-brand/5",)}/>diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 9e8f9b6a43..85ea932a58 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -9,7 +9,7 @@ import {import { IssueFlowCard } from "../../workflows/issue-flow-card";import { IssueAppRequests } from "../../common/app-requests";import { useStatusLabel } from "../utils/status-label";-import { formatActivity, type ActivityT } from "./activity-text";+import { formatActivity, latestSquadHandoffRound, squadHandoffNote, type ActivityT } from "./activity-text";import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";import { useState, useEffect, useLayoutEffect, useCallback, useMemo, useRef, useId, Fragment, type ComponentProps, type ReactNode } from "react";import { AnimatePresence } from "motion/react";@@ -703,7 +703,11 @@ function ActivityBlock({const isDueDateChange = entry.action === "due_date_changed";const isWakeup = WAKEUP_ACTIVITY_ACTIONS.has(entry.action ?? "");- const chip = isWakeup ? wakeupActivityChip(entry, t, wakeupText, getActorName) : null;+ const chip = isWakeup+ ? wakeupActivityChip(entry, t, wakeupText, getActorName)+ : entry.action === "squad_handoff"+ ? squadHandoffNote(entry, t)+ : null;let leadIcon: React.ReactNode;if (isWakeup) {leadIcon = <WakeupActivityIcon entry={entry} />;@@ -1825,6 +1829,7 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = tru} = useIssueTimeline(id, user?.id, activeDeliverableJump?.commentId);const { data: commentTasks, isLoading: commentTasksLoading } = useQuery({ ...issueTasksOptions(id), enabled: !guest });+ const handoffRound = useMemo(() => latestSquadHandoffRound(timeline), [timeline]);// Only a landing on data already in hand is worth holding the chrome for;// while the timeline is still on its way, the chrome renders in the wait.useEffect(() => {@@ -1934,6 +1939,7 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = tru// Duplicate marks name a different issue on every row.const NEVER_COALESCE_ACTIONS = new Set(["squad_leader_evaluated",+ "squad_handoff","wakeup_created","wakeup_triggered","wakeup_timed_out",@@ -2043,6 +2049,15 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = tru}return null;}, [timelineView.groups]);+ // Squad handoffs say who holds the issue between comments, so their blocks+ // open by default like the trailing one.+ const handoffActivityGroupIds = useMemo(() => {+ const ids = new Set<string>();+ for (const g of timelineView.groups) {+ if (g.type === "activities" && g.entries.some((e) => e.action === "squad_handoff")) ids.add(g.entries[0]!.id);+ }+ return ids;+ }, [timelineView.groups]);// Map of reply-comment id → root-comment id, so a deep-link to a reply// (which lives inside a CommentCard, not in the flat items array) can fall@@ -2153,7 +2168,7 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = tru// Mirrors renderItem: only the trailing block opens by default, and it// shows its latest entries until the reader asks for older ones.activityLines: (itemId) => {- const expanded = expandedActivityIds.has(itemId) || (!collapsedActivityIds.has(itemId) && itemId === lastActivityGroupId);+ const expanded = expandedActivityIds.has(itemId) || (!collapsedActivityIds.has(itemId) && (itemId === lastActivityGroupId || handoffActivityGroupIds.has(itemId)));if (!expanded) return 0;const count = activityCounts.get(itemId) ?? 0;return itemId === lastActivityGroupId && !showOlderActivityIds.has(itemId)@@ -2162,7 +2177,7 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = tru},);}, [timelineMeasured, scrollContainerWidth, items, timelineView.threadReplies, commentRuns, expandedResolved,- collapsedThreadIds, expandedActivityIds, collapsedActivityIds, showOlderActivityIds, lastActivityGroupId]);+ collapsedThreadIds, expandedActivityIds, collapsedActivityIds, showOlderActivityIds, lastActivityGroupId, handoffActivityGroupIds]);// Whether Virtuoso can place a row by index. Without estimates it needs one// measured row first: the timeline is scrolled into view to get it. With// estimates it already can, and that detour would mount the top of the@@ -3686,7 +3701,7 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = tru? true: collapsedActivityIds.has(item.id)? false- : item.id === lastActivityGroupId;+ : item.id === lastActivityGroupId || handoffActivityGroupIds.has(item.id);const truncateOlder = item.id === lastActivityGroupId;const showOlder = showOlderActivityIds.has(item.id);return (@@ -3822,7 +3837,7 @@ export function IssueDetail({ issueId, onDelete, inbox, defaultSidebarOpen = truonJump={jumpToCollaborator}/>)}- <IssueAgentHeaderChip issueId={id} onJumpToRun={jumpToRun} />+ <IssueAgentHeaderChip issueId={id} onJumpToRun={jumpToRun} handoffRound={handoffRound} /></div>)}{inbox && (diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 95c58e9c89..77979cdfcb 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -659,6 +659,13 @@"squad_leader_no_action_reason": "evaluated: no action needed ({{reason}})","squad_leader_failed": "evaluation failed","squad_leader_failed_reason": "evaluation failed: {{reason}}",+ "squad_handoff_to": "handed off to {{name}}",+ "squad_handoff_human": "asked {{name}} to decide",+ "squad_handoff_leader": "handed back to {{name}}",+ "squad_handoff_round": "round {{round}}",+ "squad_handoff_reason_round_limit": "{{limit}}-round limit reached",+ "squad_handoff_reason_daily_limit": "daily handoff limit reached",+ "squad_handoff_reason_run_failed": "run failed","coalesced_badge": "×{{count}}","activity_count_one": "{{count}} activity","activity_count_other": "{{count}} activities",@@ -882,6 +889,7 @@},"agent_live": {"is_working": "{{name}} is working",+ "is_working_round": "{{label}} · round {{round}}","is_queued": "{{name}} is queued","is_waiting_local_directory": "{{name}} is waiting for the local directory","queued_elapsed_prefix": "queued for {{elapsed}}",diff --git a/packages/views/locales/en/squads.json b/packages/views/locales/en/squads.jsonindex 56cf2831de..353edcc26f 100644--- a/packages/views/locales/en/squads.json+++ b/packages/views/locales/en/squads.json@@ -93,6 +93,21 @@"visibility": "Visibility","visibility_workspace": "Workspace"},+ "handoff": {+ "section_title": "Collaboration",+ "mode_leader_title": "Leader assigns",+ "mode_leader_description": "Every step returns to the leader, {{leader}}, who picks the next one. The default for existing squads.",+ "mode_direct_title": "Members hand off directly",+ "mode_direct_description": "The leader assigns the first step and handles exceptions. Members pick the next step themselves; handing off for review or asking a person no longer wakes the leader.",+ "guard_rounds": "Back-and-forth: up to {{limit}} rounds",+ "guard_daily": "Up to {{limit}} handoffs per issue per day",+ "guard_failed": "Run failed → back to leader",+ "guard_no_next": "No next step → back to leader",+ "saved": "Collaboration mode updated",+ "brief_title": "What members receive",+ "brief_hint": "Added to every run on an issue assigned to this squad",+ "brief_empty": "No agent members yet"+ },"toasts": {"member_added": "Member added","member_add_failed": "Failed to add member",@@ -117,7 +132,7 @@"more_members_other": "+{{count}} more"},"instructions_tab": {- "description": "The leader reads these instructions whenever it works on an issue assigned to this squad.",+ "description": "The leader and every agent member read these instructions whenever they work on an issue assigned to this squad.","unsaved_changes": "Unsaved changes","save_button": "Save","placeholder": "e.g. Always start by writing a failing test. Prefer small, atomic commits."diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex 40c226f074..8b17141140 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -642,6 +642,13 @@"squad_leader_no_action_reason": "evaluó: no hacía falta actuar ({{reason}})","squad_leader_failed": "la evaluación falló","squad_leader_failed_reason": "la evaluación falló: {{reason}}",+ "squad_handoff_to": "se lo pasó a {{name}}",+ "squad_handoff_human": "pidió a {{name}} que decida",+ "squad_handoff_leader": "se lo devolvió a {{name}}",+ "squad_handoff_round": "ronda {{round}}",+ "squad_handoff_reason_round_limit": "límite de {{limit}} rondas",+ "squad_handoff_reason_daily_limit": "límite diario de traspasos",+ "squad_handoff_reason_run_failed": "ejecución fallida","coalesced_badge": "×{{count}}","activity_count_one": "{{count}} actividad","activity_count_other": "{{count}} actividades",@@ -865,6 +872,7 @@},"agent_live": {"is_working": "{{name}} está trabajando",+ "is_working_round": "{{label}} · ronda {{round}}","is_queued": "{{name}} está en cola","is_waiting_local_directory": "{{name}} está esperando el directorio local","queued_elapsed_prefix": "en cola desde hace {{elapsed}}",diff --git a/packages/views/locales/es/squads.json b/packages/views/locales/es/squads.jsonindex 8eb6edb5ec..c64e0c2fe0 100644--- a/packages/views/locales/es/squads.json+++ b/packages/views/locales/es/squads.json@@ -78,6 +78,21 @@"visibility": "Visibilidad","visibility_workspace": "Espacio de trabajo"},+ "handoff": {+ "section_title": "Colaboración",+ "mode_leader_title": "El líder asigna",+ "mode_leader_description": "Cada paso vuelve al líder, {{leader}}, que elige el siguiente. Es lo predeterminado en los squads existentes.",+ "mode_direct_title": "Los miembros se pasan el trabajo",+ "mode_direct_description": "El líder asigna el primer paso y atiende las excepciones. Cada miembro elige el siguiente paso; pasar a revisión o consultar a una persona ya no despierta al líder.",+ "guard_rounds": "Idas y vueltas: hasta {{limit}} rondas",+ "guard_daily": "Hasta {{limit}} traspasos por tarea al día",+ "guard_failed": "Ejecución fallida → vuelve al líder",+ "guard_no_next": "Sin siguiente paso → vuelve al líder",+ "saved": "Modo de colaboración actualizado",+ "brief_title": "Lo que reciben los miembros",+ "brief_hint": "Se añade a cada ejecución en una tarea asignada a este squad",+ "brief_empty": "Aún no hay agentes miembros"+ },"toasts": {"member_added": "Miembro añadido","member_add_failed": "No se ha podido añadir el miembro",@@ -102,7 +117,7 @@"more_members_other": "+{{count}} más"},"instructions_tab": {- "description": "El líder lee estas instrucciones cada vez que trabaja en una tarea asignada a este squad.",+ "description": "El líder y cada agente miembro leen estas instrucciones cada vez que trabajan en una tarea asignada a este squad.","unsaved_changes": "Cambios sin guardar","save_button": "Guardar","placeholder": "p. ej., Empieza siempre escribiendo un test que falle. Prefiere commits pequeños y atómicos."diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 58230ed9a6..0dd72a50ce 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -659,6 +659,13 @@"squad_leader_no_action_reason": "a évalué : aucune action nécessaire ({{reason}})","squad_leader_failed": "évaluation en échec","squad_leader_failed_reason": "évaluation en échec : {{reason}}",+ "squad_handoff_to": "a passé la main à {{name}}",+ "squad_handoff_human": "a demandé à {{name}} de décider",+ "squad_handoff_leader": "a rendu la main à {{name}}",+ "squad_handoff_round": "tour {{round}}",+ "squad_handoff_reason_round_limit": "limite de {{limit}} tours atteinte",+ "squad_handoff_reason_daily_limit": "limite quotidienne de passations atteinte",+ "squad_handoff_reason_run_failed": "exécution échouée","coalesced_badge": "×{{count}}","activity_count_one": "{{count}} activité","activity_count_other": "{{count}} activités",@@ -882,6 +889,7 @@},"agent_live": {"is_working": "{{name}} travaille",+ "is_working_round": "{{label}} · tour {{round}}","is_queued": "{{name}} est en file d'attente","is_waiting_local_directory": "{{name}} attend le répertoire local","queued_elapsed_prefix": "en file d'attente depuis {{elapsed}}",diff --git a/packages/views/locales/fr/squads.json b/packages/views/locales/fr/squads.jsonindex 92d7d9f819..4d5fc2bb24 100644--- a/packages/views/locales/fr/squads.json+++ b/packages/views/locales/fr/squads.json@@ -93,6 +93,21 @@"visibility": "Visibilité","visibility_workspace": "Espace de travail"},+ "handoff": {+ "section_title": "Collaboration",+ "mode_leader_title": "Le chef attribue",+ "mode_leader_description": "Chaque étape revient au chef, {{leader}}, qui choisit la suivante. C’est le comportement par défaut des squads existants.",+ "mode_direct_title": "Les membres se passent la main",+ "mode_direct_description": "Le chef attribue la première étape et gère les exceptions. Chaque membre choisit l’étape suivante ; passer en revue ou consulter une personne ne réveille plus le chef.",+ "guard_rounds": "Allers-retours : {{limit}} tours max.",+ "guard_daily": "{{limit}} passations max. par tâche et par jour",+ "guard_failed": "Exécution échouée → retour au chef",+ "guard_no_next": "Pas d’étape suivante → retour au chef",+ "saved": "Mode de collaboration mis à jour",+ "brief_title": "Ce que reçoivent les membres",+ "brief_hint": "Ajouté à chaque exécution sur une tâche assignée à ce squad",+ "brief_empty": "Aucun agent membre pour l’instant"+ },"toasts": {"member_added": "Membre ajouté","member_add_failed": "Échec de l'ajout du membre",@@ -117,7 +132,7 @@"more_members_other": "+{{count}} de plus"},"instructions_tab": {- "description": "Le chef lit ces instructions chaque fois qu’il travaille sur une tâche assignée à ce squad.",+ "description": "Le chef et chaque agent membre lisent ces instructions chaque fois qu’ils travaillent sur une tâche assignée à ce squad.","unsaved_changes": "Modifications non enregistrées","save_button": "Enregistrer","placeholder": "Par exemple : commencez toujours par écrire un test qui échoue. Privilégiez des commits petits et atomiques."diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 9d53a11bb2..4737fdb94f 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -645,6 +645,13 @@"squad_leader_no_action_reason": "評価完了: 必要なアクションはありません({{reason}})","squad_leader_failed": "評価に失敗しました","squad_leader_failed_reason": "評価に失敗しました: {{reason}}",+ "squad_handoff_to": "{{name}} に引き継ぎました",+ "squad_handoff_human": "{{name}} に判断を依頼しました",+ "squad_handoff_leader": "{{name}} に差し戻しました",+ "squad_handoff_round": "{{round}} 往復目",+ "squad_handoff_reason_round_limit": "{{limit}} 往復の上限に到達",+ "squad_handoff_reason_daily_limit": "本日の引き継ぎ上限に到達",+ "squad_handoff_reason_run_failed": "実行失敗","coalesced_badge": "×{{count}}","activity_count_other": "アクティビティ {{count}} 件","show_more_activities_other": "アクティビティをさらに {{count}} 件表示",@@ -847,6 +854,7 @@},"agent_live": {"is_working": "{{name}} が作業中",+ "is_working_round": "{{label}} · {{round}} 往復目","is_queued": "{{name}} が待機中","is_waiting_local_directory": "{{name}} がローカルディレクトリを待機中","queued_elapsed_prefix": "{{elapsed}} 待機中",diff --git a/packages/views/locales/ja/squads.json b/packages/views/locales/ja/squads.jsonindex 6a217aab9a..2e8d42bb57 100644--- a/packages/views/locales/ja/squads.json+++ b/packages/views/locales/ja/squads.json@@ -93,6 +93,21 @@"visibility": "公開範囲","visibility_workspace": "ワークスペース"},+ "handoff": {+ "section_title": "連携方法",+ "mode_leader_title": "リーダーが割り振る",+ "mode_leader_description": "各ステップはリーダー {{leader}} に戻り、次の担当をリーダーが決めます。既存のスクワッドの既定です。",+ "mode_direct_title": "メンバーが直接引き継ぐ",+ "mode_direct_description": "リーダーは最初の担当と例外対応を受け持ちます。メンバーは次のステップを自分で選び、レビューや人への確認の引き継ぎではリーダーを起こしません。",+ "guard_rounds": "レビューの往復は最大 {{limit}} 回",+ "guard_daily": "1 タスクあたり 1 日最大 {{limit}} 回の引き継ぎ",+ "guard_failed": "実行失敗 → リーダーに戻す",+ "guard_no_next": "次の担当なし → リーダーに戻す",+ "saved": "連携方法を更新しました",+ "brief_title": "メンバーが受け取る内容",+ "brief_hint": "このスクワッドのタスクで実行するたびに追加されます",+ "brief_empty": "エージェントメンバーはまだいません"+ },"toasts": {"member_added": "メンバーを追加しました","member_add_failed": "メンバーを追加できませんでした",@@ -115,7 +130,7 @@"more_members_other": "他 {{count}}名"},"instructions_tab": {- "description": "リーダーは、このスクワッドに割り当てられたタスクを処理するたびにこの指示を読みます。",+ "description": "リーダーとすべてのエージェントメンバーは、このスクワッドに割り当てられたタスクを処理するたびにこの指示を読みます。","unsaved_changes": "保存していない変更","save_button": "保存","placeholder": "例:必ず失敗するテストから始める。コミットは小さく独立させる。"diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 62906b9178..70dcd38d25 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -645,6 +645,13 @@"squad_leader_no_action_reason": "평가 완료: 필요한 작업 없음({{reason}})","squad_leader_failed": "평가 실패","squad_leader_failed_reason": "평가 실패: {{reason}}",+ "squad_handoff_to": "{{name}}님에게 넘겼습니다",+ "squad_handoff_human": "{{name}}님에게 결정을 요청했습니다",+ "squad_handoff_leader": "{{name}}님에게 되돌렸습니다",+ "squad_handoff_round": "{{round}}회차",+ "squad_handoff_reason_round_limit": "{{limit}}회 왕복 한도 도달",+ "squad_handoff_reason_daily_limit": "오늘 인계 한도 도달",+ "squad_handoff_reason_run_failed": "실행 실패","coalesced_badge": "×{{count}}","activity_count_other": "활동 {{count}}개","show_more_activities_other": "활동 {{count}}개 더 보기",@@ -847,6 +854,7 @@},"agent_live": {"is_working": "{{name}} 작업 중",+ "is_working_round": "{{label}} · {{round}}회차","is_queued": "{{name}} 대기 중","is_waiting_local_directory": "{{name}} 로컬 디렉터리 대기 중","queued_elapsed_prefix": "{{elapsed}} 동안 대기 중",diff --git a/packages/views/locales/ko/squads.json b/packages/views/locales/ko/squads.jsonindex b3ae11dde0..2d74384e15 100644--- a/packages/views/locales/ko/squads.json+++ b/packages/views/locales/ko/squads.json@@ -93,6 +93,21 @@"visibility": "공개 범위","visibility_workspace": "워크스페이스"},+ "handoff": {+ "section_title": "협업 방식",+ "mode_leader_title": "리더가 배정",+ "mode_leader_description": "모든 단계가 리더 {{leader}}에게 돌아가고, 리더가 다음 담당을 정합니다. 기존 스쿼드의 기본값입니다.",+ "mode_direct_title": "멤버가 직접 인계",+ "mode_direct_description": "리더는 첫 단계 배정과 예외 처리를 맡습니다. 멤버가 다음 단계를 직접 정하며, 리뷰나 사람 확인을 위한 인계는 리더를 깨우지 않습니다.",+ "guard_rounds": "리뷰 왕복 최대 {{limit}}회",+ "guard_daily": "태스크당 하루 최대 {{limit}}회 인계",+ "guard_failed": "실행 실패 → 리더에게 되돌림",+ "guard_no_next": "다음 단계 없음 → 리더에게 되돌림",+ "saved": "협업 방식이 업데이트되었습니다",+ "brief_title": "멤버가 실제로 받는 내용",+ "brief_hint": "이 스쿼드의 태스크에서 실행할 때마다 추가됩니다",+ "brief_empty": "아직 에이전트 멤버가 없습니다"+ },"toasts": {"member_added": "멤버를 추가했습니다","member_add_failed": "멤버를 추가하지 못했습니다",@@ -115,7 +130,7 @@"more_members_other": "+{{count}}명 더 보기"},"instructions_tab": {- "description": "리더는 이 스쿼드에 할당된 태스크를 처리할 때마다 이 지침을 읽습니다.",+ "description": "리더와 모든 에이전트 멤버는 이 스쿼드에 할당된 태스크를 처리할 때마다 이 지침을 읽습니다.","unsaved_changes": "저장하지 않은 변경사항","save_button": "저장","placeholder": "예: 항상 실패하는 테스트부터 작성합니다. 커밋은 작고 독립적으로 유지합니다."diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.jsonindex fd6e11d68c..843ee09936 100644--- a/packages/views/locales/ru/issues.json+++ b/packages/views/locales/ru/issues.json@@ -682,6 +682,13 @@"squad_leader_no_action_reason": "оценил(а): действие не требуется ({{reason}})","squad_leader_failed": "оценка завершилась ошибкой","squad_leader_failed_reason": "оценка завершилась ошибкой: {{reason}}",+ "squad_handoff_to": "передал(а) {{name}}",+ "squad_handoff_human": "попросил(а) {{name}} решить",+ "squad_handoff_leader": "вернул(а) {{name}}",+ "squad_handoff_round": "раунд {{round}}",+ "squad_handoff_reason_round_limit": "достигнут лимит раундов: {{limit}}",+ "squad_handoff_reason_daily_limit": "достигнут дневной лимит передач",+ "squad_handoff_reason_run_failed": "запуск не удался","coalesced_badge": "×{{count}}","activity_count_one": "{{count}} событие","activity_count_other": "{{count}} события",@@ -951,6 +958,7 @@},"agent_live": {"is_working": "{{name}} работает",+ "is_working_round": "{{label}} · раунд {{round}}","is_queued": "{{name}} в очереди","is_waiting_local_directory": "{{name}} ожидает локальную директорию","queued_elapsed_prefix": "в очереди {{elapsed}}",diff --git a/packages/views/locales/ru/squads.json b/packages/views/locales/ru/squads.jsonindex 5760a05767..fa0b38a028 100644--- a/packages/views/locales/ru/squads.json+++ b/packages/views/locales/ru/squads.json@@ -93,6 +93,21 @@"visibility": "Видимость","visibility_workspace": "Рабочее пространство"},+ "handoff": {+ "section_title": "Совместная работа",+ "mode_leader_title": "Лидер распределяет",+ "mode_leader_description": "Каждый шаг возвращается к лидеру, {{leader}}, который выбирает следующий. Так работают существующие команды по умолчанию.",+ "mode_direct_title": "Участники передают напрямую",+ "mode_direct_description": "Лидер назначает первый шаг и разбирает исключения. Участники сами выбирают следующий шаг; передача на ревью или вопрос человеку больше не будят лидера.",+ "guard_rounds": "Ревью туда-обратно: не более {{limit}} раундов",+ "guard_daily": "Не более {{limit}} передач по задаче в день",+ "guard_failed": "Запуск не удался → к лидеру",+ "guard_no_next": "Нет следующего шага → к лидеру",+ "saved": "Режим совместной работы обновлён",+ "brief_title": "Что получают участники",+ "brief_hint": "Добавляется к каждому запуску в задаче этой команды",+ "brief_empty": "Пока нет агентов-участников"+ },"toasts": {"member_added": "Участник добавлен","member_add_failed": "Не удалось добавить участника",@@ -121,7 +136,7 @@"more_members_many": "+{{count}} ещё"},"instructions_tab": {- "description": "Лидер читает эти инструкции при каждой работе над задачей, назначенной этой команде.",+ "description": "Лидер и каждый агент-участник читают эти инструкции при каждой работе над задачей, назначенной этой команде.","unsaved_changes": "Несохранённые изменения","save_button": "Сохранить","placeholder": "например: Всегда начинайте с падающего теста. Предпочитайте небольшие, атомарные коммиты."diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 4e5b80bfd4..6be6fbdf3b 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -645,6 +645,13 @@"squad_leader_no_action_reason": "已评估:无需操作({{reason}})","squad_leader_failed": "评估失败","squad_leader_failed_reason": "评估失败:{{reason}}",+ "squad_handoff_to": "交给了 {{name}}",+ "squad_handoff_human": "请 {{name}} 决定",+ "squad_handoff_leader": "交回 {{name}}",+ "squad_handoff_round": "第 {{round}} 轮",+ "squad_handoff_reason_round_limit": "已来回 {{limit}} 轮",+ "squad_handoff_reason_daily_limit": "今日交接已达上限",+ "squad_handoff_reason_run_failed": "运行失败","coalesced_badge": "×{{count}}","activity_count_other": "{{count}} 条动态","show_more_activities_other": "展开更早 {{count}} 条动态",@@ -847,6 +854,7 @@},"agent_live": {"is_working": "{{name}} 在工作",+ "is_working_round": "{{label}} · 第 {{round}} 轮","is_queued": "{{name}} 排队中","is_waiting_local_directory": "{{name}} 正在等待本地目录","queued_elapsed_prefix": "已排队 {{elapsed}}",diff --git a/packages/views/locales/zh-Hans/squads.json b/packages/views/locales/zh-Hans/squads.jsonindex 1939be6f39..9ba33041be 100644--- a/packages/views/locales/zh-Hans/squads.json+++ b/packages/views/locales/zh-Hans/squads.json@@ -93,6 +93,21 @@"visibility": "可见范围","visibility_workspace": "工作区"},+ "handoff": {+ "section_title": "协作方式",+ "mode_leader_title": "由队长派活",+ "mode_leader_description": "每一步都回到队长 {{leader}},由它决定下一棒。现有小队默认这样。",+ "mode_direct_title": "成员直接交接",+ "mode_direct_description": "队长派第一棒、处理异常;成员做完自己选下一步,审查、@ 人确认这类交接不再唤醒队长。",+ "guard_rounds": "审查来回最多 {{limit}} 轮",+ "guard_daily": "每个任务每天最多交接 {{limit}} 次",+ "guard_failed": "运行失败 → 交回队长",+ "guard_no_next": "没写下一步 → 交回队长",+ "saved": "协作方式已更新",+ "brief_title": "成员实际会收到什么",+ "brief_hint": "每次在这个小队的任务里运行时注入",+ "brief_empty": "还没有智能体成员"+ },"toasts": {"member_added": "已添加成员","member_add_failed": "添加成员失败",@@ -115,7 +130,7 @@"more_members_other": "还有 {{count}} 人"},"instructions_tab": {- "description": "队长每次处理指派给此小队的任务时,都会读取这些指令。",+ "description": "队长和每位智能体成员处理指派给此小队的任务时,都会读取这些指令。","unsaved_changes": "有未保存的修改","save_button": "保存","placeholder": "例如:始终先编写失败测试。提交应保持小而独立。"diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex 580efea962..b98b9a22f7 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -645,6 +645,13 @@"squad_leader_no_action_reason": "已評估:無需操作({{reason}})","squad_leader_failed": "評估失敗","squad_leader_failed_reason": "評估失敗:{{reason}}",+ "squad_handoff_to": "交給了 {{name}}",+ "squad_handoff_human": "請 {{name}} 決定",+ "squad_handoff_leader": "交回 {{name}}",+ "squad_handoff_round": "第 {{round}} 輪",+ "squad_handoff_reason_round_limit": "已來回 {{limit}} 輪",+ "squad_handoff_reason_daily_limit": "今日交接已達上限",+ "squad_handoff_reason_run_failed": "執行失敗","coalesced_badge": "×{{count}}","activity_count_other": "{{count}} 條動態","show_more_activities_other": "展開更早 {{count}} 條動態",@@ -847,6 +854,7 @@},"agent_live": {"is_working": "{{name}} 在工作",+ "is_working_round": "{{label}} · 第 {{round}} 輪","is_queued": "{{name}} 排隊中","is_waiting_local_directory": "{{name}} 正在等待本地目錄","queued_elapsed_prefix": "已排隊 {{elapsed}}",diff --git a/packages/views/locales/zh-Hant/squads.json b/packages/views/locales/zh-Hant/squads.jsonindex b1bc7cd59f..2479267083 100644--- a/packages/views/locales/zh-Hant/squads.json+++ b/packages/views/locales/zh-Hant/squads.json@@ -93,6 +93,21 @@"visibility": "可見範圍","visibility_workspace": "工作區"},+ "handoff": {+ "section_title": "協作方式",+ "mode_leader_title": "由隊長派工",+ "mode_leader_description": "每一步都回到隊長 {{leader}},由它決定下一棒。現有小隊預設如此。",+ "mode_direct_title": "成員直接交接",+ "mode_direct_description": "隊長派第一棒、處理異常;成員做完自己選下一步,審查、@ 人確認這類交接不再喚醒隊長。",+ "guard_rounds": "審查來回最多 {{limit}} 輪",+ "guard_daily": "每個任務每天最多交接 {{limit}} 次",+ "guard_failed": "執行失敗 → 交回隊長",+ "guard_no_next": "沒寫下一步 → 交回隊長",+ "saved": "協作方式已更新",+ "brief_title": "成員實際會收到什麼",+ "brief_hint": "每次在這個小隊的任務裡執行時注入",+ "brief_empty": "還沒有智能體成員"+ },"toasts": {"member_added": "已新增成員","member_add_failed": "新增成員失敗",@@ -115,7 +130,7 @@"more_members_other": "還有 {{count}} 人"},"instructions_tab": {- "description": "隊長每次處理分配給此小隊的任務時,都會讀取這些指引。",+ "description": "隊長和每位智能體成員處理分配給此小隊的任務時,都會讀取這些指引。","unsaved_changes": "有未儲存的修改","save_button": "儲存","placeholder": "例如:始終先編寫失敗測試。提交應保持小而獨立。"diff --git a/packages/views/squads/components/squad-detail-page.test.tsx b/packages/views/squads/components/squad-detail-page.test.tsxindex 0166235e42..65aca6ffc0 100644--- a/packages/views/squads/components/squad-detail-page.test.tsx+++ b/packages/views/squads/components/squad-detail-page.test.tsx@@ -39,7 +39,8 @@ vi.mock("@multica/core/workspace/queries", () => ({agentListOptions: () => ({ queryKey: ["agents"] }),memberListOptions: () => ({ queryKey: ["members"] }),squadMemberStatusOptions: () => ({ queryKey: ["member-status"] }),- workspaceKeys: { squads: () => ["squads"] },+ squadBriefsOptions: () => ({ queryKey: ["briefs"] }),+ workspaceKeys: { squads: () => ["squads"], squadBriefs: () => ["briefs"] },}));vi.mock("@multica/core/api", () => ({ api: mocks.api }));vi.mock("@multica/core/auth", () => ({@@ -163,6 +164,15 @@ function seed(squad: Squad | undefined = SQUAD, extra: Record<string, QueryResul"squads/sq-1/members": { data: MEMBERS },"member-status": { data: { members: STATUSES } },"squads/sq-1/recent-issues": { data: { issues: [ISSUE], total: 1 } },+ briefs: {+ data: {+ handoff_mode: "leader",+ briefs: [+ { member_type: "agent", member_id: "agent-lead", is_leader: true, brief: "## Squad Operating Protocol" },+ { member_type: "agent", member_id: "agent-2", is_leader: false, brief: "## Squad Member Brief\nYou are Kappa" },+ ],+ },+ },agents: {data: [{ id: "agent-lead", name: "Lambda", archived_at: null },@@ -290,6 +300,33 @@ describe("SquadDetailPage", () => {});});+ it("switches how members hand off and previews what they receive", async () => {+ const user = userEvent.setup();+ renderPage();++ const collaboration = section("Collaboration");+ expect(within(collaboration).getByRole("radio", { name: /Leader assigns/ })).toHaveAttribute("aria-checked", "true");+ expect(within(collaboration).queryByText(/up to 3 rounds/)).toBeNull();+ await user.click(within(collaboration).getByRole("radio", { name: /Members hand off directly/ }));+ expect(mocks.api.updateSquad).toHaveBeenCalledWith("sq-1", { handoff_mode: "direct" });++ const preview = section("What members receive");+ expect(within(preview).getByRole("tab", { name: "Kappa" })).toHaveAttribute("aria-selected", "true");+ expect(within(preview).getByText(/You are Kappa/)).toBeInTheDocument();+ await user.click(within(preview).getByRole("tab", { name: "Lambda" }));+ expect(within(preview).getByText("## Squad Operating Protocol")).toBeInTheDocument();+ });++ it("states the direct mode's fixed guardrails", () => {+ seed({ ...SQUAD, handoff_mode: "direct" });+ renderPage();++ const collaboration = section("Collaboration");+ expect(within(collaboration).getByRole("radio", { name: /Members hand off directly/ })).toHaveAttribute("aria-checked", "true");+ expect(within(collaboration).getByText("Back-and-forth: up to 3 rounds")).toBeInTheDocument();+ expect(within(collaboration).getByText("Run failed → back to leader")).toBeInTheDocument();+ });+it("edits instructions in place", async () => {const user = userEvent.setup();renderPage();@@ -397,6 +434,8 @@ describe("SquadDetailPage", () => {expect(screen.queryByRole("button", { name: "Add member" })).toBeNull();expect(within(section("Instructions")).queryByRole("button", { name: "Edit" })).toBeNull();expect(screen.queryByTestId("avatar-upload")).toBeNull();+ expect(within(section("Collaboration")).getByRole("radio", { name: /Members hand off directly/ })).toBeDisabled();+ expect(screen.queryByRole("heading", { level: 2, name: "What members receive" })).toBeNull();await user.click(screen.getByRole("button", { name: "More actions" }));expect(await screen.findByRole("menuitem", { name: "Copy link" })).toBeInTheDocument();diff --git a/packages/views/squads/components/squad-detail-page.tsx b/packages/views/squads/components/squad-detail-page.tsxindex a895f0afcc..af5d43fd89 100644--- a/packages/views/squads/components/squad-detail-page.tsx+++ b/packages/views/squads/components/squad-detail-page.tsx@@ -97,8 +97,9 @@ import {PickerEmpty,} from "../../issues/components/pickers/property-picker";import { toast } from "sonner";-import type { Issue, Squad, SquadMember, SquadMemberStatus, Agent, MemberWithUser } from "@multica/core/types";+import type { Issue, Squad, SquadHandoffMode, SquadMember, SquadMemberStatus, Agent, MemberWithUser } from "@multica/core/types";import { matchesPinyin } from "../../editor/extensions/pinyin-match";+import { SquadBriefsSection, SquadHandoffSection } from "./squad-handoff-sections";const RECENT_WORK_LIMIT = 5;@@ -178,8 +179,12 @@ export function SquadDetailPage() {// a discard so Escape cancels here the same way it does for the description.const discardNameRef = useRef(false);+ // The previewed briefs render the roster and roles, so they follow member edits.+ const refreshBriefs = () =>+ queryClient.invalidateQueries({ queryKey: workspaceKeys.squadBriefs(wsId, squadId) });+const updateSquadMut = useMutation({- mutationFn: (data: { name?: string; description?: string; instructions?: string; avatar_url?: string; leader_id?: string }) => api.updateSquad(squadId, data),+ mutationFn: (data: { name?: string; description?: string; instructions?: string; avatar_url?: string; leader_id?: string; handoff_mode?: SquadHandoffMode }) => api.updateSquad(squadId, data),onSuccess: (updated) => {queryClient.setQueryData([...workspaceKeys.squads(wsId), squadId], updated);refetchSquad();@@ -197,14 +202,14 @@ export function SquadDetailPage() {member_id: input.id,role: input.role?.trim() || undefined,}),- onSuccess: () => { refetchMembers(); toast.success(t(($) => $.toasts.member_added)); },+ onSuccess: () => { refetchMembers(); refreshBriefs(); toast.success(t(($) => $.toasts.member_added)); },onError: (err) =>toast.error(err instanceof Error && err.message ? err.message : t(($) => $.toasts.member_add_failed)),});const removeMemberMut = useMutation({mutationFn: (m: SquadMember) => api.removeSquadMember(squadId, { member_type: m.member_type, member_id: m.member_id }),- onSuccess: () => { refetchMembers(); toast.success(t(($) => $.toasts.member_removed)); },+ onSuccess: () => { refetchMembers(); refreshBriefs(); toast.success(t(($) => $.toasts.member_removed)); },onError: (err) =>toast.error(err instanceof Error && err.message ? err.message : t(($) => $.toasts.member_remove_failed)),});@@ -216,7 +221,7 @@ export function SquadDetailPage() {member_id: input.member.member_id,role: input.role,}),- onSuccess: () => { refetchMembers(); toast.success(t(($) => $.toasts.role_updated)); },+ onSuccess: () => { refetchMembers(); refreshBriefs(); toast.success(t(($) => $.toasts.role_updated)); },onError: (err) =>toast.error(err instanceof Error && err.message ? err.message : t(($) => $.toasts.role_update_failed)),});@@ -458,12 +463,22 @@ export function SquadDetailPage() {setLeaderPending={setLeaderMut.isPending}/>+ <SquadHandoffSection+ squad={squad}+ leaderName={getEntityName("agent", squad.leader_id)}+ canManage={canManage && !archived}+ pending={updateSquadMut.isPending}+ onChange={(mode) => updateSquadMut.mutate({ handoff_mode: mode }, { onSuccess: () => toast.success(t(($) => $.handoff.saved)) })}+ />+<SquadInstructionsSectionsquad={squad}canManage={canManage && !archived}onSave={async (next) => { await updateSquadMut.mutateAsync({ instructions: next }); toast.success(t(($) => $.toasts.instructions_saved)); }}/>+ {canManage && <SquadBriefsSection squadId={squad.id} getEntityName={getEntityName} />}+<SquadRecentWorkSectionissues={recentWork?.issues}loading={recentWorkPending}diff --git a/packages/views/squads/components/squad-handoff-sections.tsx b/packages/views/squads/components/squad-handoff-sections.tsxnew file mode 100644index 0000000000..f59c4e3616--- /dev/null+++ b/packages/views/squads/components/squad-handoff-sections.tsx@@ -0,0 +1,202 @@+"use client";++import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { useWorkspaceId } from "@multica/core/hooks";+import { squadBriefsOptions } from "@multica/core/workspace/queries";+import {+ SQUAD_HANDOFF_DAILY_LIMIT,+ SQUAD_HANDOFF_ROUND_LIMIT,+ type Squad,+ type SquadHandoffMode,+} from "@multica/core/types";+import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { cn } from "@multica/ui/lib/utils";+import { Bot } from "@multica/ui/icons";+import { ActorAvatar } from "../../common/actor-avatar";+import {+ ObjectSection,+ ObjectSectionCard,+ ObjectSectionEmpty,+} from "../../layout/object-page";+import { useT } from "../../i18n";++/**+ * How work moves between the squad's members. Read-only for people who cannot+ * edit the squad; the guardrails of the direct mode are fixed, so they are+ * stated rather than offered as settings.+ */+export function SquadHandoffSection({+ squad,+ leaderName,+ canManage,+ pending,+ onChange,+}: {+ squad: Squad;+ leaderName: string;+ canManage: boolean;+ pending: boolean;+ onChange: (mode: SquadHandoffMode) => void;+}) {+ const { t } = useT("squads");+ const mode = squad.handoff_mode ?? "leader";+ const select = (next: SquadHandoffMode) => {+ if (next !== mode) onChange(next);+ };++ return (+ <ObjectSection title={t(($) => $.handoff.section_title)}>+ <ObjectSectionCard>+ <div role="radiogroup" aria-label={t(($) => $.handoff.section_title)} className="divide-y">+ <HandoffModeOption+ title={t(($) => $.handoff.mode_leader_title)}+ description={t(($) => $.handoff.mode_leader_description, { leader: leaderName })}+ selected={mode === "leader"}+ disabled={!canManage || pending}+ onSelect={() => select("leader")}+ />+ <HandoffModeOption+ title={t(($) => $.handoff.mode_direct_title)}+ description={t(($) => $.handoff.mode_direct_description)}+ selected={mode === "direct"}+ disabled={!canManage || pending}+ onSelect={() => select("direct")}+ >+ {mode === "direct" && (+ <span className="mt-2 flex flex-wrap gap-1.5">+ {[+ t(($) => $.handoff.guard_rounds, { limit: SQUAD_HANDOFF_ROUND_LIMIT }),+ t(($) => $.handoff.guard_daily, { limit: SQUAD_HANDOFF_DAILY_LIMIT }),+ t(($) => $.handoff.guard_failed),+ t(($) => $.handoff.guard_no_next),+ ].map((guard) => (+ <span+ key={guard}+ className="rounded-xs bg-muted px-1.5 py-0.5 text-caption text-muted-foreground"+ >+ {guard}+ </span>+ ))}+ </span>+ )}+ </HandoffModeOption>+ </div>+ </ObjectSectionCard>+ </ObjectSection>+ );+}++function HandoffModeOption({+ title,+ description,+ selected,+ disabled,+ onSelect,+ children,+}: {+ title: string;+ description: string;+ selected: boolean;+ disabled: boolean;+ onSelect: () => void;+ children?: React.ReactNode;+}) {+ return (+ <button+ type="button"+ role="radio"+ aria-checked={selected}+ disabled={disabled}+ onClick={onSelect}+ className={cn(+ "flex w-full items-start gap-3 px-3 py-2.5 text-left transition-colors",+ !disabled && "hover:bg-accent/50",+ disabled && "cursor-default",+ )}+ >+ <span+ aria-hidden="true"+ className={cn(+ "mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border",+ selected ? "border-primary" : "border-input",+ )}+ >+ {selected && <span className="size-2 rounded-full bg-primary" />}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-body font-medium">{title}</span>+ <span className="mt-0.5 block text-caption text-muted-foreground">{description}</span>+ {children}+ </span>+ </button>+ );+}++/**+ * The squad context each agent of the squad actually gets on its runs, as the+ * server renders it. Shown to the people who can edit the squad.+ */+export function SquadBriefsSection({+ squadId,+ getEntityName,+}: {+ squadId: string;+ getEntityName: (type: string, id: string) => string;+}) {+ const { t } = useT("squads");+ const wsId = useWorkspaceId();+ const { data, isPending } = useQuery(squadBriefsOptions(wsId, squadId));+ const briefs = data?.briefs ?? [];+ const [selectedId, setSelectedId] = useState<string | null>(null);+ const selected =+ briefs.find((b) => b.member_id === selectedId) ??+ briefs.find((b) => !b.is_leader) ??+ briefs[0];++ return (+ <ObjectSection+ title={t(($) => $.handoff.brief_title)}+ // The section's caption slot, used here for where the brief goes.+ count={t(($) => $.handoff.brief_hint)}+ >+ {isPending ? (+ <Skeleton className="h-40 w-full rounded-lg" />+ ) : selected ? (+ <ObjectSectionCard>+ <div role="tablist" className="flex items-center gap-1 overflow-x-auto bg-muted/50 px-2 py-1.5">+ {briefs.map((b) => {+ const active = b.member_id === selected.member_id;+ return (+ <button+ key={b.member_id}+ type="button"+ role="tab"+ aria-selected={active}+ onClick={() => setSelectedId(b.member_id)}+ className={cn(+ "flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-label transition-colors",+ active+ ? "bg-background font-medium text-foreground shadow-xs"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ <ActorAvatar actorType="agent" actorId={b.member_id} size="xs" />+ {getEntityName("agent", b.member_id)}+ </button>+ );+ })}+ </div>+ <pre+ role="tabpanel"+ className="max-h-96 overflow-auto whitespace-pre-wrap break-words px-3 py-2.5 font-mono text-caption text-foreground"+ >+ {selected.brief}+ </pre>+ </ObjectSectionCard>+ ) : (+ <ObjectSectionEmpty icon={Bot} description={t(($) => $.handoff.brief_empty)} />+ )}+ </ObjectSection>+ );+}diff --git a/server/cmd/multica/cmd_squad.go b/server/cmd/multica/cmd_squad.goindex 2b30e2b5e8..7542de11d5 100644--- a/server/cmd/multica/cmd_squad.go+++ b/server/cmd/multica/cmd_squad.go@@ -102,6 +102,7 @@ func runSquadGet(cmd *cobra.Command, args []string) error {fmt.Printf("Name: %s\n", strVal(squad, "name"))fmt.Printf("Description: %s\n", strVal(squad, "description"))fmt.Printf("Leader ID: %s\n", strVal(squad, "leader_id"))+ fmt.Printf("Handoff mode: %s\n", squadHandoffModeDisplay(squad))fmt.Printf("Created: %s\n", strVal(squad, "created_at"))if inst := strVal(squad, "instructions"); inst != "" {fmt.Printf("Instructions: %s\n", inst)@@ -109,6 +110,20 @@ func runSquadGet(cmd *cobra.Command, args []string) error {return nil}+// squadHandoffModeDisplay reads handoff_mode, treating a server that predates+// the field as the original leader mode.+func squadHandoffModeDisplay(squad map[string]any) string {+ if mode := strVal(squad, "handoff_mode"); mode != "" {+ return mode+ }+ return squadHandoffModeLeader+}++const (+ squadHandoffModeLeader = "leader"+ squadHandoffModeDirect = "direct"+)+// ── Create ──────────────────────────────────────────────────────────────────var squadCreateCmd = &cobra.Command{@@ -166,11 +181,30 @@ func runSquadCreate(cmd *cobra.Command, _ []string) error {var squadUpdateCmd = &cobra.Command{Use: "update <squad-id>",Short: "Update a squad",- Args: exactArgs(1),- RunE: runSquadUpdate,+ Long: `Update a squad's fields. Only the flags you pass are changed.++--handoff-mode decides who picks the next step after a member finishes:+ leader every member reply returns to the leader (default)+ direct members hand off to each other by @mention; the leader assigns the+ first step and gets the issue back when a guard trips (3 rounds+ between two members, 20 member handoffs per issue per day, a failed+ member run, or a reply that names no next owner)++Changing the handoff mode requires permission to manage the squad.`,+ Args: exactArgs(1),+ RunE: runSquadUpdate,}func runSquadUpdate(cmd *cobra.Command, args []string) error {+ body := map[string]any{}+ if cmd.Flags().Changed("handoff-mode") {+ v, _ := cmd.Flags().GetString("handoff-mode")+ if v != squadHandoffModeLeader && v != squadHandoffModeDirect {+ return fmt.Errorf("--handoff-mode must be 'leader' or 'direct'")+ }+ body["handoff_mode"] = v+ }+client, err := newAPIClient(cmd)if err != nil {return err@@ -178,7 +212,6 @@ func runSquadUpdate(cmd *cobra.Command, args []string) error {ctx, cancel := cli.APIContext(context.Background())defer cancel()- body := map[string]any{}if cmd.Flags().Changed("name") {v, _ := cmd.Flags().GetString("name")body["name"] = v@@ -205,7 +238,7 @@ func runSquadUpdate(cmd *cobra.Command, args []string) error {}if len(body) == 0 {- return fmt.Errorf("no fields to update; use flags like --name, --description, --instructions, --leader")+ return fmt.Errorf("no fields to update; use flags like --name, --description, --instructions, --leader, --handoff-mode")}var result map[string]any@@ -221,6 +254,80 @@ func runSquadUpdate(cmd *cobra.Command, args []string) error {return nil}+// ── Briefs ──────────────────────────────────────────────────────────────────++var squadBriefsCmd = &cobra.Command{+ Use: "briefs <squad-id>",+ Short: "Show the squad context each agent receives",+ Long: `Show the squad section Multica appends to each agent's instructions when it+works on an issue assigned to this squad: the leader briefing for the leader,+and the member brief for every other agent member. Use --agent to print one.++Requires permission to manage the squad.`,+ Args: exactArgs(1),+ RunE: runSquadBriefs,+}++func runSquadBriefs(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var resp struct {+ HandoffMode string `json:"handoff_mode"`+ Briefs []map[string]any `json:"briefs"`+ }+ if err := client.GetJSON(ctx, "/api/squads/"+args[0]+"/briefs", &resp); err != nil {+ return fmt.Errorf("get squad briefs: %w", err)+ }++ briefs := resp.Briefs+ if cmd.Flags().Changed("agent") {+ v, _ := cmd.Flags().GetString("agent")+ agentID, err := resolveAgent(ctx, client, v)+ if err != nil {+ return fmt.Errorf("resolve agent: %w", err)+ }+ briefs = nil+ for _, b := range resp.Briefs {+ if strVal(b, "member_id") == agentID {+ briefs = append(briefs, b)+ }+ }+ if len(briefs) == 0 {+ return fmt.Errorf("agent %s is not an agent member of this squad", agentID)+ }+ }++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ if resp.HandoffMode == "" {+ resp.HandoffMode = squadHandoffModeLeader+ }+ return cli.PrintJSON(os.Stdout, map[string]any{"handoff_mode": resp.HandoffMode, "briefs": briefs})+ }++ if len(briefs) == 0 {+ fmt.Fprintln(os.Stderr, "No agent members.")+ return nil+ }+ for i, b := range briefs {+ if i > 0 {+ fmt.Println()+ }+ role := "member"+ if leader, _ := b["is_leader"].(bool); leader {+ role = "leader"+ }+ fmt.Printf("==> %s (%s)\n", strVal(b, "member_id"), role)+ fmt.Println(strVal(b, "brief"))+ }+ return nil+}+// ── Delete ──────────────────────────────────────────────────────────────────var squadDeleteCmd = &cobra.Command{@@ -523,8 +630,13 @@ func init() {squadUpdateCmd.Flags().String("instructions", "", "New instructions")squadUpdateCmd.Flags().String("leader", "", "New leader agent (name or ID)")squadUpdateCmd.Flags().String("avatar-url", "", "New avatar URL")+ squadUpdateCmd.Flags().String("handoff-mode", "", "How members hand off: leader or direct")squadUpdateCmd.Flags().String("output", "json", "Output format: table or json")+ // briefs+ squadBriefsCmd.Flags().String("agent", "", "Only this agent member (name or ID)")+ squadBriefsCmd.Flags().String("output", "table", "Output format: table or json")+// deletesquadDeleteCmd.Flags().String("output", "table", "Output format: table or json")@@ -561,6 +673,7 @@ func init() {squadCmd.AddCommand(squadGetCmd)squadCmd.AddCommand(squadCreateCmd)squadCmd.AddCommand(squadUpdateCmd)+ squadCmd.AddCommand(squadBriefsCmd)squadCmd.AddCommand(squadDeleteCmd)squadCmd.AddCommand(squadMemberCmd)squadCmd.AddCommand(squadActivityCmd)diff --git a/server/cmd/multica/cmd_squad_test.go b/server/cmd/multica/cmd_squad_test.goindex add3481428..eda4419b34 100644--- a/server/cmd/multica/cmd_squad_test.go+++ b/server/cmd/multica/cmd_squad_test.go@@ -4,6 +4,7 @@ import ("encoding/json""net/http""net/http/httptest"+ "strings""testing""github.com/spf13/cobra"@@ -71,6 +72,135 @@ func TestRunSquadMemberSetRolePatchesRole(t *testing.T) {}}+func newSquadTestCmd(use string, flags map[string]string) *cobra.Command {+ cmd := &cobra.Command{Use: use}+ for _, name := range []string{"server-url", "workspace-id", "profile"} {+ cmd.Flags().String(name, "", "")+ }+ for name, def := range flags {+ cmd.Flags().String(name, def, "")+ }+ return cmd+}++func squadTestServer(t *testing.T, handler http.HandlerFunc) {+ t.Helper()+ redirectTestHome(t, t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")+ srv := httptest.NewServer(handler)+ t.Cleanup(srv.Close)+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+}++func newSquadUpdateTestCmd() *cobra.Command {+ return newSquadTestCmd("update", map[string]string{+ "name": "", "description": "", "instructions": "", "leader": "", "avatar-url": "",+ "handoff-mode": "", "output": "json",+ })+}++func TestRunSquadUpdateSendsHandoffMode(t *testing.T) {+ var gotMethod, gotPath string+ var gotBody map[string]any+ squadTestServer(t, func(w http.ResponseWriter, r *http.Request) {+ gotMethod, gotPath = r.Method, r.URL.Path+ if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {+ t.Fatalf("decode request body: %v", err)+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "squad-123", "name": "Delivery", "handoff_mode": "direct"})+ })++ cmd := newSquadUpdateTestCmd()+ _ = cmd.Flags().Set("handoff-mode", "direct")+ if _, err := captureStdout(t, func() error { return runSquadUpdate(cmd, []string{"squad-123"}) }); err != nil {+ t.Fatalf("runSquadUpdate: %v", err)+ }+ if gotMethod != http.MethodPut || gotPath != "/api/squads/squad-123" {+ t.Fatalf("request = %s %s, want PUT /api/squads/squad-123", gotMethod, gotPath)+ }+ if len(gotBody) != 1 || gotBody["handoff_mode"] != "direct" {+ t.Fatalf("body = %#v, want only handoff_mode=direct", gotBody)+ }+}++func TestRunSquadUpdateRejectsUnknownHandoffMode(t *testing.T) {+ squadTestServer(t, func(w http.ResponseWriter, r *http.Request) {+ t.Fatalf("an invalid mode must not reach the server: %s %s", r.Method, r.URL.Path)+ })+ cmd := newSquadUpdateTestCmd()+ _ = cmd.Flags().Set("handoff-mode", "round_robin")+ if err := runSquadUpdate(cmd, []string{"squad-123"}); err == nil || !strings.Contains(err.Error(), "--handoff-mode") {+ t.Fatalf("err = %v, want a --handoff-mode validation error", err)+ }+}++func TestRunSquadBriefs(t *testing.T) {+ const memberID = "11111111-1111-4111-8111-111111111111"+ squadTestServer(t, func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/api/squads/squad-123/briefs" {+ t.Fatalf("request = %s %s, want GET /api/squads/squad-123/briefs", r.Method, r.URL.Path)+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "handoff_mode": "direct",+ "briefs": []map[string]any{+ {"member_type": "agent", "member_id": "22222222-2222-4222-8222-222222222222", "is_leader": true, "brief": "## Squad Operating Protocol"},+ {"member_type": "agent", "member_id": memberID, "is_leader": false, "brief": "## Squad Member Brief"},+ },+ })+ })+ newCmd := func() *cobra.Command { return newSquadTestCmd("briefs", map[string]string{"agent": "", "output": "table"}) }++ t.Run("table prints every agent", func(t *testing.T) {+ out, err := captureStdout(t, func() error { return runSquadBriefs(newCmd(), []string{"squad-123"}) })+ if err != nil {+ t.Fatalf("runSquadBriefs: %v", err)+ }+ if !strings.Contains(out, "(leader)\n## Squad Operating Protocol") || !strings.Contains(out, memberID+" (member)\n## Squad Member Brief") {+ t.Fatalf("output = %q", out)+ }+ })++ t.Run("agent filter and json", func(t *testing.T) {+ cmd := newCmd()+ _ = cmd.Flags().Set("agent", memberID)+ _ = cmd.Flags().Set("output", "json")+ out, err := captureStdout(t, func() error { return runSquadBriefs(cmd, []string{"squad-123"}) })+ if err != nil {+ t.Fatalf("runSquadBriefs: %v", err)+ }+ var got struct {+ HandoffMode string `json:"handoff_mode"`+ Briefs []map[string]any `json:"briefs"`+ }+ if err := json.Unmarshal([]byte(out), &got); err != nil {+ t.Fatalf("decode %q: %v", out, err)+ }+ if got.HandoffMode != "direct" || len(got.Briefs) != 1 || got.Briefs[0]["member_id"] != memberID {+ t.Fatalf("json = %+v", got)+ }+ })++ t.Run("agent outside the squad", func(t *testing.T) {+ cmd := newCmd()+ _ = cmd.Flags().Set("agent", "33333333-3333-4333-8333-333333333333")+ if err := runSquadBriefs(cmd, []string{"squad-123"}); err == nil {+ t.Fatal("expected an error for an agent that is not a squad member")+ }+ })+}++func TestSquadHandoffModeDisplayDefaultsToLeader(t *testing.T) {+ if got := squadHandoffModeDisplay(map[string]any{"id": "squad-123"}); got != "leader" {+ t.Fatalf("missing handoff_mode = %q, want leader", got)+ }+ if got := squadHandoffModeDisplay(map[string]any{"handoff_mode": "direct"}); got != "direct" {+ t.Fatalf("handoff_mode = %q, want direct", got)+ }+}+func TestRunSquadMemberSetRoleValidatesRequiredFlags(t *testing.T) {cmd := newSquadMemberSetRoleTestCmd()if err := runSquadMemberSetRole(cmd, []string{"squad-123"}); err == nil {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex e46b09e088..07e328e5a1 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2505,6 +2505,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Delete("/", h.DeleteSquad)r.Get("/members", h.ListSquadMembers)r.Get("/members/status", h.ListSquadMemberStatus)+ r.Get("/briefs", h.ListSquadBriefs)r.Post("/members", h.AddSquadMember)r.Delete("/members", h.RemoveSquadMember)r.Patch("/members/role", h.UpdateSquadMemberRole)diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.goindex 04189b0f73..17e84d4394 100644--- a/server/internal/dispatch/reason.go+++ b/server/internal/dispatch/reason.go@@ -96,6 +96,10 @@ const (// ReasonQuotaExceeded is a policy-neutral refusal for an exhausted// Cloud-provided autopilot interval.ReasonQuotaExceeded ReasonCode = "quota_exceeded"+ // ReasonHandedToLeader: a squad member handed the issue to another member,+ // but the squad's handoff guard (round or daily limit) sent it to the squad+ // leader instead. The leader's run covers the comment.+ ReasonHandedToLeader ReasonCode = "handed_to_leader"// ReasonInternalError: an unexpected server error prevented a clean decision.ReasonInternalError ReasonCode = "internal_error")diff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.goindex a998a0fc1d..d53ebfd859 100644--- a/server/internal/handler/admission.go+++ b/server/internal/handler/admission.go@@ -69,6 +69,7 @@ const (ReasonSelfTriggerSuppressed = dispatch.ReasonSelfTriggerSuppressedReasonIssueInTriage = dispatch.ReasonIssueInTriageReasonProjectAccessBlocked = dispatch.ReasonProjectAccessBlocked+ ReasonHandedToLeader = dispatch.ReasonHandedToLeaderReasonInternalError = dispatch.ReasonInternalError)diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex dc7f3d3f83..36432a704e 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1510,6 +1510,9 @@ type commentTriggerComputeOptions struct {// by the originator, not the immediate agent principal. Members are their// own originator so this may be empty for member-authored triggers.OriginatorUserID string+ // handoffPlan collects the squad handoffs this comment records once its+ // routing is enqueued. Nil for previews, which must not record anything.+ handoffPlan *squadHandoffPlan}func commentAgentTriggerReason(trigger commentAgentTrigger) string {@@ -2035,10 +2038,12 @@ func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, coif isNoteComment(comment.Content) {return nil}+ handoffPlan := &squadHandoffPlan{}triggers, targets := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{ExcludeTriggerCommentID: comment.ID,AuthoringTaskID: comment.SourceTaskID,OriginatorUserID: originatorUserID,+ handoffPlan: handoffPlan,})triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)h.noteBlockedRuntimeTargets(ctx, issue, targets)@@ -2047,6 +2052,7 @@ func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, cofor agentID, result := range steered {enqueued[agentID] = result}+ h.recordSquadHandoffs(ctx, issue, comment, handoffPlan, enqueued)if commentResultsTriggeredAgent(enqueued) {h.archiveActorInboxOnAgentTrigger(ctx, uuidToString(issue.WorkspaceID), uuidToString(issue.ID), actorType, actorID)}@@ -2740,6 +2746,11 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu// creator's authority by commenting on that autopilot's issue.mentions := util.ParseMentions(content)+ handoffAuthor := h.directSquadHandoffAuthor(ctx, issue, actorType, actorID, opts.AuthoringTaskID)+ if opts.handoffPlan != nil {+ opts.handoffPlan.author = handoffAuthor+ }+ memberHandoff := handoffAuthor != nil && !handoffAuthor.isLeader// EXPLICIT @agent / @squad mentions are a direct request and win over the// @all broadcast (MUL-5411). @all only suppresses the IMPLICIT routing@@ -2749,7 +2760,11 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu// `all` is neither "agent" nor "squad", so it is skipped inside// resolveMentionedAgentCommentTriggers and never enqueues a run of its own.if hasAgentOrSquadMention(mentions) {- return h.resolveMentionedAgentCommentTriggers(ctx, issue, mentions, actorType, actorID, opts)+ triggers, targets := h.resolveMentionedAgentCommentTriggers(ctx, issue, mentions, actorType, actorID, opts)+ if handoffAuthor != nil {+ triggers, targets = h.applyDirectSquadHandoff(ctx, issue, handoffAuthor, triggers, targets, opts)+ }+ return triggers, targets}// A member who @mentions people (a member or @all) and no agent/squad is// talking to humans, so the implicit fallbacks stay quiet. An agent's@@ -2774,9 +2789,20 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issureturn triggers, nil}}+ // In direct handoff mode a member that hands the issue to a person is+ // waiting on that person, not on the leader.+ if memberHandoff {+ if userID, ok := firstMemberMention(mentions); ok {+ opts.handoffPlan.add(squadHandoffRecord{kind: squadHandoffKindHuman, toType: "member", toID: userID})+ return nil, nil+ }+ }if issue.AssigneeType.Valid && issue.AssigneeType.String == "squad" {if trigger, ok := h.routeAssignedSquadLeaderFallback(ctx, issue, actorType, actorID, opts); ok {trigger.NonLeaderAgentReply = actorType == "agent" && actorID != uuidToString(trigger.Agent.ID)+ if memberHandoff {+ opts.handoffPlan.add(squadHandoffRecord{kind: squadHandoffKindLeader, toType: "agent", toID: trigger.Agent.ID, agentID: trigger.Agent.ID})+ }return []commentAgentTrigger{trigger}, nil}}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex b5aa229ce5..c04653896c 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -3403,6 +3403,18 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu"agent_id", uuidToString(task.AgentID),)}+ } else if resp.Agent != nil {+ // A member's run on its squad's issue carries the squad context the+ // leader already gets: roster, rules, its role, and how to hand off.+ if agent, err := h.Queries.GetAgent(r.Context(), task.AgentID); err == nil {+ if brief := squadMemberBriefingForClaim(r.Context(), h.Queries, issue, agent); brief != "" {+ if strings.TrimSpace(resp.Agent.Instructions) == "" {+ resp.Agent.Instructions = brief+ } else {+ resp.Agent.Instructions = resp.Agent.Instructions + "\n\n" + brief+ }+ }+ }}projectCtx, projectErr := h.resolveClaimProjectContext(r.Context(), issue.ProjectID, issue.WorkspaceID)diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.goindex 1fda43d0ca..e5df6ae29a 100644--- a/server/internal/handler/squad.go+++ b/server/internal/handler/squad.go@@ -13,6 +13,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/logger"obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/dbid"@@ -27,6 +28,7 @@ type SquadResponse struct {Name string `json:"name"`Description string `json:"description"`Instructions string `json:"instructions"`+ HandoffMode string `json:"handoff_mode"`AvatarURL *string `json:"avatar_url"`LeaderID string `json:"leader_id"`CreatorID string `json:"creator_id"`@@ -67,6 +69,7 @@ func (h *Handler) squadToResponse(s db.Squad) SquadResponse {Name: s.Name,Description: s.Description,Instructions: s.Instructions,+ HandoffMode: s.HandoffMode,AvatarURL: h.resolveAvatarURLPtr(textToPtr(s.AvatarUrl)),LeaderID: uuidToString(s.LeaderID),CreatorID: uuidToString(s.CreatorID),@@ -387,6 +390,7 @@ func (h *Handler) UpdateSquad(w http.ResponseWriter, r *http.Request) {Name *string `json:"name"`Description *string `json:"description"`Instructions *string `json:"instructions"`+ HandoffMode *string `json:"handoff_mode"`LeaderID *string `json:"leader_id"`AvatarURL *string `json:"avatar_url"`}@@ -405,6 +409,13 @@ func (h *Handler) UpdateSquad(w http.ResponseWriter, r *http.Request) {if req.Instructions != nil {params.Instructions = pgtype.Text{String: *req.Instructions, Valid: true}}+ if req.HandoffMode != nil {+ if !service.IsValidSquadHandoffMode(*req.HandoffMode) {+ writeError(w, http.StatusBadRequest, "handoff_mode must be 'leader' or 'direct'")+ return+ }+ params.HandoffMode = pgtype.Text{String: *req.HandoffMode, Valid: true}+ }if req.AvatarURL != nil {accepted, ok := h.acceptAvatarURL(w, r, *req.AvatarURL, squad.AvatarUrl.String)if !ok {@@ -1294,3 +1305,62 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, au}return DispatchQueued, ReasonQueued}++type SquadBriefResponse struct {+ MemberType string `json:"member_type"`+ MemberID string `json:"member_id"`+ IsLeader bool `json:"is_leader"`+ Brief string `json:"brief"`+}++type SquadBriefsResponse struct {+ HandoffMode string `json:"handoff_mode"`+ Briefs []SquadBriefResponse `json:"briefs"`+}++// ListSquadBriefs previews the squad context each agent of the squad receives+// on an issue assigned to the squad: the leader briefing for the leader, the+// member brief for every other non-archived agent member. Limited to the+// people who can edit the squad — it is a configuration aid, and the roster it+// renders names agents a regular member may not otherwise see.+func (h *Handler) ListSquadBriefs(w http.ResponseWriter, r *http.Request) {+ workspaceID := workspaceIDFromURL(r, "workspaceId")+ member, ok := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found")+ if !ok {+ return+ }+ squad, _, ok := h.loadSquadInWorkspace(w, r)+ if !ok {+ return+ }+ if !canManageSquad(member, squad) {+ writeError(w, http.StatusForbidden, "insufficient permissions")+ return+ }+ members, err := h.Queries.ListSquadMembers(r.Context(), squad.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list squad members")+ return+ }+ resp := SquadBriefsResponse{HandoffMode: squad.HandoffMode, Briefs: []SquadBriefResponse{{+ MemberType: "agent",+ MemberID: uuidToString(squad.LeaderID),+ IsLeader: true,+ Brief: buildSquadLeaderBriefing(r.Context(), h.Queries, squad, true, leaderNoWorkflow, true),+ }}}+ for _, m := range members {+ if m.MemberType != "agent" || m.MemberID == squad.LeaderID {+ continue+ }+ agent, err := h.Queries.GetAgent(r.Context(), m.MemberID)+ if err != nil || agent.ArchivedAt.Valid {+ continue+ }+ resp.Briefs = append(resp.Briefs, SquadBriefResponse{+ MemberType: "agent",+ MemberID: uuidToString(m.MemberID),+ Brief: buildSquadMemberBriefing(r.Context(), h.Queries, squad, agent),+ })+ }+ writeJSON(w, http.StatusOK, resp)+}diff --git a/server/internal/handler/squad_briefing.go b/server/internal/handler/squad_briefing.goindex 1d7a6ff292..4bf3e169a6 100644--- a/server/internal/handler/squad_briefing.go+++ b/server/internal/handler/squad_briefing.go@@ -2,9 +2,11 @@ package handlerimport ("context"+ "fmt""strings""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -255,6 +257,22 @@ const squadSteerRule = `- A worker already running on this issue gets a new commthe command reports per run whether it was. New work is still a normaldelegation.`+// squadLeaderDirectHandoff tells the leader of a direct-handoff squad which+// replies still reach it. It narrows responsibility 4's re-trigger list; the+// guard numbers are the server's (service.SquadHandoff*Limit).+var squadLeaderDirectHandoff = fmt.Sprintf(`## Handoff Mode: Direct++Members of this squad hand the issue to each other directly: when a member+finishes, it @mentions the next member (or a person) in its result comment,+and that handoff does NOT wake you. Delegate only the first step, then handle+exceptions. You are woken when:+- a member replies without naming a next step, or reports the issue done;+- a member's run fails;+- the same two members pass the issue back and forth more than %d rounds;+- the issue exceeds %d member handoffs in 24 hours.+When you delegate the next step after one of these, the round count starts over.`,+ service.SquadHandoffRoundLimit, service.SquadHandoffDailyLimit)+// squadOperatingProtocolFor assembles the protocol, selecting the parent-status// responsibility that matches this leader's actual authority over the issue// and, for an owner, whether the issue's project workflow governs its moves.@@ -306,6 +324,10 @@ func buildSquadLeaderBriefing(ctx context.Context, q *db.Queries, squad db.Squadsb.WriteString("\n")sb.WriteString(squadSteerRule)}+ if squad.HandoffMode == service.SquadHandoffModeDirect {+ sb.WriteString("\n\n")+ sb.WriteString(squadLeaderDirectHandoff)+ }sb.WriteString("\n\n")sb.WriteString(buildSquadRoster(ctx, q, squad))@@ -476,3 +498,140 @@ func formatRosterRow(name, kind, role, skills, mention string) string {func formatMention(name, mentionType, id string) string {return "[@" + name + "](mention://" + mentionType + "/" + id + ")"}++// squadMemberHandoffLeader and squadMemberHandoffDirect are the "Handing Off"+// section of a member brief, one per squad handoff mode. %s is the leader's+// name; the direct text also takes the two guard limits.+const squadMemberHandoffLeader = `## Handing Off++This squad uses leader dispatch. When you finish your part, post your result+as one comment on this issue. Your reply wakes the leader, %s, who decides+the next step.`++const squadMemberHandoffDirect = `## Handing Off++Members of this squad hand the issue to each other directly. When you finish+your part, decide the next step yourself and state it in your result comment:+- Another member should continue or review the work: @mention exactly that+ member, using the mention markdown under Your Squad. Never ask for a review+ of your own work.+- A person needs to decide: @mention that person. The leader is not woken;+ the person replies on the issue.+- You are blocked, the work is out of scope, or you are unsure what comes+ next: do not @mention anyone and say why. Your reply goes to the leader, %s.+- The whole issue is done: say so without @mentioning anyone. The leader+ wraps it up.+Name one next owner per comment. The same two members can pass the issue back+and forth at most %d rounds, and an issue takes at most %d member handoffs in+24 hours. Past either limit, or when a member's run fails, the issue goes back+to the leader.`++// buildSquadMemberBriefing composes the squad context appended to a member's+// Instructions when it claims a non-leader task on an issue assigned to its+// squad: who it is in the squad, the roster it can hand off to, the squad's+// rules, and how it hands off under the squad's handoff mode.+//+// It must never contain squadBriefingMarker ("## Squad Operating Protocol"):+// a daemon that predates leader_role_resolved infers the leader role from+// that heading.+func buildSquadMemberBriefing(ctx context.Context, q *db.Queries, squad db.Squad, self db.Agent) string {+ leaderName := "the leader"+ if leader, err := q.GetAgent(ctx, squad.LeaderID); err == nil {+ leaderName = leader.Name+ }+ members, err := q.ListSquadMembers(ctx, squad.ID)+ if err != nil {+ members = nil+ }+ selfID := util.UUIDToString(self.ID)+ role := ""+ for _, m := range members {+ if m.MemberType == "agent" && util.UUIDToString(m.MemberID) == selfID {+ role = strings.TrimSpace(m.Role)+ }+ }++ var sb strings.Builder+ sb.WriteString("## Squad Member Brief\n\n")+ sb.WriteString("You are working on this issue as ")+ sb.WriteString(self.Name)+ sb.WriteString(", a member of the squad \"")+ sb.WriteString(squad.Name)+ sb.WriteString("\". The squad leader, ")+ sb.WriteString(leaderName)+ sb.WriteString(", dispatches work and handles exceptions; you do your part and hand off.")+ if role != "" {+ sb.WriteString("\nYour role in this squad: \"")+ sb.WriteString(role)+ sb.WriteString("\".")+ }+ sb.WriteString("\n\n")+ sb.WriteString(buildSquadMemberRoster(ctx, q, squad, leaderName, members, selfID))++ if trimmed := strings.TrimSpace(squad.Instructions); trimmed != "" {+ sb.WriteString("\n## Squad Rules (")+ sb.WriteString(squad.Name)+ sb.WriteString(")\n\n")+ sb.WriteString(trimmed)+ sb.WriteString("\n")+ }+ sb.WriteString("\n")+ if squad.HandoffMode == service.SquadHandoffModeDirect {+ sb.WriteString(fmt.Sprintf(squadMemberHandoffDirect, leaderName, service.SquadHandoffRoundLimit, service.SquadHandoffDailyLimit))+ } else {+ sb.WriteString(fmt.Sprintf(squadMemberHandoffLeader, leaderName))+ }+ return sb.String()+}++// buildSquadMemberRoster is buildSquadRoster from a member's seat: the leader+// row, then every other non-archived member. The member itself is left out so+// it cannot pick itself as the next owner.+func buildSquadMemberRoster(ctx context.Context, q *db.Queries, squad db.Squad, leaderName string, members []db.SquadMember, selfID string) string {+ var sb strings.Builder+ sb.WriteString("## Your Squad\n\nLeader:\n- ")+ sb.WriteString(leaderName)+ sb.WriteString(" — agent — `")+ sb.WriteString(formatMention(leaderName, "agent", util.UUIDToString(squad.LeaderID)))+ sb.WriteString("`\n")++ leaderID := util.UUIDToString(squad.LeaderID)+ skillNamesByAgentID, skillsLoaded := loadSquadMemberSkillNames(ctx, q, members, leaderID)+ rows := make([]string, 0, len(members))+ for _, m := range members {+ id := util.UUIDToString(m.MemberID)+ if m.MemberType == "agent" && (id == leaderID || id == selfID) {+ continue+ }+ if row := renderMemberRow(ctx, q, m, skillNamesByAgentID, skillsLoaded); row != "" {+ rows = append(rows, row)+ }+ }+ if len(rows) == 0 {+ sb.WriteString("\nOther members: (none)\n")+ return sb.String()+ }+ sb.WriteString("\nOther members:\n")+ for _, r := range rows {+ sb.WriteString(r)+ }+ return sb.String()+}++// squadMemberBriefingForClaim returns the member brief for a non-leader claim+// on an issue assigned to a squad the agent belongs to, or "" when the run is+// not a squad member turn.+func squadMemberBriefingForClaim(ctx context.Context, q *db.Queries, issue db.Issue, agent db.Agent) string {+ if !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" || !issue.AssigneeID.Valid {+ return ""+ }+ squad, err := q.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: issue.AssigneeID, WorkspaceID: issue.WorkspaceID})+ if err != nil || squad.ArchivedAt.Valid || squad.LeaderID == agent.ID {+ return ""+ }+ isMember, err := q.IsSquadMember(ctx, db.IsSquadMemberParams{SquadID: squad.ID, MemberType: "agent", MemberID: agent.ID})+ if err != nil || !isMember {+ return ""+ }+ return buildSquadMemberBriefing(ctx, q, squad, agent)+}diff --git a/server/internal/handler/squad_handoff.go b/server/internal/handler/squad_handoff.gonew file mode 100644index 0000000000..8ad1eb8ee4--- /dev/null+++ b/server/internal/handler/squad_handoff.go@@ -0,0 +1,315 @@+package handler++import (+ "context"+ "encoding/json"+ "log/slog"+ "strconv"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// A squad in direct handoff mode lets members pass the issue to each other by+// @mention without waking the leader. Every pass is recorded as a+// squad_handoff activity; the round and daily guards below read those rows, so+// the guards only ever see handoffs this server actually routed.+//+// The limits and mode names live in the service package so the failure+// recovery path, which hands a failed member run to the leader, shares them.++const squadHandoffHistoryLimit = 50++// Handoff kinds stored in squad_handoff details. Only "member" counts toward+// the round and daily guards; "dispatch" is the leader handing out a step and+// resets the back-and-forth count.+const (+ squadHandoffKindDispatch = "dispatch"+ squadHandoffKindMember = "member"+ squadHandoffKindHuman = "human"+ squadHandoffKindLeader = "leader"+)++// Reasons for a handoff that a guard sent back to the leader. A member reply+// that names no next owner goes back without one: it may be a finished issue+// as much as a stuck one.+const (+ squadHandoffReasonRoundLimit = "round_limit"+ squadHandoffReasonDailyLimit = "daily_limit"+)++// squadHandoffAuthor is an agent comment written by a run of a direct-mode+// squad's own leader or member on an issue assigned to that squad.+type squadHandoffAuthor struct {+ squad db.Squad+ agentID pgtype.UUID+ isLeader bool+}++// squadHandoffRecord is one handoff the comment will record once its routing+// has been enqueued. Records whose target agent did not end up with a run are+// dropped at write time.+type squadHandoffRecord struct {+ kind string+ toType string+ toID pgtype.UUID+ round int+ reason string+ agentID pgtype.UUID // the agent whose run carries this handoff, if any+}++type squadHandoffPlan struct {+ author *squadHandoffAuthor+ records []squadHandoffRecord+}++func (p *squadHandoffPlan) add(r squadHandoffRecord) {+ if p != nil {+ p.records = append(p.records, r)+ }+}++// directSquadHandoffAuthor resolves the squad context of an agent comment on a+// direct-mode squad issue. It fails closed to nil — today's routing — whenever+// the authoring run cannot be proven to be the squad's leader turn or a member+// turn on this very issue.+func (h *Handler) directSquadHandoffAuthor(ctx context.Context, issue db.Issue, actorType, actorID string, authoringTaskID pgtype.UUID) *squadHandoffAuthor {+ if actorType != "agent" || !authoringTaskID.Valid ||+ !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" || !issue.AssigneeID.Valid {+ return nil+ }+ squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{+ ID: issue.AssigneeID,+ WorkspaceID: issue.WorkspaceID,+ })+ if err != nil || squad.ArchivedAt.Valid || squad.HandoffMode != service.SquadHandoffModeDirect {+ return nil+ }+ task, err := h.Queries.GetAgentTask(ctx, authoringTaskID)+ if err != nil || !task.AgentID.Valid || uuidToString(task.AgentID) != actorID || task.IssueID != issue.ID {+ return nil+ }+ if task.AgentID == squad.LeaderID {+ if !task.IsLeaderTask || task.SquadID != squad.ID {+ return nil+ }+ return &squadHandoffAuthor{squad: squad, agentID: task.AgentID, isLeader: true}+ }+ if task.IsLeaderTask || !h.isSquadAgentMember(ctx, squad, task.AgentID) {+ return nil+ }+ return &squadHandoffAuthor{squad: squad, agentID: task.AgentID}+}++func (h *Handler) isSquadAgentMember(ctx context.Context, squad db.Squad, agentID pgtype.UUID) bool {+ if agentID == squad.LeaderID {+ return false+ }+ ok, err := h.Queries.IsSquadMember(ctx, db.IsSquadMemberParams{SquadID: squad.ID, MemberType: "agent", MemberID: agentID})+ return err == nil && ok+}++// applyDirectSquadHandoff records the handoffs in an explicit-mention comment+// and enforces the member guards: a pass between two members that would start+// a round past the limit, or the issue's daily member-handoff budget running+// out, goes to the leader instead of the named member.+func (h *Handler) applyDirectSquadHandoff(ctx context.Context, issue db.Issue, author *squadHandoffAuthor, triggers []commentAgentTrigger, targets []commentMentionTarget, opts commentTriggerComputeOptions) ([]commentAgentTrigger, []commentMentionTarget) {+ plan := opts.handoffPlan+ if author.isLeader {+ for _, trigger := range triggers {+ if h.isSquadAgentMember(ctx, author.squad, trigger.Agent.ID) {+ plan.add(squadHandoffRecord{kind: squadHandoffKindDispatch, toType: "agent", toID: trigger.Agent.ID, agentID: trigger.Agent.ID})+ }+ }+ return triggers, targets+ }++ var history []db.ActivityLog+ historyLoaded := false+ var memberHandoffsToday int64 = -1+ redirect := ""+ kept := triggers[:0:0]+ for _, trigger := range triggers {+ if trigger.Source != commentTriggerSourceMentionAgent || trigger.Agent.ID == author.agentID ||+ !h.isSquadAgentMember(ctx, author.squad, trigger.Agent.ID) {+ kept = append(kept, trigger)+ continue+ }+ if !historyLoaded {+ history, _ = h.Queries.ListRecentSquadHandoffs(ctx, db.ListRecentSquadHandoffsParams{IssueID: issue.ID, RowLimit: squadHandoffHistoryLimit})+ historyLoaded = true+ }+ round := squadHandoffRound(history, author.agentID, trigger.Agent.ID)+ reason := ""+ if round > service.SquadHandoffRoundLimit {+ reason = squadHandoffReasonRoundLimit+ } else {+ if memberHandoffsToday < 0 {+ memberHandoffsToday, _ = h.Queries.CountSquadMemberHandoffsSince(ctx, db.CountSquadMemberHandoffsSinceParams{+ IssueID: issue.ID,+ Since: pgtype.Timestamptz{Time: time.Now().Add(-24 * time.Hour), Valid: true},+ })+ }+ if memberHandoffsToday >= service.SquadHandoffDailyLimit {+ reason = squadHandoffReasonDailyLimit+ }+ }+ if reason == "" {+ plan.add(squadHandoffRecord{kind: squadHandoffKindMember, toType: "agent", toID: trigger.Agent.ID, round: round, agentID: trigger.Agent.ID})+ kept = append(kept, trigger)+ memberHandoffsToday+++ continue+ }+ if redirect == "" {+ redirect = reason+ }+ agentID := uuidToString(trigger.Agent.ID)+ for i := range targets {+ if targets[i].ExecAgentID == agentID {+ targets[i].ExecAgentID = ""+ targets[i].Status = DispatchBlocked+ targets[i].ReasonCode = ReasonHandedToLeader+ }+ }+ }+ if redirect == "" {+ for _, trigger := range kept {+ if trigger.Source == commentTriggerSourceMentionAgent && trigger.Agent.ID == author.squad.LeaderID {+ plan.add(squadHandoffRecord{kind: squadHandoffKindLeader, toType: "agent", toID: author.squad.LeaderID, agentID: author.squad.LeaderID})+ break+ }+ }+ return kept, targets+ }+ for _, trigger := range kept {+ if trigger.Agent.ID == author.squad.LeaderID {+ plan.add(squadHandoffRecord{kind: squadHandoffKindLeader, toType: "agent", toID: author.squad.LeaderID, reason: redirect, agentID: author.squad.LeaderID})+ return kept, targets+ }+ }+ if leader, ok := h.routeAssignedSquadLeaderFallback(ctx, issue, "agent", uuidToString(author.agentID), opts); ok {+ leader.NonLeaderAgentReply = true+ kept = append(kept, leader)+ plan.add(squadHandoffRecord{kind: squadHandoffKindLeader, toType: "agent", toID: author.squad.LeaderID, reason: redirect, agentID: author.squad.LeaderID})+ }+ return kept, targets+}++// squadHandoffRound is the round a new from→to member handoff would start:+// one more than the from→to passes in the unbroken streak of member handoffs+// between the same two agents at the head of the history. Any other record —+// a leader dispatch, a third member, a pass to a human — ends the streak.+func squadHandoffRound(history []db.ActivityLog, from, to pgtype.UUID) int {+ round := 1+ for _, row := range history {+ var d struct {+ Kind string `json:"kind"`+ ToID string `json:"to_id"`+ }+ if json.Unmarshal(row.Details, &d) != nil || d.Kind != squadHandoffKindMember {+ break+ }+ rowFrom, rowTo := uuidToString(row.ActorID), d.ToID+ switch {+ case rowFrom == uuidToString(from) && rowTo == uuidToString(to):+ round+++ case rowFrom == uuidToString(to) && rowTo == uuidToString(from):+ default:+ return round+ }+ }+ return round+}++// recordSquadHandoffs writes the plan's squad_handoff rows after the comment's+// routing ran. A record whose agent did not get a run (refused, unchecked in+// the composer) is not a handoff. Re-routing the same comment — an edit — does+// not record it twice.+func (h *Handler) recordSquadHandoffs(ctx context.Context, issue db.Issue, comment db.Comment, plan *squadHandoffPlan, enqueued map[string]commentEnqueueResult) {+ if plan == nil || plan.author == nil || len(plan.records) == 0 {+ return+ }+ history, err := h.Queries.ListRecentSquadHandoffs(ctx, db.ListRecentSquadHandoffsParams{IssueID: issue.ID, RowLimit: squadHandoffHistoryLimit})+ if err != nil {+ slog.Warn("squad handoff: load history failed", "issue_id", uuidToString(issue.ID), "error", err)+ return+ }+ commentID := uuidToString(comment.ID)+ for _, row := range history {+ var d struct {+ CommentID string `json:"comment_id"`+ }+ if json.Unmarshal(row.Details, &d) == nil && d.CommentID == commentID {+ return+ }+ }+ for _, rec := range plan.records {+ if rec.agentID.Valid {+ res, ok := enqueued[uuidToString(rec.agentID)]+ if !ok || res.status == DispatchBlocked {+ continue+ }+ }+ details := map[string]string{+ "squad_id": uuidToString(plan.author.squad.ID),+ "comment_id": commentID,+ "kind": rec.kind,+ "to_type": rec.toType,+ "to_id": uuidToString(rec.toID),+ }+ if rec.round > 1 {+ details["round"] = strconv.Itoa(rec.round)+ }+ if rec.reason != "" {+ details["reason"] = rec.reason+ }+ h.createSquadHandoffActivity(ctx, issue, plan.author.agentID, details)+ }+}++func (h *Handler) createSquadHandoffActivity(ctx context.Context, issue db.Issue, actorID pgtype.UUID, details map[string]string) {+ raw, _ := json.Marshal(details)+ activity, err := h.Queries.CreateActivity(ctx, db.CreateActivityParams{+ ID: dbid.NewV7(),+ WorkspaceID: issue.WorkspaceID,+ IssueID: issue.ID,+ ActorType: pgtype.Text{String: "agent", Valid: true},+ ActorID: actorID,+ Action: service.SquadHandoffAction,+ Details: raw,+ })+ if err != nil {+ slog.Warn("squad handoff: record failed", "issue_id", uuidToString(issue.ID), "error", err)+ return+ }+ h.publish(protocol.EventActivityCreated, uuidToString(issue.WorkspaceID), "agent", uuidToString(actorID), map[string]any{+ "issue_id": uuidToString(issue.ID),+ "entry": map[string]any{+ "type": "activity",+ "id": uuidToString(activity.ID),+ "actor_type": "agent",+ "actor_id": uuidToString(actorID),+ "action": activity.Action,+ "details": json.RawMessage(raw),+ "created_at": timestampToString(activity.CreatedAt),+ },+ })+}++// firstMemberMention is the human an agent comment hands the issue to.+func firstMemberMention(mentions []util.Mention) (pgtype.UUID, bool) {+ for _, m := range mentions {+ if m.Type != "member" {+ continue+ }+ if id, err := util.ParseUUID(m.ID); err == nil {+ return id, true+ }+ }+ return pgtype.UUID{}, false+}diff --git a/server/internal/handler/squad_handoff_test.go b/server/internal/handler/squad_handoff_test.gonew file mode 100644index 0000000000..a182b1b5f9--- /dev/null+++ b/server/internal/handler/squad_handoff_test.go@@ -0,0 +1,336 @@+package handler++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestSquadHandoffRound(t *testing.T) {+ a, b, c := parseUUID("00000000-0000-0000-0000-00000000000a"), parseUUID("00000000-0000-0000-0000-00000000000b"), parseUUID("00000000-0000-0000-0000-00000000000c")+ row := func(kind string, from, to pgtype.UUID) db.ActivityLog {+ details, _ := json.Marshal(map[string]string{"kind": kind, "to_id": uuidToString(to)})+ return db.ActivityLog{ActorID: from, Details: details}+ }+ cases := []struct {+ name string+ history []db.ActivityLog // newest first+ want int+ }{+ {name: "first handoff", want: 1},+ {name: "after a leader dispatch", history: []db.ActivityLog{row(squadHandoffKindDispatch, c, a)}, want: 1},+ {name: "reply after one round", history: []db.ActivityLog{row(squadHandoffKindMember, b, a), row(squadHandoffKindMember, a, b)}, want: 2},+ {name: "third round", history: []db.ActivityLog{+ row(squadHandoffKindMember, b, a), row(squadHandoffKindMember, a, b),+ row(squadHandoffKindMember, b, a), row(squadHandoffKindMember, a, b),+ }, want: 3},+ {name: "a third member breaks the streak", history: []db.ActivityLog{+ row(squadHandoffKindMember, b, a), row(squadHandoffKindMember, c, b), row(squadHandoffKindMember, a, b),+ }, want: 1},+ {name: "a person in between breaks the streak", history: []db.ActivityLog{+ row(squadHandoffKindMember, b, a), row(squadHandoffKindHuman, a, c), row(squadHandoffKindMember, a, b),+ }, want: 1},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := squadHandoffRound(tc.history, a, b); got != tc.want {+ t.Fatalf("round = %d, want %d", got, tc.want)+ }+ })+ }+}++type squadHandoffFixture struct {+ issueID, squadID string+ leaderID, memberA, memberB string+ leaderRuntime, runtimeA, runtimeB string+ memberATask string+}++func newSquadHandoffFixture(t *testing.T, mode string) squadHandoffFixture {+ t.Helper()+ var f squadHandoffFixture+ f.leaderRuntime = dbfx.Runtime(t, "Handoff leader runtime")+ f.leaderID = dbfx.Agent(t, "Handoff Leader", f.leaderRuntime)+ f.runtimeA = dbfx.Runtime(t, "Handoff A runtime")+ f.memberA = dbfx.Agent(t, "Handoff Builder", f.runtimeA)+ f.runtimeB = dbfx.Runtime(t, "Handoff B runtime")+ f.memberB = dbfx.Agent(t, "Handoff Reviewer", f.runtimeB)+ f.squadID = dbfx.Squad(t, "Handoff squad", f.leaderID, testutil.Cols{"handoff_mode": mode})+ dbfx.SquadMember(t, f.squadID, "agent", f.memberA)+ dbfx.SquadMember(t, f.squadID, "agent", f.memberB)+ f.issueID = dbfx.Issue(t, "Squad handoff", testutil.Cols{+ "status": "in_progress", "assignee_type": "squad", "assignee_id": f.squadID,+ })+ f.memberATask = dbfx.Task(t, f.memberA, testutil.Cols{+ "runtime_id": f.runtimeA, "issue_id": f.issueID, "status": "running",+ "originator_user_id": testUserID, "accountable_user_id": testUserID,+ })+ return f+}++func (f squadHandoffFixture) postAsMemberA(t *testing.T, content string) {+ t.Helper()+ req := withURLParam(newRequest(http.MethodPost, "/api/issues/"+f.issueID+"/comments", map[string]any{+ "content": content,+ }), "id", f.issueID)+ req.Header.Set("X-Agent-ID", f.memberA)+ req.Header.Set("X-Task-ID", f.memberATask)+ testutil.Call(t, testHandler.CreateComment, req).Want(http.StatusCreated)+}++func (f squadHandoffFixture) queuedTasks(t *testing.T, agentID string) int {+ t.Helper()+ var n int+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`, f.issueID, agentID).Scan(&n)+ return n+}++func (f squadHandoffFixture) handoffs(t *testing.T) []map[string]string {+ t.Helper()+ rows, err := testHandler.Queries.ListRecentSquadHandoffs(t.Context(), db.ListRecentSquadHandoffsParams{IssueID: parseUUID(f.issueID), RowLimit: 50})+ if err != nil {+ t.Fatal(err)+ }+ out := make([]map[string]string, 0, len(rows))+ for _, row := range rows {+ var d map[string]string+ if err := json.Unmarshal(row.Details, &d); err != nil {+ t.Fatal(err)+ }+ d["actor_id"] = uuidToString(row.ActorID)+ out = append(out, d)+ }+ return out+}++func (f squadHandoffFixture) seedMemberHandoff(t *testing.T, from, to string) {+ t.Helper()+ dbfx.Insert(t, "activity_log", testutil.Cols{+ "workspace_id": testWorkspaceID, "issue_id": f.issueID, "actor_type": "agent", "actor_id": from,+ "action": service.SquadHandoffAction,+ "details": fmt.Sprintf(`{"kind":"member","to_type":"agent","to_id":%q}`, to),+ })+}++func handoffMention(kind, name, id string) string {+ return fmt.Sprintf("[@%s](mention://%s/%s)", name, kind, id)+}++func TestDirectSquadHandoffRouting(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ t.Run("member to member skips the leader", func(t *testing.T) {+ f := newSquadHandoffFixture(t, service.SquadHandoffModeDirect)+ f.postAsMemberA(t, handoffMention("agent", "Reviewer", f.memberB)+" please review the PR")+ if f.queuedTasks(t, f.memberB) != 1 || f.queuedTasks(t, f.leaderID) != 0 {+ t.Fatal("a member handoff must wake only the named member")+ }+ got := f.handoffs(t)+ if len(got) != 1 || got[0]["kind"] != "member" || got[0]["to_id"] != f.memberB || got[0]["actor_id"] != f.memberA || got[0]["round"] != "" {+ t.Fatalf("handoff records = %+v", got)+ }+ })++ t.Run("member to a person does not wake the leader", func(t *testing.T) {+ f := newSquadHandoffFixture(t, service.SquadHandoffModeDirect)+ f.postAsMemberA(t, handoffMention("member", "Owner", testUserID)+" which option should ship?")+ if f.queuedTasks(t, f.leaderID) != 0 {+ t.Fatal("asking a person must not wake the leader in direct mode")+ }+ got := f.handoffs(t)+ if len(got) != 1 || got[0]["kind"] != "human" || got[0]["to_id"] != testUserID {+ t.Fatalf("handoff records = %+v", got)+ }+ })++ t.Run("no next owner goes back to the leader", func(t *testing.T) {+ f := newSquadHandoffFixture(t, service.SquadHandoffModeDirect)+ f.postAsMemberA(t, "Done: the change is merged-ready.")+ if f.queuedTasks(t, f.leaderID) != 1 {+ t.Fatal("a reply naming no next owner must reach the leader")+ }+ got := f.handoffs(t)+ if len(got) != 1 || got[0]["kind"] != "leader" || got[0]["to_id"] != f.leaderID || got[0]["reason"] != "" {+ t.Fatalf("handoff records = %+v", got)+ }+ })++ t.Run("mentioning the leader is recorded and ends the round", func(t *testing.T) {+ f := newSquadHandoffFixture(t, service.SquadHandoffModeDirect)+ f.seedMemberHandoff(t, f.memberA, f.memberB)+ f.seedMemberHandoff(t, f.memberB, f.memberA)+ f.postAsMemberA(t, handoffMention("agent", "Leader", f.leaderID)+" the spec contradicts itself, please decide")+ if f.queuedTasks(t, f.leaderID) != 1 {+ t.Fatal("an explicit leader mention must reach the leader")+ }+ got := f.handoffs(t)+ if got[0]["kind"] != "leader" || got[0]["to_id"] != f.leaderID || got[0]["reason"] != "" {+ t.Fatalf("handoff records = %+v", got)+ }+ f.postAsMemberA(t, handoffMention("agent", "Reviewer", f.memberB)+" decided, please review")+ if got := f.handoffs(t); got[0]["kind"] != "member" || got[0]["round"] != "" {+ t.Fatalf("a pass after going to the leader must start at round 1, got %+v", got[0])+ }+ })++ t.Run("second round is recorded", func(t *testing.T) {+ f := newSquadHandoffFixture(t, service.SquadHandoffModeDirect)+ f.seedMemberHandoff(t, f.memberA, f.memberB)+ f.seedMemberHandoff(t, f.memberB, f.memberA)+ f.postAsMemberA(t, handoffMention("agent", "Reviewer", f.memberB)+" fixed, please re-review")+ got := f.handoffs(t)+ if f.queuedTasks(t, f.memberB) != 1 || got[0]["kind"] != "member" || got[0]["round"] != "2" {+ t.Fatalf("handoff records = %+v", got)+ }+ })++ t.Run("round limit sends the issue to the leader", func(t *testing.T) {+ f := newSquadHandoffFixture(t, service.SquadHandoffModeDirect)+ for i := 0; i < service.SquadHandoffRoundLimit; i++ {+ f.seedMemberHandoff(t, f.memberA, f.memberB)+ f.seedMemberHandoff(t, f.memberB, f.memberA)+ }+ f.postAsMemberA(t, handoffMention("agent", "Reviewer", f.memberB)+" one more pass please")+ if f.queuedTasks(t, f.memberB) != 0 || f.queuedTasks(t, f.leaderID) != 1 {+ t.Fatal("a handoff past the round limit must go to the leader instead")+ }+ got := f.handoffs(t)+ if got[0]["kind"] != "leader" || got[0]["reason"] != "round_limit" {+ t.Fatalf("handoff records = %+v", got)+ }+ })++ t.Run("daily limit sends the issue to the leader", func(t *testing.T) {+ f := newSquadHandoffFixture(t, service.SquadHandoffModeDirect)+ other := dbfx.Agent(t, "Handoff Third", f.runtimeB)+ dbfx.SquadMember(t, f.squadID, "agent", other)+ // Alternate pairs so no single pair reaches the round limit.+ for i := 0; i < service.SquadHandoffDailyLimit; i++ {+ if i%2 == 0 {+ f.seedMemberHandoff(t, other, f.memberB)+ } else {+ f.seedMemberHandoff(t, f.memberB, other)+ }+ f.seedMemberHandoff(t, f.memberA, other)+ }+ f.postAsMemberA(t, handoffMention("agent", "Reviewer", f.memberB)+" please review")+ if f.queuedTasks(t, f.memberB) != 0 || f.queuedTasks(t, f.leaderID) != 1 {+ t.Fatal("a handoff past the daily limit must go to the leader instead")+ }+ if got := f.handoffs(t); got[0]["reason"] != "daily_limit" {+ t.Fatalf("handoff records = %+v", got[0])+ }+ })++ t.Run("leader mode keeps today's routing", func(t *testing.T) {+ f := newSquadHandoffFixture(t, service.SquadHandoffModeLeader)+ f.postAsMemberA(t, handoffMention("member", "Owner", testUserID)+" which option should ship?")+ if f.queuedTasks(t, f.leaderID) != 1 {+ t.Fatal("leader mode must still wake the leader on a member reply")+ }+ if got := f.handoffs(t); len(got) != 0 {+ t.Fatalf("leader mode must not record handoffs, got %+v", got)+ }+ })+}++func TestClaim_SquadMemberTaskGetsMemberBrief(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ for _, mode := range []string{service.SquadHandoffModeLeader, service.SquadHandoffModeDirect} {+ t.Run(mode, func(t *testing.T) {+ f := newSquadHandoffFixture(t, mode)+ dbfx.Exec(t, `UPDATE squad SET instructions = 'Every change needs a second review.' WHERE id = $1`, f.squadID)+ dbfx.Exec(t, `UPDATE squad_member SET role = 'reviews PRs' WHERE squad_id = $1 AND member_id = $2`, f.squadID, f.memberB)+ want := dbfx.Task(t, f.memberB, testutil.Cols{+ "runtime_id": f.runtimeB, "issue_id": f.issueID, "status": "queued",+ "originator_user_id": testUserID, "accountable_user_id": testUserID,+ })+ got, instr, isLeader, raw := claimAgentInstructionsForTest(t, f.runtimeB)+ if got != want || isLeader {+ t.Fatalf("claimed %q leader=%v, want member task %q: %s", got, isLeader, want, raw)+ }+ for _, part := range []string{"## Squad Member Brief", `Your role in this squad: "reviews PRs"`, "Every change needs a second review.", "mention://agent/" + f.memberA} {+ if !strings.Contains(instr, part) {+ t.Fatalf("member brief misses %q:\n%s", part, instr)+ }+ }+ if strings.Contains(instr, "## Squad Operating Protocol") || strings.Contains(instr, "mention://agent/"+f.memberB) {+ t.Fatalf("member brief must not carry the leader protocol or offer the member itself:\n%s", instr)+ }+ direct := strings.Contains(instr, "hand the issue to each other directly")+ if direct != (mode == service.SquadHandoffModeDirect) {+ t.Fatalf("handoff section does not follow mode %s:\n%s", mode, instr)+ }+ })+ }+}++func TestUpdateSquadHandoffMode(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ f := newSquadHandoffFixture(t, service.SquadHandoffModeLeader)+ put := func(mode string) *httptest.ResponseRecorder {+ w := httptest.NewRecorder()+ testHandler.UpdateSquad(w, squadScopeReq("", http.MethodPut, "/api/squads/"+f.squadID, map[string]any{"handoff_mode": mode}, map[string]string{"id": f.squadID}))+ return w+ }+ if w := put("sometimes"); w.Code != http.StatusBadRequest {+ t.Fatalf("unknown mode: got %d", w.Code)+ }+ w := put(service.SquadHandoffModeDirect)+ var resp SquadResponse+ if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &resp) != nil || resp.HandoffMode != service.SquadHandoffModeDirect {+ t.Fatalf("set direct: %d %s", w.Code, w.Body.String())+ }+ // A write that leaves the mode out keeps it.+ w = httptest.NewRecorder()+ testHandler.UpdateSquad(w, squadScopeReq("", http.MethodPut, "/api/squads/"+f.squadID, map[string]any{"description": "kept"}, map[string]string{"id": f.squadID}))+ if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &resp) != nil || resp.HandoffMode != service.SquadHandoffModeDirect {+ t.Fatalf("partial update changed the mode: %d %s", w.Code, w.Body.String())+ }+}++func TestListSquadBriefs(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ f := newSquadHandoffFixture(t, service.SquadHandoffModeDirect)+ w := httptest.NewRecorder()+ testHandler.ListSquadBriefs(w, squadScopeReq("", http.MethodGet, "/api/squads/"+f.squadID+"/briefs", nil, map[string]string{"id": f.squadID}))+ var resp SquadBriefsResponse+ if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &resp) != nil {+ t.Fatalf("list briefs: %d %s", w.Code, w.Body.String())+ }+ if resp.HandoffMode != service.SquadHandoffModeDirect || len(resp.Briefs) != 3 {+ t.Fatalf("briefs = %+v", resp)+ }+ if !resp.Briefs[0].IsLeader || resp.Briefs[0].MemberID != f.leaderID || !strings.Contains(resp.Briefs[0].Brief, "## Handoff Mode: Direct") {+ t.Fatalf("leader brief = %+v", resp.Briefs[0])+ }+ for _, b := range resp.Briefs[1:] {+ if b.IsLeader || !strings.Contains(b.Brief, "## Squad Member Brief") {+ t.Fatalf("member brief = %+v", b)+ }+ }++ stranger := createPlainMember(t, "[email protected]")+ w = httptest.NewRecorder()+ testHandler.ListSquadBriefs(w, squadScopeReq(stranger, http.MethodGet, "/api/squads/"+f.squadID+"/briefs", nil, map[string]string{"id": f.squadID}))+ if w.Code != http.StatusForbidden {+ t.Fatalf("a member who cannot edit the squad: got %d", w.Code)+ }+}diff --git a/server/internal/service/builtin_skills/multica-platform/references/squads.md b/server/internal/service/builtin_skills/multica-platform/references/squads.mdindex 37da978be4..13c760bfff 100644--- a/server/internal/service/builtin_skills/multica-platform/references/squads.md+++ b/server/internal/service/builtin_skills/multica-platform/references/squads.md@@ -9,6 +9,8 @@ it does not run work by itself.- [Squad fields](#squad-fields)- [Creation and leader membership](#creation-and-leader-membership)- [Leader briefing](#leader-briefing)+- [Member brief](#member-brief)+- [Handoff mode](#handoff-mode)- [Issue assignment behavior](#issue-assignment-behavior)- [Comment and mention behavior](#comment-and-mention-behavior)- [Autopilot behavior](#autopilot-behavior)@@ -38,7 +40,10 @@ Squad-routed work runs through the squad's `leader_id` agent. Consequences:- mentioning a squad routes to the leader;- squad-assigned autopilot resolves to the leader;- squad members are not automatically fanned out;-- squad `instructions` are leader briefing content, not member prompts.+- squad `instructions` go into the leader briefing and into every agent+ member's member brief on the squad's issues;+- `handoff_mode` decides whether a member's reply goes back to the leader+ (`leader`, default) or members hand off to each other (`direct`).## CLI@@ -48,10 +53,16 @@ Squad commands:multica squad list --output jsonmultica squad get <squad-id> --output jsonmultica squad create --name <name> --leader <agent-name-or-id> --output json-multica squad update <squad-id> --instructions "<leader coordination policy>" --output json+multica squad update <squad-id> --instructions "<squad coordination policy>" --output json+multica squad update <squad-id> --handoff-mode leader|direct --output json+multica squad briefs <squad-id> [--agent <agent-name-or-id>] [--output json]multica squad delete <squad-id>```+`squad briefs` prints the exact squad section each agent receives (leader+briefing or member brief). Both `--handoff-mode` and `briefs` require+permission to manage the squad (its creator, or a workspace owner/admin).+Member commands:```bash@@ -103,8 +114,10 @@ unbounded pull.- `name` — display name; unique per workspace.- `description` — human-facing metadata/display text. Do not assume runtimeprompt impact.-- `instructions` — squad-level instructions added to the squad leader briefing.- They are not directly injected into every squad member.+- `instructions` — squad-level instructions added to the squad leader briefing+ and to the member brief of every agent member.+- `handoff_mode` — `leader` (default) or `direct`. See+ [Handoff mode](#handoff-mode).- `avatar_url` — optional squad avatar URL.- `leader_id` — agent ID of the squad leader; the runtime target forsquad-routed work.@@ -114,9 +127,9 @@ unbounded pull.- `member_count` — list response count of squad members.- `member_preview` — list response preview of squad members.-Use `instructions` for leader-facing coordination policy: squad responsibility,-delegation expectations, when to ask humans, and review/handoff rules. Do not-write it as if every member automatically receives it.+Use `instructions` for squad coordination policy: squad responsibility,+delegation expectations, when to ask humans, and review/handoff rules. The+leader and every agent member read it, so write it for both.## Squad member fields@@ -154,6 +167,38 @@ members carry no skills segment. Built-in `multica-*` skills are not listed —only the workspace skills explicitly attached to the agent. Archived agentmembers are skipped from the briefing roster.+In `direct` handoff mode the briefing adds a "Handoff Mode: Direct" section:+the leader assigns the first step and handles what comes back to it.++## Member brief++When a non-leader agent member claims a run on an issue assigned to its squad,+Multica appends a "Squad Member Brief": the member's role, the rest of the+roster with mention markdown, the squad instructions, and how to hand off under+the squad's handoff mode. It never contains the leader's Squad Operating+Protocol.++## Handoff mode++`leader` (default): every member reply wakes the leader, as described under+[Comment and mention behavior](#comment-and-mention-behavior).++`direct`, for a comment written by a member's run on the squad's own issue:++- mentioning another squad member runs only that member; the leader is not+ woken;+- mentioning a person (and no agent) wakes nobody; the person replies;+- a reply that names no next owner goes back to the leader;+- the issue goes back to the leader instead of the named member when the same+ two members have already passed it back and forth 3 rounds, or the issue has+ taken 20 member handoffs in 24 hours;+- a failed member run is recovered by the leader, not by the member that+ handed the work over.++Each routed handoff is recorded as a `squad_handoff` activity on the issue+(`kind` dispatch / member / human / leader, the target, `round` when above 1,+and `reason` when a guard sent it back). These limits are fixed.+## Issue assignment behaviorIssues can be assigned to squads with:@@ -236,6 +281,7 @@ These actions can trigger agent work or mutate durable state:- creating a squad;- updating squad fields;- changing `leader_id`;+- changing `handoff_mode` (changes who later comments wake);- adding/removing members;- changing member roles;- assigning an issue to a squad;@@ -253,7 +299,9 @@ These actions can trigger agent work or mutate durable state:- Squad mention routes to the leader, not every member.- Squad assignment routes to the leader, not every member.- Squad autopilot resolves to the leader as executable agent.-- `instructions` are leader briefing content, not automatic member prompts.+- `instructions` are not leader-only: agent members receive them too.+- A member's reply does not always wake the leader: in `direct` handoff mode a+ member-to-member or member-to-person handoff skips it.- `description` has no proven runtime prompt effect.- `role` is roster context, not automatic scheduling.- Backlog assignment does not immediately start work.diff --git a/server/internal/service/squad_handoff.go b/server/internal/service/squad_handoff.gonew file mode 100644index 0000000000..2017778748--- /dev/null+++ b/server/internal/service/squad_handoff.go@@ -0,0 +1,115 @@+package service++import (+ "context"+ "encoding/json"+ "fmt"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// Squad handoff modes. "leader" is the original behaviour: every member reply+// goes back to the squad leader, who dispatches the next step. "direct" lets+// members hand the issue to each other by @mention; the leader is woken only+// for exceptions.+const (+ SquadHandoffModeLeader = "leader"+ SquadHandoffModeDirect = "direct"+)++// SquadHandoffAction is the activity_log action of one recorded squad handoff.+const SquadHandoffAction = "squad_handoff"++// Guards for direct handoff. Fixed on purpose: they are backstops against+// members passing work around forever, not tuning knobs.+const (+ // SquadHandoffRoundLimit is how many times one member may hand the issue+ // to the same other member in an unbroken back-and-forth.+ SquadHandoffRoundLimit = 3+ // SquadHandoffDailyLimit is how many member-to-member handoffs one issue+ // may take in 24 hours.+ SquadHandoffDailyLimit = 20+)++// IsValidSquadHandoffMode reports whether mode is a handoff mode the API accepts.+func IsValidSquadHandoffMode(mode string) bool {+ return mode == SquadHandoffModeLeader || mode == SquadHandoffModeDirect+}++// squadDirectHandoffLeader returns the squad whose leader should recover a+// failed member run instead of the member that handed the work over. That is+// the case only for a direct-handoff squad's issue, when the run that handed+// off was a member turn on that same issue: a leader dispatch already recovers+// to the leader, and a handoff across issues keeps its own coordinator.+func squadDirectHandoffLeader(ctx context.Context, q *db.Queries, issue db.Issue, failed, source db.AgentTaskQueue) *db.Squad {+ if source.IsLeaderTask || failed.IssueID != issue.ID ||+ !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" || !issue.AssigneeID.Valid {+ return nil+ }+ squad, err := q.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: issue.AssigneeID, WorkspaceID: issue.WorkspaceID})+ if err != nil || squad.ArchivedAt.Valid || squad.HandoffMode != SquadHandoffModeDirect || squad.LeaderID == source.AgentID {+ return nil+ }+ isMember, err := q.IsSquadMember(ctx, db.IsSquadMemberParams{SquadID: squad.ID, MemberType: "agent", MemberID: source.AgentID})+ if err != nil || !isMember {+ return nil+ }+ return &squad+}++// createSquadFailureHandoff records the failed member handing the issue back+// to its squad leader, in the transaction that creates the recovery signal.+func createSquadFailureHandoff(ctx context.Context, qtx *db.Queries, target *delegatedFailureRecoveryTarget) (db.ActivityLog, error) {+ details, _ := json.Marshal(map[string]string{+ "squad_id": util.UUIDToString(target.leaderSquad.ID),+ "comment_id": util.UUIDToString(target.comment.ID),+ "kind": "leader",+ "to_type": "agent",+ "to_id": util.UUIDToString(target.leaderSquad.LeaderID),+ "reason": "run_failed",+ })+ row, err := qtx.CreateActivity(ctx, db.CreateActivityParams{+ ID: dbid.NewV7(),+ WorkspaceID: target.issue.WorkspaceID,+ IssueID: target.issue.ID,+ ActorType: pgtype.Text{String: "agent", Valid: true},+ ActorID: target.failed.AgentID,+ Action: SquadHandoffAction,+ Details: details,+ })+ if err != nil {+ return db.ActivityLog{}, fmt.Errorf("record squad failure handoff: %w", err)+ }+ return row, nil+}++func (s *TaskService) publishSquadHandoffActivity(row db.ActivityLog) {+ if s.Bus == nil {+ return+ }+ actorID := util.UUIDToString(row.ActorID)+ s.Bus.Publish(events.Event{+ Type: protocol.EventActivityCreated,+ WorkspaceID: util.UUIDToString(row.WorkspaceID),+ ActorType: "agent",+ ActorID: actorID,+ Payload: map[string]any{+ "issue_id": util.UUIDToString(row.IssueID),+ "entry": map[string]any{+ "type": "activity",+ "id": util.UUIDToString(row.ID),+ "actor_type": "agent",+ "actor_id": actorID,+ "action": row.Action,+ "details": json.RawMessage(row.Details),+ "created_at": row.CreatedAt.Time.UTC().Format(time.RFC3339Nano),+ },+ },+ })+}diff --git a/server/internal/service/squad_handoff_test.go b/server/internal/service/squad_handoff_test.gonew file mode 100644index 0000000000..b12689104b--- /dev/null+++ b/server/internal/service/squad_handoff_test.go@@ -0,0 +1,137 @@+package service++import (+ "context"+ "encoding/json"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+)++// A member run that fails on a direct-handoff squad's issue goes back to the+// squad leader in its leader role, not to the member that handed the work+// over; under leader dispatch the coordinator stays the recovery target.+func TestDelegatedFailureRecoveryGoesToDirectSquadLeader(t *testing.T) {+ for _, mode := range []string{SquadHandoffModeDirect, SquadHandoffModeLeader} {+ t.Run(mode, func(t *testing.T) {+ ctx := context.Background()+ f, svc := seedDelegatedFailureFixture(t)+ var leaderID, squadID string+ if err := f.pool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, runtime_mode, runtime_config, runtime_id, visibility,+ max_concurrent_tasks, owner_id, instructions, custom_env, custom_args+ )+ VALUES ($1, 'squad-leader', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3, '', '{}'::jsonb, '[]'::jsonb)+ RETURNING id`, f.workspaceID, f.runtimeID, f.userID).Scan(&leaderID); err != nil {+ t.Fatalf("seed leader: %v", err)+ }+ if err := f.pool.QueryRow(ctx, `+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id, handoff_mode)+ VALUES ($1, 'handoff squad', '', $2, $3, $4)+ RETURNING id`, f.workspaceID, leaderID, f.userID, mode).Scan(&squadID); err != nil {+ t.Fatalf("seed squad: %v", err)+ }+ t.Cleanup(func() {+ f.pool.Exec(context.Background(), `DELETE FROM squad_member WHERE squad_id = $1`, squadID)+ f.pool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID)+ })+ for _, member := range []string{f.coordinator, f.worker} {+ if _, err := f.pool.Exec(ctx, `INSERT INTO squad_member (squad_id, member_type, member_id) VALUES ($1, 'agent', $2)`, squadID, member); err != nil {+ t.Fatalf("seed squad member: %v", err)+ }+ }+ if _, err := f.pool.Exec(ctx, `UPDATE issue SET assignee_type = 'squad', assignee_id = $2 WHERE id = $1`, f.issueID, squadID); err != nil {+ t.Fatalf("assign squad: %v", err)+ }+ var failedID pgtype.UUID+ if err := f.pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, attempt, max_attempts,+ originator_user_id, accountable_user_id, originator_source, delegated_from_task_id+ )+ VALUES ($1, $2, $3, 'failed', 0, 1, 1, $4, $4, 'delegation', $5)+ RETURNING id`, f.worker, f.runtimeID, f.issueID, f.userID, f.sourceTask).Scan(&failedID); err != nil {+ t.Fatalf("seed failed member task: %v", err)+ }++ target, created, err := svc.ensureDelegatedFailureRecoveryComment(ctx, failedID)+ if err != nil || target == nil || !created {+ t.Fatalf("recovery signal: created=%v err=%v", created, err)+ }+ wantAgent := f.coordinator+ if mode == SquadHandoffModeDirect {+ wantAgent = leaderID+ }+ if util.UUIDToString(target.agent.ID) != wantAgent || (target.leaderSquad != nil) != (mode == SquadHandoffModeDirect) {+ t.Fatalf("recovery target = %s (leader squad %v), want %s", util.UUIDToString(target.agent.ID), target.leaderSquad != nil, wantAgent)+ }++ var handoffs []json.RawMessage+ rows, err := f.pool.Query(ctx, `SELECT details FROM activity_log WHERE issue_id = $1 AND action = $2`, f.issueID, SquadHandoffAction)+ if err != nil {+ t.Fatal(err)+ }+ for rows.Next() {+ var d json.RawMessage+ if err := rows.Scan(&d); err != nil {+ t.Fatal(err)+ }+ handoffs = append(handoffs, d)+ }+ rows.Close()+ if mode == SquadHandoffModeLeader {+ if len(handoffs) != 0 {+ t.Fatalf("leader mode must not record a handoff, got %s", handoffs)+ }+ return+ }+ var d map[string]string+ if len(handoffs) != 1 || json.Unmarshal(handoffs[0], &d) != nil || d["kind"] != "leader" || d["reason"] != "run_failed" || d["to_id"] != leaderID {+ t.Fatalf("failure handoff = %s", handoffs)+ }++ // The sweeper must judge the leader, not the member that handed+ // off: that member going away cannot strand the signal, and the+ // leader's queued run covers it.+ if _, err := f.pool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, f.coordinator); err != nil {+ t.Fatalf("archive handing-off member: %v", err)+ }+ if !recoveryPending(t, svc, target.comment.ID) {+ t.Fatal("recovery signal not pending for the leader after the handing-off member was archived")+ }++ if outcome, err := svc.dispatchDelegatedFailureRecovery(ctx, target, pgtype.UUID{}); err != nil || outcome != delegatedFailureRecoveryReplayed {+ t.Fatalf("dispatch = %v, %v", outcome, err)+ }+ var isLeader bool+ var taskSquad string+ if err := f.pool.QueryRow(ctx, `+ SELECT is_leader_task, squad_id::text FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`, f.issueID, leaderID).Scan(&isLeader, &taskSquad); err != nil {+ t.Fatalf("load leader recovery run: %v", err)+ }+ if !isLeader || taskSquad != squadID {+ t.Fatalf("leader recovery run is_leader_task=%v squad=%s, want true/%s", isLeader, taskSquad, squadID)+ }+ if recoveryPending(t, svc, target.comment.ID) {+ t.Fatal("recovery signal still pending while the leader's recovery run is queued")+ }+ })+ }+}++func recoveryPending(t *testing.T, svc *TaskService, commentID pgtype.UUID) bool {+ t.Helper()+ pending, err := svc.Queries.ListPendingDelegatedFailureRecoveries(context.Background(), 1000)+ if err != nil {+ t.Fatalf("ListPendingDelegatedFailureRecoveries: %v", err)+ }+ for _, c := range pending {+ if c.ID == commentID {+ return true+ }+ }+ return false+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 7fc2cec679..23a0e41abe 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -6830,6 +6830,10 @@ type delegatedFailureRecoveryTarget struct {issue db.Issueagent db.Agentcomment db.Comment+ // leaderSquad is set when the failure goes to a direct-handoff squad's+ // leader instead of the member that handed the work over; agent is then+ // that leader and the recovery run carries its leader role.+ leaderSquad *db.Squad}// IsDelegatedFailureRecoveryComment identifies the durable platform signal@@ -6898,17 +6902,22 @@ func loadDelegatedFailureRecoveryTarget(ctx context.Context, q *db.Queries, fail}return nil, fmt.Errorf("load source issue: %w", err)}- agent, err := q.GetAgent(ctx, source.AgentID)+ coordinatorID := source.AgentID+ leaderSquad := squadDirectHandoffLeader(ctx, q, issue, failed, source)+ if leaderSquad != nil {+ coordinatorID = leaderSquad.LeaderID+ }+ agent, err := q.GetAgent(ctx, coordinatorID)if err != nil {if errors.Is(err, pgx.ErrNoRows) {return nil, nil}return nil, fmt.Errorf("load source agent: %w", err)}- if agent.ArchivedAt.Valid || !agent.RuntimeID.Valid || agent.WorkspaceID != issue.WorkspaceID {+ if agent.ArchivedAt.Valid || !agent.RuntimeID.Valid || agent.WorkspaceID != issue.WorkspaceID || agent.ID == failed.AgentID {return nil, nil}- return &delegatedFailureRecoveryTarget{failed: failed, source: source, issue: issue, agent: agent}, nil+ return &delegatedFailureRecoveryTarget{failed: failed, source: source, issue: issue, agent: agent, leaderSquad: leaderSquad}, nil}// canDispatchDelegatedFailureRecovery matches the lifecycle predicate in@@ -6934,6 +6943,7 @@ func canDispatchDelegatedFailureRecovery(ctx context.Context, q *db.Queries, iss// mention-notification side effects.func (s *TaskService) ensureDelegatedFailureRecoveryComment(ctx context.Context, failedID pgtype.UUID) (*delegatedFailureRecoveryTarget, bool, error) {var target *delegatedFailureRecoveryTarget+ var handoff db.ActivityLogcreated := falseif err := s.runInTx(ctx, func(qtx *db.Queries) error {failed, err := qtx.GetAgentTaskForDelegatedFailureUpdate(ctx, failedID)@@ -6972,6 +6982,12 @@ func (s *TaskService) ensureDelegatedFailureRecoveryComment(ctx context.Context,}target.comment = createdComment.Comment()created = true+ if target.leaderSquad != nil {+ handoff, err = createSquadFailureHandoff(ctx, qtx, target)+ if err != nil {+ return err+ }+ }return nil}); err != nil {return nil, false, err@@ -6979,6 +6995,9 @@ func (s *TaskService) ensureDelegatedFailureRecoveryComment(ctx context.Context,if target == nil {return nil, false, nil}+ if handoff.ID.Valid {+ s.publishSquadHandoffActivity(handoff)+ }if created && s.Bus != nil {s.Bus.Publish(events.Event{Type: protocol.EventCommentCreated,@@ -7243,6 +7262,10 @@ func (s *TaskService) dispatchDelegatedFailureRecovery(ctx context.Context, targreturn delegatedFailureRecoveryCovered, err}overlay := s.buildRuntimeMCPOverlay(ctx, originator, target.agent)+ isLeader, squadID := target.source.IsLeaderTask, target.source.SquadID+ if target.leaderSquad != nil {+ isLeader, squadID = true, target.leaderSquad.ID+ }task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{ID: dbid.NewV7(),AgentID: target.agent.ID,@@ -7251,8 +7274,8 @@ func (s *TaskService) dispatchDelegatedFailureRecovery(ctx context.Context, targPriority: priorityToInt(target.issue.Priority),TriggerCommentID: target.comment.ID,TriggerSummary: s.buildCommentTriggerSummary(ctx, target.issue.WorkspaceID, target.comment.ID),- IsLeaderTask: pgtype.Bool{Bool: target.source.IsLeaderTask, Valid: target.source.IsLeaderTask},- SquadID: target.source.SquadID,+ IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},+ SquadID: squadID,OriginatorUserID: originator,AccountableUserID: accountable,RuntimeMcpOverlay: overlay.Overlay,diff --git a/server/migrations/747_squad_handoff_mode.down.sql b/server/migrations/747_squad_handoff_mode.down.sqlnew file mode 100644index 0000000000..9e84a28e81--- /dev/null+++ b/server/migrations/747_squad_handoff_mode.down.sql@@ -0,0 +1 @@+ALTER TABLE squad DROP COLUMN IF EXISTS handoff_mode;diff --git a/server/migrations/747_squad_handoff_mode.up.sql b/server/migrations/747_squad_handoff_mode.up.sqlnew file mode 100644index 0000000000..b07e87d37c--- /dev/null+++ b/server/migrations/747_squad_handoff_mode.up.sql@@ -0,0 +1 @@+ALTER TABLE squad ADD COLUMN handoff_mode TEXT NOT NULL DEFAULT 'leader';diff --git a/server/pkg/db/generated/activity.sql.go b/server/pkg/db/generated/activity.sql.goindex a11cfbd62c..a3acfaa9fd 100644--- a/server/pkg/db/generated/activity.sql.go+++ b/server/pkg/db/generated/activity.sql.go@@ -58,6 +58,26 @@ func (q *Queries) CountAssigneeChangesByActor(ctx context.Context, arg CountAssireturn items, nil}+const countSquadMemberHandoffsSince = `-- name: CountSquadMemberHandoffsSince :one+SELECT count(*) FROM activity_log+WHERE issue_id = $1+ AND action = 'squad_handoff'+ AND details->>'kind' = 'member'+ AND created_at > $2+`++type CountSquadMemberHandoffsSinceParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ Since pgtype.Timestamptz `json:"since"`+}++func (q *Queries) CountSquadMemberHandoffsSince(ctx context.Context, arg CountSquadMemberHandoffsSinceParams) (int64, error) {+ row := q.db.QueryRow(ctx, countSquadMemberHandoffsSince, arg.IssueID, arg.Since)+ var count int64+ err := row.Scan(&count)+ return count, err+}+const createActivity = `-- name: CreateActivity :oneINSERT INTO activity_log (workspace_id, issue_id, actor_type, actor_id, action, details, id@@ -225,3 +245,47 @@ func (q *Queries) ListActivitiesForIssue(ctx context.Context, arg ListActivities}return items, nil}++const listRecentSquadHandoffs = `-- name: ListRecentSquadHandoffs :many+SELECT id, workspace_id, issue_id, actor_type, actor_id, action, details, created_at FROM activity_log+WHERE issue_id = $1+ AND action = 'squad_handoff'+ORDER BY created_at DESC, id DESC+LIMIT $2+`++type ListRecentSquadHandoffsParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ RowLimit int32 `json:"row_limit"`+}++// The newest squad handoff records on one issue, newest first. Served by+// idx_activity_log_issue_keyset; the action filter is applied to that window.+func (q *Queries) ListRecentSquadHandoffs(ctx context.Context, arg ListRecentSquadHandoffsParams) ([]ActivityLog, error) {+ rows, err := q.db.Query(ctx, listRecentSquadHandoffs, arg.IssueID, arg.RowLimit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ActivityLog{}+ for rows.Next() {+ var i ActivityLog+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.IssueID,+ &i.ActorType,+ &i.ActorID,+ &i.Action,+ &i.Details,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 8892be4369..050b29e712 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -5936,7 +5936,23 @@ FROM comment recoveryJOIN agent_task_queue failed ON failed.id = recovery.source_task_idJOIN agent_task_queue source ON source.id = failed.delegated_from_task_idJOIN issue source_issue ON source_issue.id = source.issue_id-JOIN agent source_agent ON source_agent.id = source.agent_id+LEFT JOIN squad direct_squad+ ON NOT source.is_leader_task+ AND failed.issue_id = source_issue.id+ AND source_issue.assignee_type = 'squad'+ AND direct_squad.id = source_issue.assignee_id+ AND direct_squad.workspace_id = source_issue.workspace_id+ AND direct_squad.archived_at IS NULL+ AND direct_squad.handoff_mode = 'direct'+ AND direct_squad.leader_id <> source.agent_id+ AND EXISTS (+ SELECT 1+ FROM squad_member direct_member+ WHERE direct_member.squad_id = direct_squad.id+ AND direct_member.member_type = 'agent'+ AND direct_member.member_id = source.agent_id+ )+JOIN agent source_agent ON source_agent.id = COALESCE(direct_squad.leader_id, source.agent_id)LEFT JOIN issue_status source_statusON source_status.workspace_id = source_issue.workspace_idAND source_status.key = source_issue.status@@ -5955,6 +5971,7 @@ WHERE recovery.author_type = 'system'AND source.autopilot_run_id IS NULLAND source.issue_id IS NOT NULLAND source.agent_id <> failed.agent_id+ AND source_agent.id <> failed.agent_id-- Match canDispatchDelegatedFailureRecovery: lifecycle permits recovery only-- for open work; parking belongs exclusively to the fixed Backlog status.-- Built-ins resolve without catalog rows; unknown custom states stay pending.@@ -5983,7 +6000,7 @@ WHERE recovery.author_type = 'system'SELECT 1FROM agent_task_queue coveringWHERE covering.issue_id = source_issue.id- AND covering.agent_id = source.agent_id+ AND covering.agent_id = source_agent.idAND (recovery.id = ANY(covering.delivered_comment_ids)OR (@@ -6020,6 +6037,9 @@ LIMIT $1// of idx_comment_delegated_failure_unsettled matches the first four conditions,// narrowing the scan to unsettled signals. Reversible eligibility must still// be checked before LIMIT so paused signals cannot starve executable ones.+// A member turn on a direct-handoff squad's own issue recovers to the squad+// leader, not to the member that handed the work over. Must match+// squadDirectHandoffLeader, which picks the same target at dispatch.func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, maxPerTick int32) ([]Comment, error) {rows, err := q.db.Query(ctx, listPendingDelegatedFailureRecoveries, maxPerTick)if err != nil {diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex b2416e2c25..00e671815f 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1981,6 +1981,7 @@ type Squad struct {ArchivedBy pgtype.UUID `json:"archived_by"`AvatarUrl pgtype.Text `json:"avatar_url"`Instructions string `json:"instructions"`+ HandoffMode string `json:"handoff_mode"`}type SquadMember struct {diff --git a/server/pkg/db/generated/squad.sql.go b/server/pkg/db/generated/squad.sql.goindex 293f3f7d09..ca736df3a9 100644--- a/server/pkg/db/generated/squad.sql.go+++ b/server/pkg/db/generated/squad.sql.go@@ -46,7 +46,7 @@ func (q *Queries) AddSquadMember(ctx context.Context, arg AddSquadMemberParams)const archiveSquad = `-- name: ArchiveSquad :oneUPDATE squad SET archived_at = now(), archived_by = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions+RETURNING id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions, handoff_mode`type ArchiveSquadParams struct {@@ -70,6 +70,7 @@ func (q *Queries) ArchiveSquad(ctx context.Context, arg ArchiveSquadParams) (Squ&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,)return i, err}@@ -88,7 +89,7 @@ func (q *Queries) CountSquadMembers(ctx context.Context, squadID pgtype.UUID) (iconst createSquad = `-- name: CreateSquad :oneINSERT INTO squad (workspace_id, name, description, leader_id, creator_id, avatar_url)VALUES ($1, $2, $3, $4, $5, $6)-RETURNING id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions+RETURNING id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions, handoff_mode`type CreateSquadParams struct {@@ -123,12 +124,13 @@ func (q *Queries) CreateSquad(ctx context.Context, arg CreateSquadParams) (Squad&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,)return i, err}const getSquad = `-- name: GetSquad :one-SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions FROM squad WHERE id = $1+SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions, handoff_mode FROM squad WHERE id = $1`func (q *Queries) GetSquad(ctx context.Context, id pgtype.UUID) (Squad, error) {@@ -147,12 +149,13 @@ func (q *Queries) GetSquad(ctx context.Context, id pgtype.UUID) (Squad, error) {&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,)return i, err}const getSquadByAssignee = `-- name: GetSquadByAssignee :one-SELECT s.id, s.workspace_id, s.name, s.description, s.leader_id, s.creator_id, s.created_at, s.updated_at, s.archived_at, s.archived_by, s.avatar_url, s.instructions FROM squad s WHERE s.id = $1 AND s.workspace_id = $2+SELECT s.id, s.workspace_id, s.name, s.description, s.leader_id, s.creator_id, s.created_at, s.updated_at, s.archived_at, s.archived_by, s.avatar_url, s.instructions, s.handoff_mode FROM squad s WHERE s.id = $1 AND s.workspace_id = $2`type GetSquadByAssigneeParams struct {@@ -177,12 +180,13 @@ func (q *Queries) GetSquadByAssignee(ctx context.Context, arg GetSquadByAssignee&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,)return i, err}const getSquadInWorkspace = `-- name: GetSquadInWorkspace :one-SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions FROM squad WHERE id = $1 AND workspace_id = $2+SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions, handoff_mode FROM squad WHERE id = $1 AND workspace_id = $2`type GetSquadInWorkspaceParams struct {@@ -206,6 +210,7 @@ func (q *Queries) GetSquadInWorkspace(ctx context.Context, arg GetSquadInWorkspa&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,)return i, err}@@ -231,7 +236,7 @@ func (q *Queries) IsSquadMember(ctx context.Context, arg IsSquadMemberParams) (b}const listAllSquads = `-- name: ListAllSquads :many-SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions FROM squad WHERE workspace_id = $1 ORDER BY created_at ASC+SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions, handoff_mode FROM squad WHERE workspace_id = $1 ORDER BY created_at ASC`func (q *Queries) ListAllSquads(ctx context.Context, workspaceID pgtype.UUID) ([]Squad, error) {@@ -256,6 +261,7 @@ func (q *Queries) ListAllSquads(ctx context.Context, workspaceID pgtype.UUID) ([&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,); err != nil {return nil, err}@@ -518,7 +524,7 @@ func (q *Queries) ListSquadMembers(ctx context.Context, squadID pgtype.UUID) ([]}const listSquads = `-- name: ListSquads :many-SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions FROM squad WHERE workspace_id = $1 AND archived_at IS NULL ORDER BY created_at ASC+SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions, handoff_mode FROM squad WHERE workspace_id = $1 AND archived_at IS NULL ORDER BY created_at ASC`func (q *Queries) ListSquads(ctx context.Context, workspaceID pgtype.UUID) ([]Squad, error) {@@ -543,6 +549,7 @@ func (q *Queries) ListSquads(ctx context.Context, workspaceID pgtype.UUID) ([]Sq&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,); err != nil {return nil, err}@@ -555,7 +562,7 @@ func (q *Queries) ListSquads(ctx context.Context, workspaceID pgtype.UUID) ([]Sq}const listSquadsByMember = `-- name: ListSquadsByMember :many-SELECT s.id, s.workspace_id, s.name, s.description, s.leader_id, s.creator_id, s.created_at, s.updated_at, s.archived_at, s.archived_by, s.avatar_url, s.instructions FROM squad s+SELECT s.id, s.workspace_id, s.name, s.description, s.leader_id, s.creator_id, s.created_at, s.updated_at, s.archived_at, s.archived_by, s.avatar_url, s.instructions, s.handoff_mode FROM squad sJOIN squad_member sm ON sm.squad_id = s.idWHERE s.workspace_id = $1 AND sm.member_type = $2 AND sm.member_id = $3ORDER BY s.created_at ASC@@ -590,6 +597,7 @@ func (q *Queries) ListSquadsByMember(ctx context.Context, arg ListSquadsByMember&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,); err != nil {return nil, err}@@ -602,7 +610,7 @@ func (q *Queries) ListSquadsByMember(ctx context.Context, arg ListSquadsByMember}const lockSquadForAutopilotAssignment = `-- name: LockSquadForAutopilotAssignment :one-SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions FROM squad+SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions, handoff_mode FROM squadWHERE id = $1 AND workspace_id = $2FOR SHARE`@@ -632,12 +640,13 @@ func (q *Queries) LockSquadForAutopilotAssignment(ctx context.Context, arg LockS&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,)return i, err}const lockSquadForUpdate = `-- name: LockSquadForUpdate :one-SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions FROM squad+SELECT id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions, handoff_mode FROM squadWHERE id = $1 AND workspace_id = $2FOR UPDATE`@@ -666,6 +675,7 @@ func (q *Queries) LockSquadForUpdate(ctx context.Context, arg LockSquadForUpdate&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,)return i, err}@@ -736,9 +746,10 @@ UPDATE squad SETleader_id = COALESCE($4, leader_id),avatar_url = COALESCE($5, avatar_url),instructions = COALESCE($6, instructions),+ handoff_mode = COALESCE($7, handoff_mode),updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions+RETURNING id, workspace_id, name, description, leader_id, creator_id, created_at, updated_at, archived_at, archived_by, avatar_url, instructions, handoff_mode`type UpdateSquadParams struct {@@ -748,6 +759,7 @@ type UpdateSquadParams struct {LeaderID pgtype.UUID `json:"leader_id"`AvatarUrl pgtype.Text `json:"avatar_url"`Instructions pgtype.Text `json:"instructions"`+ HandoffMode pgtype.Text `json:"handoff_mode"`}func (q *Queries) UpdateSquad(ctx context.Context, arg UpdateSquadParams) (Squad, error) {@@ -758,6 +770,7 @@ func (q *Queries) UpdateSquad(ctx context.Context, arg UpdateSquadParams) (Squadarg.LeaderID,arg.AvatarUrl,arg.Instructions,+ arg.HandoffMode,)var i Squaderr := row.Scan(@@ -773,6 +786,7 @@ func (q *Queries) UpdateSquad(ctx context.Context, arg UpdateSquadParams) (Squad&i.ArchivedBy,&i.AvatarUrl,&i.Instructions,+ &i.HandoffMode,)return i, err}diff --git a/server/pkg/db/queries/activity.sql b/server/pkg/db/queries/activity.sqlindex 5a3d48adb3..f70785d039 100644--- a/server/pkg/db/queries/activity.sql+++ b/server/pkg/db/queries/activity.sql@@ -66,3 +66,19 @@ SELECT actor_type, actor_id FROM activity_logWHERE issue_id = @issue_id AND action = 'status_changed'ORDER BY created_at DESC, id DESCLIMIT 1;++-- name: ListRecentSquadHandoffs :many+-- The newest squad handoff records on one issue, newest first. Served by+-- idx_activity_log_issue_keyset; the action filter is applied to that window.+SELECT * FROM activity_log+WHERE issue_id = @issue_id+ AND action = 'squad_handoff'+ORDER BY created_at DESC, id DESC+LIMIT @row_limit;++-- name: CountSquadMemberHandoffsSince :one+SELECT count(*) FROM activity_log+WHERE issue_id = @issue_id+ AND action = 'squad_handoff'+ AND details->>'kind' = 'member'+ AND created_at > @since;diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 873fd8699d..f9a99aea78 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -2145,7 +2145,26 @@ FROM comment recoveryJOIN agent_task_queue failed ON failed.id = recovery.source_task_idJOIN agent_task_queue source ON source.id = failed.delegated_from_task_idJOIN issue source_issue ON source_issue.id = source.issue_id-JOIN agent source_agent ON source_agent.id = source.agent_id+-- A member turn on a direct-handoff squad's own issue recovers to the squad+-- leader, not to the member that handed the work over. Must match+-- squadDirectHandoffLeader, which picks the same target at dispatch.+LEFT JOIN squad direct_squad+ ON NOT source.is_leader_task+ AND failed.issue_id = source_issue.id+ AND source_issue.assignee_type = 'squad'+ AND direct_squad.id = source_issue.assignee_id+ AND direct_squad.workspace_id = source_issue.workspace_id+ AND direct_squad.archived_at IS NULL+ AND direct_squad.handoff_mode = 'direct'+ AND direct_squad.leader_id <> source.agent_id+ AND EXISTS (+ SELECT 1+ FROM squad_member direct_member+ WHERE direct_member.squad_id = direct_squad.id+ AND direct_member.member_type = 'agent'+ AND direct_member.member_id = source.agent_id+ )+JOIN agent source_agent ON source_agent.id = COALESCE(direct_squad.leader_id, source.agent_id)LEFT JOIN issue_status source_statusON source_status.workspace_id = source_issue.workspace_idAND source_status.key = source_issue.status@@ -2164,6 +2183,7 @@ WHERE recovery.author_type = 'system'AND source.autopilot_run_id IS NULLAND source.issue_id IS NOT NULLAND source.agent_id <> failed.agent_id+ AND source_agent.id <> failed.agent_id-- Match canDispatchDelegatedFailureRecovery: lifecycle permits recovery only-- for open work; parking belongs exclusively to the fixed Backlog status.-- Built-ins resolve without catalog rows; unknown custom states stay pending.@@ -2192,7 +2212,7 @@ WHERE recovery.author_type = 'system'SELECT 1FROM agent_task_queue coveringWHERE covering.issue_id = source_issue.id- AND covering.agent_id = source.agent_id+ AND covering.agent_id = source_agent.idAND (recovery.id = ANY(covering.delivered_comment_ids)OR (diff --git a/server/pkg/db/queries/squad.sql b/server/pkg/db/queries/squad.sqlindex fa41bd443c..5e3c534032 100644--- a/server/pkg/db/queries/squad.sql+++ b/server/pkg/db/queries/squad.sql@@ -79,6 +79,7 @@ UPDATE squad SETleader_id = COALESCE(sqlc.narg('leader_id'), leader_id),avatar_url = COALESCE(sqlc.narg('avatar_url'), avatar_url),instructions = COALESCE(sqlc.narg('instructions'), instructions),+ handoff_mode = COALESCE(sqlc.narg('handoff_mode'), handoff_mode),updated_at = now()WHERE id = $1RETURNING *;