Skip to content

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

Go

fix(squad): wake leader when dual-role agent posts as worker (MUL-2218) (#2626)

Jiayuan Zhang4d6b5ad06f12
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index ed7b9e628d..f1b360cec9 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -451,8 +451,12 @@ func (h *Handler) enqueueMentionedAgentTasks(ctx context.Context, issue db.Issue
continue
}
leaderID := squad.LeaderID
- // Prevent self-trigger: skip if the comment author is the leader.
- if authorType == "agent" && authorID == uuidToString(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.
+ if authorType == "agent" && authorID == uuidToString(leaderID) &&
+ h.lastTaskWasLeader(ctx, issue.ID, leaderID) {
continue
}
// Verify leader agent is ready (has runtime, not archived).
@@ -475,7 +479,7 @@ func (h *Handler) enqueueMentionedAgentTasks(ctx context.Context, issue db.Issue
if err != nil || hasPending {
continue
}
- if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, leaderID, comment.ID); err != nil {
+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, leaderID, comment.ID); err != nil {
slog.Warn("enqueue squad leader mention task failed", "issue_id", uuidToString(issue.ID), "squad_id", m.ID, "error", err)
}
continue
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index f3a481f6e7..b2abdb7c30 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -622,10 +622,14 @@ func (h *Handler) shouldEnqueueSquadLeaderOnComment(ctx context.Context, issue d
return false
}
- // Skip if the comment author is the squad leader itself (prevent self-trigger).
- // Other squad members ARE allowed to trigger the leader — the leader uses
- // silent/no-op turns when no action is needed.
- if authorType == "agent" && authorID == uuidToString(squad.LeaderID) {
+ // Skip if the comment author is the squad leader itself AND the agent's
+ // last activity on this issue was in the leader role (prevent self-trigger
+ // loop). An agent that is simultaneously the squad's leader and one of its
+ // workers must still wake the leader role after posting a comment from
+ // its worker task — role is inferred from the agent's most recent task
+ // on the issue, not from author ID alone.
+ if authorType == "agent" && authorID == uuidToString(squad.LeaderID) &&
+ h.lastTaskWasLeader(ctx, issue.ID, squad.LeaderID) {
return false
}
@@ -647,6 +651,24 @@ func (h *Handler) shouldEnqueueSquadLeaderOnComment(ctx context.Context, issue d
return true
}
+// 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{
+ IssueID: issueID,
+ AgentID: agentID,
+ })
+ if err != nil {
+ return false
+ }
+ return flag
+}
+
// commentMentionsAnyone returns true when the comment body contains at least
// one routing-style mention — [@Name](mention://agent|member|squad|all/<id>).
// Issue cross-references (mention://issue/...) are ignored because they are
@@ -713,7 +735,7 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, tr
return
}
- if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, squad.LeaderID, triggerCommentID); err != nil {
+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, squad.LeaderID, triggerCommentID); err != nil {
slog.Warn("enqueue squad leader task failed",
"issue_id", uuidToString(issue.ID),
"squad_id", uuidToString(squad.ID),
diff --git a/server/internal/handler/squad_comment_trigger_test.go b/server/internal/handler/squad_comment_trigger_test.go
index 852ba7141f..99b4a5cc5b 100644
--- a/server/internal/handler/squad_comment_trigger_test.go
+++ b/server/internal/handler/squad_comment_trigger_test.go
@@ -189,14 +189,6 @@ func TestShouldEnqueueSquadLeaderOnComment_SkipsWhenMemberMentionsAnyone(t *test
want: true,
description: "agent-authored replies always reach leader so it can coordinate next step",
},
- {
- name: "leader self-comment does NOT re-trigger leader",
- content: "noted",
- authorType: "agent",
- authorID: fx.LeaderID,
- want: false,
- description: "existing self-trigger guard must still hold",
- },
}
for _, tc := range cases {
@@ -210,6 +202,76 @@ func TestShouldEnqueueSquadLeaderOnComment_SkipsWhenMemberMentionsAnyone(t *test
}
}
+// TestShouldEnqueueSquadLeaderOnComment_LeaderSelfTriggerByRole covers the
+// role-aware self-trigger guard added for MUL-2218. The leader agent itself
+// should be skipped only when its last activity on the issue was a leader
+// task — never just because the comment author equals the leader ID. This
+// matters for dual-role agents (leader + worker of the same squad): a
+// comment posted from the worker task must still wake the leader.
+func TestShouldEnqueueSquadLeaderOnComment_LeaderSelfTriggerByRole(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fx := newSquadCommentTriggerFixture(t)
+ ctx := context.Background()
+ issueID := uuidToString(fx.Issue.ID)
+
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ clearTasks := func() {
+ if _, err := testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID); err != nil {
+ t.Fatalf("clear tasks: %v", err)
+ }
+ }
+ insertTask := func(isLeader bool, status string) {
+ t.Helper()
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, fx.LeaderID).Scan(&runtimeID); err != nil {
+ 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 {
+ t.Fatalf("insert task: %v", err)
+ }
+ }
+
+ t.Run("no prior task wakes leader (fresh external trigger)", func(t *testing.T) {
+ clearTasks()
+ if got := testHandler.shouldEnqueueSquadLeaderOnComment(ctx, fx.Issue, "noted", "agent", fx.LeaderID); !got {
+ t.Fatalf("no prior task: expected leader to be enqueued, got skip")
+ }
+ })
+
+ t.Run("prior leader task suppresses self-trigger", func(t *testing.T) {
+ clearTasks()
+ insertTask(true, "completed")
+ if got := testHandler.shouldEnqueueSquadLeaderOnComment(ctx, fx.Issue, "noted", "agent", fx.LeaderID); got {
+ t.Fatalf("after leader task: expected skip (anti-loop), got enqueue")
+ }
+ })
+
+ t.Run("prior worker task still wakes leader (dual-role agent)", func(t *testing.T) {
+ clearTasks()
+ insertTask(false, "completed")
+ if got := testHandler.shouldEnqueueSquadLeaderOnComment(ctx, fx.Issue, "result", "agent", fx.LeaderID); !got {
+ t.Fatalf("after worker task: expected leader to be enqueued (MUL-2218), got skip")
+ }
+ })
+
+ t.Run("most recent task is the one that matters", func(t *testing.T) {
+ clearTasks()
+ insertTask(true, "completed") // older leader task
+ insertTask(false, "completed") // newer worker task
+ if got := testHandler.shouldEnqueueSquadLeaderOnComment(ctx, fx.Issue, "result", "agent", fx.LeaderID); !got {
+ t.Fatalf("latest task is worker: expected leader to be enqueued, got skip")
+ }
+ })
+}
+
// TestCreateComment_SquadLeaderSkipOnlyInspectsCurrentMention drives the
// full CreateComment handler to lock the call-site wiring (comment.go) for
// the squad-leader-skip rule. Specifically it proves that:
@@ -287,6 +349,131 @@ func TestCreateComment_SquadLeaderSkipOnlyInspectsCurrentMention(t *testing.T) {
}
}
+// TestCreateComment_DualRoleAgentWorkerCommentWakesLeader is the full-stack
+// regression test for MUL-2218. Scenario:
+//
+// - Agent L is the leader of squad S and also a worker assigned tasks on
+// issues belonging to S.
+// - L is woken in its worker role (is_leader_task=false) and posts a comment.
+// - The squad-leader self-trigger guard MUST still wake L in its leader role
+// so it can react to the worker output (e.g. delegate the next step).
+//
+// Before the fix the role-blind authorID == leaderID check skipped the
+// leader, leaving the issue stalled.
+func TestCreateComment_DualRoleAgentWorkerCommentWakesLeader(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)
+ })
+
+ // 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
+ // 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 {
+ t.Fatalf("load runtime: %v", err)
+ }
+ 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)
+ RETURNING id
+ `, fx.LeaderID, runtimeID, issueID).Scan(&workerTaskID); err != nil {
+ t.Fatalf("seed worker task: %v", err)
+ }
+
+ // L posts a comment in its agent identity (X-Agent-ID + X-Task-ID, the
+ // pair required by resolveActor to trust the agent header).
+ w := httptest.NewRecorder()
+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{
+ "content": "done — pushed the change",
+ })
+ r.Header.Set("X-Agent-ID", fx.LeaderID)
+ r.Header.Set("X-Task-ID", workerTaskID)
+ r = withURLParam(r, "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // A NEW leader-role task must be enqueued for L on this issue so the
+ // leader role can react to its own worker output.
+ var leaderTasks 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(&leaderTasks); err != nil {
+ t.Fatalf("count leader tasks: %v", err)
+ }
+ if leaderTasks != 1 {
+ t.Fatalf("after worker comment from dual-role agent: expected 1 queued leader task, got %d", leaderTasks)
+ }
+}
+
+// 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
+// demotes a retried leader task to a worker task, and the self-trigger guard
+// in shouldEnqueueSquadLeaderOnComment / comment.go stops recognising the
+// retried leader's own comments — re-opening the bug this issue fixes.
+func TestCreateRetryTask_InheritsIsLeaderTask(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)
+ })
+
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, fx.LeaderID).Scan(&runtimeID); err != nil {
+ t.Fatalf("load runtime: %v", err)
+ }
+
+ cases := []struct {
+ name string
+ isLeader bool
+ }{
+ {name: "leader task retry stays leader", isLeader: true},
+ {name: "worker task retry stays worker", isLeader: false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ var parentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, attempt, max_attempts, is_leader_task)
+ VALUES ($1, $2, $3, 'failed', 1, 3, $4)
+ RETURNING id
+ `, fx.LeaderID, runtimeID, issueID, tc.isLeader).Scan(&parentID); err != nil {
+ t.Fatalf("seed parent task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1 OR parent_task_id = $1`, parentID)
+ })
+
+ child, err := testHandler.Queries.CreateRetryTask(ctx, util.MustParseUUID(parentID))
+ if err != nil {
+ t.Fatalf("CreateRetryTask: %v", err)
+ }
+ if child.IsLeaderTask != tc.isLeader {
+ t.Fatalf("child.IsLeaderTask = %v, want %v (parent role must be inherited)", child.IsLeaderTask, tc.isLeader)
+ }
+ })
+ }
+}
+
// TestCreateComment_SquadMentionPrivateLeaderBlocksPlainMember verifies that
// a plain workspace member cannot trigger a private squad leader via @squad
// mention. This is the regression test for the P1 finding: without the
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 839cb45564..7aa9e0983a 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -441,6 +441,20 @@ func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, trig
// Unlike EnqueueTaskForIssue, this takes an explicit agent ID rather than
// deriving it from the issue assignee.
func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {
+ return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false)
+}
+
+// EnqueueTaskForSquadLeader is the leader-role variant of EnqueueTaskForMention.
+// The resulting task carries is_leader_task=true so that downstream
+// self-trigger guards can distinguish a comment posted while the agent was
+// acting as the squad's leader (skip) from one posted while it was acting
+// as a worker (do not skip). This matters for agents that are simultaneously
+// the leader and a worker of the same squad — see migration 090.
+func (s *TaskService) EnqueueTaskForSquadLeader(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {
+ return s.enqueueMentionTask(ctx, issue, leaderID, triggerCommentID, true)
+}
+
+func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool) (db.AgentTaskQueue, error) {
agent, err := s.Queries.GetAgent(ctx, agentID)
if err != nil {
slog.Error("mention task enqueue failed: agent not found", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)
@@ -462,13 +476,14 @@ func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue,
Priority: priorityToInt(issue.Priority),
TriggerCommentID: triggerCommentID,
TriggerSummary: s.buildCommentTriggerSummary(ctx, triggerCommentID),
+ IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},
})
if err != nil {
slog.Error("mention task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)
return db.AgentTaskQueue{}, fmt.Errorf("create task: %w", err)
}
- slog.Info("mention task enqueued", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))
+ slog.Info("mention task enqueued", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "is_leader_task", isLeader)
// See EnqueueTaskForIssue for ordering rationale.
s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
s.NotifyTaskEnqueued(ctx, task)
@@ -1355,12 +1370,13 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, trigg
// enqueueRerunTask enqueues a fresh task for the given agent on the issue.
// For agent-assigned issues it uses enqueueIssueTask (which reads AssigneeID);
-// for squad-assigned issues it uses EnqueueTaskForMention with the leader ID.
+// for squad-assigned issues the rerun targets the squad leader and is flagged
+// as a leader task so the self-trigger guard treats it correctly.
func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {
if issue.AssigneeType.String == "agent" {
return s.enqueueIssueTask(ctx, issue, triggerCommentID, true)
}
- return s.EnqueueTaskForMention(ctx, issue, agentID, triggerCommentID)
+ return s.EnqueueTaskForSquadLeader(ctx, issue, agentID, triggerCommentID)
}
// HandleFailedTasks runs the post-failure side effects for a batch of
diff --git a/server/migrations/090_task_is_leader.down.sql b/server/migrations/090_task_is_leader.down.sql
new file mode 100644
index 0000000000..e6eaa2f7f7
--- /dev/null
+++ b/server/migrations/090_task_is_leader.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_task_queue
+ DROP COLUMN is_leader_task;
diff --git a/server/migrations/090_task_is_leader.up.sql b/server/migrations/090_task_is_leader.up.sql
new file mode 100644
index 0000000000..5d840a54bb
--- /dev/null
+++ b/server/migrations/090_task_is_leader.up.sql
@@ -0,0 +1,9 @@
+-- agent_task_queue.is_leader_task marks a task as enqueued in the squad-leader
+-- role. The squad-leader self-trigger guard previously skipped a comment
+-- whenever its author equalled `squad.LeaderID`, which mis-fired for an agent
+-- that is simultaneously a leader and a worker of the same squad: a comment
+-- posted by the agent in its worker role never woke its leader role. The
+-- guard now consults the agent's most recent task on the issue and skips
+-- only when that task was itself a leader task.
+ALTER TABLE agent_task_queue
+ ADD COLUMN is_leader_task BOOLEAN NOT NULL DEFAULT FALSE;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 9240521305..af96545a81 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -113,7 +113,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running')
-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
+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
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -144,6 +144,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
@@ -152,7 +153,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running')
-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
+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
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -194,6 +195,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -209,7 +211,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running')
-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
+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
`
// Cancels active tasks belonging to a chat session. Called from
@@ -251,6 +253,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -266,7 +269,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running')
-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
+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
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -308,6 +311,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -323,7 +327,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgen
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running')
-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
+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
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -369,6 +373,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -384,7 +389,7 @@ const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerComm
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running')
-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
+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
`
// Cancels active tasks whose trigger is the given comment. Called when a
@@ -426,6 +431,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -464,7 +470,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-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
+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
`
// Claims the next queued task for an agent, enforcing per-(issue, agent) serialization:
@@ -504,6 +510,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (Agen
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
@@ -547,7 +554,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :one
UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4
WHERE id = $1 AND status = 'running'
-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
+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
`
type CompleteAgentTaskParams struct {
@@ -590,6 +597,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
@@ -681,14 +689,15 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent
const createAgentTask = `-- name: CreateAgentTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
- trigger_summary, force_fresh_session
+ trigger_summary, force_fresh_session, is_leader_task
)
VALUES (
$1, $2, $3, 'queued', $4, $5,
$6,
- COALESCE($7::boolean, FALSE)
+ COALESCE($7::boolean, FALSE),
+ COALESCE($8::boolean, FALSE)
)
-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
+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
`
type CreateAgentTaskParams struct {
@@ -699,6 +708,7 @@ type CreateAgentTaskParams struct {
TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
TriggerSummary pgtype.Text `json:"trigger_summary"`
ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
+ IsLeaderTask pgtype.Bool `json:"is_leader_task"`
}
func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams) (AgentTaskQueue, error) {
@@ -710,6 +720,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
arg.TriggerCommentID,
arg.TriggerSummary,
arg.ForceFreshSession,
+ arg.IsLeaderTask,
)
var i AgentTaskQueue
err := row.Scan(
@@ -737,6 +748,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
@@ -744,7 +756,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
const createQuickCreateTask = `-- name: CreateQuickCreateTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, context)
VALUES ($1, $2, NULL, 'queued', $3, $4)
-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
+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
`
type CreateQuickCreateTaskParams struct {
@@ -790,6 +802,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
@@ -799,22 +812,25 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
status, priority, trigger_comment_id, trigger_summary, context,
session_id, work_dir,
- attempt, max_attempts, parent_task_id
+ attempt, max_attempts, parent_task_id, is_leader_task
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
'queued', p.priority, p.trigger_comment_id, p.trigger_summary, p.context,
p.session_id, p.work_dir,
- p.attempt + 1, p.max_attempts, p.id
+ p.attempt + 1, p.max_attempts, p.id, p.is_leader_task
FROM agent_task_queue p
WHERE p.id = $1
-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
+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
`
// Clones a parent task into a fresh queued attempt. Carries forward the
// agent's resume context (session_id/work_dir) so the child can continue
// the conversation when the backend supports it. attempt is incremented;
-// max_attempts and trigger_comment_id are inherited.
+// max_attempts, trigger_comment_id, and is_leader_task are inherited so
+// the retried task keeps the same squad-role provenance as its parent and
+// the self-trigger guard in shouldEnqueueSquadLeaderOnComment continues to
+// recognise it as a leader task.
func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, createRetryTask, id)
var i AgentTaskQueue
@@ -843,6 +859,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
@@ -865,7 +882,7 @@ FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
AND t.created_at < now() - make_interval(secs => $1::double precision)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task
`
type ExpireStaleQueuedTasksParams struct {
@@ -930,6 +947,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -950,7 +968,7 @@ SET status = 'failed',
session_id = COALESCE($4, session_id),
work_dir = COALESCE($5, work_dir)
WHERE id = $1 AND status IN ('dispatched', 'running')
-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
+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
`
type FailAgentTaskParams struct {
@@ -1004,6 +1022,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
@@ -1014,7 +1033,7 @@ SET status = 'failed', completed_at = now(), error = 'task timed out',
failure_reason = 'timeout'
WHERE (status = 'dispatched' AND dispatched_at < now() - make_interval(secs => $1::double precision))
OR (status = 'running' AND started_at < now() - make_interval(secs => $2::double precision))
-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
+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
`
type FailStaleTasksParams struct {
@@ -1059,6 +1078,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -1144,7 +1164,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE id = $1
`
@@ -1176,6 +1196,7 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
@@ -1244,6 +1265,31 @@ func (q *Queries) GetLastTaskSession(ctx context.Context, arg GetLastTaskSession
return i, err
}
+const getLatestTaskIsLeaderForIssueAndAgent = `-- name: GetLatestTaskIsLeaderForIssueAndAgent :one
+SELECT is_leader_task FROM agent_task_queue
+WHERE issue_id = $1 AND agent_id = $2
+ORDER BY created_at DESC
+LIMIT 1
+`
+
+type GetLatestTaskIsLeaderForIssueAndAgentParams 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
+}
+
const getWorkspaceAgentActivity30d = `-- name: GetWorkspaceAgentActivity30d :many
SELECT
atq.agent_id,
@@ -1415,7 +1461,7 @@ func (q *Queries) LinkTaskToIssue(ctx context.Context, arg LinkTaskToIssueParams
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running')
ORDER BY created_at DESC
`
@@ -1459,6 +1505,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -1471,7 +1518,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -1510,6 +1557,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -1618,7 +1666,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -1657,6 +1705,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -1669,7 +1718,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -1716,6 +1765,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -1728,7 +1778,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT 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 FROM agent_task_queue
+SELECT 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 FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -1767,6 +1817,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -1779,15 +1830,15 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running')
UNION ALL
-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session FROM (
- SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session
+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task FROM (
+ SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
@@ -1848,6 +1899,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -1866,7 +1918,7 @@ SET status = 'failed',
error = 'daemon restarted while task was in flight',
failure_reason = 'runtime_recovery'
WHERE runtime_id = $1 AND status IN ('dispatched', 'running')
-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
+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
`
// Called by the daemon at startup. Atomically fails any dispatched/running
@@ -1907,6 +1959,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -1997,7 +2050,7 @@ const startAgentTask = `-- name: StartAgentTask :one
UPDATE agent_task_queue
SET status = 'running', started_at = now()
WHERE id = $1 AND status = 'dispatched'
-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
+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
`
func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -2028,6 +2081,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 8be3aeaae8..01e4ff491c 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -204,7 +204,7 @@ const createAutopilotTask = `-- name: CreateAutopilotTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)
VALUES ($1, $2, NULL, 'queued', $3, $4, $5)
-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
+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
`
type CreateAutopilotTaskParams struct {
@@ -252,6 +252,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index bfc5539a72..e8250e07ed 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -90,7 +90,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
const createChatTask = `-- name: CreateChatTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id)
VALUES ($1, $2, NULL, 'queued', $3, $4)
-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
+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
`
type CreateChatTaskParams struct {
@@ -133,6 +133,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 932139ae69..f5de7faf62 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -94,6 +94,7 @@ type AgentTaskQueue struct {
FailureReason pgtype.Text `json:"failure_reason"`
TriggerSummary pgtype.Text `json:"trigger_summary"`
ForceFreshSession bool `json:"force_fresh_session"`
+ IsLeaderTask bool `json:"is_leader_task"`
}
type Attachment struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 14b063bf00..5a22e281c4 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running')
-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
+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
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -72,6 +72,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
@@ -186,7 +187,7 @@ WHERE status IN ('dispatched', 'running')
AND runtime_id IN (
SELECT id FROM agent_runtime WHERE status = 'offline'
)
-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
+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
`
// Marks dispatched/running tasks as failed when their runtime is offline.
@@ -225,6 +226,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.FailureReason,
&i.TriggerSummary,
&i.ForceFreshSession,
+ &i.IsLeaderTask,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 188e2546df..e6ffede7f1 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -77,12 +77,13 @@ ORDER BY created_at DESC;
-- name: CreateAgentTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
- trigger_summary, force_fresh_session
+ trigger_summary, force_fresh_session, is_leader_task
)
VALUES (
$1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),
sqlc.narg(trigger_summary),
- COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE)
+ COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),
+ COALESCE(sqlc.narg('is_leader_task')::boolean, FALSE)
)
RETURNING *;
@@ -108,18 +109,21 @@ WHERE id = $1 AND issue_id IS NULL;
-- Clones a parent task into a fresh queued attempt. Carries forward the
-- agent's resume context (session_id/work_dir) so the child can continue
-- the conversation when the backend supports it. attempt is incremented;
--- max_attempts and trigger_comment_id are inherited.
+-- max_attempts, trigger_comment_id, and is_leader_task are inherited so
+-- the retried task keeps the same squad-role provenance as its parent and
+-- the self-trigger guard in shouldEnqueueSquadLeaderOnComment continues to
+-- recognise it as a leader task.
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
status, priority, trigger_comment_id, trigger_summary, context,
session_id, work_dir,
- attempt, max_attempts, parent_task_id
+ attempt, max_attempts, parent_task_id, is_leader_task
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
'queued', p.priority, p.trigger_comment_id, p.trigger_summary, p.context,
p.session_id, p.work_dir,
- p.attempt + 1, p.max_attempts, p.id
+ p.attempt + 1, p.max_attempts, p.id, p.is_leader_task
FROM agent_task_queue p
WHERE p.id = $1
RETURNING *;
@@ -401,6 +405,18 @@ WHERE issue_id = $1 AND status IN ('queued', 'dispatched');
SELECT count(*) > 0 AS has_pending FROM agent_task_queue
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched');
+-- 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
+WHERE issue_id = $1 AND agent_id = $2
+ORDER BY created_at DESC
+LIMIT 1;
+
-- name: ListPendingTasksByRuntime :many
SELECT * FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')