Skip to content

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

Go

fix(squad): inject leader briefing by task flag, not issue assignee (MUL-3730) (#4606)

LinYushen3692b6a86265
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 768fc03236..7b1d40b88a 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1325,7 +1325,7 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu
switch trigger.Source {
case commentTriggerSourceIssueAssignee:
if trigger.Squad != nil {
- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, triggerCommentID); err != nil {
+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {
slog.Warn("enqueue squad leader task failed",
"issue_id", uuidToString(issue.ID),
"squad_id", uuidToString(trigger.Squad.ID),
@@ -1338,7 +1338,7 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu
slog.Warn("enqueue agent task on comment failed", "issue_id", uuidToString(issue.ID), "error", err)
}
case commentTriggerSourceMentionSquadLeader:
- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, triggerCommentID); err != nil {
+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {
slog.Warn("enqueue squad leader mention task failed",
"issue_id", uuidToString(issue.ID),
"agent_id", uuidToString(trigger.Agent.ID),
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index cf66df2d9a..c7d47429f3 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1384,16 +1384,45 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
resp.WorkspaceID = uuidToString(issue.WorkspaceID)
resp.ThreadName = issue.Title
- // Squad-leader briefing injection: when the issue is assigned
- // to a squad and the claiming agent is that squad's current
- // leader, append a full briefing (Operating Protocol + Roster
- // + user Instructions) to the agent's own Instructions. We
- // append (not replace) so per-agent instructions remain
- // authoritative for general behavior; the squad briefing
+ // Squad-leader briefing injection: keyed off the task being a
+ // leader-task (is_leader_task) carrying a squad_id — NOT off the
+ // issue being assigned to a squad. The task flag is stamped at
+ // enqueue time and is true for every ISSUE-BOUND path that routes
+ // work to a squad leader: direct assign-to-squad, comment
+ // @squad-mention (even when the issue itself is assigned to a
+ // plain agent — the MUL-3724 case), sub-issue done callback,
+ // autopilot squad-assignee, and retry-clone inheritance. The old
+ // issue.AssigneeType=="squad" gate missed the comment-mention
+ // path, so the leader booted with zero squad context and
+ // degraded into doing the work itself instead of orchestrating.
+ //
+ // NOTE: quick-create tasks do NOT reach this block — they have a
+ // NULL issue_id (so the enclosing `task.IssueID.Valid` is false)
+ // and do NOT carry is_leader_task / squad_id columns. They route
+ // their squad through the task CONTEXT JSON (QuickCreateContext.
+ // SquadID) and get their briefing from the separate quick-create
+ // branch further below (search `qc.SquadID`). Do not "unify" the
+ // two by deleting that branch: it also sets resp.SquadID /
+ // resp.SquadName so the new issue defaults to the squad assignee,
+ // and there is no issue row to hang this column-based path on.
+ //
+ // We resolve the squad directly from task.SquadID rather than
+ // reverse-looking-up "which squad is this agent the leader of",
+ // which is ambiguous when one agent leads multiple squads. The
+ // uuidToString(squad.LeaderID) == resp.Agent.ID re-check is kept
+ // as a defensive gate: if the squad's leader was swapped after the
+ // task was enqueued, we never feed a stale briefing to a
+ // non-leader. It also doubles as the dangling-squad_id guard: a
+ // squad hard-deleted after enqueue makes GetSquadInWorkspace
+ // return no row (err != nil) — we skip injection silently, which
+ // is exactly the same observable result as "condition not
+ // matched". Claim still succeeds; no stale briefing is emitted.
+ // (No FK on squad_id — see migration 127.) We append (not replace)
+ // so per-agent instructions stay authoritative; the squad briefing
// stacks on top as task-specific squad context.
- if resp.Agent != nil && issue.AssigneeType.Valid && issue.AssigneeType.String == "squad" && issue.AssigneeID.Valid {
+ if resp.Agent != nil && task.IsLeaderTask && task.SquadID.Valid {
if squad, err := h.Queries.GetSquadInWorkspace(r.Context(), db.GetSquadInWorkspaceParams{
- ID: issue.AssigneeID,
+ ID: task.SquadID,
WorkspaceID: issue.WorkspaceID,
}); err == nil && uuidToString(squad.LeaderID) == resp.Agent.ID {
briefing := buildSquadLeaderBriefing(r.Context(), h.Queries, squad)
diff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.go
index 401fa1da08..2726c8e493 100644
--- a/server/internal/handler/issue_child_done.go
+++ b/server/internal/handler/issue_child_done.go
@@ -516,7 +516,7 @@ func (h *Handler) triggerChildDoneSquad(ctx context.Context, parent, child db.Is
return
}
- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, parent, squad.LeaderID, triggerCommentID); err != nil {
+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, parent, squad.LeaderID, squad.ID, triggerCommentID); err != nil {
slog.Warn("child done: enqueue parent squad leader task failed",
"error", err,
"parent_id", uuidToString(parent.ID),
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index 66671a159d..58443adca0 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -975,7 +975,7 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, tr
// triggerCommentID is always empty on the assign/promote path; the handoff
// note rides its own task column, never trigger_comment_id.
_ = triggerCommentID
- if _, err := h.TaskService.EnqueueTaskForSquadLeaderWithHandoff(ctx, issue, squad.LeaderID, handoffNote); err != nil {
+ if _, err := h.TaskService.EnqueueTaskForSquadLeaderWithHandoff(ctx, issue, squad.LeaderID, squad.ID, handoffNote); 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_briefing.go b/server/internal/handler/squad_briefing.go
index 3a2962da93..e40693e19f 100644
--- a/server/internal/handler/squad_briefing.go
+++ b/server/internal/handler/squad_briefing.go
@@ -19,8 +19,13 @@ import (
// through util.ParseMentions, and the protocol text refers to that format.
const squadOperatingProtocol = `## Squad Operating Protocol
-You are the LEADER of a squad. Your job is to **coordinate**, not to execute
-the work yourself.
+**If you are reading this section, you have been activated as a squad LEADER
+for this task — regardless of how the work reached you (direct assignment,
+an @squad mention in a comment, quick-create, or autopilot).** Your job is to
+**coordinate**, NOT to do the work yourself. Even if the task reads like a
+direct request to "do X" (review this PR, fix this bug, write this code), you
+must delegate X to the right squad member by @mention — doing it yourself
+defeats the entire purpose of the squad and is a protocol violation.
Your responsibilities, in order:
diff --git a/server/internal/handler/squad_briefing_claim_test.go b/server/internal/handler/squad_briefing_claim_test.go
new file mode 100644
index 0000000000..c7ccca2a83
--- /dev/null
+++ b/server/internal/handler/squad_briefing_claim_test.go
@@ -0,0 +1,216 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// claimAgentInstructionsForTest claims the next queued task for runtimeID and
+// returns the claimed task id plus the agent Instructions carried on the claim
+// response (the field the squad-leader briefing is injected into). Empty task
+// id means no task was claimed.
+func claimAgentInstructionsForTest(t *testing.T, runtimeID string) (taskID string, instructions string, raw string) {
+ t.Helper()
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "squad-briefing-claim")
+ req = withURLParam(req, "runtimeId", runtimeID)
+
+ testHandler.ClaimTaskByRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp struct {
+ Task *struct {
+ ID string `json:"id"`
+ Agent *struct {
+ Instructions string `json:"instructions"`
+ } `json:"agent"`
+ } `json:"task"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode claim response: %v", err)
+ }
+ if resp.Task == nil {
+ return "", "", w.Body.String()
+ }
+ var instr string
+ if resp.Task.Agent != nil {
+ instr = resp.Task.Agent.Instructions
+ }
+ return resp.Task.ID, instr, w.Body.String()
+}
+
+// squadBriefingClaimFixture wires a runtime + leader agent + squad and returns
+// the IDs needed to enqueue leader tasks against that runtime.
+type squadBriefingClaimFixture struct {
+ RuntimeID string
+ AgentID string // squad leader, has the runtime and empty instructions
+ SquadID string
+ IssueID string // assignee_type='agent' (NOT squad) — reproduces MUL-3724
+}
+
+func newSquadBriefingClaimFixture(t *testing.T, ctx context.Context, name string) squadBriefingClaimFixture {
+ t.Helper()
+
+ runtimeID := createClaimReclaimRuntime(t, ctx, name+" runtime")
+ // Leader agent + an issue assigned to that agent (assignee_type='agent').
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, name+" leader")
+ // Force empty instructions so the test asserts the briefing alone — this
+ // mirrors MUL-3724 where the leader's own instructions were blank.
+ if _, err := testPool.Exec(ctx, `UPDATE agent SET instructions = '' WHERE id = $1`, agentID); err != nil {
+ t.Fatalf("clear leader instructions: %v", err)
+ }
+ // Make the issue assignee an agent (NOT the squad). The pre-fix code only
+ // injected the briefing when issue.assignee_type='squad', so this is the
+ // exact gap the fix closes: a comment @squad-mention leader task running on
+ // an agent-assigned issue.
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, issueID, agentID); err != nil {
+ t.Fatalf("set issue agent assignee: %v", err)
+ }
+
+ var squadID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)
+ VALUES ($1, $2, '', $3, $4)
+ RETURNING id
+ `, testWorkspaceID, name+" squad", agentID, testUserID).Scan(&squadID); err != nil {
+ t.Fatalf("create squad: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID) })
+
+ return squadBriefingClaimFixture{
+ RuntimeID: runtimeID,
+ AgentID: agentID,
+ SquadID: squadID,
+ IssueID: issueID,
+ }
+}
+
+func enqueueClaimTask(t *testing.T, ctx context.Context, fx squadBriefingClaimFixture, isLeader bool, withSquadID bool) string {
+ t.Helper()
+ var taskID string
+ var squadArg any
+ if withSquadID {
+ squadArg = fx.SquadID
+ } else {
+ squadArg = nil
+ }
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, is_leader_task, squad_id)
+ VALUES ($1, $2, $3, 'queued', 0, $4, $5)
+ RETURNING id
+ `, fx.AgentID, fx.RuntimeID, fx.IssueID, isLeader, squadArg).Scan(&taskID); err != nil {
+ t.Fatalf("enqueue claim task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+ return taskID
+}
+
+// TestClaim_LeaderTaskFromCommentMention_InjectsBriefing is the MUL-3724
+// reproduction: a leader task (is_leader_task=true) carrying a squad_id, on an
+// issue assigned to a plain AGENT (not the squad). The pre-fix gate
+// (issue.assignee_type='squad') would NOT inject the briefing here, so the
+// leader booted with no squad context and degraded into doing the work itself.
+// After the fix the briefing is keyed off the task flag + squad_id, so it is
+// injected regardless of issue assignee.
+func TestClaim_LeaderTaskFromCommentMention_InjectsBriefing(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fx := newSquadBriefingClaimFixture(t, ctx, "Briefing inject")
+ want := enqueueClaimTask(t, ctx, fx, true /*isLeader*/, true /*withSquadID*/)
+
+ got, instr, raw := claimAgentInstructionsForTest(t, fx.RuntimeID)
+ if got != want {
+ t.Fatalf("claimed task id = %q, want %q: %s", got, want, raw)
+ }
+ if !strings.Contains(instr, "## Squad Operating Protocol") || !strings.Contains(instr, "## Squad Roster") {
+ t.Fatalf("expected squad-leader briefing in agent instructions, got:\n%s", instr)
+ }
+}
+
+// TestClaim_NonLeaderTask_NoBriefing guards the negative: a task that is NOT a
+// leader task (is_leader_task=false), even with a squad_id present, must not
+// receive the briefing. This keeps worker/mention runs free of leader framing.
+func TestClaim_NonLeaderTask_NoBriefing(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fx := newSquadBriefingClaimFixture(t, ctx, "Briefing nonleader")
+ enqueueClaimTask(t, ctx, fx, false /*isLeader*/, true /*withSquadID*/)
+
+ _, instr, _ := claimAgentInstructionsForTest(t, fx.RuntimeID)
+ if strings.Contains(instr, "## Squad Operating Protocol") || strings.Contains(instr, "## Squad Roster") {
+ t.Fatalf("non-leader task must NOT get squad briefing, got:\n%s", instr)
+ }
+}
+
+// TestClaim_LeaderTaskWithDanglingSquadID_NoBriefing is the load-bearing
+// contract for dropping the FK on agent_task_queue.squad_id (migration 127):
+// when a squad is hard-deleted AFTER a leader task was enqueued, the task row
+// keeps a now-dangling squad_id. The claim must still succeed (HTTP 200, task
+// delivered) and simply skip briefing injection — GetSquadInWorkspace returns
+// no row, so the err != nil guard makes this identical to "condition not
+// matched". Never a 500, never a stale/empty briefing. Without the FK nothing
+// in the DB prevents the dangling row, so this guard lives entirely in the
+// claim handler and must stay tested.
+func TestClaim_LeaderTaskWithDanglingSquadID_NoBriefing(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fx := newSquadBriefingClaimFixture(t, ctx, "Briefing dangling")
+ want := enqueueClaimTask(t, ctx, fx, true /*isLeader*/, true /*withSquadID*/)
+
+ // Hard-delete the squad AFTER enqueue, leaving task.squad_id dangling.
+ // There is no FK (migration 127), so the task row is untouched.
+ if _, err := testPool.Exec(ctx, `DELETE FROM squad WHERE id = $1`, fx.SquadID); err != nil {
+ t.Fatalf("delete squad: %v", err)
+ }
+ // Confirm the task still carries the (now orphaned) squad_id — i.e. the
+ // delete did not cascade/null it, which is the whole point of no-FK.
+ var stillSet bool
+ if err := testPool.QueryRow(ctx,
+ `SELECT squad_id = $2 FROM agent_task_queue WHERE id = $1`, want, fx.SquadID,
+ ).Scan(&stillSet); err != nil {
+ t.Fatalf("reload task squad_id: %v", err)
+ }
+ if !stillSet {
+ t.Fatalf("expected task.squad_id to remain the dangling UUID after squad delete (no FK)")
+ }
+
+ got, instr, raw := claimAgentInstructionsForTest(t, fx.RuntimeID)
+ if got != want {
+ t.Fatalf("claimed task id = %q, want %q (claim must still succeed 200): %s", got, want, raw)
+ }
+ if strings.Contains(instr, "## Squad Operating Protocol") || strings.Contains(instr, "## Squad Roster") {
+ t.Fatalf("dangling squad_id must NOT get squad briefing, got:\n%s", instr)
+ }
+}
+
+// leader tasks enqueued before migration 127 (or by an old binary) have a NULL
+// squad_id. The claim handler must skip injection rather than panic or guess —
+// equivalent to the pre-fix "condition not matched" behavior, never a stale
+// briefing.
+func TestClaim_LeaderTaskWithoutSquadID_NoBriefing(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fx := newSquadBriefingClaimFixture(t, ctx, "Briefing nullsquad")
+ enqueueClaimTask(t, ctx, fx, true /*isLeader*/, false /*withSquadID*/)
+
+ _, instr, _ := claimAgentInstructionsForTest(t, fx.RuntimeID)
+ if strings.Contains(instr, "## Squad Operating Protocol") || strings.Contains(instr, "## Squad Roster") {
+ t.Fatalf("leader task with NULL squad_id must NOT get squad briefing, got:\n%s", instr)
+ }
+}
diff --git a/server/internal/handler/squad_briefing_test.go b/server/internal/handler/squad_briefing_test.go
index e8a8e9fa6e..903d11fbf0 100644
--- a/server/internal/handler/squad_briefing_test.go
+++ b/server/internal/handler/squad_briefing_test.go
@@ -330,10 +330,12 @@ RETURNING id
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
if err := testPool.QueryRow(ctx, `
-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)
-VALUES ($1, $2, $3, 'queued', 0)
+INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, is_leader_task, squad_id)
+VALUES ($1, $2, $3, 'queued', 0,
+ ($1::uuid = (SELECT leader_id FROM squad WHERE id = $4::uuid)),
+ $4::uuid)
RETURNING id
-`, agentID, runtimeID, issueID).Scan(&taskID); err != nil {
+`, agentID, runtimeID, issueID, squadID).Scan(&taskID); err != nil {
t.Fatalf("queue task: %v", err)
}
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
diff --git a/server/internal/handler/squad_id_enqueue_test.go b/server/internal/handler/squad_id_enqueue_test.go
new file mode 100644
index 0000000000..057dbfa5d0
--- /dev/null
+++ b/server/internal/handler/squad_id_enqueue_test.go
@@ -0,0 +1,129 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// TestCreateComment_SquadMentionStampsSquadIDOnLeaderTask locks the enqueue
+// side of the MUL-3730 fix: when a comment @mentions a squad, the leader task
+// it enqueues must carry squad_id on the task row, so the daemon claim handler
+// can locate the squad and inject the briefing (keyed off is_leader_task +
+// squad_id, not issue assignee). The issue here is NOT assigned to the squad —
+// exactly the comment-mention path that the old issue-assignee gate missed.
+func TestCreateComment_SquadMentionStampsSquadIDOnLeaderTask(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var leaderID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id FROM agent WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1
+ `, testWorkspaceID).Scan(&leaderID); err != nil {
+ t.Fatalf("load leader agent: %v", err)
+ }
+
+ var squadID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)
+ VALUES ($1, 'Squad ID Stamp Squad', '', $2, $3)
+ RETURNING id
+ `, testWorkspaceID, leaderID, testUserID).Scan(&squadID); err != nil {
+ t.Fatalf("create squad: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID) })
+
+ // Issue assigned to nobody (definitely not the squad) — the leader task is
+ // produced purely by the @squad comment mention.
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, creator_type, creator_id, title)
+ VALUES ($1, 'member', $2, 'squad_id stamp test')
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ 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)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ w := httptest.NewRecorder()
+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{
+ "content": "[@Squad](mention://squad/" + squadID + ") please handle this",
+ })
+ 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())
+ }
+
+ // The leader task must be queued AND carry squad_id = squadID, with
+ // is_leader_task = true.
+ var gotSquadID string
+ var isLeader bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT squad_id::text, is_leader_task
+ FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, leaderID).Scan(&gotSquadID, &isLeader); err != nil {
+ t.Fatalf("load leader task: %v", err)
+ }
+ if gotSquadID != squadID {
+ t.Fatalf("leader task squad_id = %q, want %q", gotSquadID, squadID)
+ }
+ if !isLeader {
+ t.Fatalf("leader task is_leader_task = false, want true")
+ }
+}
+
+// TestCreateRetryTask_InheritsSquadID locks the retry-clone contract for the
+// MUL-3730 fix: a retried leader task must inherit squad_id from its parent so
+// the squad-leader briefing keeps being injected across retries. Parallels
+// TestCreateRetryTask_InheritsIsLeaderTask.
+func TestCreateRetryTask_InheritsSquadID(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)
+ }
+
+ 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, squad_id)
+ VALUES ($1, $2, $3, 'failed', 1, 3, TRUE, $4)
+ RETURNING id
+ `, fx.LeaderID, runtimeID, issueID, fx.SquadID).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.SquadID.Valid || util.UUIDToString(child.SquadID) != fx.SquadID {
+ t.Fatalf("child.SquadID = %v (valid=%v), want %s", util.UUIDToString(child.SquadID), child.SquadID.Valid, fx.SquadID)
+ }
+ if !child.IsLeaderTask {
+ t.Fatalf("child.IsLeaderTask = false, want true (provenance must survive retry)")
+ }
+}
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 4b0ec50b9a..88e1577d0e 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -403,7 +403,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
if leader.Visibility == "private" && !s.canCreatorAccessPrivateLeader(ctx, ap, leader) {
return fmt.Errorf("autopilot creator cannot access private squad leader")
}
- if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, pgtype.UUID{}); err != nil {
+ if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, ap.AssigneeID, pgtype.UUID{}); err != nil {
return fmt.Errorf("enqueue squad leader task: %w", err)
}
} else {
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index b7cace5606..60350fa0fa 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -468,7 +468,7 @@ func (s *IssueService) enqueueSquadLeaderTask(ctx context.Context, issue db.Issu
if err != nil || hasPending {
return
}
- if _, err := s.TaskService.EnqueueTaskForSquadLeader(ctx, issue, squad.LeaderID, triggerCommentID); err != nil {
+ if _, err := s.TaskService.EnqueueTaskForSquadLeader(ctx, issue, squad.LeaderID, squad.ID, triggerCommentID); err != nil {
slog.Warn("enqueue squad leader task on create failed",
"issue_id", util.UUIDToString(issue.ID),
"squad_id", util.UUIDToString(squad.ID),
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 3f1441e556..9ae6b6ed92 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -509,7 +509,7 @@ 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, false, "")
+ return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, false, "")
}
// EnqueueTaskForSquadLeader is the leader-role variant of EnqueueTaskForMention.
@@ -518,18 +518,23 @@ func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue,
// 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, false, "")
+//
+// squadID is stamped onto the task's squad_id column so the daemon claim
+// handler can locate the squad and inject its briefing regardless of how the
+// leader task was triggered (comment @squad, issue assign, autopilot,
+// sub-issue done callback). See migration 127.
+func (s *TaskService) EnqueueTaskForSquadLeader(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, squadID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {
+ return s.enqueueMentionTask(ctx, issue, leaderID, triggerCommentID, true, squadID, false, "")
}
// EnqueueTaskForSquadLeaderWithHandoff is the assign/promote variant carrying a
// handoff note into the leader run's opening context (MUL-3375). Empty note
// behaves exactly like EnqueueTaskForSquadLeader.
-func (s *TaskService) EnqueueTaskForSquadLeaderWithHandoff(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, handoffNote string) (db.AgentTaskQueue, error) {
- return s.enqueueMentionTask(ctx, issue, leaderID, pgtype.UUID{}, true, false, handoffNote)
+func (s *TaskService) EnqueueTaskForSquadLeaderWithHandoff(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, squadID pgtype.UUID, handoffNote string) (db.AgentTaskQueue, error) {
+ return s.enqueueMentionTask(ctx, issue, leaderID, pgtype.UUID{}, true, squadID, false, handoffNote)
}
-func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
+func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string) (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)
@@ -554,6 +559,7 @@ func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, ag
IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},
ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},
HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},
+ SquadID: squadID,
})
if err != nil {
slog.Error("mention task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)
@@ -1687,6 +1693,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
var (
agentID pgtype.UUID
isLeader bool
+ squadID pgtype.UUID
)
if sourceTaskID.Valid {
sourceTask, err := s.Queries.GetAgentTask(ctx, sourceTaskID)
@@ -1698,6 +1705,10 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
}
agentID = sourceTask.AgentID
isLeader = sourceTask.IsLeaderTask
+ // Carry the source task's squad provenance so a rerun of a leader
+ // task still injects the squad briefing at claim time (see migration
+ // 127 / daemon claim handler).
+ squadID = sourceTask.SquadID
// Inherit trigger provenance so a per-row rerun of a comment- or
// mention-triggered task stays a comment-triggered task. Without
// this the daemon's buildCommentPrompt path is skipped (it keys on
@@ -1718,6 +1729,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
}
agentID = squad.LeaderID
isLeader = true
+ squadID = issue.AssigneeID
default:
return nil, fmt.Errorf("issue is not assigned to an agent or squad")
}
@@ -1741,7 +1753,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
}
- task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, isLeader)
+ task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, isLeader, squadID)
if err != nil {
return nil, err
}
@@ -1762,12 +1774,12 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
// stays in sync; otherwise (squad member, prior assignee that has since been
// reassigned, mention agent) we use the mention path with the same
// force_fresh_session=true contract.
-func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool) (db.AgentTaskQueue, error) {
+func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, squadID pgtype.UUID) (db.AgentTaskQueue, error) {
if issue.AssigneeType.String == "agent" && issue.AssigneeID.Valid &&
util.UUIDToString(issue.AssigneeID) == util.UUIDToString(agentID) {
return s.enqueueIssueTask(ctx, issue, triggerCommentID, true, "")
}
- return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, isLeader, true, "")
+ return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, isLeader, squadID, true, "")
}
// HandleFailedTasks runs the post-failure side effects for a batch of
diff --git a/server/migrations/127_task_squad_id.down.sql b/server/migrations/127_task_squad_id.down.sql
new file mode 100644
index 0000000000..27c4af4e0a
--- /dev/null
+++ b/server/migrations/127_task_squad_id.down.sql
@@ -0,0 +1,2 @@
+DROP INDEX IF EXISTS agent_task_queue_squad_id_idx;
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS squad_id;
diff --git a/server/migrations/127_task_squad_id.up.sql b/server/migrations/127_task_squad_id.up.sql
new file mode 100644
index 0000000000..cfc8685e47
--- /dev/null
+++ b/server/migrations/127_task_squad_id.up.sql
@@ -0,0 +1,24 @@
+-- agent_task_queue.squad_id records the squad a leader-task belongs to. The
+-- daemon uses it at claim time to locate the squad whose briefing (Operating
+-- Protocol + Roster + Instructions) should be injected onto the leader agent's
+-- instructions, instead of inferring the squad by reverse-looking-up
+-- "which squad is this agent the leader of" (which is ambiguous when one
+-- agent leads multiple squads).
+--
+-- No FK to squad(id) on purpose: agent_task_queue is a hot, high-write task
+-- queue, and we don't want squad maintenance (archive / hard-delete) to take
+-- cross-table locks against it. If a squad is hard-deleted and a stale UUID
+-- lingers here, the daemon's GetSquadInWorkspace lookup simply returns no row
+-- and the claim path skips injection (err != nil branch) — exactly the same
+-- observable behavior as "injection condition not matched". No stale briefing
+-- is ever emitted.
+ALTER TABLE agent_task_queue
+ ADD COLUMN squad_id UUID NULL;
+
+-- Partial index over leader-task rows only: small, high hit-rate. It serves
+-- admin / debug queries ("which leader tasks is this squad currently
+-- running"). The daemon claim path does NOT use it — that goes through the
+-- task_id primary-key path.
+CREATE INDEX agent_task_queue_squad_id_idx
+ ON agent_task_queue (squad_id)
+ WHERE squad_id IS NOT NULL;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 372daa0e6b..8628dd45d5 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -178,7 +178,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-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
+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
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -214,6 +214,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -222,7 +223,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-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
+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
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -269,6 +270,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -284,7 +286,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-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
+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
`
// Cancels active tasks belonging to a chat session. Called from
@@ -331,6 +333,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -346,7 +349,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-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
+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
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -393,6 +396,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -408,7 +412,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgen
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-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
+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
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -459,6 +463,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -474,7 +479,7 @@ const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerComm
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-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
+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
`
// Cancels active tasks whose trigger is the given comment. Called when a
@@ -521,6 +526,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -561,7 +567,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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+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
`
type ClaimAgentTaskParams struct {
@@ -611,6 +617,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -694,7 +701,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :one
UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4, prepare_lease_expires_at = NULL
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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+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
`
type CompleteAgentTaskParams struct {
@@ -742,6 +749,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -836,16 +844,18 @@ 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, is_leader_task, handoff_note
+ trigger_summary, force_fresh_session, is_leader_task, handoff_note,
+ squad_id
)
VALUES (
$1, $2, $3, 'queued', $4, $5,
$6,
COALESCE($7::boolean, FALSE),
COALESCE($8::boolean, FALSE),
- $9
+ $9,
+ $10
)
-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
+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
`
type CreateAgentTaskParams struct {
@@ -858,6 +868,7 @@ type CreateAgentTaskParams struct {
ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
IsLeaderTask pgtype.Bool `json:"is_leader_task"`
HandoffNote pgtype.Text `json:"handoff_note"`
+ SquadID pgtype.UUID `json:"squad_id"`
}
func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams) (AgentTaskQueue, error) {
@@ -871,6 +882,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
arg.ForceFreshSession,
arg.IsLeaderTask,
arg.HandoffNote,
+ arg.SquadID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -903,6 +915,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -910,7 +923,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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+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
`
type CreateQuickCreateTaskParams struct {
@@ -961,6 +974,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -970,7 +984,8 @@ 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, force_fresh_session, is_leader_task
+ attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task,
+ squad_id
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
@@ -979,10 +994,11 @@ SELECT
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,
p.attempt + 1, p.max_attempts, p.id,
p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',
- p.is_leader_task
+ p.is_leader_task,
+ p.squad_id
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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+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
`
// Clones a parent task into a fresh queued attempt. Carries forward the
@@ -991,10 +1007,11 @@ RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, c
// retried as fresh sessions so the child does not inherit a stuck agent
// conversation. Keep the CASE WHEN predicates in sync with
// resumeUnsafeFailureReason and the resume lookup blacklists. attempt is
-// incremented; max_attempts, trigger_comment_id, and is_leader_task are
-// inherited so the retried task keeps the same squad-role provenance as its
+// incremented; max_attempts, trigger_comment_id, is_leader_task, and squad_id
+// 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.
+// continues to recognise it as a leader task. Inheriting squad_id also keeps
+// the squad-leader briefing injection working across retries.
func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, createRetryTask, id)
var i AgentTaskQueue
@@ -1028,6 +1045,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -1051,7 +1069,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, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at
+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, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id
`
type ExpireStaleQueuedTasksParams struct {
@@ -1121,6 +1139,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -1139,7 +1158,7 @@ WHERE id = $1
AND runtime_id = $2
AND status IN ('dispatched', 'waiting_local_directory')
AND started_at IS NULL
-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
+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
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -1185,6 +1204,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -1199,7 +1219,7 @@ SET status = 'failed',
work_dir = COALESCE($5, work_dir),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-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
+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
`
type FailAgentTaskParams struct {
@@ -1258,6 +1278,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -1273,7 +1294,7 @@ WHERE (
AND (prepare_lease_expires_at IS NULL OR prepare_lease_expires_at < now())
)
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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+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
`
type FailStaleTasksParams struct {
@@ -1331,6 +1352,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -1454,7 +1476,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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at 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, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id FROM agent_task_queue
WHERE id = $1
`
@@ -1491,12 +1513,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-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, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at 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, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -1546,6 +1569,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -1975,7 +1999,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim
}
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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at 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, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -2024,6 +2048,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -2036,7 +2061,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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at 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, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -2080,6 +2105,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -2190,7 +2216,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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at 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, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -2234,6 +2260,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -2246,7 +2273,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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at 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, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -2298,6 +2325,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -2310,7 +2338,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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at 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, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -2354,6 +2382,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -2366,15 +2395,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, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at 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, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id 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', 'waiting_local_directory')
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, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at 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, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at
+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, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id 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, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
@@ -2440,6 +2469,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -2457,7 +2487,7 @@ SET status = 'waiting_local_directory',
wait_reason = $2,
prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+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
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -2508,6 +2538,7 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -2527,7 +2558,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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+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
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -2574,6 +2605,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
@@ -2587,7 +2619,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-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
+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
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -2635,6 +2667,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -2730,7 +2763,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
-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
+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
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -2772,6 +2805,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index e3e3e9beda..6bf975a89d 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -176,7 +176,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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+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
`
type CreateAutopilotTaskParams struct {
@@ -229,6 +229,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index d83657ddbb..d9bead86cb 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -96,7 +96,7 @@ VALUES (
$1, $2, NULL, 'queued', $3, $4, $5,
COALESCE($6::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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+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
`
type CreateChatTaskParams struct {
@@ -148,6 +148,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 6d42b81e1e..9bb784662d 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -101,6 +101,7 @@ type AgentTaskQueue struct {
InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
HandoffNote pgtype.Text `json:"handoff_note"`
PrepareLeaseExpiresAt pgtype.Timestamptz `json:"prepare_lease_expires_at"`
+ SquadID pgtype.UUID `json:"squad_id"`
}
type Attachment struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index bf71663198..1f5b21671b 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', 'waiting_local_directory')
-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
+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
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -77,6 +77,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
@@ -196,7 +197,7 @@ WHERE status IN ('dispatched', 'running', 'waiting_local_directory')
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, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at
+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
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -241,6 +242,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.InitiatorUserID,
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
+ &i.SquadID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 01a7dd7e51..59cbba67ee 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -136,14 +136,16 @@ 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, is_leader_task, handoff_note
+ trigger_summary, force_fresh_session, is_leader_task, handoff_note,
+ squad_id
)
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('is_leader_task')::boolean, FALSE),
- sqlc.narg(handoff_note)
+ sqlc.narg(handoff_note),
+ sqlc.narg(squad_id)
)
RETURNING *;
@@ -172,15 +174,17 @@ WHERE id = $1 AND issue_id IS NULL;
-- retried as fresh sessions so the child does not inherit a stuck agent
-- conversation. Keep the CASE WHEN predicates in sync with
-- resumeUnsafeFailureReason and the resume lookup blacklists. attempt is
--- incremented; max_attempts, trigger_comment_id, and is_leader_task are
--- inherited so the retried task keeps the same squad-role provenance as its
+-- incremented; max_attempts, trigger_comment_id, is_leader_task, and squad_id
+-- 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.
+-- continues to recognise it as a leader task. Inheriting squad_id also keeps
+-- the squad-leader briefing injection working across retries.
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, force_fresh_session, is_leader_task
+ attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task,
+ squad_id
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
@@ -189,7 +193,8 @@ SELECT
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,
p.attempt + 1, p.max_attempts, p.id,
p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',
- p.is_leader_task
+ p.is_leader_task,
+ p.squad_id
FROM agent_task_queue p
WHERE p.id = $1
RETURNING *;