Skip to content

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

Go

MUL-3794: rewrite comment routing cascade

Multica Eve5d79696fb506
diff --git a/server/cmd/server/comment_trigger_integration_test.go b/server/cmd/server/comment_trigger_integration_test.go
index 8c03e98ccf..aabe5263b5 100644
--- a/server/cmd/server/comment_trigger_integration_test.go
+++ b/server/cmd/server/comment_trigger_integration_test.go
@@ -8,6 +8,7 @@ import (
"io"
"net/http"
"testing"
+ "time"
)
// authRequestWithAgent makes an authenticated request with X-Agent-ID +
@@ -84,6 +85,18 @@ func countPendingTasks(t *testing.T, issueID string) int {
return count
}
+func countPendingTasksForAgent(t *testing.T, issueID, agentID string) int {
+ t.Helper()
+ var count int
+ err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched')`,
+ issueID, agentID).Scan(&count)
+ if err != nil {
+ t.Fatalf("failed to count pending tasks for agent: %v", err)
+ }
+ return count
+}
+
// clearTasks deletes all tasks for an issue (cleanup between subtests).
func clearTasks(t *testing.T, issueID string) {
t.Helper()
@@ -141,7 +154,7 @@ func createSecondAgent(t *testing.T) string {
runtimeID := agents[0]["runtime_id"].(string)
resp = authRequest(t, "POST", "/api/agents?workspace_id="+testWorkspaceID, map[string]any{
- "name": "Second Test Agent",
+ "name": fmt.Sprintf("Second Test Agent %d", time.Now().UnixNano()),
"runtime_id": runtimeID,
"visibility": "workspace",
})
@@ -304,7 +317,7 @@ func TestCommentTriggerOnComment(t *testing.T) {
}
})
- t.Run("reply to member thread without mentions suppresses trigger", func(t *testing.T) {
+ t.Run("reply to member thread without mentions falls back to assignee", func(t *testing.T) {
clearTasks(t, issueID)
// Member starts a thread.
threadID := postComment(t, issueID, "Hey team, what do you think?", nil)
@@ -312,8 +325,8 @@ func TestCommentTriggerOnComment(t *testing.T) {
clearTasks(t, issueID)
// Another member reply (same user in this test, but the key is parent is by member).
postComment(t, issueID, "I agree with you", strPtr(threadID))
- if n := countPendingTasks(t, issueID); n != 0 {
- t.Errorf("expected 0 pending tasks (member-to-member reply), got %d", n)
+ if n := countPendingTasks(t, issueID); n != 1 {
+ t.Errorf("expected 1 pending task (assignee fallback), got %d", n)
}
})
@@ -459,10 +472,10 @@ func TestCommentTriggerOnMentionNoStatusGate(t *testing.T) {
}
}
-// TestCommentTriggerThreadInheritedMention verifies that when a top-level
-// comment @mentions an agent (not the assignee), replies in that thread
-// also trigger the mentioned agent — even without explicitly re-mentioning it.
-func TestCommentTriggerThreadInheritedMention(t *testing.T) {
+// TestCommentTriggerThreadExplicitMentions verifies that a member root @mention
+// owns plain replies in that thread, while explicit mentions in the reply still
+// trigger normally.
+func TestCommentTriggerThreadExplicitMentions(t *testing.T) {
agentID := getAgentID(t)
// Create an issue NOT assigned to the agent, so on_comment won't fire.
@@ -473,7 +486,7 @@ func TestCommentTriggerThreadInheritedMention(t *testing.T) {
resp.Body.Close()
})
- t.Run("reply in thread inherits parent mention", func(t *testing.T) {
+ t.Run("plain reply in thread routes to root mention owner", func(t *testing.T) {
clearTasks(t, issueID)
// Top-level comment @mentions the agent.
content := fmt.Sprintf("[@Agent](mention://agent/%s) can you review this?", agentID)
@@ -486,7 +499,36 @@ func TestCommentTriggerThreadInheritedMention(t *testing.T) {
// Reply in the thread WITHOUT mentioning the agent.
postComment(t, issueID, "Here is more context for you", strPtr(threadID))
if n := countPendingTasks(t, issueID); n != 1 {
- t.Errorf("expected 1 pending task from thread-inherited mention, got %d", n)
+ t.Errorf("expected 1 pending task from root mention owner, got %d", n)
+ }
+ })
+
+ t.Run("plain reply to multi-agent root routes only first mention", func(t *testing.T) {
+ clearTasks(t, issueID)
+ agentB := createSecondAgent(t)
+ content := fmt.Sprintf(
+ "[@AgentA](mention://agent/%s) [@AgentB](mention://agent/%s) can you both review this?",
+ agentID,
+ agentB,
+ )
+ threadID := postComment(t, issueID, content, nil)
+ if n := countPendingTasksForAgent(t, issueID, agentID); n != 1 {
+ t.Fatalf("expected 1 pending root task for first agent, got %d", n)
+ }
+ if n := countPendingTasksForAgent(t, issueID, agentB); n != 1 {
+ t.Fatalf("expected 1 pending root task for second agent, got %d", n)
+ }
+ clearTasks(t, issueID)
+
+ postComment(t, issueID, "Here is more context for you both", strPtr(threadID))
+ if n := countPendingTasksForAgent(t, issueID, agentID); n != 1 {
+ t.Errorf("expected 1 pending reply task for first agent, got %d", n)
+ }
+ if n := countPendingTasksForAgent(t, issueID, agentB); n != 0 {
+ t.Errorf("expected 0 pending reply tasks for second agent, got %d", n)
+ }
+ if n := countPendingTasks(t, issueID); n != 1 {
+ t.Errorf("expected exactly 1 pending task after multi-agent root reply, got %d", n)
}
})
diff --git a/server/internal/handler/agent_access_test.go b/server/internal/handler/agent_access_test.go
index b35db45bc4..ed33ec39cb 100644
--- a/server/internal/handler/agent_access_test.go
+++ b/server/internal/handler/agent_access_test.go
@@ -584,7 +584,7 @@ func TestShouldEnqueueOnComment_PrivateAgentGate(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- got := testHandler.shouldEnqueueOnComment(ctx, issue, tc.actorType, tc.actorID, commentTriggerComputeOptions{})
+ got := testHandler.shouldEnqueueAssigneeFallback(ctx, issue, tc.actorType, tc.actorID, commentTriggerComputeOptions{})
if got != tc.want {
t.Fatalf("%s\n actor=%s/%s got=%v want=%v",
tc.reason, tc.actorType, tc.actorID, got, tc.want)
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 8b6af60fdc..1cda9dcb95 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1001,12 +1001,43 @@ const (
commentTriggerSourceIssueAssignee commentAgentTriggerSource = "issue_assignee"
commentTriggerSourceMentionAgent commentAgentTriggerSource = "mention_agent"
commentTriggerSourceMentionSquadLeader commentAgentTriggerSource = "mention_squad_leader"
+ commentTriggerSourceThreadParent commentAgentTriggerSource = "thread_parent"
+ commentTriggerSourceConversation commentAgentTriggerSource = "conversation_continuation"
)
+const defaultCommentRoutingEscalationDelay = 5 * time.Minute
+
+func (h *Handler) commentRoutingEscalationDelay(ctx context.Context, workspaceID pgtype.UUID) time.Duration {
+ ws, err := h.Queries.GetWorkspace(ctx, workspaceID)
+ if err != nil || len(ws.Settings) == 0 {
+ return defaultCommentRoutingEscalationDelay
+ }
+
+ var settings struct {
+ CommentRouting struct {
+ EscalationSeconds *int `json:"escalation_seconds"`
+ } `json:"comment_routing"`
+ }
+ if err := json.Unmarshal(ws.Settings, &settings); err != nil || settings.CommentRouting.EscalationSeconds == nil {
+ return defaultCommentRoutingEscalationDelay
+ }
+ if *settings.CommentRouting.EscalationSeconds <= 0 {
+ return 0
+ }
+ return time.Duration(*settings.CommentRouting.EscalationSeconds) * time.Second
+}
+
+type commentEscalationFallback struct {
+ Agent db.Agent
+ Squad *db.Squad
+}
+
type commentAgentTrigger struct {
- Agent db.Agent
- Source commentAgentTriggerSource
- Squad *db.Squad
+ Agent db.Agent
+ Source commentAgentTriggerSource
+ Squad *db.Squad
+ EscalationFallback *commentEscalationFallback
+ AlreadyPending bool
}
type commentTriggerComputeOptions struct {
@@ -1021,6 +1052,10 @@ func commentAgentTriggerReason(trigger commentAgentTrigger) string {
return "This agent was mentioned in the comment."
case commentTriggerSourceMentionSquadLeader:
return "A mentioned squad will trigger its leader."
+ case commentTriggerSourceThreadParent:
+ return "This reply will trigger the parent comment's author."
+ case commentTriggerSourceConversation:
+ return "This follow-up will continue the recent agent conversation."
default:
return "This comment will trigger this agent."
}
@@ -1264,6 +1299,9 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
// the agent task path (TaskService.createAgentComment) — both reply paths
// must keep the resolved root in sync.
h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(issue.WorkspaceID), authorType, authorID)
+ if authorType == "agent" {
+ h.TaskService.CancelDeferredEscalationsForIssueAgent(r.Context(), issue.ID, comment.AuthorID)
+ }
h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, suppressAgentIDs)
@@ -1292,7 +1330,9 @@ func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, co
if isNoteComment(comment.Content) {
return
}
- triggers := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{})
+ triggers := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
+ ExcludeTriggerCommentID: comment.ID,
+ })
triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)
h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
}
@@ -1321,7 +1361,19 @@ func filterSuppressedCommentAgentTriggers(triggers []commentAgentTrigger, suppre
}
func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, triggers []commentAgentTrigger) {
+ var escalationDelay time.Duration
+ escalationDelayLoaded := false
+ getEscalationDelay := func() time.Duration {
+ if !escalationDelayLoaded {
+ escalationDelay = h.commentRoutingEscalationDelay(ctx, issue.WorkspaceID)
+ escalationDelayLoaded = true
+ }
+ return escalationDelay
+ }
for _, trigger := range triggers {
+ if trigger.AlreadyPending {
+ continue
+ }
switch trigger.Source {
case commentTriggerSourceIssueAssignee:
if trigger.Squad != nil {
@@ -1351,6 +1403,36 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu
"agent_id", uuidToString(trigger.Agent.ID),
"error", err)
}
+ case commentTriggerSourceThreadParent, commentTriggerSourceConversation:
+ var task db.AgentTaskQueue
+ var err error
+ if trigger.Source == commentTriggerSourceConversation && trigger.Squad != nil {
+ task, err = h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID)
+ } else {
+ task, err = h.TaskService.EnqueueTaskForThreadParent(ctx, issue, trigger.Agent.ID, triggerCommentID)
+ }
+ if err != nil {
+ slog.Warn("enqueue routed comment agent task failed",
+ "issue_id", uuidToString(issue.ID),
+ "agent_id", uuidToString(trigger.Agent.ID),
+ "source", trigger.Source,
+ "error", err)
+ continue
+ }
+ if trigger.EscalationFallback == nil || getEscalationDelay() <= 0 {
+ continue
+ }
+ var squadID pgtype.UUID
+ if trigger.EscalationFallback.Squad != nil {
+ squadID = trigger.EscalationFallback.Squad.ID
+ }
+ if _, err := h.TaskService.EnqueueDeferredAssigneeFallback(ctx, issue, trigger.EscalationFallback.Agent.ID, squadID, task.ID, triggerCommentID, time.Now().Add(escalationDelay)); err != nil {
+ slog.Warn("enqueue deferred assignee fallback failed",
+ "issue_id", uuidToString(issue.ID),
+ "primary_agent_id", uuidToString(trigger.Agent.ID),
+ "fallback_agent_id", uuidToString(trigger.EscalationFallback.Agent.ID),
+ "error", err)
+ }
}
}
}
@@ -1360,43 +1442,247 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu
return nil
}
- seen := make(map[string]struct{})
- triggers := make([]commentAgentTrigger, 0, 2)
- add := func(trigger commentAgentTrigger) {
- id := uuidToString(trigger.Agent.ID)
- if _, ok := seen[id]; ok {
- return
+ mentions := util.ParseMentions(content)
+ if util.HasMentionAll(mentions) {
+ return nil
+ }
+
+ if hasAgentOrSquadMention(mentions) {
+ return h.resolveMentionedAgentCommentTriggers(ctx, issue, mentions, actorType, actorID, opts)
+ }
+ if hasMemberMention(mentions) {
+ return nil
+ }
+
+ if actorType != "member" {
+ return nil
+ }
+
+ if parentComment != nil && parentComment.AuthorType == "agent" {
+ trigger, ok := h.routeReplyToParentAuthor(ctx, issue, parentComment, actorType, actorID, opts)
+ if !ok {
+ return nil
}
- seen[id] = struct{}{}
- triggers = append(triggers, trigger)
+ if fallback, ok := h.routeAssigneeFallback(ctx, issue, actorType, actorID, opts); ok &&
+ uuidToString(fallback.Agent.ID) != uuidToString(trigger.Agent.ID) {
+ trigger.EscalationFallback = &commentEscalationFallback{
+ Agent: fallback.Agent,
+ Squad: fallback.Squad,
+ }
+ }
+ return []commentAgentTrigger{trigger}
}
- if actorType == "member" && h.shouldEnqueueOnComment(ctx, issue, actorType, actorID, opts) &&
- !h.commentMentionsOthersButNotAssignee(content, issue) &&
- !h.isReplyToMemberThread(ctx, parentComment, content, issue) {
- if agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
- ID: issue.AssigneeID,
- WorkspaceID: issue.WorkspaceID,
- }); err == nil {
- add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceIssueAssignee})
+ if parentComment != nil {
+ triggers, handled := h.routeThreadRootOwners(ctx, issue, parentComment, actorID, opts)
+ if handled {
+ if len(triggers) == 0 {
+ return nil
+ }
+ if len(triggers) == 1 {
+ if fallback, ok := h.routeAssigneeFallback(ctx, issue, actorType, actorID, opts); ok &&
+ uuidToString(fallback.Agent.ID) != uuidToString(triggers[0].Agent.ID) {
+ triggers[0].EscalationFallback = &commentEscalationFallback{
+ Agent: fallback.Agent,
+ Squad: fallback.Squad,
+ }
+ }
+ }
+ return triggers
}
}
- if trigger, ok := h.computeAssignedSquadLeaderCommentTrigger(ctx, issue, content, parentComment, actorType, actorID, opts); ok {
- add(trigger)
+ if trigger, ok := h.routeAssigneeFallback(ctx, issue, actorType, actorID, opts); ok {
+ return []commentAgentTrigger{trigger}
}
+ return nil
+}
- for _, trigger := range h.computeMentionedAgentCommentTriggers(ctx, issue, content, parentComment, actorType, actorID, opts) {
- add(trigger)
+func hasAgentOrSquadMention(mentions []util.Mention) bool {
+ for _, m := range mentions {
+ if m.Type == "agent" || m.Type == "squad" {
+ return true
+ }
}
+ return false
+}
- return triggers
+func hasMemberMention(mentions []util.Mention) bool {
+ for _, m := range mentions {
+ if m.Type == "member" {
+ return true
+ }
+ }
+ return false
+}
+
+func (h *Handler) routeReplyToParentAuthor(ctx context.Context, issue db.Issue, parent *db.Comment, authorType, authorID string, opts commentTriggerComputeOptions) (commentAgentTrigger, bool) {
+ if parent == nil || parent.AuthorType != "agent" || !parent.AuthorID.Valid {
+ return commentAgentTrigger{}, false
+ }
+ agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
+ ID: parent.AuthorID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
+ return commentAgentTrigger{}, false
+ }
+ if !h.canAccessPrivateAgent(ctx, agent, authorType, authorID, uuidToString(issue.WorkspaceID)) {
+ return commentAgentTrigger{}, false
+ }
+ hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, parent.AuthorID, opts)
+ if err != nil {
+ return commentAgentTrigger{}, false
+ }
+ return commentAgentTrigger{Agent: agent, Source: commentTriggerSourceThreadParent, AlreadyPending: hasPending}, true
+}
+
+type conversationRoutedAgentInfo struct {
+ SquadID pgtype.UUID
+}
+
+func (h *Handler) routeThreadRootOwners(ctx context.Context, issue db.Issue, parent *db.Comment, memberID string, opts commentTriggerComputeOptions) ([]commentAgentTrigger, bool) {
+ if parent == nil || !parent.ID.Valid {
+ return nil, false
+ }
+ root, err := h.Queries.GetThreadRoot(ctx, db.GetThreadRootParams{
+ CommentID: parent.ID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil || !root.ID.Valid || root.AuthorType != "member" {
+ return nil, false
+ }
+ return h.routeConversationOwnersForRoot(ctx, issue, root, memberID, opts)
+}
+
+func (h *Handler) routeConversationOwnersForRoot(ctx context.Context, issue db.Issue, root db.Comment, memberID string, opts commentTriggerComputeOptions) ([]commentAgentTrigger, bool) {
+ if !root.ID.Valid || root.AuthorType != "member" {
+ return nil, false
+ }
+ if trigger, hasExplicitOwner, ok := h.routeFirstExplicitRootMentionOwner(ctx, issue, root, memberID, opts); hasExplicitOwner {
+ if !ok {
+ return nil, true
+ }
+ return []commentAgentTrigger{trigger}, true
+ }
+
+ rootID := uuidToString(root.ID)
+ excludedID := uuidToString(opts.ExcludeTriggerCommentID)
+
+ tasks, err := h.Queries.ListTasksByIssue(ctx, issue.ID)
+ if err != nil {
+ return nil, false
+ }
+ routedAgents := make(map[string]conversationRoutedAgentInfo)
+ for _, task := range tasks {
+ if !task.TriggerCommentID.Valid || !task.AgentID.Valid {
+ continue
+ }
+ if excludedID != "" && uuidToString(task.TriggerCommentID) == excludedID {
+ continue
+ }
+ if uuidToString(task.TriggerCommentID) != rootID {
+ continue
+ }
+ agentID := uuidToString(task.AgentID)
+ info := routedAgents[agentID]
+ if !info.SquadID.Valid {
+ info.SquadID = task.SquadID
+ }
+ routedAgents[agentID] = info
+ }
+ if len(routedAgents) == 0 {
+ return nil, false
+ }
+
+ triggers := make([]commentAgentTrigger, 0, len(routedAgents))
+ for agentID, info := range routedAgents {
+ trigger, ok := h.routeConversationContinuationToAgent(ctx, issue, parseUUID(agentID), info.SquadID, memberID, opts)
+ if ok {
+ triggers = append(triggers, trigger)
+ }
+ }
+ return triggers, true
+}
+
+func (h *Handler) routeFirstExplicitRootMentionOwner(ctx context.Context, issue db.Issue, root db.Comment, memberID string, opts commentTriggerComputeOptions) (commentAgentTrigger, bool, bool) {
+ for _, mention := range util.ParseMentions(root.Content) {
+ switch mention.Type {
+ case "agent":
+ agentID, err := util.ParseUUID(mention.ID)
+ if err != nil {
+ return commentAgentTrigger{}, true, false
+ }
+ trigger, ok := h.routeConversationContinuationToAgent(ctx, issue, agentID, pgtype.UUID{}, memberID, opts)
+ return trigger, true, ok
+ case "squad":
+ squadID, err := util.ParseUUID(mention.ID)
+ if err != nil {
+ return commentAgentTrigger{}, true, false
+ }
+ squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
+ ID: squadID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ return commentAgentTrigger{}, true, false
+ }
+ trigger, ok := h.routeConversationContinuationToAgent(ctx, issue, squad.LeaderID, squadID, memberID, opts)
+ return trigger, true, ok
+ }
+ }
+ return commentAgentTrigger{}, false, false
+}
+
+func (h *Handler) routeConversationContinuationToAgent(ctx context.Context, issue db.Issue, agentID, squadID pgtype.UUID, memberID string, opts commentTriggerComputeOptions) (commentAgentTrigger, bool) {
+ if !agentID.Valid {
+ return commentAgentTrigger{}, false
+ }
+ agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
+ ID: agentID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
+ return commentAgentTrigger{}, false
+ }
+ if !h.canAccessPrivateAgent(ctx, agent, "member", memberID, uuidToString(issue.WorkspaceID)) {
+ return commentAgentTrigger{}, false
+ }
+ hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, agentID, opts)
+ if err != nil {
+ return commentAgentTrigger{}, false
+ }
+ trigger := commentAgentTrigger{Agent: agent, Source: commentTriggerSourceConversation, AlreadyPending: hasPending}
+ if squadID.Valid {
+ if squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
+ ID: squadID,
+ WorkspaceID: issue.WorkspaceID,
+ }); err == nil {
+ trigger.Squad = &squad
+ }
+ }
+ return trigger, true
}
-func (h *Handler) computeAssignedSquadLeaderCommentTrigger(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, authorType, authorID string, opts commentTriggerComputeOptions) (commentAgentTrigger, bool) {
- if !issue.AssigneeType.Valid || issue.AssigneeType.String != "squad" || !issue.AssigneeID.Valid {
+func (h *Handler) routeAssigneeFallback(ctx context.Context, issue db.Issue, authorType, authorID string, opts commentTriggerComputeOptions) (commentAgentTrigger, bool) {
+ if !issue.AssigneeType.Valid || !issue.AssigneeID.Valid {
return commentAgentTrigger{}, false
}
+ switch issue.AssigneeType.String {
+ case "agent":
+ agent, hasPending, ok := h.assigneeFallbackAgent(ctx, issue, authorType, authorID, opts)
+ if !ok {
+ return commentAgentTrigger{}, false
+ }
+ return commentAgentTrigger{Agent: agent, Source: commentTriggerSourceIssueAssignee, AlreadyPending: hasPending}, true
+ case "squad":
+ return h.routeAssignedSquadLeaderFallback(ctx, issue, authorType, authorID, opts)
+ default:
+ return commentAgentTrigger{}, false
+ }
+}
+
+func (h *Handler) routeAssignedSquadLeaderFallback(ctx context.Context, issue db.Issue, authorType, authorID string, opts commentTriggerComputeOptions) (commentAgentTrigger, bool) {
squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
ID: issue.AssigneeID,
WorkspaceID: issue.WorkspaceID,
@@ -1408,17 +1694,6 @@ func (h *Handler) computeAssignedSquadLeaderCommentTrigger(ctx context.Context,
h.lastTaskWasLeader(ctx, issue.ID, squad.LeaderID) {
return commentAgentTrigger{}, false
}
- // Suppress the leader trigger when a member comment routes work to
- // someone — either by an explicit @mention in this comment, or via the
- // parent-inheritance path that the @mention trigger uses (a plain reply
- // to a member-authored parent inherits the parent's mentions; see
- // shouldInheritParentMentions). Without the inheritance check, a reply
- // like "hello" to a parent that @mentions AgentX double-triggers: the
- // squad leader wakes via this branch AND AgentX wakes via the mention
- // branch's inheritance — see MUL-3744.
- if authorType == "member" && commentRoutesViaMention(content, parentComment, authorType) {
- return commentAgentTrigger{}, false
- }
agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
ID: squad.LeaderID,
WorkspaceID: issue.WorkspaceID,
@@ -1430,10 +1705,10 @@ func (h *Handler) computeAssignedSquadLeaderCommentTrigger(ctx context.Context,
return commentAgentTrigger{}, false
}
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, squad.LeaderID, opts)
- if err != nil || hasPending {
+ if err != nil {
return commentAgentTrigger{}, false
}
- return commentAgentTrigger{Agent: agent, Source: commentTriggerSourceIssueAssignee, Squad: &squad}, true
+ return commentAgentTrigger{Agent: agent, Source: commentTriggerSourceIssueAssignee, Squad: &squad, AlreadyPending: hasPending}, true
}
func (h *Handler) hasPendingTaskForIssueAndAgent(ctx context.Context, issueID, agentID pgtype.UUID, opts commentTriggerComputeOptions) (bool, error) {
@@ -1450,132 +1725,8 @@ func (h *Handler) hasPendingTaskForIssueAndAgent(ctx context.Context, issueID, a
})
}
-// commentMentionsOthersButNotAssignee returns true if the comment @mentions
-// anyone but does NOT @mention the issue's assignee agent. This is used to
-// suppress the on_comment trigger when the user is directing their comment at
-// someone else (e.g. sharing results with a colleague, asking another agent).
-// @all is treated as a broadcast — it suppresses the trigger because the user
-// is announcing to everyone, not specifically requesting work from the agent.
-func (h *Handler) commentMentionsOthersButNotAssignee(content string, issue db.Issue) bool {
- mentions := util.ParseMentions(content)
- // Filter out issue mentions — they are cross-references, not @people.
- filtered := mentions[:0]
- for _, m := range mentions {
- if m.Type != "issue" {
- filtered = append(filtered, m)
- }
- }
- mentions = filtered
- if len(mentions) == 0 {
- return false // No mentions (or only issue refs) — normal on_comment behavior
- }
- // @all is a broadcast to all members — suppress agent trigger.
- if util.HasMentionAll(mentions) {
- return true
- }
- if !issue.AssigneeID.Valid {
- return true // No assignee — mentions target others
- }
- assigneeID := uuidToString(issue.AssigneeID)
- for _, m := range mentions {
- if m.ID == assigneeID {
- return false // Assignee is mentioned — allow trigger
- }
- }
- return true // Others mentioned but not assignee — suppress trigger
-}
-
-// isReplyToMemberThread returns true if the comment is a reply in a thread
-// started by a member and does NOT @mention the issue's assignee agent.
-// When a member replies in a member-started thread, they are most likely
-// continuing a human conversation — not requesting work from the assigned agent.
-// Replying to an agent-started thread, or explicitly @mentioning the assignee
-// in the reply, still triggers on_comment as expected.
-// If the parent (thread root) itself @mentions the assignee, the thread is
-// considered a conversation with the agent, so replies are allowed to trigger.
-// If the assigned agent has already replied in the thread, the member is
-// conversing with the agent, so replies are allowed to trigger.
-func (h *Handler) isReplyToMemberThread(ctx context.Context, parent *db.Comment, content string, issue db.Issue) bool {
- if parent == nil {
- return false // Not a reply — normal top-level comment
- }
- if parent.AuthorType != "member" {
- return false // Thread started by an agent — allow trigger
- }
- // Thread was started by a member. Suppress on_comment unless the reply
- // or the parent explicitly @mentions the assignee agent, or the agent
- // has already participated in this thread.
- if !issue.AssigneeID.Valid {
- return true // No assignee to mention
- }
- assigneeID := uuidToString(issue.AssigneeID)
- // Check current comment mentions.
- for _, m := range util.ParseMentions(content) {
- if m.ID == assigneeID {
- return false // Assignee explicitly mentioned in reply — allow trigger
- }
- }
- // Check parent (thread root) mentions — if the thread was started by
- // mentioning the assignee, replies continue that conversation.
- for _, m := range util.ParseMentions(parent.Content) {
- if m.ID == assigneeID {
- return false // Assignee mentioned in thread root — allow trigger
- }
- }
- // Check if the assigned agent has already replied in this thread —
- // if so, the member is continuing a conversation with the agent.
- if h.Queries != nil {
- hasReplied, err := h.Queries.HasAgentRepliedInThread(ctx, db.HasAgentRepliedInThreadParams{
- ParentID: parent.ID,
- AgentID: issue.AssigneeID,
- })
- if err == nil && hasReplied {
- return false // Agent participated in thread — allow trigger
- }
- }
- return true // Reply to member thread without agent participation — suppress
-}
-
-// shouldInheritParentMentions decides whether a reply with no explicit
-// mentions should inherit the parent (thread root) comment's mentions.
-//
-// Inheritance lets a member who started a thread by @mentioning an agent
-// continue the conversation with that agent without re-typing the mention
-// on every follow-up reply.
-//
-// It is intentionally narrow:
-//
-// - Only when the reply contains zero mentions of its own. Any explicit
-// mention in the reply is a deliberate choice about who to involve.
-// - Only when the reply author is a member. Agent-authored replies must
-// never inherit, otherwise an agent posting in a thread whose root
-// mentioned another agent would re-trigger that agent and create a loop.
-// - Only when the parent author is a member. When an agent authors a
-// comment that @mentions another agent, it is typically a one-shot
-// delegation (e.g. an agent posting a PR completion that @mentions a
-// reviewer agent). Subsequent member follow-ups in the same thread are
-// directed at the assignee, not at the delegated agent — inheriting
-// would re-trigger the delegated agent on every plain reply.
-func shouldInheritParentMentions(parentComment *db.Comment, replyMentions []util.Mention, replyAuthorType string) bool {
- if parentComment == nil {
- return false
- }
- if len(replyMentions) > 0 {
- return false
- }
- if replyAuthorType == "agent" {
- return false
- }
- return parentComment.AuthorType == "member"
-}
-
-// computeMentionedAgentCommentTriggers parses @agent mentions from comment
-// content and returns a trigger for each mentioned agent. When parentComment
-// is non-nil (i.e. the comment is a reply), mentions from the parent (thread
-// root) are also included so that agents mentioned in the top-level comment
-// are re-triggered by subsequent replies in the same thread — unless the reply
-// explicitly @mentions only non-agent entities (members, issues), which
-// signals the user is talking to other people and not the agent.
+// resolveMentionedAgentCommentTriggers parses explicit @agent and @squad
+// mentions from the current comment and returns the runnable agent recipients.
// Skips agents with on_mention trigger disabled, and private agents mentioned
// by non-owner members (only the agent owner or workspace admin/owner can
// mention a private agent). Self-mentions are intentionally allowed so an
@@ -1583,14 +1734,10 @@ func shouldInheritParentMentions(parentComment *db.Comment, replyMentions []util
// a child-issue run notifying the parent issue whose assignee is the same
// agent); runaway loops are prevented by HasPendingTaskForIssueAndAgent
// dedupe and the natural queued/dispatched coalescing of the task queue.
-// Note: no status gate here — @mention is an explicit action and should work
-// even on done/cancelled issues (the agent can reopen the issue if needed).
-func (h *Handler) computeMentionedAgentCommentTriggers(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, authorType, authorID string, opts commentTriggerComputeOptions) []commentAgentTrigger {
+// Note: no issue status gate here — @mention is an explicit action and should
+// work even on done/cancelled issues (the agent can reopen the issue if needed).
+func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issue db.Issue, mentions []util.Mention, authorType, authorID string, opts commentTriggerComputeOptions) []commentAgentTrigger {
wsID := uuidToString(issue.WorkspaceID)
- mentions := util.ParseMentions(content)
- if shouldInheritParentMentions(parentComment, mentions, authorType) {
- mentions = util.ParseMentions(parentComment.Content)
- }
triggers := make([]commentAgentTrigger, 0, len(mentions))
seen := make(map[string]struct{}, len(mentions))
add := func(trigger commentAgentTrigger) {
@@ -1633,12 +1780,11 @@ func (h *Handler) computeMentionedAgentCommentTriggers(ctx context.Context, issu
if !h.canAccessPrivateAgent(ctx, agent, authorType, authorID, wsID) {
continue
}
- // Dedup: skip if leader already has a pending task for this issue.
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, leaderID, opts)
- if err != nil || hasPending {
+ if err != nil {
continue
}
- add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionSquadLeader, Squad: &squad})
+ add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionSquadLeader, Squad: &squad, AlreadyPending: hasPending})
continue
}
if m.Type != "agent" {
@@ -1663,12 +1809,11 @@ func (h *Handler) computeMentionedAgentCommentTriggers(ctx context.Context, issu
if !h.canAccessPrivateAgent(ctx, agent, authorType, authorID, wsID) {
continue
}
- // Dedup: skip if this agent already has a pending task for this issue.
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, agentUUID, opts)
- if err != nil || hasPending {
+ if err != nil {
continue
}
- add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent})
+ add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent, AlreadyPending: hasPending})
}
return triggers
}
diff --git a/server/internal/handler/comment_trigger_preview_test.go b/server/internal/handler/comment_trigger_preview_test.go
index 0d61cb3ca3..1083fd34d9 100644
--- a/server/internal/handler/comment_trigger_preview_test.go
+++ b/server/internal/handler/comment_trigger_preview_test.go
@@ -7,6 +7,9 @@ import (
"net/http"
"net/http/httptest"
"testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/util"
)
func createCommentTriggerPreviewIssue(t *testing.T, title string, assigneeType, assigneeID string) string {
@@ -124,6 +127,19 @@ func countQueuedCommentTriggerTasks(t *testing.T, issueID, agentID string) int {
return n
}
+func countCommentTriggerTasksWithStatus(t *testing.T, issueID, agentID, status string) int {
+ t.Helper()
+
+ var n int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = $3
+ `, issueID, agentID, status).Scan(&n); err != nil {
+ t.Fatalf("count %s tasks: %v", status, err)
+ }
+ return n
+}
+
func createCommentTriggerPreviewSquad(t *testing.T, name, leaderID string) string {
t.Helper()
@@ -157,14 +173,15 @@ func requirePreviewAgents(t *testing.T, preview CommentTriggerPreviewResponse, w
}
}
-func TestPreviewCommentTriggers_MatchesCreateForInheritedParentMention(t *testing.T) {
+func TestPreviewCommentTriggers_PlainReplyToMemberRootMentionRoutesToMentionedAgent(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
+ ctx := context.Background()
- waltID := createHandlerTestAgent(t, "Preview Inherit Walt", nil)
- kimID := createHandlerTestAgent(t, "Preview Inherit Kim", nil)
- issueID := createCommentTriggerPreviewIssue(t, "comment trigger preview inherits parent mention", "agent", waltID)
+ waltID := createHandlerTestAgent(t, "Preview Member Reply Walt", nil)
+ kimID := createHandlerTestAgent(t, "Preview Member Reply Kim", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "comment trigger preview member reply fallback", "agent", waltID)
topLevelPreview := previewCommentTriggersForTest(t, issueID, CommentTriggerPreviewRequest{
Content: "hello from the root composer",
@@ -172,9 +189,15 @@ func TestPreviewCommentTriggers_MatchesCreateForInheritedParentMention(t *testin
requirePreviewAgents(t, topLevelPreview, waltID)
rootContent := fmt.Sprintf("[@Kim](mention://agent/%s) can you inspect this?", kimID)
- rootID := insertMemberRootCommentForTriggerPreviewTest(t, issueID, rootContent)
- if got := countQueuedCommentTriggerTasks(t, issueID, kimID); got != 0 {
- t.Fatalf("fixture queued Kim tasks = %d, want 0", got)
+ rootID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{"content": rootContent})
+ if got := countQueuedCommentTriggerTasks(t, issueID, kimID); got != 1 {
+ t.Fatalf("root mention queued Kim tasks before completion = %d, want 1", got)
+ }
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue SET status = 'completed'
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, kimID); err != nil {
+ t.Fatalf("complete Kim root task: %v", err)
}
if got := countQueuedCommentTriggerTasks(t, issueID, waltID); got != 0 {
t.Fatalf("fixture queued Walt tasks = %d, want 0", got)
@@ -191,8 +214,8 @@ func TestPreviewCommentTriggers_MatchesCreateForInheritedParentMention(t *testin
ParentID: &replyParentID,
})
requirePreviewAgents(t, replyPreview, kimID)
- if replyPreview.Agents[0].Source != string(commentTriggerSourceMentionAgent) {
- t.Fatalf("reply preview source = %q, want %q", replyPreview.Agents[0].Source, commentTriggerSourceMentionAgent)
+ if replyPreview.Agents[0].Source != string(commentTriggerSourceConversation) {
+ t.Fatalf("reply preview source = %q, want %q", replyPreview.Agents[0].Source, commentTriggerSourceConversation)
}
postCommentForTriggerPreviewTest(t, issueID, replyBody)
@@ -204,22 +227,79 @@ func TestPreviewCommentTriggers_MatchesCreateForInheritedParentMention(t *testin
}
}
-// TestPreviewCommentTriggers_SquadAssigneeReplyDoesNotDoubleTrigger is the
-// regression test for MUL-3744. Scenario:
+func TestPreviewCommentTriggers_PlainReplyToMultiAgentRootRoutesFirstMentionedOwner(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ assigneeID := createHandlerTestAgent(t, "Preview Multi Root Assignee", nil)
+ agentAID := createHandlerTestAgent(t, "Preview Multi Root A", nil)
+ agentBID := createHandlerTestAgent(t, "Preview Multi Root B", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "multi-agent root owner reply", "agent", assigneeID)
+
+ rootContent := fmt.Sprintf(
+ "[@A](mention://agent/%s) [@B](mention://agent/%s) can you both inspect this?",
+ agentAID,
+ agentBID,
+ )
+ rootID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{"content": rootContent})
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentAID); got != 1 {
+ t.Fatalf("root mention queued agent A tasks = %d, want 1", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentBID); got != 1 {
+ t.Fatalf("root mention queued agent B tasks = %d, want 1", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {
+ t.Fatalf("root mention queued assignee tasks = %d, want 0", got)
+ }
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue SET status = 'completed'
+ WHERE issue_id = $1 AND agent_id IN ($2, $3) AND status = 'queued'
+ `, issueID, agentAID, agentBID); err != nil {
+ t.Fatalf("complete root owner tasks: %v", err)
+ }
+
+ replyContent := "plain reply with no mention"
+ replyParentID := rootID
+ replyPreview := previewCommentTriggersForTest(t, issueID, CommentTriggerPreviewRequest{
+ Content: replyContent,
+ ParentID: &replyParentID,
+ })
+ requirePreviewAgents(t, replyPreview, agentAID)
+ if replyPreview.Agents[0].Source != string(commentTriggerSourceConversation) {
+ t.Fatalf("reply preview source = %q, want %q", replyPreview.Agents[0].Source, commentTriggerSourceConversation)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": replyContent,
+ "parent_id": rootID,
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentAID); got != 1 {
+ t.Fatalf("plain reply queued agent A tasks = %d, want 1", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentBID); got != 0 {
+ t.Fatalf("plain reply queued agent B tasks = %d, want 0", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {
+ t.Fatalf("plain reply queued assignee tasks = %d, want 0", got)
+ }
+}
+
+// TestPreviewCommentTriggers_SquadAssigneePlainReplyKeepsRootMentionOwner is the
+// cascade replacement for the old MUL-3744 inherited-mention scenario:
//
// - Issue is assigned to a SQUAD (leader L).
// - Member root comment @mentions another agent (Kim).
// - Member posts a plain reply with no mention of its own ("hello").
//
-// Before the fix the trigger-preview returned BOTH L (squad leader, via the
-// assignee path because the reply itself had no routing mention) and Kim
-// (via parent-mention inheritance on the @mention path). After the fix the
-// leader stays out of the way — the @mention path is already routing the
-// reply to Kim, so only one agent fires.
-func TestPreviewCommentTriggers_SquadAssigneeReplyDoesNotDoubleTrigger(t *testing.T) {
+// New cascade behavior: the root's explicit @agent establishes the thread
+// owner, so the plain reply returns to Kim instead of the squad assignee.
+func TestPreviewCommentTriggers_SquadAssigneePlainReplyKeepsRootMentionOwner(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
+ ctx := context.Background()
leaderID := createHandlerTestAgent(t, "Preview Squad Leader L", nil)
kimID := createHandlerTestAgent(t, "Preview Squad Mention Kim", nil)
@@ -233,20 +313,23 @@ func TestPreviewCommentTriggers_SquadAssigneeReplyDoesNotDoubleTrigger(t *testin
})
requirePreviewAgents(t, topLevelPreview, leaderID)
- // Member root comment that @mentions Kim — leader is skipped here by
- // the existing rule (MUL-2170: member @-mentioning anyone skips leader).
rootContent := fmt.Sprintf("[@Kim](mention://agent/%s) can you take a look?", kimID)
- rootID := insertMemberRootCommentForTriggerPreviewTest(t, issueID, rootContent)
+ rootID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{"content": rootContent})
if got := countQueuedCommentTriggerTasks(t, issueID, leaderID); got != 0 {
t.Fatalf("fixture queued leader tasks = %d, want 0", got)
}
- if got := countQueuedCommentTriggerTasks(t, issueID, kimID); got != 0 {
- t.Fatalf("fixture queued Kim tasks = %d, want 0", got)
+ if got := countQueuedCommentTriggerTasks(t, issueID, kimID); got != 1 {
+ t.Fatalf("root mention queued Kim tasks = %d, want 1", got)
+ }
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue SET status = 'completed'
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, kimID); err != nil {
+ t.Fatalf("complete Kim root task: %v", err)
}
// Composer preview of a plain reply ("hello") to that root.
- // Expected: only Kim fires — via parent-mention inheritance on the
- // @mention path. The squad leader must NOT also be queued.
+ // Expected: only Kim fires via the root conversation owner.
replyContent := "hello"
replyParentID := rootID
replyBody := map[string]any{
@@ -258,18 +341,18 @@ func TestPreviewCommentTriggers_SquadAssigneeReplyDoesNotDoubleTrigger(t *testin
ParentID: &replyParentID,
})
requirePreviewAgents(t, replyPreview, kimID)
- if replyPreview.Agents[0].Source != string(commentTriggerSourceMentionAgent) {
- t.Fatalf("reply preview source = %q, want %q (mention path), got %+v",
- replyPreview.Agents[0].Source, commentTriggerSourceMentionAgent, replyPreview.Agents)
+ if replyPreview.Agents[0].Source != string(commentTriggerSourceConversation) {
+ t.Fatalf("reply preview source = %q, want %q (conversation owner), got %+v",
+ replyPreview.Agents[0].Source, commentTriggerSourceConversation, replyPreview.Agents)
}
- // Verify the create path matches the preview — leader stays at 0.
+ // Verify the create path matches the preview.
postCommentForTriggerPreviewTest(t, issueID, replyBody)
if got := countQueuedCommentTriggerTasks(t, issueID, leaderID); got != 0 {
- t.Fatalf("after plain reply on squad issue: expected 0 leader tasks, got %d (MUL-3744)", got)
+ t.Fatalf("after plain reply on squad issue: expected 0 leader tasks, got %d", got)
}
if got := countQueuedCommentTriggerTasks(t, issueID, kimID); got != 1 {
- t.Fatalf("after plain reply on squad issue: expected 1 Kim task (inherited mention), got %d", got)
+ t.Fatalf("after plain reply on squad issue: expected 1 Kim task, got %d", got)
}
}
@@ -306,6 +389,444 @@ func TestPreviewCommentTriggers_ReturnsMentionedAgentsAndSuppressFiltersCreate(t
}
}
+func TestPreviewCommentTriggers_ExplicitMentionSuppressesAssigneeFallback(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ assigneeID := createHandlerTestAgent(t, "Exclusive Mention Assignee", nil)
+ mentionedID := createHandlerTestAgent(t, "Exclusive Mention Target", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "explicit mention is exclusive", "agent", assigneeID)
+ content := fmt.Sprintf("[@Target](mention://agent/%s) please take this", mentionedID)
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{"content": content})
+ requirePreviewAgents(t, preview, mentionedID)
+ if preview.Agents[0].Source != string(commentTriggerSourceMentionAgent) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceMentionAgent)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{"content": content})
+ if got := countQueuedCommentTriggerTasks(t, issueID, mentionedID); got != 1 {
+ t.Fatalf("mentioned agent queued tasks = %d, want 1", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {
+ t.Fatalf("assignee fallback queued tasks = %d, want 0 for explicit mention", got)
+ }
+}
+
+func TestCreateComment_ExplicitMentionKeepsPendingRouteWithoutDuplicateTask(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ mentionedID := createHandlerTestAgent(t, "Explicit Pending Route Target", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "explicit mention pending route", "", "")
+ content := fmt.Sprintf("[@Target](mention://agent/%s) please take this", mentionedID)
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{"content": content})
+ if got := countQueuedCommentTriggerTasks(t, issueID, mentionedID); got != 1 {
+ t.Fatalf("initial mention queued tasks = %d, want 1", got)
+ }
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{"content": content + " again"})
+ requirePreviewAgents(t, preview, mentionedID)
+ if preview.Agents[0].Source != string(commentTriggerSourceMentionAgent) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceMentionAgent)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{"content": content + " again"})
+ if got := countQueuedCommentTriggerTasks(t, issueID, mentionedID); got != 1 {
+ t.Fatalf("duplicate pending mention queued tasks = %d, want 1", got)
+ }
+}
+
+func TestCreateComment_TopLevelNewThreadFallsBackToAssignee(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ assigneeID := createHandlerTestAgent(t, "Conversation Assignee", nil)
+ conversationAgentID := createHandlerTestAgent(t, "Conversation Target", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "top-level new thread falls back to assignee", "agent", assigneeID)
+
+ rootID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": fmt.Sprintf("[@Target](mention://agent/%s) ping test", conversationAgentID),
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, conversationAgentID); got != 1 {
+ t.Fatalf("initial mention queued conversation agent tasks = %d, want 1", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {
+ t.Fatalf("initial mention queued assignee tasks = %d, want 0", got)
+ }
+
+ var conversationTaskID string
+ if err := testPool.QueryRow(ctx, `
+ UPDATE agent_task_queue
+ SET status = 'completed', completed_at = now()
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ RETURNING id
+ `, issueID, conversationAgentID).Scan(&conversationTaskID); err != nil {
+ t.Fatalf("complete initial conversation task: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ r := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{
+ "content": "Pong",
+ "parent_id": rootID,
+ })
+ r = withURLParam(r, "id", issueID)
+ r.Header.Set("X-Agent-ID", conversationAgentID)
+ r.Header.Set("X-Task-ID", conversationTaskID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("agent reply: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ followUpContent := "人生的意义是什么?"
+ preview := previewCommentTriggersForTest(t, issueID, CommentTriggerPreviewRequest{
+ Content: followUpContent,
+ })
+ requirePreviewAgents(t, preview, assigneeID)
+ if preview.Agents[0].Source != string(commentTriggerSourceIssueAssignee) {
+ t.Fatalf("new thread preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceIssueAssignee)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": followUpContent,
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, conversationAgentID); got != 0 {
+ t.Fatalf("new thread queued conversation agent tasks = %d, want 0", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 1 {
+ t.Fatalf("new thread queued assignee tasks = %d, want 1", got)
+ }
+}
+
+func TestPreviewCommentTriggers_MemberMentionSuppressesAssigneeFallback(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ assigneeID := createHandlerTestAgent(t, "Member Mention Assignee", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "member mention suppresses fallback", "agent", assigneeID)
+ content := fmt.Sprintf("[@Human](mention://member/%s) can you answer?", testUserID)
+
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{"content": content})
+ requirePreviewAgents(t, preview)
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{"content": content})
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {
+ t.Fatalf("assignee fallback queued tasks = %d, want 0 for member mention", got)
+ }
+}
+
+func TestCreateComment_ThreadParentQueuesParentAndPromotesDeferredFallback(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ assigneeID := createHandlerTestAgent(t, "Thread Parent Assignee", nil)
+ parentAgentID := createHandlerTestAgent(t, "Thread Parent Owner", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "thread parent deferred fallback", "agent", assigneeID)
+
+ var parentCommentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)
+ VALUES ($1, $2, 'agent', $3, 'I am handling this')
+ RETURNING id
+ `, testWorkspaceID, issueID, parentAgentID).Scan(&parentCommentID); err != nil {
+ t.Fatalf("insert parent agent comment: %v", err)
+ }
+
+ replyContent := "can you follow up here?"
+ preview := previewCommentTriggersForTest(t, issueID, CommentTriggerPreviewRequest{
+ Content: replyContent,
+ ParentID: &parentCommentID,
+ })
+ requirePreviewAgents(t, preview, parentAgentID)
+ if preview.Agents[0].Source != string(commentTriggerSourceThreadParent) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceThreadParent)
+ }
+
+ replyID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": replyContent,
+ "parent_id": parentCommentID,
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, parentAgentID); got != 1 {
+ t.Fatalf("parent agent queued tasks = %d, want 1", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {
+ t.Fatalf("assignee queued tasks before timeout = %d, want 0", got)
+ }
+
+ var primaryTaskID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, parentAgentID).Scan(&primaryTaskID); err != nil {
+ t.Fatalf("load primary task: %v", err)
+ }
+
+ var fallbackTaskID, escalationForTaskID, triggerCommentID string
+ var fireAt time.Time
+ if err := testPool.QueryRow(ctx, `
+ SELECT id, escalation_for_task_id, trigger_comment_id, fire_at
+ FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'deferred'
+ `, issueID, assigneeID).Scan(&fallbackTaskID, &escalationForTaskID, &triggerCommentID, &fireAt); err != nil {
+ t.Fatalf("load deferred fallback task: %v", err)
+ }
+ if escalationForTaskID != primaryTaskID {
+ t.Fatalf("deferred fallback escalation_for_task_id = %s, want %s", escalationForTaskID, primaryTaskID)
+ }
+ if triggerCommentID != replyID {
+ t.Fatalf("deferred fallback trigger_comment_id = %s, want %s", triggerCommentID, replyID)
+ }
+ if fireAt.Before(time.Now().Add(4*time.Minute)) || fireAt.After(time.Now().Add(6*time.Minute)) {
+ t.Fatalf("deferred fallback fire_at = %s, want about 5 minutes from now", fireAt.Format(time.RFC3339))
+ }
+
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET fire_at = now() - interval '1 second' WHERE id = $1`, fallbackTaskID); err != nil {
+ t.Fatalf("make deferred fallback due: %v", err)
+ }
+ if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, util.MustParseUUID(testRuntimeID)); err != nil {
+ t.Fatalf("promote due deferred fallback: %v", err)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 1 {
+ t.Fatalf("assignee queued tasks after timeout promotion = %d, want 1", got)
+ }
+}
+
+func TestCreateComment_ThreadParentSkipsDeferredFallbackWhenParentIsAssignee(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ assigneeID := createHandlerTestAgent(t, "Thread Parent Same Assignee", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "thread parent same as assignee", "agent", assigneeID)
+
+ var parentCommentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)
+ VALUES ($1, $2, 'agent', $3, 'I am handling this')
+ RETURNING id
+ `, testWorkspaceID, issueID, assigneeID).Scan(&parentCommentID); err != nil {
+ t.Fatalf("insert parent agent comment: %v", err)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "can you follow up here?",
+ "parent_id": parentCommentID,
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 1 {
+ t.Fatalf("parent assignee queued tasks = %d, want 1", got)
+ }
+ if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "deferred"); got != 0 {
+ t.Fatalf("deferred fallback for same parent assignee = %d, want 0", got)
+ }
+}
+
+func TestCreateComment_ThreadParentEscalationCanBeDisabled(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var previousSettings string
+ if err := testPool.QueryRow(ctx,
+ `SELECT COALESCE(settings, '{}'::jsonb)::text FROM workspace WHERE id = $1`,
+ testWorkspaceID,
+ ).Scan(&previousSettings); err != nil {
+ t.Fatalf("load workspace settings: %v", err)
+ }
+ if _, err := testPool.Exec(ctx,
+ `UPDATE workspace SET settings = '{"comment_routing":{"escalation_seconds":0}}'::jsonb WHERE id = $1`,
+ testWorkspaceID,
+ ); err != nil {
+ t.Fatalf("disable comment routing escalation: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `UPDATE workspace SET settings = $1::jsonb WHERE id = $2`, previousSettings, testWorkspaceID)
+ })
+
+ assigneeID := createHandlerTestAgent(t, "Thread Parent Disabled Assignee", nil)
+ parentAgentID := createHandlerTestAgent(t, "Thread Parent Disabled Owner", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "thread parent disabled fallback", "agent", assigneeID)
+
+ var parentCommentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)
+ VALUES ($1, $2, 'agent', $3, 'I am handling this')
+ RETURNING id
+ `, testWorkspaceID, issueID, parentAgentID).Scan(&parentCommentID); err != nil {
+ t.Fatalf("insert parent agent comment: %v", err)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "can you follow up here?",
+ "parent_id": parentCommentID,
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, parentAgentID); got != 1 {
+ t.Fatalf("parent agent queued tasks = %d, want 1", got)
+ }
+ if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "deferred"); got != 0 {
+ t.Fatalf("disabled deferred assignee fallback = %d, want 0", got)
+ }
+}
+
+func TestCreateComment_ParentAgentReplyCancelsPromotedFallbackBeforeClaim(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ assigneeID := createHandlerTestAgent(t, "Thread Parent Cancel Assignee", nil)
+ parentAgentID := createHandlerTestAgent(t, "Thread Parent Cancel Owner", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "thread parent deferred cancel", "agent", assigneeID)
+
+ var parentCommentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)
+ VALUES ($1, $2, 'agent', $3, 'I am handling this')
+ RETURNING id
+ `, testWorkspaceID, issueID, parentAgentID).Scan(&parentCommentID); err != nil {
+ t.Fatalf("insert parent agent comment: %v", err)
+ }
+
+ memberReplyID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "can you follow up here?",
+ "parent_id": parentCommentID,
+ })
+ if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "deferred"); got != 1 {
+ t.Fatalf("deferred assignee fallback before parent ack = %d, want 1", got)
+ }
+
+ var primaryTaskID, fallbackTaskID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, parentAgentID).Scan(&primaryTaskID); err != nil {
+ t.Fatalf("load primary task: %v", err)
+ }
+ if err := testPool.QueryRow(ctx, `
+ UPDATE agent_task_queue
+ SET fire_at = now() - interval '1 second'
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'deferred'
+ RETURNING id
+ `, issueID, assigneeID).Scan(&fallbackTaskID); err != nil {
+ t.Fatalf("make deferred fallback due: %v", err)
+ }
+ if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, util.MustParseUUID(testRuntimeID)); err != nil {
+ t.Fatalf("promote due deferred fallback: %v", err)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 1 {
+ t.Fatalf("queued assignee fallback before parent ack = %d, want 1", got)
+ }
+
+ w := httptest.NewRecorder()
+ r := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{
+ "content": "acknowledged",
+ "parent_id": memberReplyID,
+ })
+ r = withURLParam(r, "id", issueID)
+ r.Header.Set("X-Agent-ID", parentAgentID)
+ r.Header.Set("X-Task-ID", primaryTaskID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("agent ack comment: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "deferred"); got != 0 {
+ t.Fatalf("deferred assignee fallback after parent ack = %d, want 0", got)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {
+ t.Fatalf("queued assignee fallback after parent ack = %d, want 0", got)
+ }
+ if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "cancelled"); got != 1 {
+ t.Fatalf("cancelled assignee fallback after parent ack = %d, want 1", got)
+ }
+ claimed, err := testHandler.TaskService.ClaimTask(ctx, util.MustParseUUID(assigneeID))
+ if err != nil {
+ t.Fatalf("claim assignee fallback after parent ack: %v", err)
+ }
+ if claimed != nil {
+ t.Fatalf("assignee claimed cancelled fallback %s after parent ack; fallback task was %s", util.UUIDToString(claimed.ID), fallbackTaskID)
+ }
+}
+
+func TestStartTaskCancelsPromotedFallbackBeforeAssigneeCanClaim(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ assigneeID := createHandlerTestAgent(t, "Thread Parent Start Cancel Assignee", nil)
+ parentAgentID := createHandlerTestAgent(t, "Thread Parent Start Cancel Owner", nil)
+ issueID := createCommentTriggerPreviewIssue(t, "thread parent start cancels fallback", "agent", assigneeID)
+
+ var parentCommentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)
+ VALUES ($1, $2, 'agent', $3, 'I am handling this')
+ RETURNING id
+ `, testWorkspaceID, issueID, parentAgentID).Scan(&parentCommentID); err != nil {
+ t.Fatalf("insert parent agent comment: %v", err)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "can you follow up here?",
+ "parent_id": parentCommentID,
+ })
+ if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "deferred"); got != 1 {
+ t.Fatalf("deferred assignee fallback before start = %d, want 1", got)
+ }
+
+ primary, err := testHandler.TaskService.ClaimTask(ctx, util.MustParseUUID(parentAgentID))
+ if err != nil {
+ t.Fatalf("claim parent task: %v", err)
+ }
+ if primary == nil {
+ t.Fatal("claim parent task returned nil")
+ }
+
+ var fallbackTaskID string
+ if err := testPool.QueryRow(ctx, `
+ UPDATE agent_task_queue
+ SET fire_at = now() - interval '1 second'
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'deferred'
+ RETURNING id
+ `, issueID, assigneeID).Scan(&fallbackTaskID); err != nil {
+ t.Fatalf("make deferred fallback due: %v", err)
+ }
+ if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, util.MustParseUUID(testRuntimeID)); err != nil {
+ t.Fatalf("promote due deferred fallback: %v", err)
+ }
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 1 {
+ t.Fatalf("queued assignee fallback before parent start = %d, want 1", got)
+ }
+
+ if _, err := testHandler.TaskService.StartTask(ctx, primary.ID); err != nil {
+ t.Fatalf("start parent task: %v", err)
+ }
+
+ if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {
+ t.Fatalf("queued assignee fallback after parent start = %d, want 0", got)
+ }
+ if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "cancelled"); got != 1 {
+ t.Fatalf("cancelled assignee fallback after parent start = %d, want 1", got)
+ }
+ claimed, err := testHandler.TaskService.ClaimTask(ctx, util.MustParseUUID(assigneeID))
+ if err != nil {
+ t.Fatalf("claim assignee fallback after parent start: %v", err)
+ }
+ if claimed != nil {
+ t.Fatalf("assignee claimed cancelled fallback %s after parent start; fallback task was %s", util.UUIDToString(claimed.ID), fallbackTaskID)
+ }
+}
+
func TestPreviewCommentTriggers_EditExcludesSameCommentPendingTask(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -416,7 +937,10 @@ func TestPreviewCommentTriggers_EditExclusionDoesNotIgnoreOtherCommentPendingTas
"content": content,
"editing_comment_id": editingCommentID,
})
- requirePreviewAgents(t, preview)
+ requirePreviewAgents(t, preview, agentID)
+ if preview.Agents[0].Source != string(commentTriggerSourceMentionAgent) {
+ t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceMentionAgent)
+ }
}
func TestUpdateComment_SuppressAgentIDsFiltersEditRetrigger(t *testing.T) {
@@ -551,8 +1075,16 @@ func TestPreviewCommentTriggers_AllSuppressesAssigneeAndPendingDedupes(t *testin
pendingPreview := previewCommentTriggersForTest(t, issueID, map[string]any{
"content": "can you continue here?",
})
- if got := len(pendingPreview.Agents); got != 0 {
- t.Fatalf("pending preview agents = %d, want 0: %+v", got, pendingPreview.Agents)
+ requirePreviewAgents(t, pendingPreview, agentID)
+ if pendingPreview.Agents[0].Source != string(commentTriggerSourceIssueAssignee) {
+ t.Fatalf("pending preview source = %q, want %q", pendingPreview.Agents[0].Source, commentTriggerSourceIssueAssignee)
+ }
+
+ postCommentForTriggerPreviewTest(t, issueID, map[string]any{
+ "content": "can you continue here?",
+ })
+ if got := countQueuedCommentTriggerTasks(t, issueID, agentID); got != 1 {
+ t.Fatalf("pending assignee create queued tasks = %d, want 1", got)
}
}
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index 0769680030..38a314cdaa 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -3330,11 +3330,10 @@ func TestDaemonRegisterMissingWorkspaceReturns404(t *testing.T) {
}
}
-// TestAgentReplyDoesNotInheritParentMentions verifies that agent-authored
-// replies do NOT inherit parent-comment mentions, preventing agent-to-agent
-// re-trigger loops (e.g. "No reply needed" chains). Member-authored replies
-// still inherit parent mentions as expected.
-func TestAgentReplyDoesNotInheritParentMentions(t *testing.T) {
+// TestRootMentionOwnerRoutesMemberReplyButNotAgentReply verifies that a member
+// root @mention owns later member replies, while agent-authored acknowledgments
+// still do not self-expand the route.
+func TestRootMentionOwnerRoutesMemberReplyButNotAgentReply(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -3418,7 +3417,7 @@ func TestAgentReplyDoesNotInheritParentMentions(t *testing.T) {
}
// 3. Agent A posts a reply in the same thread with NO mentions.
- // With the fix, this must NOT inherit the parent mention of Agent B.
+ // Agent-authored comments still do not inherit the root mention of Agent B.
// resolveActor requires X-Task-ID paired with X-Agent-ID to trust the
// agent identity, so we seed a task that belongs to agent A.
agentATask := createHandlerTestTaskForAgent(t, agentA)
@@ -3437,7 +3436,7 @@ func TestAgentReplyDoesNotInheritParentMentions(t *testing.T) {
cancelTasks(agentB)
// 5. Member posts a reply in the same thread with NO mentions.
- // This SHOULD inherit the parent mention and re-trigger Agent B.
+ // The member-authored root @mention owns the thread, so this routes to B.
w = postComment(issueID, map[string]any{
"content": "Thanks for the review.",
"parent_id": parentComment.ID,
@@ -3446,7 +3445,7 @@ func TestAgentReplyDoesNotInheritParentMentions(t *testing.T) {
t.Fatalf("member reply: expected 201, got %d: %s", w.Code, w.Body.String())
}
if countTasks(agentB) != 1 {
- t.Fatalf("expected 1 task for Agent B after member reply (parent inheritance allowed), got %d", countTasks(agentB))
+ t.Fatalf("expected 1 task for Agent B after member reply (root owner), got %d", countTasks(agentB))
}
}
@@ -3546,10 +3545,10 @@ func TestMemberReplyToAgentRootDoesNotInheritParentMentions(t *testing.T) {
}
}
-// TestNestedMemberReplyUsesDirectParentForMentionInheritance is the regression
+// TestNestedMemberReplyUsesDirectParentForThreadOwnership is the regression
// for parent-root write normalization leaking root mentions into plain nested
-// replies. Stored parent_id keeps the direct parent, and trigger logic evaluates
-// that direct parent rather than the thread root.
+// replies. Stored parent_id keeps the direct parent, and trigger logic routes
+// to that direct agent parent rather than the thread root's explicit mention.
func TestNestedMemberReplyUsesDirectParentForMentionInheritance(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -3558,6 +3557,7 @@ func TestNestedMemberReplyUsesDirectParentForMentionInheritance(t *testing.T) {
assigneeAgent := createHandlerTestAgent(t, "Nested Mention Assignee", nil)
mentionedAgent := createHandlerTestAgent(t, "Nested Mention Target", nil)
+ parentAgent := createHandlerTestAgent(t, "Nested Direct Parent", nil)
var number int
if err := testPool.QueryRow(ctx, `
@@ -3624,7 +3624,7 @@ func TestNestedMemberReplyUsesDirectParentForMentionInheritance(t *testing.T) {
INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, parent_id)
VALUES ($1, $2, 'agent', $3, $4, $5)
RETURNING id
- `, testWorkspaceID, issueID, mentionedAgent, "looks like redirect config", root.ID).Scan(&directParentID); err != nil {
+ `, testWorkspaceID, issueID, parentAgent, "looks like redirect config", root.ID).Scan(&directParentID); err != nil {
t.Fatalf("insert direct parent reply: %v", err)
}
@@ -3638,11 +3638,14 @@ func TestNestedMemberReplyUsesDirectParentForMentionInheritance(t *testing.T) {
if got := countQueued(mentionedAgent); got != 0 {
t.Fatalf("plain nested reply must not inherit root mention from non-direct parent; got %d queued tasks", got)
}
+ if got := countQueued(parentAgent); got != 1 {
+ t.Fatalf("plain nested reply should route to direct agent parent; got %d queued tasks", got)
+ }
}
-// TestNestedMemberReplyUsesDirectParentForAssigneeParticipation is the
-// regression for treating any prior agent reply in the root thread as direct
-// participation in a nested human sub-thread.
+// TestNestedMemberReplyWithMemberParentFallsBackToAssignee verifies that a
+// nested reply whose direct parent is human-owned does not route to a sibling
+// agent reply. It falls through to the issue assignee instead.
func TestNestedMemberReplyUsesDirectParentForAssigneeParticipation(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -3731,8 +3734,8 @@ func TestNestedMemberReplyUsesDirectParentForAssigneeParticipation(t *testing.T)
if nested.ParentID == nil || *nested.ParentID != humanParentID {
t.Fatalf("stored nested reply parent_id should keep direct parent %s, got %v", humanParentID, nested.ParentID)
}
- if got := countAssigneeQueued(); got != 0 {
- t.Fatalf("plain nested human reply must not wake assignee just because assignee replied elsewhere under root; got %d queued tasks", got)
+ if got := countAssigneeQueued(); got != 1 {
+ t.Fatalf("plain nested human reply should fall back to assignee; got %d queued tasks", got)
}
}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 0a07ec3393..50002d6e0b 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -2694,35 +2694,39 @@ func (h *Handler) shouldEnqueueAgentTask(ctx context.Context, issue db.Issue) bo
return h.isAgentAssigneeReady(ctx, issue)
}
-// shouldEnqueueOnComment returns true if a member comment on this issue should
-// trigger the assigned agent. Fires for any status — comments are
+// shouldEnqueueAssigneeFallback returns true when comment routing can fall back
+// to the issue's assigned agent. Fires for any status — comments are
// conversational and can happen at any stage, including after completion
// (e.g. follow-up questions on a done issue).
//
-// Mirrors the private-agent gate that computeMentionedAgentCommentTriggers applies on the
+// Mirrors the private-agent gate that resolveMentionedAgentCommentTriggers applies on the
// @mention path: once an owner/admin assigns a private agent to an issue, the
// agent's UUID is "welded" onto the issue and remains visible to every member
// who can view it. Without this check any of those members could dispatch a new
// task to the private agent simply by commenting (#3300).
-func (h *Handler) shouldEnqueueOnComment(ctx context.Context, issue db.Issue, actorType, actorID string, opts commentTriggerComputeOptions) bool {
+func (h *Handler) shouldEnqueueAssigneeFallback(ctx context.Context, issue db.Issue, actorType, actorID string, opts commentTriggerComputeOptions) bool {
+ _, hasPending, ok := h.assigneeFallbackAgent(ctx, issue, actorType, actorID, opts)
+ return ok && !hasPending
+}
+
+func (h *Handler) assigneeFallbackAgent(ctx context.Context, issue db.Issue, actorType, actorID string, opts commentTriggerComputeOptions) (db.Agent, bool, bool) {
if !issue.AssigneeType.Valid || issue.AssigneeType.String != "agent" || !issue.AssigneeID.Valid {
- return false
+ return db.Agent{}, false, false
}
agent, err := h.Queries.GetAgent(ctx, issue.AssigneeID)
if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
- return false
+ return db.Agent{}, false, false
}
if !h.canAccessPrivateAgent(ctx, agent, actorType, actorID, uuidToString(issue.WorkspaceID)) {
- return false
+ return db.Agent{}, false, false
}
- // Coalescing queue: allow enqueue when a task is running (so the agent
- // picks up new comments on the next cycle) but skip if this agent already
- // has a pending task (natural dedup for rapid-fire comments).
+ // Coalescing queue: pending is still a valid route target, but callers
+ // that actually enqueue tasks use this flag to avoid piling on duplicates.
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, issue.AssigneeID, opts)
- if err != nil || hasPending {
- return false
+ if err != nil {
+ return db.Agent{}, false, false
}
- return true
+ return agent, hasPending, true
}
// isAgentRunningOnIssue reports whether the calling agent's current task
diff --git a/server/internal/handler/mention_self_trigger_test.go b/server/internal/handler/mention_self_trigger_test.go
index a4e7ae27bc..d31fd63a11 100644
--- a/server/internal/handler/mention_self_trigger_test.go
+++ b/server/internal/handler/mention_self_trigger_test.go
@@ -9,18 +9,17 @@ import (
)
// enqueueMentionedAgentTasksForTest mirrors the production comment path for
-// @mention triggers: compute the mention trigger set, then enqueue it. Kept as
-// a test helper so these integration tests keep asserting enqueue side effects
-// without preserving a production wrapper that nothing else calls.
+// @mention triggers: compute the cascade trigger set, then enqueue it. Kept as a
+// test helper so these integration tests keep asserting enqueue side effects.
func enqueueMentionedAgentTasksForTest(t *testing.T, ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, authorType, authorID string) {
t.Helper()
- triggers := testHandler.computeMentionedAgentCommentTriggers(ctx, issue, comment.Content, parentComment, authorType, authorID, commentTriggerComputeOptions{})
+ triggers := testHandler.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, authorType, authorID, commentTriggerComputeOptions{})
testHandler.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
}
// selfMentionFixture wires the seeded "Handler Test Agent" as J plus two
// fresh issues so we can exercise the agent-self-mention path on the @mention
-// branch of computeMentionedAgentCommentTriggers. The three tests below cover
+// branch of computeCommentAgentTriggers. The three tests below cover
// the behavior we want post-MUL-2338:
//
// - cross-issue self-mention enqueues (child→parent handoff between issues
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index fcd6787130..58443adca0 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -937,24 +937,6 @@ func commentMentionsAnyone(content string) bool {
return false
}
-// commentRoutesViaMention returns true when the comment will route work via
-// the @mention trigger path — either through its own routing mention, or by
-// inheriting the parent (thread root) mentions on a plain reply (see
-// shouldInheritParentMentions). The squad-leader skip rule treats inherited
-// mentions identically to direct ones: if the @mention path is going to fire,
-// the leader stays out of the way so the same comment never enqueues two
-// agents for the same intent (MUL-3744).
-func commentRoutesViaMention(content string, parentComment *db.Comment, authorType string) bool {
- if commentMentionsAnyone(content) {
- return true
- }
- own := util.ParseMentions(content)
- if !shouldInheritParentMentions(parentComment, own, authorType) {
- return false
- }
- return commentMentionsAnyone(parentComment.Content)
-}
-
// The squad-leader assign/promotion readiness decision now lives in the single
// service.IssueService.WillEnqueueRun predicate (MUL-3375), shared by the issue
// write paths and the preview endpoint. The former handler-local mirrors
diff --git a/server/internal/handler/squad_comment_trigger_test.go b/server/internal/handler/squad_comment_trigger_test.go
index a96834ef58..dda82c1787 100644
--- a/server/internal/handler/squad_comment_trigger_test.go
+++ b/server/internal/handler/squad_comment_trigger_test.go
@@ -42,112 +42,28 @@ func TestCommentMentionsAnyone(t *testing.T) {
}
}
-// TestCommentRoutesViaMention covers the parent-aware variant that drives the
-// squad-leader skip rule on REPLY (MUL-3744). It is a pure helper test that
-// runs without a database connection.
-func TestCommentRoutesViaMention(t *testing.T) {
- memberRoot := func(body string) *db.Comment {
- return &db.Comment{AuthorType: "member", Content: body}
- }
- agentRoot := func(body string) *db.Comment {
- return &db.Comment{AuthorType: "agent", Content: body}
- }
-
- cases := []struct {
- name string
- content string
- parent *db.Comment
- authorType string
- want bool
- }{
- {
- name: "own agent mention counts",
- content: "[@A](mention://agent/11111111-1111-1111-1111-111111111111) please",
- parent: nil,
- authorType: "member",
- want: true,
- },
- {
- name: "plain top-level comment does not route",
- content: "please take a look",
- parent: nil,
- authorType: "member",
- want: false,
- },
- {
- name: "plain reply to member parent with @agent inherits",
- content: "any update?",
- parent: memberRoot("[@A](mention://agent/11111111-1111-1111-1111-111111111111) handle this"),
- authorType: "member",
- want: true,
- },
- {
- name: "plain reply to member parent with no routing mention does not inherit",
- content: "any update?",
- parent: memberRoot("see [MUL-1](mention://issue/33333333-3333-3333-3333-333333333333)"),
- authorType: "member",
- want: false,
- },
- {
- name: "plain reply to agent parent does not inherit",
- content: "any update?",
- parent: agentRoot("[@A](mention://agent/11111111-1111-1111-1111-111111111111) handle this"),
- authorType: "member",
- want: false,
- },
- {
- name: "agent reply never inherits",
- content: "noted",
- parent: memberRoot("[@A](mention://agent/11111111-1111-1111-1111-111111111111) handle this"),
- authorType: "agent",
- want: false,
- },
- {
- name: "reply with own mention does not inherit",
- content: "[@B](mention://agent/22222222-2222-2222-2222-222222222222) over to you",
- parent: memberRoot("[@A](mention://agent/11111111-1111-1111-1111-111111111111) handle this"),
- authorType: "member",
- want: true,
- },
- {
- name: "plain reply to member parent with @all inherits",
- content: "any update?",
- parent: memberRoot("[@all](mention://all/all) heads up"),
- authorType: "member",
- want: true,
- },
- }
- for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
- if got := commentRoutesViaMention(tc.content, tc.parent, tc.authorType); got != tc.want {
- t.Fatalf("commentRoutesViaMention(%q, parent=%+v, %s) = %v, want %v",
- tc.content, tc.parent, tc.authorType, got, tc.want)
- }
- })
- }
-}
-
-// shouldEnqueueSquadLeaderOnCommentForTest reports whether the shared comment
-// trigger computation would wake the issue's assigned squad leader — the
-// boolean view these integration tests assert on. Use
-// shouldEnqueueSquadLeaderOnReplyForTest when the scenario is a reply that
-// might inherit parent mentions.
+// shouldEnqueueSquadLeaderOnCommentForTest reports whether the shared cascade
+// would wake the issue's assigned squad leader.
func shouldEnqueueSquadLeaderOnCommentForTest(ctx context.Context, issue db.Issue, content, authorType, authorID string) bool {
- _, ok := testHandler.computeAssignedSquadLeaderCommentTrigger(ctx, issue, content, nil, authorType, authorID, commentTriggerComputeOptions{})
- return ok
+ return triggersContainIssueAssigneeSquadLeader(testHandler.computeCommentAgentTriggers(ctx, issue, content, nil, authorType, authorID, commentTriggerComputeOptions{}))
}
-// shouldEnqueueSquadLeaderOnReplyForTest is the reply variant: it threads the
-// parent comment into computeAssignedSquadLeaderCommentTrigger so the helper
-// can see inherited routing mentions (MUL-3744).
func shouldEnqueueSquadLeaderOnReplyForTest(ctx context.Context, issue db.Issue, content string, parent *db.Comment, authorType, authorID string) bool {
- _, ok := testHandler.computeAssignedSquadLeaderCommentTrigger(ctx, issue, content, parent, authorType, authorID, commentTriggerComputeOptions{})
- return ok
+ return triggersContainIssueAssigneeSquadLeader(testHandler.computeCommentAgentTriggers(ctx, issue, content, parent, authorType, authorID, commentTriggerComputeOptions{}))
+}
+
+func triggersContainIssueAssigneeSquadLeader(triggers []commentAgentTrigger) bool {
+ for _, trigger := range triggers {
+ if trigger.Source == commentTriggerSourceIssueAssignee && trigger.Squad != nil {
+ return true
+ }
+ }
+ return false
}
// squadCommentTriggerFixture wires a squad assigned to a fresh issue and
// returns the loaded db.Issue plus the leader agent UUID for use in
-// computeAssignedSquadLeaderCommentTrigger integration tests.
+// cascade integration tests.
type squadCommentTriggerFixture struct {
Issue db.Issue
SquadID string
@@ -208,11 +124,10 @@ func newSquadCommentTriggerFixture(t *testing.T) squadCommentTriggerFixture {
}
}
-// TestShouldEnqueueSquadLeaderOnComment_SkipsWhenMemberMentionsAnyone
-// encodes Bohan's rule (MUL-2170): a member comment that explicitly @mentions
-// anyone — agent, member, squad, or @all — must NOT wake the squad leader.
-// Issue cross-references are not routing and do not suppress the leader.
-// Agent-authored comments are exempt: the leader still coordinates threads.
+// TestShouldEnqueueSquadLeaderOnComment_SkipsWhenCommentRoutesElsewhere
+// pins the cascade: explicit participant mentions do not also wake the assigned
+// squad leader. Issue cross-references are not routing and do not suppress the
+// leader.
func TestShouldEnqueueSquadLeaderOnComment_SkipsWhenMemberMentionsAnyone(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -285,12 +200,12 @@ func TestShouldEnqueueSquadLeaderOnComment_SkipsWhenMemberMentionsAnyone(t *test
description: "@squad routes the issue to that squad's leader — current leader stays out",
},
{
- name: "agent comment with @agent still triggers leader",
+ name: "agent comment with @agent does not implicitly trigger leader",
content: "delegating to [@Other](mention://agent/" + fx.OtherID + ")",
authorType: "agent",
authorID: fx.OtherID,
- want: true,
- description: "agent-authored replies always reach leader so it can coordinate next step",
+ want: false,
+ description: "agent→agent routing now requires explicit mentions only; assignee fallback is member-authored only",
},
}
@@ -305,13 +220,10 @@ 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) {
+// TestShouldEnqueueSquadLeaderOnComment_AgentAuthoredCommentsDoNotFallback
+// pins the cascade loop guard: agent-authored comments never reach the assignee
+// fallback branch. Agent→agent work handoff must be explicit @mention.
+func TestShouldEnqueueSquadLeaderOnComment_AgentAuthoredCommentsDoNotFallback(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
@@ -342,69 +254,47 @@ func TestShouldEnqueueSquadLeaderOnComment_LeaderSelfTriggerByRole(t *testing.T)
}
}
- t.Run("no prior task wakes leader (fresh external trigger)", func(t *testing.T) {
+ t.Run("no prior task still does not fallback", func(t *testing.T) {
clearTasks()
- if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "noted", "agent", fx.LeaderID); !got {
- t.Fatalf("no prior task: expected leader to be enqueued, got skip")
+ if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "noted", "agent", fx.LeaderID); got {
+ t.Fatalf("no prior task: expected no implicit leader fallback, got enqueue")
}
})
- t.Run("prior leader task suppresses self-trigger", func(t *testing.T) {
+ t.Run("prior leader task still does not fallback", func(t *testing.T) {
clearTasks()
insertTask(true, "completed")
if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "noted", "agent", fx.LeaderID); got {
- t.Fatalf("after leader task: expected skip (anti-loop), got enqueue")
+ t.Fatalf("after leader task: expected no implicit leader fallback, got enqueue")
}
})
- t.Run("prior worker task still wakes leader (dual-role agent)", func(t *testing.T) {
+ t.Run("prior worker task still does not fallback", func(t *testing.T) {
clearTasks()
insertTask(false, "completed")
- if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "result", "agent", fx.LeaderID); !got {
- t.Fatalf("after worker task: expected leader to be enqueued (MUL-2218), got skip")
+ if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "result", "agent", fx.LeaderID); got {
+ t.Fatalf("after worker task: expected no implicit leader fallback, got enqueue")
}
})
- t.Run("most recent task is the one that matters", func(t *testing.T) {
+ t.Run("most recent task does not change agent-authored fallback guard", func(t *testing.T) {
clearTasks()
insertTask(true, "completed") // older leader task
insertTask(false, "completed") // newer worker task
- if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "result", "agent", fx.LeaderID); !got {
- t.Fatalf("latest task is worker: expected leader to be enqueued, got skip")
+ if got := shouldEnqueueSquadLeaderOnCommentForTest(ctx, fx.Issue, "result", "agent", fx.LeaderID); got {
+ t.Fatalf("latest task is worker: expected no implicit leader fallback, got enqueue")
}
})
}
-// 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:
-//
-// - A member top-level comment that @mentions another agent does NOT
-// enqueue the squad leader (the mentioned agent owns the next step).
-// - A subsequent member REPLY in the same thread, containing no mentions
-// of its own, DOES enqueue the squad leader — i.e. the parent's
-// @agent mention is not inherited into the leader-skip decision.
-//
-// The matching unit test above exercises the helper in isolation; this
-// test catches a class of regression where someone refactors comment.go
-// to pass the parent's content (or the merged thread content) by mistake.
-// TestCreateComment_SquadLeaderSkipHonorsInheritedMention drives the full
-// CreateComment handler to lock the call-site wiring (comment.go) for the
-// squad-leader-skip rule across the reply path. Specifically it proves that:
+// TestCreateComment_SquadPlainReplyToMemberParentKeepsRootMentionOwner drives the
+// full CreateComment handler to lock the cascade's reply behavior:
//
// - A member top-level comment that @mentions another agent does NOT
// enqueue the squad leader (the mentioned agent owns the next step).
-// - A subsequent member REPLY in the same thread that has no mentions of
-// its own does NOT re-wake the squad leader either, because the
-// @mention path inherits the parent's mention and routes the reply to
-// the originally mentioned agent. Without this rule the reply
-// double-triggers — leader via this branch AND the mentioned agent via
-// parent-mention inheritance (MUL-3744).
-//
-// The matching unit test above exercises the helper in isolation; this
-// test catches a class of regression where someone refactors comment.go
-// to drop the parent-aware leader-skip check.
-func TestCreateComment_SquadLeaderSkipHonorsInheritedMention(t *testing.T) {
+// - A subsequent member reply to that member-authored root with no explicit
+// agent mention continues to the root owner instead of the assignee.
+func TestCreateComment_SquadPlainReplyToMemberParentKeepsRootMentionOwner(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
@@ -456,9 +346,8 @@ func TestCreateComment_SquadLeaderSkipHonorsInheritedMention(t *testing.T) {
t.Fatalf("after parent (@OtherAgent): expected 1 OtherAgent task (mention path), got %d", got)
}
- // 2. Mark OtherAgent's parent task done so the @mention dedup
- // (HasPendingTaskForIssueAndAgent) does not mask whether the reply
- // re-fires the mention path via inheritance.
+ // 2. Mark OtherAgent's parent task done so queued-task counts below only
+ // reflect what the plain reply does.
if _, err := testPool.Exec(ctx, `
UPDATE agent_task_queue SET status = 'completed'
WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
@@ -467,35 +356,29 @@ func TestCreateComment_SquadLeaderSkipHonorsInheritedMention(t *testing.T) {
}
// 3. Member posts a reply in the same thread with NO mentions.
- // The leader-skip helper must see that the parent's @OtherAgent
- // mention is inherited into the @mention path, and stay out of the
- // way. Result:
- // - leader: still 0 queued tasks (no double-trigger)
- // - OtherAgent: re-queued via inherited mention (one new task)
+ // The root's @OtherAgent mention owns the thread, so the reply returns
+ // to OtherAgent instead of falling back to the assigned squad leader.
postMemberComment(map[string]any{
"content": "any update?",
"parent_id": parent.ID,
})
if got := countQueued(fx.LeaderID); got != 0 {
- t.Fatalf("after plain reply: expected 0 leader tasks (inherited mention routes), got %d (MUL-3744)", got)
+ t.Fatalf("after plain reply: expected 0 leader tasks, got %d", got)
}
if got := countQueued(fx.OtherID); got != 1 {
- t.Fatalf("after plain reply: expected 1 OtherAgent task (inherited mention path), got %d", got)
+ t.Fatalf("after plain reply: expected 1 OtherAgent task, got %d", got)
}
}
-// TestCreateComment_DualRoleAgentWorkerCommentWakesLeader is the full-stack
-// regression test for MUL-2218. Scenario:
+// TestCreateComment_DualRoleAgentWorkerCommentDoesNotImplicitlyWakeLeader pins
+// the cascade's agent-authored loop guard. 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) {
+// - No leader fallback is enqueued; agent→agent handoff requires explicit
+// mention under the routing cascade.
+func TestCreateComment_DualRoleAgentWorkerCommentDoesNotImplicitlyWakeLeader(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
}
@@ -540,8 +423,7 @@ func TestCreateComment_DualRoleAgentWorkerCommentWakesLeader(t *testing.T) {
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.
+ // No new leader-role task is enqueued implicitly.
var leaderTasks int
if err := testPool.QueryRow(ctx, `
SELECT count(*) FROM agent_task_queue
@@ -549,17 +431,16 @@ func TestCreateComment_DualRoleAgentWorkerCommentWakesLeader(t *testing.T) {
`, 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)
+ if leaderTasks != 0 {
+ t.Fatalf("after worker comment from dual-role agent: expected 0 queued leader tasks, 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 computeAssignedSquadLeaderCommentTrigger / comment.go stops recognising the
-// retried leader's own comments — re-opening the bug this issue fixes.
+// demotes a retried leader task to a worker task, and role-specific claim-time
+// briefing/self-mention guards lose the leader provenance.
func TestCreateRetryTask_InheritsIsLeaderTask(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
diff --git a/server/internal/handler/squad_private_leader_test.go b/server/internal/handler/squad_private_leader_test.go
index 47b8d64998..65a57d42cd 100644
--- a/server/internal/handler/squad_private_leader_test.go
+++ b/server/internal/handler/squad_private_leader_test.go
@@ -290,7 +290,7 @@ func TestChildDone_SquadPrivateLeader_PlainMemberNoEnqueue(t *testing.T) {
}
// TestComment_SquadPrivateLeader_AgentActorAllowed verifies that an agent
-// actor CAN trigger the private leader via comment on a squad-assigned issue.
+// actor CAN explicitly trigger the private leader via a squad mention.
func TestComment_SquadPrivateLeader_AgentActorAllowed(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -340,10 +340,10 @@ func TestComment_SquadPrivateLeader_AgentActorAllowed(t *testing.T) {
testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
})
- // Agent posts a comment.
+ // Agent posts a comment with an explicit squad mention.
w := httptest.NewRecorder()
r := newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{
- "content": "agent reporting in",
+ "content": "[@Squad](mention://squad/" + squadID + ") agent reporting in",
})
r.Header.Set("X-Agent-ID", otherAgentID)
r.Header.Set("X-Task-ID", taskID)
@@ -353,7 +353,8 @@ func TestComment_SquadPrivateLeader_AgentActorAllowed(t *testing.T) {
t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
}
- // The private leader SHOULD have a queued task — agents bypass private gate.
+ // The private leader SHOULD have a queued task — agents bypass private gate
+ // for explicit routing.
var count int
if err := testPool.QueryRow(ctx,
`SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`,
@@ -362,6 +363,6 @@ func TestComment_SquadPrivateLeader_AgentActorAllowed(t *testing.T) {
t.Fatalf("count tasks: %v", err)
}
if count == 0 {
- t.Fatalf("private leader got 0 queued tasks from agent actor comment; want ≥1 (agents bypass private gate)")
+ t.Fatalf("private leader got 0 queued tasks from agent actor squad mention; want >=1 (agents bypass private gate)")
}
}
diff --git a/server/internal/handler/trigger_test.go b/server/internal/handler/trigger_test.go
index 4e3be4b60e..fc0dec1e4b 100644
--- a/server/internal/handler/trigger_test.go
+++ b/server/internal/handler/trigger_test.go
@@ -38,282 +38,32 @@ func issueNoAssignee() db.Issue {
return db.Issue{}
}
-// -------------------------------------------------------------------
-// commentMentionsOthersButNotAssignee
-// -------------------------------------------------------------------
-
-func TestCommentMentionsOthersButNotAssignee(t *testing.T) {
- h := &Handler{} // nil handler — method doesn't use h
-
- issue := issueWithAgentAssignee()
-
- tests := []struct {
- name string
- content string
- want bool
- }{
- {
- name: "no mentions → allow trigger",
- content: "just a plain comment",
- want: false,
- },
- {
- name: "mentions assignee → allow trigger",
- content: fmt.Sprintf("[@Agent](mention://agent/%s) please fix", agentAssigneeID),
- want: false,
- },
- {
- name: "mentions other agent only → suppress",
- content: fmt.Sprintf("[@Other](mention://agent/%s) what do you think?", otherAgentID),
- want: true,
- },
- {
- name: "mentions other member only → suppress",
- content: fmt.Sprintf("[@Bob](mention://member/%s) take a look", memberID),
- want: true,
- },
- {
- name: "mentions both assignee and other → allow trigger",
- content: fmt.Sprintf("[@Agent](mention://agent/%s) and [@Other](mention://agent/%s)", agentAssigneeID, otherAgentID),
- want: false,
- },
- {
- name: "@all mention → suppress (broadcast, not directed at agent)",
- content: "[@All](mention://all/all) heads up everyone",
- want: true,
- },
- {
- name: "@all with assignee mention → suppress (@all takes precedence)",
- content: fmt.Sprintf("[@All](mention://all/all) [@Agent](mention://agent/%s) fyi", agentAssigneeID),
- want: true,
- },
- {
- name: "issue mention only → allow trigger (cross-reference, not @person)",
- content: "[PAN-1](mention://issue/44c266e7-f6dd-4be3-9140-5ac40233f79c) is related",
- want: false,
- },
- {
- name: "issue mention + other agent → suppress (agent mention matters)",
- content: fmt.Sprintf("[PAN-1](mention://issue/44c266e7-f6dd-4be3-9140-5ac40233f79c) cc [@Other](mention://agent/%s)", otherAgentID),
- want: true,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := h.commentMentionsOthersButNotAssignee(tt.content, issue)
- if got != tt.want {
- t.Errorf("commentMentionsOthersButNotAssignee() = %v, want %v", got, tt.want)
- }
- })
- }
-}
-
-func TestCommentMentionsOthersButNotAssignee_NoAssignee(t *testing.T) {
- h := &Handler{}
- issue := issueNoAssignee()
-
- // Any mention on an unassigned issue → suppress
- content := fmt.Sprintf("[@Agent](mention://agent/%s) help", otherAgentID)
- if got := h.commentMentionsOthersButNotAssignee(content, issue); !got {
- t.Errorf("expected true for mentions on unassigned issue, got false")
- }
-}
-
-// -------------------------------------------------------------------
-// isReplyToMemberThread
-// -------------------------------------------------------------------
-
-func TestIsReplyToMemberThread(t *testing.T) {
- h := &Handler{}
- issue := issueWithAgentAssignee()
-
- memberParent := &db.Comment{AuthorType: "member", AuthorID: testUUID(memberID), Content: "plain thread starter"}
- agentParent := &db.Comment{AuthorType: "agent", AuthorID: testUUID(agentAssigneeID), Content: "agent thread starter"}
- // Member-started thread root that @mentions the assignee agent.
- memberParentMentioningAssignee := &db.Comment{
- AuthorType: "member",
- AuthorID: testUUID(memberID),
- Content: fmt.Sprintf("[@Agent](mention://agent/%s) can you look at this?", agentAssigneeID),
- }
- // Member-started thread root that @mentions a non-assignee agent.
- memberParentMentioningOther := &db.Comment{
- AuthorType: "member",
- AuthorID: testUUID(memberID),
- Content: fmt.Sprintf("[@Other](mention://agent/%s) what do you think?", otherAgentID),
- }
-
+func TestHasAgentOrSquadMention(t *testing.T) {
tests := []struct {
name string
- parent *db.Comment
content string
want bool
}{
- {
- name: "top-level comment (nil parent) → allow",
- parent: nil,
- content: "a comment",
- want: false,
- },
- {
- name: "reply to agent thread, no mentions → allow",
- parent: agentParent,
- content: "sounds good",
- want: false,
- },
- {
- name: "reply to agent thread, mention other member → allow (handled by other check)",
- parent: agentParent,
- content: fmt.Sprintf("[@Bob](mention://member/%s) thoughts?", memberID),
- want: false, // isReplyToMemberThread only checks member threads
- },
- {
- name: "reply to member thread, no mentions → suppress",
- parent: memberParent,
- content: "I agree with you",
- want: true,
- },
- {
- name: "reply to member thread, mention other member → suppress",
- parent: memberParent,
- content: fmt.Sprintf("[@Alice](mention://member/%s) what about this?", otherMemberID),
- want: true,
- },
- {
- name: "reply to member thread, mention assignee agent → allow",
- parent: memberParent,
- content: fmt.Sprintf("[@Agent](mention://agent/%s) can you help?", agentAssigneeID),
- want: false,
- },
- {
- name: "reply to member thread, mention other agent (not assignee) → suppress",
- parent: memberParent,
- content: fmt.Sprintf("[@Other](mention://agent/%s) take a look", otherAgentID),
- want: true,
- },
- {
- name: "reply to member thread that @mentioned assignee, no re-mention → allow",
- parent: memberParentMentioningAssignee,
- content: "here is more context for you",
- want: false,
- },
- {
- name: "reply to member thread that @mentioned other agent, no re-mention → suppress",
- parent: memberParentMentioningOther,
- content: "here is more context",
- want: true, // parent mentioned other agent, not assignee — still suppress on_comment
- },
+ {"plain", "just a plain comment", false},
+ {"agent", fmt.Sprintf("[@Agent](mention://agent/%s) please fix", agentAssigneeID), true},
+ {"squad", "[@Squad](mention://squad/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa) please coordinate", true},
+ {"member only", fmt.Sprintf("[@Bob](mention://member/%s) take a look", memberID), false},
+ {"issue only", "[PAN-1](mention://issue/44c266e7-f6dd-4be3-9140-5ac40233f79c) is related", false},
+ {"all only", "[@all](mention://all/all) heads up", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- got := h.isReplyToMemberThread(context.Background(), tt.parent, tt.content, issue)
+ got := hasAgentOrSquadMention(parseMentionsForTest(tt.content))
if got != tt.want {
- t.Errorf("isReplyToMemberThread() = %v, want %v", got, tt.want)
+ t.Errorf("hasAgentOrSquadMention() = %v, want %v", got, tt.want)
}
})
}
}
-// -------------------------------------------------------------------
-// shouldInheritParentMentions
-// -------------------------------------------------------------------
-
-func TestShouldInheritParentMentions(t *testing.T) {
- memberParent := &db.Comment{AuthorType: "member", AuthorID: testUUID(memberID), Content: "thread starter"}
- agentParent := &db.Comment{AuthorType: "agent", AuthorID: testUUID(agentAssigneeID), Content: "agent thread starter"}
- someMention := []util.Mention{{Type: "agent", ID: otherAgentID}}
-
- tests := []struct {
- name string
- parent *db.Comment
- replyMentions []util.Mention
- replyAuthorType string
- want bool
- }{
- {"nil parent → false", nil, nil, "member", false},
- {"reply has explicit mentions → false", memberParent, someMention, "member", false},
- {"agent-authored reply, member parent → false (loop guard)", memberParent, nil, "agent", false},
- {"member reply, agent parent → false (parent author guard)", agentParent, nil, "member", false},
- {"member reply, member parent, no mentions → true (intended use)", memberParent, nil, "member", true},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := shouldInheritParentMentions(tt.parent, tt.replyMentions, tt.replyAuthorType)
- if got != tt.want {
- t.Errorf("shouldInheritParentMentions() = %v, want %v", got, tt.want)
- }
- })
- }
-}
-
-// Regression for the case from MUL-1535: J posts a PR completion comment
-// that @mentions GPT-Boy for review; later a member posts a plain follow-up
-// reply asking the assignee a question. GPT-Boy must NOT be re-triggered.
-func TestShouldInheritParentMentions_AgentReviewDelegationDoesNotLeak(t *testing.T) {
- jPRCompletion := &db.Comment{
- AuthorType: "agent",
- AuthorID: testUUID(agentAssigneeID),
- Content: fmt.Sprintf("PR ready. [@GPT-Boy](mention://agent/%s) please review this.", otherAgentID),
- }
- if got := shouldInheritParentMentions(jPRCompletion, nil, "member"); got {
- t.Fatal("member follow-up to an agent's PR-review delegation must not inherit the @reviewer mention")
- }
-}
-
-// -------------------------------------------------------------------
-// Combined trigger decision (simulates the full on_comment check)
-// -------------------------------------------------------------------
-
-func TestOnCommentTriggerDecision(t *testing.T) {
- h := &Handler{}
- issue := issueWithAgentAssignee()
-
- memberParent := &db.Comment{AuthorType: "member", AuthorID: testUUID(memberID), Content: "plain thread starter"}
- agentParent := &db.Comment{AuthorType: "agent", AuthorID: testUUID(agentAssigneeID), Content: "agent thread starter"}
- memberParentMentioningAssignee := &db.Comment{
- AuthorType: "member",
- AuthorID: testUUID(memberID),
- Content: fmt.Sprintf("[@Agent](mention://agent/%s) help me", agentAssigneeID),
- }
-
- // Simulates the combined check from CreateComment:
- // !commentMentionsOthersButNotAssignee && !isReplyToMemberThread
- shouldTrigger := func(parent *db.Comment, content string) bool {
- return !h.commentMentionsOthersButNotAssignee(content, issue) &&
- !h.isReplyToMemberThread(context.Background(), parent, content, issue)
- }
-
- tests := []struct {
- name string
- parent *db.Comment
- content string
- want bool
- }{
- {"top-level, no mention", nil, "hello agent", true},
- {"top-level, mention assignee", nil, fmt.Sprintf("[@Agent](mention://agent/%s) fix this", agentAssigneeID), true},
- {"top-level, mention other only", nil, fmt.Sprintf("[@Other](mention://agent/%s) look", otherAgentID), false},
- {"reply agent thread, no mention", agentParent, "got it", true},
- {"reply agent thread, mention other member", agentParent, fmt.Sprintf("[@Bob](mention://member/%s) ?", memberID), false},
- {"reply agent thread, mention assignee", agentParent, fmt.Sprintf("[@Agent](mention://agent/%s) yes", agentAssigneeID), true},
- {"reply member thread, no mention", memberParent, "agreed", false},
- {"reply member thread, mention other member", memberParent, fmt.Sprintf("[@Bob](mention://member/%s) ok", memberID), false},
- {"reply member thread, mention assignee", memberParent, fmt.Sprintf("[@Agent](mention://agent/%s) help", agentAssigneeID), true},
- {"reply member thread that @mentioned assignee, no re-mention", memberParentMentioningAssignee, "here is more info", true},
- {"top-level, @all broadcast", nil, "[@All](mention://all/all) heads up team", false},
- {"reply agent thread, @all broadcast", agentParent, "[@All](mention://all/all) update for everyone", false},
- {"reply member thread, @all broadcast", memberParent, "[@All](mention://all/all) fyi", false},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := shouldTrigger(tt.parent, tt.content)
- if got != tt.want {
- t.Errorf("shouldTrigger() = %v, want %v", got, tt.want)
- }
- })
- }
+func parseMentionsForTest(content string) []util.Mention {
+ return util.ParseMentions(content)
}
// -------------------------------------------------------------------
@@ -352,12 +102,9 @@ func TestIsNoteComment(t *testing.T) {
}
// TestTriggerTasksForComment_NoteShortCircuits proves a /note comment returns
-// before any of the three trigger paths run. shouldEnqueueOnComment,
-// computeAssignedSquadLeaderCommentTrigger, and
-// computeMentionedAgentCommentTriggers all dereference h.Queries, so a
-// nil-Queries Handler would panic if the /note guard were missing or moved
-// below them. The comment also @mentions an agent to exercise the mention
-// path specifically.
+// before the cascade tries to resolve mentions, parent ownership, or assignee
+// fallback. A nil-Queries Handler would panic if the /note guard were missing or
+// moved below those branches.
func TestTriggerTasksForComment_NoteShortCircuits(t *testing.T) {
h := &Handler{} // nil Queries / TaskService on purpose
issue := issueWithAgentAssignee()
diff --git a/server/internal/service/issue_trigger.go b/server/internal/service/issue_trigger.go
index 647864d33f..f0175a99ec 100644
--- a/server/internal/service/issue_trigger.go
+++ b/server/internal/service/issue_trigger.go
@@ -68,7 +68,7 @@ func allowAllAgents(db.Agent) bool { return true }
// omitted, four entry points inconsistent — see MUL-3375).
//
// It is intentionally a distinct predicate from the comment trigger
-// (shouldEnqueueOnComment): issue writes park on backlog while comments fire
+// (assignee fallback comment routing): issue writes park on backlog while comments fire
// in any status. The two only share leaf readiness checks (AgentReadiness,
// the pending-task dedup), not the top-level decision.
//
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 4ae3f2d581..b5b2a465a5 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -512,6 +512,12 @@ func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue,
return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, false, "")
}
+// EnqueueTaskForThreadParent creates a queued task for the agent who authored
+// the direct parent comment a member replied to.
+func (s *TaskService) EnqueueTaskForThreadParent(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {
+ return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, 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
@@ -573,6 +579,50 @@ func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, ag
return task, nil
}
+// EnqueueDeferredAssigneeFallback creates an inert task that becomes claimable
+// only after PromoteDueDeferredTasksForRuntime flips it from deferred to queued.
+func (s *TaskService) EnqueueDeferredAssigneeFallback(ctx context.Context, issue db.Issue, agentID, squadID pgtype.UUID, escalationForTaskID pgtype.UUID, triggerCommentID pgtype.UUID, fireAt time.Time) (db.AgentTaskQueue, error) {
+ agent, err := s.Queries.GetAgent(ctx, agentID)
+ if err != nil {
+ slog.Error("deferred fallback enqueue failed: agent not found", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)
+ return db.AgentTaskQueue{}, fmt.Errorf("load agent: %w", err)
+ }
+ if agent.ArchivedAt.Valid {
+ slog.Debug("deferred fallback enqueue skipped: agent is archived", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))
+ return db.AgentTaskQueue{}, fmt.Errorf("agent is archived")
+ }
+ if !agent.RuntimeID.Valid {
+ slog.Error("deferred fallback enqueue failed: agent has no runtime", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))
+ return db.AgentTaskQueue{}, fmt.Errorf("agent has no runtime")
+ }
+
+ isLeader := squadID.Valid
+ task, err := s.Queries.CreateDeferredAgentTask(ctx, db.CreateDeferredAgentTaskParams{
+ AgentID: agentID,
+ RuntimeID: agent.RuntimeID,
+ IssueID: issue.ID,
+ Priority: priorityToInt(issue.Priority),
+ TriggerCommentID: triggerCommentID,
+ TriggerSummary: s.buildCommentTriggerSummary(ctx, triggerCommentID),
+ IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},
+ SquadID: squadID,
+ EscalationForTaskID: escalationForTaskID,
+ FireAt: pgtype.Timestamptz{Time: fireAt, Valid: true},
+ })
+ if err != nil {
+ slog.Error("deferred fallback enqueue failed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)
+ return db.AgentTaskQueue{}, fmt.Errorf("create deferred task: %w", err)
+ }
+
+ slog.Info("deferred fallback task enqueued",
+ "task_id", util.UUIDToString(task.ID),
+ "issue_id", util.UUIDToString(issue.ID),
+ "agent_id", util.UUIDToString(agentID),
+ "fire_at", fireAt.UTC().Format(time.RFC3339),
+ )
+ return task, nil
+}
+
// QuickCreateContext is the JSON payload stored on a quick-create task's
// context column. The daemon detects this variant via Type == "quick_create"
// and switches to the quick-create prompt template; the completion path
@@ -1085,6 +1135,11 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
}()
runtimeKey := util.UUIDToString(runtimeID)
+ if err := s.PromoteDueDeferredTasksForRuntime(ctx, runtimeID); err != nil {
+ outcome = "error_promote_deferred"
+ return nil, err
+ }
+
// Check this before EmptyClaim: a lost claim response moves the task out of
// `queued`, so the empty-queued cache cannot represent recoverability.
stale, err := s.Queries.ReclaimStaleDispatchedTaskForRuntime(ctx, db.ReclaimStaleDispatchedTaskForRuntimeParams{
@@ -1166,6 +1221,23 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
return claimed, nil
}
+func (s *TaskService) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) error {
+ tasks, err := s.Queries.PromoteDueDeferredTasksForRuntime(ctx, runtimeID)
+ if err != nil {
+ return fmt.Errorf("promote due deferred tasks: %w", err)
+ }
+ for _, task := range tasks {
+ slog.Info("deferred fallback task promoted",
+ "task_id", util.UUIDToString(task.ID),
+ "runtime_id", util.UUIDToString(runtimeID),
+ "agent_id", util.UUIDToString(task.AgentID),
+ )
+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
+ s.NotifyTaskEnqueued(ctx, task)
+ }
+ return nil
+}
+
// maybeLogClaimSlow emits one structured log per ClaimTask call when its total
// latency exceeds 300ms, so the prod tail can be diagnosed without flooding
// logs at normal poll rates. Called via defer so it captures the full path
@@ -1195,6 +1267,7 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Ag
if err != nil {
return nil, fmt.Errorf("start task: %w", err)
}
+ s.cancelDeferredEscalationsForTask(ctx, task.ID)
slog.Info("task started", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
s.captureTaskStarted(ctx, task)
@@ -1208,6 +1281,43 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Ag
return &task, nil
}
+func (s *TaskService) cancelDeferredEscalationsForTask(ctx context.Context, taskID pgtype.UUID) {
+ cancelled, err := s.Queries.CancelDeferredEscalationsForTask(ctx, taskID)
+ if err != nil {
+ slog.Warn("cancel deferred escalations for task failed", "task_id", util.UUIDToString(taskID), "error", err)
+ return
+ }
+ for _, task := range cancelled {
+ slog.Info("deferred fallback task cancelled",
+ "task_id", util.UUIDToString(task.ID),
+ "primary_task_id", util.UUIDToString(taskID),
+ "reason", "primary_acknowledged",
+ )
+ }
+}
+
+func (s *TaskService) CancelDeferredEscalationsForIssueAgent(ctx context.Context, issueID, agentID pgtype.UUID) {
+ cancelled, err := s.Queries.CancelDeferredEscalationsForIssueAgent(ctx, db.CancelDeferredEscalationsForIssueAgentParams{
+ IssueID: issueID,
+ AgentID: agentID,
+ })
+ if err != nil {
+ slog.Warn("cancel deferred escalations for issue agent failed",
+ "issue_id", util.UUIDToString(issueID),
+ "agent_id", util.UUIDToString(agentID),
+ "error", err)
+ return
+ }
+ for _, task := range cancelled {
+ slog.Info("deferred fallback task cancelled",
+ "task_id", util.UUIDToString(task.ID),
+ "issue_id", util.UUIDToString(issueID),
+ "agent_id", util.UUIDToString(agentID),
+ "reason", "agent_comment_acknowledged",
+ )
+ }
+}
+
// ExtendTaskPrepareLease keeps a claimed-but-not-started task protected while
// the daemon resolves cached inputs and prepares the execution environment.
func (s *TaskService) ExtendTaskPrepareLease(ctx context.Context, taskID, runtimeID pgtype.UUID) (*db.AgentTaskQueue, error) {
@@ -2340,6 +2450,7 @@ func (s *TaskService) createAgentComment(ctx context.Context, issueID, agentID p
if err != nil {
return
}
+ s.CancelDeferredEscalationsForIssueAgent(ctx, issueID, agentID)
s.Bus.Publish(events.Event{
Type: protocol.EventCommentCreated,
WorkspaceID: util.UUIDToString(issue.WorkspaceID),
diff --git a/server/migrations/128_comment_routing_escalation.down.sql b/server/migrations/128_comment_routing_escalation.down.sql
new file mode 100644
index 0000000000..3e2fd36743
--- /dev/null
+++ b/server/migrations/128_comment_routing_escalation.down.sql
@@ -0,0 +1,24 @@
+DROP INDEX IF EXISTS idx_agent_task_queue_escalation_for;
+DROP INDEX IF EXISTS idx_agent_task_queue_deferred_fire;
+
+UPDATE agent_task_queue
+SET status = 'cancelled',
+ completed_at = COALESCE(completed_at, now())
+WHERE status = 'deferred';
+
+ALTER TABLE agent_task_queue
+ DROP CONSTRAINT agent_task_queue_status_check,
+ ADD CONSTRAINT agent_task_queue_status_check
+ CHECK (status IN (
+ 'queued',
+ 'dispatched',
+ 'running',
+ 'completed',
+ 'failed',
+ 'cancelled',
+ 'waiting_local_directory'
+ ));
+
+ALTER TABLE agent_task_queue
+ DROP COLUMN fire_at,
+ DROP COLUMN escalation_for_task_id;
diff --git a/server/migrations/128_comment_routing_escalation.up.sql b/server/migrations/128_comment_routing_escalation.up.sql
new file mode 100644
index 0000000000..294db81989
--- /dev/null
+++ b/server/migrations/128_comment_routing_escalation.up.sql
@@ -0,0 +1,25 @@
+ALTER TABLE agent_task_queue
+ ADD COLUMN escalation_for_task_id UUID,
+ ADD COLUMN fire_at TIMESTAMPTZ;
+
+ALTER TABLE agent_task_queue
+ DROP CONSTRAINT agent_task_queue_status_check,
+ ADD CONSTRAINT agent_task_queue_status_check
+ CHECK (status IN (
+ 'queued',
+ 'dispatched',
+ 'running',
+ 'completed',
+ 'failed',
+ 'cancelled',
+ 'waiting_local_directory',
+ 'deferred'
+ ));
+
+CREATE INDEX idx_agent_task_queue_deferred_fire
+ ON agent_task_queue (runtime_id, fire_at)
+ WHERE status = 'deferred';
+
+CREATE INDEX idx_agent_task_queue_escalation_for
+ ON agent_task_queue (escalation_for_task_id)
+ WHERE escalation_for_task_id IS NOT NULL;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 8628dd45d5..eadfe31e56 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -177,8 +177,8 @@ func (q *Queries) ArchiveAgentsByRuntime(ctx context.Context, arg ArchiveAgentsB
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, squad_id
+WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+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, escalation_for_task_id, fire_at
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -215,6 +215,8 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
@@ -222,8 +224,8 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
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, squad_id
+WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+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, escalation_for_task_id, fire_at
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -271,6 +273,8 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -285,8 +289,8 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :many
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, squad_id
+WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+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, escalation_for_task_id, fire_at
`
// Cancels active tasks belonging to a chat session. Called from
@@ -334,6 +338,8 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -348,8 +354,8 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
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, squad_id
+WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+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, escalation_for_task_id, fire_at
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -397,6 +403,8 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -411,8 +419,8 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgent :many
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, squad_id
+WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+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, escalation_for_task_id, fire_at
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -464,6 +472,8 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -478,8 +488,8 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerComment :many
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, squad_id
+WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+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, escalation_for_task_id, fire_at
`
// Cancels active tasks whose trigger is the given comment. Called when a
@@ -527,6 +537,176 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const cancelDeferredEscalationsForIssueAgent = `-- name: CancelDeferredEscalationsForIssueAgent :many
+WITH cancelled AS (
+ UPDATE agent_task_queue fallback
+ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+ FROM agent_task_queue primary_task
+ WHERE fallback.escalation_for_task_id = primary_task.id
+ AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
+ AND primary_task.issue_id = $1
+ AND primary_task.agent_id = $2
+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.escalation_for_task_id, fallback.fire_at
+)
+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, escalation_for_task_id, fire_at FROM cancelled
+`
+
+type CancelDeferredEscalationsForIssueAgentParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+type CancelDeferredEscalationsForIssueAgentRow struct {
+ ID pgtype.UUID `json:"id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Status string `json:"status"`
+ Priority int32 `json:"priority"`
+ DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
+ StartedAt pgtype.Timestamptz `json:"started_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+ Result []byte `json:"result"`
+ Error pgtype.Text `json:"error"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ Context []byte `json:"context"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ Attempt int32 `json:"attempt"`
+ MaxAttempts int32 `json:"max_attempts"`
+ ParentTaskID pgtype.UUID `json:"parent_task_id"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ ForceFreshSession bool `json:"force_fresh_session"`
+ IsLeaderTask bool `json:"is_leader_task"`
+ WaitReason pgtype.Text `json:"wait_reason"`
+ 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"`
+ EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`
+ FireAt pgtype.Timestamptz `json:"fire_at"`
+}
+
+func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {
+ rows, err := q.db.Query(ctx, cancelDeferredEscalationsForIssueAgent, arg.IssueID, arg.AgentID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []CancelDeferredEscalationsForIssueAgentRow{}
+ for rows.Next() {
+ var i CancelDeferredEscalationsForIssueAgentRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const cancelDeferredEscalationsForTask = `-- name: CancelDeferredEscalationsForTask :many
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+WHERE escalation_for_task_id = $1
+ AND status IN ('deferred', 'queued', '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, squad_id, escalation_for_task_id, fire_at
+`
+
+func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, cancelDeferredEscalationsForTask, escalationForTaskID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -567,7 +747,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, squad_id
+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, escalation_for_task_id, fire_at
`
type ClaimAgentTaskParams struct {
@@ -618,6 +798,8 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
@@ -701,7 +883,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, squad_id
+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, escalation_for_task_id, fire_at
`
type CompleteAgentTaskParams struct {
@@ -750,6 +932,8 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
@@ -855,7 +1039,7 @@ VALUES (
$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, squad_id
+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, escalation_for_task_id, fire_at
`
type CreateAgentTaskParams struct {
@@ -916,6 +1100,92 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ )
+ return i, err
+}
+
+const createDeferredAgentTask = `-- name: CreateDeferredAgentTask :one
+INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
+ trigger_summary, is_leader_task, squad_id, escalation_for_task_id, fire_at
+)
+VALUES (
+ $1, $2, $3, 'deferred', $4,
+ $5,
+ $6,
+ COALESCE($7::boolean, FALSE),
+ $8,
+ $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, squad_id, escalation_for_task_id, fire_at
+`
+
+type CreateDeferredAgentTaskParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Priority int32 `json:"priority"`
+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ IsLeaderTask pgtype.Bool `json:"is_leader_task"`
+ SquadID pgtype.UUID `json:"squad_id"`
+ EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`
+ FireAt pgtype.Timestamptz `json:"fire_at"`
+}
+
+// Deferred tasks are inert until PromoteDueDeferredTasksForRuntime flips them
+// to queued. Used for comment-routing escalation: a thread-owner primary task
+// gets a delayed assignee fallback without waking both agents at t=0.
+func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferredAgentTaskParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, createDeferredAgentTask,
+ arg.AgentID,
+ arg.RuntimeID,
+ arg.IssueID,
+ arg.Priority,
+ arg.TriggerCommentID,
+ arg.TriggerSummary,
+ arg.IsLeaderTask,
+ arg.SquadID,
+ arg.EscalationForTaskID,
+ arg.FireAt,
+ )
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
@@ -923,7 +1193,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, squad_id
+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, escalation_for_task_id, fire_at
`
type CreateQuickCreateTaskParams struct {
@@ -975,6 +1245,8 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
@@ -998,7 +1270,7 @@ SELECT
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, squad_id
+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, escalation_for_task_id, fire_at
`
// Clones a parent task into a fresh queued attempt. Carries forward the
@@ -1046,6 +1318,8 @@ func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
@@ -1069,7 +1343,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, t.squad_id
+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, t.escalation_for_task_id, t.fire_at
`
type ExpireStaleQueuedTasksParams struct {
@@ -1140,6 +1414,8 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -1158,7 +1434,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, squad_id
+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, escalation_for_task_id, fire_at
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -1205,6 +1481,8 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
@@ -1219,7 +1497,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, squad_id
+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, escalation_for_task_id, fire_at
`
type FailAgentTaskParams struct {
@@ -1279,6 +1557,8 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
@@ -1294,7 +1574,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, squad_id
+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, escalation_for_task_id, fire_at
`
type FailStaleTasksParams struct {
@@ -1353,6 +1633,8 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -1476,7 +1758,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, squad_id 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, escalation_for_task_id, fire_at FROM agent_task_queue
WHERE id = $1
`
@@ -1514,12 +1796,14 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
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, atq.squad_id 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, atq.escalation_for_task_id, atq.fire_at FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -1570,6 +1854,8 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
@@ -1999,7 +2285,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, squad_id 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, escalation_for_task_id, fire_at FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -2049,6 +2335,8 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -2061,7 +2349,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, squad_id 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, escalation_for_task_id, fire_at FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -2106,6 +2394,8 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -2216,7 +2506,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, squad_id 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, escalation_for_task_id, fire_at FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -2261,6 +2551,8 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -2273,7 +2565,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, squad_id 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, escalation_for_task_id, fire_at FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -2326,6 +2618,8 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -2338,7 +2632,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, squad_id 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, escalation_for_task_id, fire_at FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -2383,6 +2677,8 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -2395,15 +2691,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, atq.squad_id 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, atq.escalation_for_task_id, atq.fire_at 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, 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
+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, t.escalation_for_task_id, t.fire_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, atq.squad_id, atq.escalation_for_task_id, atq.fire_at
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
@@ -2470,6 +2766,8 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -2487,7 +2785,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, squad_id
+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, escalation_for_task_id, fire_at
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -2539,10 +2837,74 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
+const promoteDueDeferredTasksForRuntime = `-- name: PromoteDueDeferredTasksForRuntime :many
+UPDATE agent_task_queue
+SET status = 'queued'
+WHERE runtime_id = $1
+ AND status = 'deferred'
+ AND fire_at <= now()
+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, escalation_for_task_id, fire_at
+`
+
+func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, promoteDueDeferredTasksForRuntime, runtimeID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const reclaimStaleDispatchedTaskForRuntime = `-- name: ReclaimStaleDispatchedTaskForRuntime :one
UPDATE agent_task_queue
SET dispatched_at = now(),
@@ -2558,7 +2920,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, squad_id
+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, escalation_for_task_id, fire_at
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -2606,6 +2968,8 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
@@ -2619,7 +2983,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, squad_id
+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, escalation_for_task_id, fire_at
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -2668,6 +3032,8 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -2763,7 +3129,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, squad_id
+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, escalation_for_task_id, fire_at
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -2806,6 +3172,8 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 512d50174c..b41d1910a4 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, squad_id
+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, escalation_for_task_id, fire_at
`
type CreateAutopilotTaskParams struct {
@@ -230,6 +230,8 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index d9bead86cb..be2e2a1d8a 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, squad_id
+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, escalation_for_task_id, fire_at
`
type CreateChatTaskParams struct {
@@ -149,6 +149,8 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 9bb784662d..389a294dfa 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -102,6 +102,8 @@ type AgentTaskQueue struct {
HandoffNote pgtype.Text `json:"handoff_note"`
PrepareLeaseExpiresAt pgtype.Timestamptz `json:"prepare_lease_expires_at"`
SquadID pgtype.UUID `json:"squad_id"`
+ EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`
+ FireAt pgtype.Timestamptz `json:"fire_at"`
}
type Attachment struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 1f5b21671b..c04d5aadfe 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, squad_id
+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, escalation_for_task_id, fire_at
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -78,6 +78,8 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
@@ -197,7 +199,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, squad_id
+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, escalation_for_task_id, fire_at
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -243,6 +245,8 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.HandoffNote,
&i.PrepareLeaseExpiresAt,
&i.SquadID,
+ &i.EscalationForTaskID,
+ &i.FireAt,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 59cbba67ee..912553064f 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -157,6 +157,25 @@ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority,
VALUES ($1, $2, NULL, 'queued', $3, $4)
RETURNING *;
+-- name: CreateDeferredAgentTask :one
+-- Deferred tasks are inert until PromoteDueDeferredTasksForRuntime flips them
+-- to queued. Used for comment-routing escalation: a thread-owner primary task
+-- gets a delayed assignee fallback without waking both agents at t=0.
+INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
+ trigger_summary, is_leader_task, squad_id, escalation_for_task_id, fire_at
+)
+VALUES (
+ @agent_id, @runtime_id, @issue_id, 'deferred', @priority,
+ sqlc.narg(trigger_comment_id),
+ sqlc.narg(trigger_summary),
+ COALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),
+ sqlc.narg(squad_id),
+ @escalation_for_task_id,
+ @fire_at
+)
+RETURNING *;
+
-- name: LinkTaskToIssue :exec
-- Attaches the issue a quick-create task produced back to the task row, once
-- the agent has finished and the issue exists. Guarded by `issue_id IS NULL`
@@ -207,7 +226,7 @@ RETURNING *;
-- status="working" with no self-correction.
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')
+WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
-- name: CancelAgentTasksByIssueAndAgent :many
@@ -217,7 +236,7 @@ RETURNING *;
-- still-running @-mention agent on the same issue.
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')
+WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
-- name: CancelAgentTasksByAgent :many
@@ -228,7 +247,7 @@ RETURNING *;
-- behave consistently.
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')
+WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
-- name: CancelAgentTasksByTriggerComment :many
@@ -239,7 +258,7 @@ RETURNING *;
-- and we'd lose the ability to find the affected tasks.
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')
+WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
-- name: CancelAgentTasksByChatSession :many
@@ -250,7 +269,7 @@ RETURNING *;
-- could no longer reach those tasks.
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')
+WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
-- name: GetAgentTask :one
@@ -559,7 +578,7 @@ RETURNING t.*;
-- 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')
+WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
-- name: CountRunningTasks :one
@@ -631,6 +650,34 @@ SELECT * FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC;
+-- name: PromoteDueDeferredTasksForRuntime :many
+UPDATE agent_task_queue
+SET status = 'queued'
+WHERE runtime_id = @runtime_id
+ AND status = 'deferred'
+ AND fire_at <= now()
+RETURNING *;
+
+-- name: CancelDeferredEscalationsForTask :many
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+WHERE escalation_for_task_id = $1
+ AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
+RETURNING *;
+
+-- name: CancelDeferredEscalationsForIssueAgent :many
+WITH cancelled AS (
+ UPDATE agent_task_queue fallback
+ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
+ FROM agent_task_queue primary_task
+ WHERE fallback.escalation_for_task_id = primary_task.id
+ AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
+ AND primary_task.issue_id = @issue_id
+ AND primary_task.agent_id = @agent_id
+ RETURNING fallback.*
+)
+SELECT * FROM cancelled;
+
-- name: ListActiveTasksByIssue :many
-- Backs the issue-detail "agent live" banner. Includes 'queued' so the
-- banner shows up the moment a task is enqueued — not only after a runtime