Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7745 MUL-9463: fix(squads): run an @agent mention of the assigned squad's leader as a leader task (#8918)

Danila Katalshov874897897fdd
diff --git a/apps/docs/content/docs/squads.fr.mdx b/apps/docs/content/docs/squads.fr.mdx
index 2d4feec685..aff23de88e 100644
--- a/apps/docs/content/docs/squads.fr.mdx
+++ b/apps/docs/content/docs/squads.fr.mdx
@@ -62,6 +62,7 @@ Après la première répartition, le chef est automatiquement réveillé par **l
|---|---|---|
| Un non-membre (rapporteur humain, agent externe) publie un commentaire | Oui | |
| 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 |
| 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 |
diff --git a/apps/docs/content/docs/squads.ja.mdx b/apps/docs/content/docs/squads.ja.mdx
index d91b5f70cf..22aeaa6efb 100644
--- a/apps/docs/content/docs/squads.ja.mdx
+++ b/apps/docs/content/docs/squads.ja.mdx
@@ -62,6 +62,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";
|---|---|---|
| スクワッド外の人(人間、外部のエージェント)がコメントする | する | |
| スクワッドのメンバーが `@` なしで進捗を投稿する | する | リーダーが次の手を評価し直す |
+| メンバーまたは作業エージェントが、担当スクワッドのリーダーをエージェントとして明示的にメンションする | する | リーダーとして実行され、`multica squad activity` で判断を記録できる |
| 人間のメンバーが他のメンバーまたは `@all` だけをメンションする | しない | 人には通知が届くが、エージェントへの暗黙のルーティングは抑制される |
| リーダー以外のエージェントがメンバーまたは `@all` だけをメンションする | する | ワーカーの結果はリーダーに戻り、人への通知も通常どおり届く |
| 誰かがエージェントまたはスクワッドを明示的にメンションする | 指名された場合のみ | 指名されたエージェントまたはスクワッドのリーダーだけが実行され、リーダーへの追加のフォールバックはない |
diff --git a/apps/docs/content/docs/squads.ko.mdx b/apps/docs/content/docs/squads.ko.mdx
index d00e5947d3..fb5ca19387 100644
--- a/apps/docs/content/docs/squads.ko.mdx
+++ b/apps/docs/content/docs/squads.ko.mdx
@@ -62,6 +62,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";
|---|---|---|
| 스쿼드 멤버가 아닌 쪽(사람, 외부 에이전트)이 댓글을 남김 | 예 | |
| 스쿼드 멤버가 `@` 없이 진행 상황을 올림 | 예 | 리더가 다음 단계를 다시 평가 |
+| 멤버 또는 작업 에이전트가 담당 스쿼드의 리더를 에이전트로 직접 멘션함 | 예 | 리더 역할로 실행되어 `multica squad activity`로 판단을 기록할 수 있음 |
| 사람 멤버가 다른 멤버 또는 `@all`만 멘션함 | 아니요 | 사람에게 알림이 전달되지만 암시적 에이전트 라우팅은 억제됨 |
| 리더가 아닌 에이전트가 멤버 또는 `@all`만 멘션함 | 예 | 워커의 결과는 리더에게 돌아가고 사람에게도 평소처럼 알림이 전달됨 |
| 누구든 에이전트 또는 스쿼드를 명시적으로 멘션함 | 지명된 경우에만 | 지명된 에이전트 또는 스쿼드 리더만 실행되며 리더로의 추가 폴백은 없음 |
diff --git a/apps/docs/content/docs/squads.mdx b/apps/docs/content/docs/squads.mdx
index b534b7b779..dc8792c6ae 100644
--- a/apps/docs/content/docs/squads.mdx
+++ b/apps/docs/content/docs/squads.mdx
@@ -62,6 +62,7 @@ After the first dispatch, the leader is woken up automatically by **most subsequ
|---|---|---|
| A non-member (human reporter, external agent) posts a comment | Yes | |
| 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 |
| Anyone explicitly mentions an agent or squad | Only if named | Only the named agents or squad leaders run; there is no additional leader fallback |
diff --git a/apps/docs/content/docs/squads.zh-Hant.mdx b/apps/docs/content/docs/squads.zh-Hant.mdx
index 2dcd0ed1ae..354847afc4 100644
--- a/apps/docs/content/docs/squads.zh-Hant.mdx
+++ b/apps/docs/content/docs/squads.zh-Hant.mdx
@@ -62,6 +62,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";
|---|---|---|
| 非小隊成員(人類、外部 AI 代理)發評論 | 會 | |
| 小隊成員發進展更新,不帶任何 `@` | 會 | 隊長重新評估下一步 |
+| 成員或工作 AI 代理顯式提及負責該任務的小隊隊長 AI 代理 | 會 | 以隊長身分執行,可用 `multica squad activity` 記錄決策 |
| 人類成員的評論只提及其他成員或 `@all` | 不會 | 成員收到通知,隱式 AI 代理路由被抑制 |
| 非隊長 AI 代理的評論只提及成員或 `@all` | 會 | 工作 AI 代理的結果仍會交回隊長,成員照常收到通知 |
| 任何作者顯式提及 AI 代理或小隊 | 僅在被點名時 | 只執行被點名的 AI 代理或小隊隊長,不額外回退到隊長 |
diff --git a/apps/docs/content/docs/squads.zh.mdx b/apps/docs/content/docs/squads.zh.mdx
index 41174efb5f..6680a26b18 100644
--- a/apps/docs/content/docs/squads.zh.mdx
+++ b/apps/docs/content/docs/squads.zh.mdx
@@ -62,6 +62,7 @@ import { SquadDemo } from "@/components/demos/squad-demo";
|---|---|---|
| 非小队成员(人类、外部智能体)发评论 | 会 | |
| 小队成员发进展更新,不带任何 `@` | 会 | 队长重新评估下一步 |
+| 成员或工作智能体显式提及负责该任务的小队队长智能体 | 会 | 以队长身份运行,可用 `multica squad activity` 记录决策 |
| 人类成员的评论只提及其他成员或 `@all` | 不会 | 成员收到通知,隐式智能体路由被抑制 |
| 非队长智能体的评论只提及成员或 `@all` | 会 | 工作智能体的结果仍会交回队长,成员照常收到通知 |
| 任何作者显式提及智能体或小队 | 仅在被点名时 | 只运行被点名的智能体或小队队长,不额外回退到队长 |
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 585c1d16e3..150864fa87 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -2448,7 +2448,12 @@ func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issu
return commentMergeError
}
overlay, connectedApps := h.TaskService.BuildRuntimeMCPOverlayForMerge(ctx, attr.UserID, trigger.Agent)
+ var leaderSquadID pgtype.UUID
+ if trigger.Squad != nil {
+ leaderSquadID = trigger.Squad.ID
+ }
row, err := h.Queries.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
+ NewLeaderSquadID: leaderSquadID,
IssueID: issue.ID,
AgentID: trigger.Agent.ID,
NewTriggerCommentID: newTriggerCommentID,
@@ -2638,7 +2643,13 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu
return err
}
case commentTriggerSourceMentionAgent:
- if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, trigger.Agent.ID, triggerCommentID, service.OriginNamed); err != nil {
+ var err error
+ if trigger.Squad != nil {
+ _, err = h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID, service.OriginNamed)
+ } else {
+ _, err = h.TaskService.EnqueueTaskForMention(ctx, issue, trigger.Agent.ID, triggerCommentID, service.OriginNamed)
+ }
+ if err != nil {
logCommentEnqueueFailure("enqueue mention agent task failed", err,
"issue_id", uuidToString(issue.ID),
"agent_id", uuidToString(trigger.Agent.ID))
@@ -3044,6 +3055,25 @@ func (h *Handler) routeAssigneeFallback(ctx context.Context, issue db.Issue, aut
}
}
+// assignedSquadLedBy returns the squad the issue is assigned to when agentID
+// leads it, else nil. An explicit @agent mention of that leader then runs in
+// the leader role, as the implicit squad-assignee wake does; a plain mention
+// task carries no is_leader_task / squad_id, so the leader could not record
+// `multica squad activity` for the turn (#8875).
+func (h *Handler) assignedSquadLedBy(ctx context.Context, issue db.Issue, agentID pgtype.UUID) *db.Squad {
+ if !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" {
+ return nil
+ }
+ squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
+ ID: issue.AssigneeID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil || squad.LeaderID != agentID {
+ return nil
+ }
+ return &squad
+}
+
func (h *Handler) routeAssignedSquadLeaderFallback(ctx context.Context, issue db.Issue, authorType, authorID string, opts commentTriggerComputeOptions) (commentAgentTrigger, bool) {
// Checked here as well as in routeAssigneeFallback: an agent-authored
// comment reaches this one directly, without passing through that caller.
@@ -3342,7 +3372,27 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
blockTarget("agent", m.ID, ReasonInternalError)
continue
}
- add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent, AlreadyPending: hasPending})
+ squad := h.assignedSquadLedBy(ctx, issue, agentUUID)
+ if squad != nil && authorType == "agent" && authorID == uuidToString(agentUUID) {
+ suppress := h.shouldSuppressSquadLeaderSelfTrigger(ctx, issue.ID, agentUUID, squad.ID)
+ if opts.AuthoringTaskID.Valid {
+ task, err := h.Queries.GetAgentTask(ctx, opts.AuthoringTaskID)
+ if err != nil || task.AgentID != agentUUID {
+ blockTarget("agent", m.ID, ReasonInternalError)
+ continue
+ }
+ // Trusted same-issue self-mentions are suppressed above.
+ // Cross-issue handoffs remain eligible for the leader role.
+ suppress = task.IssueID == issue.ID && (task.IsLeaderTask || task.SquadID != squad.ID)
+ }
+ if suppress {
+ active, activeErr := h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, agentUUID, opts.ThreadCommentID)
+ status, reason := decideSuppressedLeaderOutcome(active, activeErr)
+ addTarget(commentMentionTarget{TargetType: "agent", TargetID: m.ID, Status: status, ReasonCode: reason})
+ continue
+ }
+ }
+ add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent, Squad: squad, AlreadyPending: hasPending})
addTarget(commentMentionTarget{TargetType: "agent", TargetID: m.ID, ExecAgentID: uuidToString(agentUUID)})
}
return triggers, targets
diff --git a/server/internal/handler/squad_comment_trigger_test.go b/server/internal/handler/squad_comment_trigger_test.go
index 867df2c00e..2350ec0b7e 100644
--- a/server/internal/handler/squad_comment_trigger_test.go
+++ b/server/internal/handler/squad_comment_trigger_test.go
@@ -481,10 +481,9 @@ func TestCreateComment_DualRoleAgentWorkerCommentWakesLeader(t *testing.T) {
// TestCreateComment_SquadLeaderMentionTaskDoesNotSelfTriggerAssignedFallback
// pins MUL-4024's direct-mention gap:
//
-// - A member explicitly @mentions the issue's assigned squad leader by agent
-// id, which queues a generic mention task for L (is_leader_task=false,
-// squad_id=NULL).
-// - L posts a plain reply while running that mention task.
+// - The issue's assigned squad leader L runs a generic task on it
+// (is_leader_task=false, squad_id=NULL).
+// - L posts a plain reply while running that generic task.
// - The assigned-squad fallback must not treat that generic mention task as a
// same-squad worker result and queue L again as the leader.
func TestCreateComment_SquadLeaderMentionTaskDoesNotSelfTriggerAssignedFallback(t *testing.T) {
@@ -539,22 +538,24 @@ func TestCreateComment_SquadLeaderMentionTaskDoesNotSelfTriggerAssignedFallback(
return n
}
+ // A member @mention of L on its own squad's issue now queues a leader task
+ // (#8875), so the generic task L runs here is seeded directly. The member
+ // comment only mentions a member, which routes to no agent.
trigger := postMemberComment(map[string]any{
- "content": "[@Leader](mention://agent/" + fx.LeaderID + ") can you check this?",
+ "content": "[@Member](mention://member/" + testUserID + ") can you check this?",
})
+ var leaderRuntimeID string
+ if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, fx.LeaderID).Scan(&leaderRuntimeID); err != nil {
+ t.Fatalf("load leader runtime: %v", err)
+ }
var mentionTaskID string
if err := testPool.QueryRow(ctx, `
- SELECT id FROM agent_task_queue
- WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
- AND is_leader_task = FALSE AND squad_id IS NULL
- ORDER BY created_at DESC
- LIMIT 1
- `, issueID, fx.LeaderID).Scan(&mentionTaskID); err != nil {
- t.Fatalf("load leader mention task: %v", err)
- }
- if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running' WHERE id = $1`, mentionTaskID); err != nil {
- t.Fatalf("mark mention task running: %v", err)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task)
+ VALUES ($1, $2, $3, 'running', FALSE)
+ RETURNING id
+ `, fx.LeaderID, leaderRuntimeID, issueID).Scan(&mentionTaskID); err != nil {
+ t.Fatalf("seed generic task: %v", err)
}
postAgentComment(mentionTaskID, map[string]any{
diff --git a/server/internal/handler/squad_id_enqueue_test.go b/server/internal/handler/squad_id_enqueue_test.go
index 256a67cb4f..44893522d4 100644
--- a/server/internal/handler/squad_id_enqueue_test.go
+++ b/server/internal/handler/squad_id_enqueue_test.go
@@ -6,6 +6,7 @@ import (
"net/http/httptest"
"testing"
+ "github.com/multica-ai/multica/server/internal/testutil"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -128,3 +129,91 @@ func TestCreateRetryTask_InheritsSquadID(t *testing.T) {
t.Fatalf("child.IsLeaderTask = false, want true (provenance must survive retry)")
}
}
+
+// TestCreateComment_LeaderAgentMentionOnAssignedSquadIssueIsLeaderTask covers
+// #8875: an explicit @agent mention of the leader of the squad the issue is
+// assigned to must enqueue a leader task (is_leader_task + squad_id), exactly
+// like the implicit squad-assignee wake, so the leader can record
+// `multica squad activity`. A plain @agent mention of a non-leader stays a
+// plain mention task.
+func TestCreateComment_LeaderAgentMentionOnAssignedSquadIssueIsLeaderTask(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ for _, author := range []string{"member", "worker"} {
+ t.Run(author, func(t *testing.T) {
+ ctx := context.Background()
+ fx := newSquadCommentTriggerFixture(t)
+ issueID := uuidToString(fx.Issue.ID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM activity_log WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)
+ })
+
+ w := httptest.NewRecorder()
+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{
+ "content": "[@Leader](mention://agent/" + fx.LeaderID + ") and [@Other](mention://agent/" + fx.OtherID + ") please review",
+ })
+ r = withURLParam(r, "id", issueID)
+ expectedAuthorType, expectedAuthorID := "member", testUserID
+ if author == "worker" {
+ workerID := createHandlerTestAgent(t, "Leader Mention Worker", nil)
+ dbfx.SquadMember(t, fx.SquadID, "agent", workerID)
+ workerTaskID := dbfx.Task(t, workerID, testutil.Cols{
+ "runtime_id": handlerTestRuntimeID(t), "issue_id": issueID,
+ "status": "running", "squad_id": fx.SquadID,
+ })
+ r.Header.Set("X-Agent-ID", workerID)
+ r.Header.Set("X-Task-ID", workerTaskID)
+ expectedAuthorType, expectedAuthorID = "agent", workerID
+ }
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var authorType, authorID string
+ if err := testPool.QueryRow(ctx, `SELECT author_type, author_id FROM comment WHERE issue_id = $1`, issueID).Scan(&authorType, &authorID); err != nil {
+ t.Fatal(err)
+ }
+ if authorType != expectedAuthorType || authorID != expectedAuthorID {
+ t.Fatalf("comment actor = %s/%s, want %s/%s", authorType, authorID, expectedAuthorType, expectedAuthorID)
+ }
+
+ load := func(agentID string) (string, string, bool) {
+ t.Helper()
+ var squadID *string
+ var isLeader bool
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id, squad_id::text, is_leader_task
+ FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, agentID).Scan(&taskID, &squadID, &isLeader); err != nil {
+ t.Fatalf("load task for agent %s: %v", agentID, err)
+ }
+ if squadID == nil {
+ return taskID, "", isLeader
+ }
+ return taskID, *squadID, isLeader
+ }
+
+ leaderTaskID, squadID, isLeader := load(fx.LeaderID)
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running' WHERE id = $1`, leaderTaskID); err != nil {
+ t.Fatal(err)
+ }
+ testutil.Call(t, testHandler.RecordSquadLeaderEvaluation,
+ evaluationRequest(issueID, fx.LeaderID, leaderTaskID, "no_action")).Want(http.StatusCreated)
+ got := loadEvaluations(t, issueID)
+ if len(got) != 1 || got[0].ActorID != fx.LeaderID || got[0].SquadID != fx.SquadID || got[0].Outcome != "no_action" {
+ t.Fatalf("leader mention did not persist its evaluation: %+v", got)
+ }
+ if !isLeader || squadID != fx.SquadID {
+ t.Fatalf("leader mention task: is_leader_task=%v squad_id=%q, want true / %q", isLeader, squadID, fx.SquadID)
+ }
+ if _, squadID, isLeader := load(fx.OtherID); isLeader || squadID != "" {
+ t.Fatalf("non-leader mention task: is_leader_task=%v squad_id=%q, want false / empty", isLeader, squadID)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/squad_leader_agent_mention_test.go b/server/internal/handler/squad_leader_agent_mention_test.go
new file mode 100644
index 0000000000..126ed124f6
--- /dev/null
+++ b/server/internal/handler/squad_leader_agent_mention_test.go
@@ -0,0 +1,172 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func assignMentionFixtureSquad(t *testing.T, f supplementFixture) string {
+ t.Helper()
+ squadID := dbfx.Squad(t, "Explicit leader mention", f.agentID)
+ dbfx.Exec(t, `UPDATE issue SET assignee_type = 'squad', assignee_id = $2 WHERE id = $1`, f.issueID, squadID)
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.issueID)
+ dbfx.Cleanup(t, `DELETE FROM activity_log WHERE issue_id = $1`, f.issueID)
+ return squadID
+}
+
+func recordMentionEvaluation(t *testing.T, issueID, agentID, taskID, squadID string) {
+ t.Helper()
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'running' WHERE id = $1`, taskID)
+ testutil.Call(t, testHandler.RecordSquadLeaderEvaluation,
+ evaluationRequest(issueID, agentID, taskID, "no_action")).Want(http.StatusCreated)
+ got := loadEvaluations(t, issueID)
+ if len(got) != 1 || got[0].ActorID != agentID || got[0].SquadID != squadID || got[0].Outcome != "no_action" {
+ t.Fatalf("recorded wrong leader evaluation: %+v", got)
+ }
+}
+
+func TestLeaderAgentMentionPreservesSelfTriggerRules(t *testing.T) {
+ for _, mode := range []string{"leader", "same-squad-worker", "cross-issue-leader"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newSupplementFixture(t, "claude", "running", false)
+ squadID := assignMentionFixtureSquad(t, f)
+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id = $2, accountable_user_id = $2, originator_source = 'comment_source', delivered_comment_ids = ARRAY[trigger_comment_id] WHERE id = $1`, f.taskID, testUserID)
+ dbfx.Exec(t, `UPDATE agent_task_queue SET is_leader_task = $2, squad_id = $3 WHERE id = $1`,
+ f.taskID, mode != "same-squad-worker", squadID)
+ issueID := f.issueID
+ if mode == "cross-issue-leader" {
+ issueID = dbfx.Issue(t, "Cross-issue leader handoff", testutil.Cols{"assignee_type": "squad", "assignee_id": squadID})
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ }
+ body := map[string]any{"content": agentMention("Leader", f.agentID) + " next step"}
+ if issueID == f.issueID {
+ body["parent_id"] = f.triggerID
+ }
+ r := withURLParam(agentRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", body, f.agentID, f.taskID), "id", issueID)
+ var created CommentResponse
+ testutil.Call(t, testHandler.CreateComment, r).Want(http.StatusCreated).JSON(&created)
+ n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued' AND is_leader_task AND squad_id = $3`, issueID, f.agentID, squadID)
+ if mode != "cross-issue-leader" {
+ if n != 0 {
+ t.Fatalf("same-issue %s self-mention queued %d more leader turns: %+v", mode, n, created.TriggerOutcomes)
+ }
+ outcome := findCommentOutcome(t, created.TriggerOutcomes, f.agentID)
+ if outcome.Status != DispatchDeferred || outcome.ReasonCode != ReasonAlreadyActive {
+ t.Fatalf("same-issue self-mention outcome: %+v", outcome)
+ }
+ completeTaskViaDaemon(t, f.taskID)
+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`, issueID, f.agentID); n != 0 {
+ t.Fatalf("same-issue %s self-mention replay queued %d turns", mode, n)
+ }
+ } else if n != 1 {
+ t.Fatalf("legitimate %s handoff queued %d leader turns: %+v", mode, n, created.TriggerOutcomes)
+ }
+ })
+ }
+}
+
+func TestLeaderAgentMentionMergesOnlyCompatibleTaskRoles(t *testing.T) {
+ for _, role := range []string{"generic", "same-leader", "worker", "different-squad-leader"} {
+ t.Run(role, func(t *testing.T) {
+ f := newSupplementFixture(t, "claude", "queued", false)
+ squadID := assignMentionFixtureSquad(t, f)
+ dbfx.Exec(t, `UPDATE agent_task_queue SET comment_thread_id = $2 WHERE id = $1`, f.taskID, f.triggerID)
+ switch role {
+ case "same-leader", "worker":
+ dbfx.Exec(t, `UPDATE agent_task_queue SET is_leader_task = $2, squad_id = $3 WHERE id = $1`, f.taskID, role == "same-leader", squadID)
+ case "different-squad-leader":
+ otherSquad := dbfx.Squad(t, "Other leader context", f.agentID)
+ dbfx.Exec(t, `UPDATE agent_task_queue SET is_leader_task = TRUE, squad_id = $2 WHERE id = $1`, f.taskID, otherSquad)
+ }
+ before, err := testHandler.Queries.GetAgentTask(context.Background(), parseUUID(f.taskID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var created CommentResponse
+ postSteeredComment(t, f.issueID, f.triggerID, agentMention("Leader", f.agentID)+" review this").Want(http.StatusCreated).JSON(&created)
+ outcome := findCommentOutcome(t, created.TriggerOutcomes, f.agentID)
+ wantTaskCount := 1
+ if role == "generic" || role == "same-leader" {
+ if outcome.Status != DispatchCoalesced {
+ t.Fatalf("compatible %s was not coalesced: %+v", role, outcome)
+ }
+ recordMentionEvaluation(t, f.issueID, f.agentID, f.taskID, squadID)
+ } else {
+ if outcome.Status != DispatchDeferred {
+ t.Fatalf("incompatible %s consumed leader input: %+v", role, outcome)
+ }
+ after, err := testHandler.Queries.GetAgentTask(context.Background(), parseUUID(f.taskID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if after.TriggerCommentID != before.TriggerCommentID || after.SquadID != before.SquadID || after.IsLeaderTask != before.IsLeaderTask {
+ t.Fatalf("incompatible %s task was modified", role)
+ }
+ claim := claimTaskRaw(t, f.runtimeID, "")
+ if claim.code != http.StatusOK || claim.task == nil {
+ t.Fatalf("claim original %s turn: %d %s", role, claim.code, claim.body)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE id = $1 AND status IN ('dispatched', 'running')`, f.taskID); n != 1 {
+ t.Fatal("original task was not claimed")
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE id = $1 AND $2 = ANY(delivered_comment_ids)`, f.taskID, created.ID); n != 0 {
+ t.Fatal("incompatible role acknowledged the leader's input")
+ }
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'running' WHERE id = $1`, f.taskID)
+ completeTaskViaDaemon(t, f.taskID)
+ var followupID string
+ if err := testPool.QueryRow(context.Background(), `SELECT id FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued' AND is_leader_task AND squad_id = $3 AND (trigger_comment_id = $4 OR $4 = ANY(coalesced_comment_ids))`, f.issueID, f.agentID, squadID, created.ID).Scan(&followupID); err != nil {
+ t.Fatalf("deferred leader input was not replayed after %s: %v", role, err)
+ }
+ recordMentionEvaluation(t, f.issueID, f.agentID, followupID, squadID)
+ wantTaskCount = 2
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, f.issueID); n != wantTaskCount {
+ t.Fatalf("role-aware merge created %d tasks", n)
+ }
+ })
+ }
+}
+
+func TestLeaderAgentMentionSteersOnlyMatchingLeaderRole(t *testing.T) {
+ for _, all := range []bool{false, true} {
+ for _, role := range []string{"worker", "matching-leader", "different-squad-leader"} {
+ t.Run(role+map[bool]string{false: "/chosen", true: "/all"}[all], func(t *testing.T) {
+ f := newSupplementFixture(t, "claude", "running", true)
+ squadID := assignMentionFixtureSquad(t, f)
+ taskSquad := squadID
+ if role == "different-squad-leader" {
+ taskSquad = dbfx.Squad(t, "Other steering context", f.agentID)
+ }
+ dbfx.Exec(t, `UPDATE agent_task_queue SET is_leader_task = $2, squad_id = $3 WHERE id = $1`, f.taskID, role != "worker", taskSquad)
+ body := map[string]any{"content": agentMention("Leader", f.agentID) + " evaluate this", "parent_id": f.triggerID}
+ if all {
+ body["steer"] = true
+ } else {
+ body["steer_task_ids"] = []string{f.taskID}
+ }
+ var created CommentResponse
+ testutil.Call(t, testHandler.CreateComment, withURLParam(newRequest(http.MethodPost, "/api/issues/"+f.issueID+"/comments", body), "id", f.issueID)).Want(http.StatusCreated).JSON(&created)
+ outcome := findCommentOutcome(t, created.TriggerOutcomes, f.agentID)
+ if role == "matching-leader" {
+ if outcome.Status != DispatchSteered || len(created.Supplements) != 1 {
+ t.Fatalf("matching leader did not receive steering: %+v", created)
+ }
+ recordMentionEvaluation(t, f.issueID, f.agentID, f.taskID, squadID)
+ } else {
+ if outcome.Status != DispatchQueued || len(created.Supplements) != 0 {
+ t.Fatalf("incompatible %s steering did not fall back to leader routing: %+v", role, created)
+ }
+ var taskID string
+ if err := testPool.QueryRow(context.Background(), `SELECT id FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued' AND is_leader_task AND squad_id = $3`, f.issueID, f.agentID, squadID).Scan(&taskID); err != nil {
+ t.Fatal(err)
+ }
+ recordMentionEvaluation(t, f.issueID, f.agentID, taskID, squadID)
+ }
+ })
+ }
+ }
+}
diff --git a/server/internal/handler/task_supplement.go b/server/internal/handler/task_supplement.go
index 74cb9293aa..8710e0b19e 100644
--- a/server/internal/handler/task_supplement.go
+++ b/server/internal/handler/task_supplement.go
@@ -221,8 +221,13 @@ func (h *Handler) steerCommentAgentTriggers(ctx context.Context, issue db.Issue,
continue
}
// The comment is its own request id: it binds to a turn at most once.
+ var leaderSquadID pgtype.UUID
+ if trigger.Squad != nil {
+ leaderSquadID = trigger.Squad.ID
+ }
bound, err := h.bindCommentSteer(ctx, db.BindCommentTaskSupplementParams{
- TaskID: taskID, IssueID: issue.ID, AgentID: trigger.Agent.ID, WorkspaceID: issue.WorkspaceID,
+ RequiredLeaderSquadID: leaderSquadID,
+ TaskID: taskID, IssueID: issue.ID, AgentID: trigger.Agent.ID, WorkspaceID: issue.WorkspaceID,
AuthorType: comment.AuthorType, MaxAgentBindings: maxAgentSteersPerTurn, MaxBindingsPerAgent: maxAgentSteersPerAgentPerTurn,
CommentID: comment.ID, AuthorID: comment.AuthorID, ClientRequestID: comment.ID,
})
diff --git a/server/internal/service/builtin_skills/multica-platform/references/squads.md b/server/internal/service/builtin_skills/multica-platform/references/squads.md
index 2de072e77b..9ac4351ef7 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/squads.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/squads.md
@@ -199,7 +199,9 @@ is leader routing, not member fan-out.
A worker's reply also wakes the assigned leader without an explicit mention. If
the leader's current run started before the reply arrived, the reply is
delivered in a follow-up run after that run completes, so the worker does not
-need to mention the leader again.
+need to mention the leader again. An explicit `@agent` mention of the leader on
+an issue assigned to its squad also runs it as the leader, so
+`multica squad activity` works on that turn too.
Squad mention format:
diff --git a/server/internal/service/retry_deferred_test.go b/server/internal/service/retry_deferred_test.go
index f07c9df421..85d67c9ce7 100644
--- a/server/internal/service/retry_deferred_test.go
+++ b/server/internal/service/retry_deferred_test.go
@@ -7,6 +7,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/testutil"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -93,7 +94,10 @@ func TestCreateRetryTaskFireAtControlsDeferral(t *testing.T) {
// promote or claim it even after fire_at is due, and a fresh online heartbeat
// releases that exact child without consuming another retry.
func TestRuntimeOfflineRetryWaitsForHealthyRuntime(t *testing.T) {
- pool := newResolveOriginatorPool(t)
+ sharedPool := newResolveOriginatorPool(t)
+ // Other packages sweep offline runtimes across all workspaces. Keep this
+ // deliberately stale fixture isolated until its own failure creates a retry.
+ pool := testutil.IsolatedDB(t, sharedPool.Config().ConnString())
ctx := context.Background()
q := db.New(pool)
_, _, agentID, issueID := seedAttributionFixture(t, pool)
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index d8b4096c4d..16e919fae0 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -7259,8 +7259,11 @@ SET coalesced_comment_ids = (
FROM unnest(array_append(coalesced_comment_ids, trigger_comment_id)) AS e
WHERE e IS NOT NULL AND e <> $1::uuid
),
+ is_leader_task = CASE WHEN $2::uuid IS NOT NULL
+ THEN TRUE ELSE is_leader_task END,
+ squad_id = COALESCE($2::uuid, squad_id),
trigger_comment_id = $1::uuid,
- trigger_summary = COALESCE($2, trigger_summary),
+ trigger_summary = COALESCE($3, trigger_summary),
-- Re-attribution is ATOMIC (MUL-4302): folding a newly-arrived comment moves the
-- WHOLE attribution snapshot to that comment's human — person columns, source
-- label, delegation lineage, rule version, and evidence — computed by the caller
@@ -7268,19 +7271,26 @@ SET coalesced_comment_ids = (
-- run showing B accountable while still pointing at A's stale source / evidence /
-- level. accountable comes from the resolved Result (finalizeAttribution already
-- guaranteed originator ⟹ accountable == originator; the cross-column CHECK backs it).
- originator_user_id = $3::uuid,
- accountable_user_id = $4::uuid,
- originator_source = $5,
- delegated_from_task_id = $6::uuid,
- rule_version_id = $7::uuid,
- trigger_evidence_kind = $8,
- trigger_evidence_ref_id = $9::uuid,
- runtime_mcp_overlay = $10,
- runtime_connected_apps = $11
+ originator_user_id = $4::uuid,
+ accountable_user_id = $5::uuid,
+ originator_source = $6,
+ delegated_from_task_id = $7::uuid,
+ rule_version_id = $8::uuid,
+ trigger_evidence_kind = $9,
+ trigger_evidence_ref_id = $10::uuid,
+ runtime_mcp_overlay = $11,
+ runtime_connected_apps = $12
WHERE id = (
SELECT t.id FROM agent_task_queue t
- WHERE t.context->>'wakeup_id' IS NULL AND t.issue_id = $12
- AND t.agent_id = $13
+ WHERE t.context->>'wakeup_id' IS NULL AND t.issue_id = $13
+ AND t.agent_id = $14
+ -- An unclaimed generic turn can become a leader turn. Never overwrite
+ -- a worker obligation or a different squad's leader context.
+ AND (
+ $2::uuid IS NULL
+ OR (t.is_leader_task AND t.squad_id = $2::uuid)
+ OR (NOT t.is_leader_task AND t.squad_id IS NULL)
+ )
AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($1::uuid)
AND (
t.status = 'queued'
@@ -7292,17 +7302,19 @@ WHERE id = (
-- into it would give a new-HEAD comment old-HEAD review coverage. Empty/
-- absent head_sha (no linked PR) matches any task, preserving coalescing.
AND (
- COALESCE($14::text, '') = ''
- OR t.context->>'head_sha' = $14::text
+ COALESCE($15::text, '') = ''
+ OR t.context->>'head_sha' = $15::text
)
ORDER BY t.created_at DESC
LIMIT 1
+ FOR UPDATE OF t
)
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type MergeCommentIntoPendingTaskParams struct {
NewTriggerCommentID pgtype.UUID `json:"new_trigger_comment_id"`
+ NewLeaderSquadID pgtype.UUID `json:"new_leader_squad_id"`
NewTriggerSummary pgtype.Text `json:"new_trigger_summary"`
NewOriginatorUserID pgtype.UUID `json:"new_originator_user_id"`
NewAccountableUserID pgtype.UUID `json:"new_accountable_user_id"`
@@ -7363,6 +7375,7 @@ type MergeCommentIntoPendingTaskParams struct {
func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeCommentIntoPendingTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, mergeCommentIntoPendingTask,
arg.NewTriggerCommentID,
+ arg.NewLeaderSquadID,
arg.NewTriggerSummary,
arg.NewOriginatorUserID,
arg.NewAccountableUserID,
diff --git a/server/pkg/db/generated/supplement.sql.go b/server/pkg/db/generated/supplement.sql.go
index 295f2c34e8..a7115b6006 100644
--- a/server/pkg/db/generated/supplement.sql.go
+++ b/server/pkg/db/generated/supplement.sql.go
@@ -103,16 +103,20 @@ WITH locked_task AS MATERIALIZED (
AND t.agent_id = $3
AND r.workspace_id = $4
AND t.status = 'running'
+ AND (
+ $5::uuid IS NULL
+ OR (t.is_leader_task AND t.squad_id = $5::uuid)
+ )
AND cap.capability = 'task-supplement-v1'
AND r.provider IN ('codex', 'claude', 'grok', 'cursor', 'kiro', 'pi')
- AND ($5::text <> 'agent' OR (
+ AND ($6::text <> 'agent' OR (
(SELECT count(*) FROM task_supplement s
JOIN comment c ON c.id = s.comment_id
- WHERE s.task_id = t.id AND c.author_type = 'agent') < $6::int
+ WHERE s.task_id = t.id AND c.author_type = 'agent') < $7::int
AND (SELECT count(*) FROM task_supplement s
JOIN comment c ON c.id = s.comment_id
WHERE s.task_id = t.id AND c.author_type = 'agent'
- AND s.author_id = $7) < $8::int
+ AND s.author_id = $8) < $9::int
))
FOR UPDATE OF t
), inserted AS (
@@ -120,8 +124,8 @@ WITH locked_task AS MATERIALIZED (
task_id, workspace_id, issue_id, comment_id, author_id,
client_request_id, status
)
- SELECT t.id, $4, t.issue_id, $9, $7,
- $10, 'pending'
+ SELECT t.id, $4, t.issue_id, $10, $8,
+ $11, 'pending'
FROM locked_task t
RETURNING task_id, workspace_id, issue_id, comment_id, author_id, client_request_id, status, failure_reason, attempt_count, created_at, updated_at, delivered_at
)
@@ -131,16 +135,17 @@ JOIN locked_task ON locked_task.id = inserted.task_id
`
type BindCommentTaskSupplementParams struct {
- TaskID pgtype.UUID `json:"task_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- AgentID pgtype.UUID `json:"agent_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- AuthorType string `json:"author_type"`
- MaxAgentBindings int32 `json:"max_agent_bindings"`
- AuthorID pgtype.UUID `json:"author_id"`
- MaxBindingsPerAgent int32 `json:"max_bindings_per_agent"`
- CommentID pgtype.UUID `json:"comment_id"`
- ClientRequestID pgtype.UUID `json:"client_request_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RequiredLeaderSquadID pgtype.UUID `json:"required_leader_squad_id"`
+ AuthorType string `json:"author_type"`
+ MaxAgentBindings int32 `json:"max_agent_bindings"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ MaxBindingsPerAgent int32 `json:"max_bindings_per_agent"`
+ CommentID pgtype.UUID `json:"comment_id"`
+ ClientRequestID pgtype.UUID `json:"client_request_id"`
}
type BindCommentTaskSupplementRow struct {
@@ -172,6 +177,7 @@ func (q *Queries) BindCommentTaskSupplement(ctx context.Context, arg BindComment
arg.IssueID,
arg.AgentID,
arg.WorkspaceID,
+ arg.RequiredLeaderSquadID,
arg.AuthorType,
arg.MaxAgentBindings,
arg.AuthorID,
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 109eac2fbe..4eae436de4 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -1879,6 +1879,9 @@ SET coalesced_comment_ids = (
FROM unnest(array_append(coalesced_comment_ids, trigger_comment_id)) AS e
WHERE e IS NOT NULL AND e <> @new_trigger_comment_id::uuid
),
+ is_leader_task = CASE WHEN sqlc.narg('new_leader_squad_id')::uuid IS NOT NULL
+ THEN TRUE ELSE is_leader_task END,
+ squad_id = COALESCE(sqlc.narg('new_leader_squad_id')::uuid, squad_id),
trigger_comment_id = @new_trigger_comment_id::uuid,
trigger_summary = COALESCE(sqlc.narg('new_trigger_summary'), trigger_summary),
-- Re-attribution is ATOMIC (MUL-4302): folding a newly-arrived comment moves the
@@ -1901,6 +1904,13 @@ WHERE id = (
SELECT t.id FROM agent_task_queue t
WHERE t.context->>'wakeup_id' IS NULL AND t.issue_id = @issue_id
AND t.agent_id = @agent_id
+ -- An unclaimed generic turn can become a leader turn. Never overwrite
+ -- a worker obligation or a different squad's leader context.
+ AND (
+ sqlc.narg('new_leader_squad_id')::uuid IS NULL
+ OR (t.is_leader_task AND t.squad_id = sqlc.narg('new_leader_squad_id')::uuid)
+ OR (NOT t.is_leader_task AND t.squad_id IS NULL)
+ )
AND t.comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id(@new_trigger_comment_id::uuid)
AND (
t.status = 'queued'
@@ -1917,6 +1927,7 @@ WHERE id = (
)
ORDER BY t.created_at DESC
LIMIT 1
+ FOR UPDATE OF t
)
RETURNING *;
diff --git a/server/pkg/db/queries/supplement.sql b/server/pkg/db/queries/supplement.sql
index 60d8f57e46..db4cae5a59 100644
--- a/server/pkg/db/queries/supplement.sql
+++ b/server/pkg/db/queries/supplement.sql
@@ -124,6 +124,10 @@ WITH locked_task AS MATERIALIZED (
AND t.agent_id = @agent_id
AND r.workspace_id = @workspace_id
AND t.status = 'running'
+ AND (
+ sqlc.narg('required_leader_squad_id')::uuid IS NULL
+ OR (t.is_leader_task AND t.squad_id = sqlc.narg('required_leader_squad_id')::uuid)
+ )
AND cap.capability = 'task-supplement-v1'
AND r.provider IN ('codex', 'claude', 'grok', 'cursor', 'kiro', 'pi')
AND (@author_type::text <> 'agent' OR (