Skip to content

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

Go

MUL-4024 tighten squad leader self-trigger guard (#4896)

Multica Eve910bbe930975
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 972dddb67c..33d73b6438 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1486,7 +1486,7 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu
// after MUL-3794 (MUL-3879): a worker-agent result comment on a
// squad-assigned issue can still wake the assigned squad leader, so
// the leader→worker→leader coordination loop stays closed. The leader
- // self-trigger guard (lastTaskWasLeader) lives in
+ // self-trigger guard lives in
// routeAssignedSquadLeaderFallback. Explicit @agent / @squad mentions
// are already handled above, so this never double-enqueues a mentioned
// target alongside the assigned leader.
@@ -1731,7 +1731,7 @@ func (h *Handler) routeAssignedSquadLeaderFallback(ctx context.Context, issue db
return commentAgentTrigger{}, false
}
if authorType == "agent" && authorID == uuidToString(squad.LeaderID) &&
- h.lastTaskWasLeader(ctx, issue.ID, squad.LeaderID) {
+ h.shouldSuppressSquadLeaderSelfTrigger(ctx, issue.ID, squad.LeaderID, squad.ID) {
return commentAgentTrigger{}, false
}
agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
@@ -1805,12 +1805,12 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
continue
}
leaderID := squad.LeaderID
- // Prevent self-trigger only when the agent's last activity on this
- // issue was itself a leader task. An agent that holds both the
- // leader and a worker role in the squad must still wake its
- // leader role after posting a comment from its worker task.
+ // Prevent self-trigger unless the agent's last activity on this
+ // issue was a worker task for this same squad. Generic non-leader
+ // tasks (direct @agent mentions, thread-parent replies) are not a
+ // worker-role handoff and must not re-enqueue the leader.
if authorType == "agent" && authorID == uuidToString(leaderID) &&
- h.lastTaskWasLeader(ctx, issue.ID, leaderID) {
+ h.shouldSuppressSquadLeaderSelfTrigger(ctx, issue.ID, leaderID, squad.ID) {
continue
}
// Verify leader agent is ready (has runtime, not archived).
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index a700e9a33e..83d9538313 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -904,22 +904,23 @@ func (h *Handler) RecordSquadLeaderEvaluation(w http.ResponseWriter, r *http.Req
// ── Squad Trigger Logic ─────────────────────────────────────────────────────
-// lastTaskWasLeader returns true when the agent's most recent task on the
-// issue was enqueued in the squad-leader role. Used by the self-trigger
-// guards to tell apart a comment posted while the agent was acting as
-// leader (skip) from one posted while it was acting as a worker (do not
-// skip). When the agent has no prior task on this issue the role is
-// undetermined and we treat it as non-leader so a brand-new external
-// trigger can still reach the leader.
-func (h *Handler) lastTaskWasLeader(ctx context.Context, issueID, agentID pgtype.UUID) bool {
- flag, err := h.Queries.GetLatestTaskIsLeaderForIssueAndAgent(ctx, db.GetLatestTaskIsLeaderForIssueAndAgentParams{
+// shouldSuppressSquadLeaderSelfTrigger reports whether a squad leader's own
+// comment should be blocked from re-enqueuing that same leader. The only
+// leader-authored non-leader task allowed to wake the assigned leader is a
+// same-squad worker task; generic agent tasks such as direct mentions and
+// thread-parent replies are not worker-role proof and must not self-trigger.
+func (h *Handler) shouldSuppressSquadLeaderSelfTrigger(ctx context.Context, issueID, leaderID, squadID pgtype.UUID) bool {
+ latest, err := h.Queries.GetLatestTaskRoleForIssueAndAgent(ctx, db.GetLatestTaskRoleForIssueAndAgentParams{
IssueID: issueID,
- AgentID: agentID,
+ AgentID: leaderID,
})
if err != nil {
return false
}
- return flag
+ if latest.IsLeaderTask {
+ return true
+ }
+ return !latest.SquadID.Valid || uuidToString(latest.SquadID) != uuidToString(squadID)
}
// commentMentionsAnyone returns true when the comment body contains at least
diff --git a/server/internal/handler/squad_comment_trigger_test.go b/server/internal/handler/squad_comment_trigger_test.go
index 27dd629e40..ae18a4037d 100644
--- a/server/internal/handler/squad_comment_trigger_test.go
+++ b/server/internal/handler/squad_comment_trigger_test.go
@@ -224,8 +224,7 @@ func TestShouldEnqueueSquadLeaderOnComment_SkipsWhenMemberMentionsAnyone(t *test
// pins the MUL-3879 restored behavior in the new MUL-3794 cascade: an
// agent-authored worker-result comment on a squad-assigned issue wakes the
// assigned squad leader so the leader→worker→leader coordination loop stays
-// closed, while the leader's own self-trigger loop stays suppressed via
-// lastTaskWasLeader.
+// closed, while the leader's own self-trigger loop stays suppressed.
func TestShouldEnqueueSquadLeaderOnComment_AgentAuthoredWorkerCommentsWakeLeader(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -243,10 +242,10 @@ func TestShouldEnqueueSquadLeaderOnComment_AgentAuthoredWorkerCommentsWakeLeader
t.Fatalf("clear tasks: %v", err)
}
}
- // insertLeaderTask seeds a task for the leader agent so the
- // lastTaskWasLeader guard can read the agent's most recent role on the
- // issue. Separate Exec calls get distinct created_at values, so the last
- // inserted row is the "latest" task.
+ // insertLeaderTask seeds a same-squad task for the leader agent so the
+ // self-trigger guard can read the agent's most recent role on the issue.
+ // Separate Exec calls get distinct created_at values, so the last inserted
+ // row is the "latest" task.
insertLeaderTask := func(isLeader bool, status string) {
t.Helper()
var runtimeID string
@@ -254,9 +253,9 @@ func TestShouldEnqueueSquadLeaderOnComment_AgentAuthoredWorkerCommentsWakeLeader
t.Fatalf("load runtime: %v", err)
}
if _, err := testPool.Exec(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task)
- VALUES ($1, $2, $3, $4, $5)
- `, fx.LeaderID, runtimeID, issueID, status, isLeader); err != nil {
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, squad_id)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ `, fx.LeaderID, runtimeID, issueID, status, isLeader, fx.SquadID); err != nil {
t.Fatalf("insert task: %v", err)
}
}
@@ -411,10 +410,10 @@ func TestCreateComment_DualRoleAgentWorkerCommentWakesLeader(t *testing.T) {
testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)
})
- // Seed a worker task for the leader agent on this issue so the guard
- // infers "agent's last activity was a worker task" — i.e. L is running
- // in its worker role when it posts the comment. We make it running (not
- // completed) so we can hand its ID back through X-Task-ID for the
+ // Seed a same-squad worker task for the leader agent on this issue so the
+ // guard infers "agent's last activity was a worker task" — i.e. L is
+ // running in its worker role when it posts the comment. We make it running
+ // (not completed) so we can hand its ID back through X-Task-ID for the
// resolveActor agent-identity check.
var runtimeID string
if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, fx.LeaderID).Scan(&runtimeID); err != nil {
@@ -422,10 +421,10 @@ func TestCreateComment_DualRoleAgentWorkerCommentWakesLeader(t *testing.T) {
}
var workerTaskID string
if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task)
- VALUES ($1, $2, $3, 'running', FALSE)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, squad_id)
+ VALUES ($1, $2, $3, 'running', FALSE, $4)
RETURNING id
- `, fx.LeaderID, runtimeID, issueID).Scan(&workerTaskID); err != nil {
+ `, fx.LeaderID, runtimeID, issueID, fx.SquadID).Scan(&workerTaskID); err != nil {
t.Fatalf("seed worker task: %v", err)
}
@@ -456,6 +455,206 @@ 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 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) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fx := newSquadCommentTriggerFixture(t)
+ issueID := uuidToString(fx.Issue.ID)
+
+ t.Cleanup(func() {
+ 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)
+ })
+
+ postMemberComment := func(body map[string]any) CommentResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", body)
+ r = withURLParam(r, "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment(member): expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CommentResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode member comment: %v", err)
+ }
+ return resp
+ }
+ postAgentComment := func(taskID string, body map[string]any) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", body)
+ r.Header.Set("X-Agent-ID", fx.LeaderID)
+ r.Header.Set("X-Task-ID", taskID)
+ r = withURLParam(r, "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment(agent): expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ }
+ countQueuedLeaderTasks := func() int {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued' AND is_leader_task = TRUE
+ `, issueID, fx.LeaderID).Scan(&n); err != nil {
+ t.Fatalf("count queued leader tasks: %v", err)
+ }
+ return n
+ }
+
+ trigger := postMemberComment(map[string]any{
+ "content": "[@Leader](mention://agent/" + fx.LeaderID + ") can you check this?",
+ })
+
+ 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)
+ }
+
+ postAgentComment(mentionTaskID, map[string]any{
+ "content": "checked, no action needed",
+ "parent_id": trigger.ID,
+ })
+
+ if got := countQueuedLeaderTasks(); got != 0 {
+ t.Fatalf("leader reply from generic mention task queued %d leader tasks, want 0", got)
+ }
+}
+
+// TestCreateComment_SquadLeaderThreadParentTaskDoesNotSelfTriggerAssignedFallback
+// pins MUL-4024's thread-parent gap: a member reply to the leader's earlier
+// comment queues L through EnqueueTaskForThreadParent (is_leader_task=false,
+// squad_id=NULL). L's reply from that generic task must not queue L again as
+// the assigned squad leader.
+func TestCreateComment_SquadLeaderThreadParentTaskDoesNotSelfTriggerAssignedFallback(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fx := newSquadCommentTriggerFixture(t)
+ issueID := uuidToString(fx.Issue.ID)
+
+ t.Cleanup(func() {
+ 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)
+ })
+
+ 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 leaderTaskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, squad_id)
+ VALUES ($1, $2, $3, 'running', TRUE, $4)
+ RETURNING id
+ `, fx.LeaderID, leaderRuntimeID, issueID, fx.SquadID).Scan(&leaderTaskID); err != nil {
+ t.Fatalf("seed leader task: %v", err)
+ }
+
+ postAgentComment := func(taskID string, body map[string]any) CommentResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", body)
+ r.Header.Set("X-Agent-ID", fx.LeaderID)
+ r.Header.Set("X-Task-ID", taskID)
+ r = withURLParam(r, "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment(agent): expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CommentResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode agent comment: %v", err)
+ }
+ return resp
+ }
+ postMemberComment := func(body map[string]any) CommentResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", body)
+ r = withURLParam(r, "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment(member): expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CommentResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode member comment: %v", err)
+ }
+ return resp
+ }
+ countQueuedLeaderTasks := func() int {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued' AND is_leader_task = TRUE
+ `, issueID, fx.LeaderID).Scan(&n); err != nil {
+ t.Fatalf("count queued leader tasks: %v", err)
+ }
+ return n
+ }
+
+ parent := postAgentComment(leaderTaskID, map[string]any{
+ "content": "coordinating this issue",
+ })
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed' WHERE id = $1`, leaderTaskID); err != nil {
+ t.Fatalf("complete leader task: %v", err)
+ }
+
+ trigger := postMemberComment(map[string]any{
+ "content": "any update?",
+ "parent_id": parent.ID,
+ })
+
+ var threadParentTaskID 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(&threadParentTaskID); err != nil {
+ t.Fatalf("load leader thread-parent task: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running' WHERE id = $1`, threadParentTaskID); err != nil {
+ t.Fatalf("mark thread-parent task running: %v", err)
+ }
+
+ postAgentComment(threadParentTaskID, map[string]any{
+ "content": "replying from the thread-parent task",
+ "parent_id": trigger.ID,
+ })
+
+ if got := countQueuedLeaderTasks(); got != 0 {
+ t.Fatalf("leader reply from generic thread-parent task queued %d leader tasks, want 0", got)
+ }
+}
+
// TestCreateRetryTask_InheritsIsLeaderTask locks the retry-clone contract for
// MUL-2218: auto-retry of a leader-role task must produce a child task that is
// also is_leader_task=true. Without this, MaybeRetryFailedTask silently
diff --git a/server/internal/handler/squad_worker_comment_wakes_leader_test.go b/server/internal/handler/squad_worker_comment_wakes_leader_test.go
index f697c91e65..5b2d7347c4 100644
--- a/server/internal/handler/squad_worker_comment_wakes_leader_test.go
+++ b/server/internal/handler/squad_worker_comment_wakes_leader_test.go
@@ -57,9 +57,9 @@ func TestCreateComment_WorkerAgentCommentWakesSquadLeader_MUL4015(t *testing.T)
t.Fatalf("seed worker task: %v", err)
}
- // Seed a completed leader task for L so lastTaskWasLeader would return
- // true if the guard triggered by author-id was flipped in the wrong
- // direction. The completed status keeps it out of the pending-task dedup.
+ // Seed a completed leader task for L so the self-trigger guard would
+ // suppress if it were keyed only on the leader's own history. The completed
+ // status keeps it out of the pending-task dedup.
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)
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index be529b7b42..c84f9c7828 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -2139,29 +2139,32 @@ func (q *Queries) GetLastTaskStartedAtForIssueAndAgent(ctx context.Context, arg
return started_at, err
}
-const getLatestTaskIsLeaderForIssueAndAgent = `-- name: GetLatestTaskIsLeaderForIssueAndAgent :one
-SELECT is_leader_task FROM agent_task_queue
+const getLatestTaskRoleForIssueAndAgent = `-- name: GetLatestTaskRoleForIssueAndAgent :one
+SELECT is_leader_task, squad_id FROM agent_task_queue
WHERE issue_id = $1 AND agent_id = $2
ORDER BY created_at DESC
LIMIT 1
`
-type GetLatestTaskIsLeaderForIssueAndAgentParams struct {
+type GetLatestTaskRoleForIssueAndAgentParams struct {
IssueID pgtype.UUID `json:"issue_id"`
AgentID pgtype.UUID `json:"agent_id"`
}
-// Returns the is_leader_task flag of the agent's most recent task on this
-// issue, or NULL if the agent has never had a task on this issue. Used by
-// the squad-leader self-trigger guard to tell whether the agent's last
-// activity on the issue was in the leader role or the worker role (an
-// agent that holds both roles in a squad would otherwise be skipped by
-// the role-blind authorID == leaderID check).
-func (q *Queries) GetLatestTaskIsLeaderForIssueAndAgent(ctx context.Context, arg GetLatestTaskIsLeaderForIssueAndAgentParams) (bool, error) {
- row := q.db.QueryRow(ctx, getLatestTaskIsLeaderForIssueAndAgent, arg.IssueID, arg.AgentID)
- var is_leader_task bool
- err := row.Scan(&is_leader_task)
- return is_leader_task, err
+type GetLatestTaskRoleForIssueAndAgentRow struct {
+ IsLeaderTask bool `json:"is_leader_task"`
+ SquadID pgtype.UUID `json:"squad_id"`
+}
+
+// Returns the role markers from the agent's most recent task on this issue.
+// Used by the squad-leader self-trigger guard to tell apart leader tasks,
+// same-squad worker tasks, and generic agent tasks such as direct mentions or
+// thread-parent replies.
+func (q *Queries) GetLatestTaskRoleForIssueAndAgent(ctx context.Context, arg GetLatestTaskRoleForIssueAndAgentParams) (GetLatestTaskRoleForIssueAndAgentRow, error) {
+ row := q.db.QueryRow(ctx, getLatestTaskRoleForIssueAndAgent, arg.IssueID, arg.AgentID)
+ var i GetLatestTaskRoleForIssueAndAgentRow
+ err := row.Scan(&i.IsLeaderTask, &i.SquadID)
+ return i, err
}
const getWorkspaceAgentActivity30d = `-- name: GetWorkspaceAgentActivity30d :many
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 0b4717444e..07c998ba1f 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -695,14 +695,12 @@ WHERE issue_id = @issue_id
OR context->>'head_sha' = sqlc.narg('head_sha')::text
);
--- name: GetLatestTaskIsLeaderForIssueAndAgent :one
--- Returns the is_leader_task flag of the agent's most recent task on this
--- issue, or NULL if the agent has never had a task on this issue. Used by
--- the squad-leader self-trigger guard to tell whether the agent's last
--- activity on the issue was in the leader role or the worker role (an
--- agent that holds both roles in a squad would otherwise be skipped by
--- the role-blind authorID == leaderID check).
-SELECT is_leader_task FROM agent_task_queue
+-- name: GetLatestTaskRoleForIssueAndAgent :one
+-- Returns the role markers from the agent's most recent task on this issue.
+-- Used by the squad-leader self-trigger guard to tell apart leader tasks,
+-- same-squad worker tasks, and generic agent tasks such as direct mentions or
+-- thread-parent replies.
+SELECT is_leader_task, squad_id FROM agent_task_queue
WHERE issue_id = $1 AND agent_id = $2
ORDER BY created_at DESC
LIMIT 1;