Skip to content

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

Go

fix(comment): compensate dropped agent→agent @mentions in completion reconcile (MUL-4304) (#5148)

Multica Eve4db1abe11d27
diff --git a/server/internal/handler/comment_reconcile_test.go b/server/internal/handler/comment_reconcile_test.go
index e67798c136..574466f51c 100644
--- a/server/internal/handler/comment_reconcile_test.go
+++ b/server/internal/handler/comment_reconcile_test.go
@@ -39,6 +39,20 @@ func pendingTaskCountForAgentIssue(t *testing.T, issueID, agentID string) int {
return n
}
+// queuedTaskCountForAgentIssue counts only QUEUED (not dispatched) tasks for an
+// (issue, agent) pair. Used to distinguish a freshly-enqueued follow-up from a
+// pre-seeded dispatched task in the same assertion.
+func queuedTaskCountForAgentIssue(t *testing.T, issueID, agentID 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 = 'queued'`,
+ issueID, agentID).Scan(&n); err != nil {
+ t.Fatalf("count queued tasks: %v", err)
+ }
+ return n
+}
+
// TestCompleteTask_ReconcilesMemberCommentPostedDuringRun proves the MUL-4195
// completion-reconciliation guarantee: a deliberate member comment that lands
// while the agent is busy (after the run's started_at) must earn a follow-up
@@ -240,6 +254,251 @@ func TestCompleteTask_DoesNotReTriggerOtherAgentMentionedDuringRun(t *testing.T)
}
}
+// TestCompleteTask_ReconcilesAgentAuthoredMentionToCompletedAgent is the
+// MUL-4304 regression test. It drives the ACTUAL drop path (review must-fix):
+//
+// - Agent B already has a DISPATCHED task on the issue. (This is the only
+// state that drops the mention. `running`/`queued` do not: a queued task
+// merges the comment in, and a running-only target is not AlreadyPending so
+// it takes the normal fresh-enqueue path.)
+// - Agent A posts an explicit `@B` comment through the real trigger path
+// (triggerTasksForComment, same entry CreateComment uses). Because B's task
+// is dispatched, `AlreadyPending` is true, mergeCommentIntoPendingTask finds
+// no QUEUED row to fold into, and the active-task check `continue`s — the
+// mention is dropped at creation time and deferred to completion reconcile.
+// - Before the fix, reconcile listed only member comments, so A's
+// agent-authored `@B` mention was NEVER replayed and B was silently never
+// re-woken. With the fix, completing B's task must enqueue exactly one
+// follow-up for B.
+//
+// The test asserts BOTH halves: no queued follow-up at creation (proving the
+// drop actually happens), then exactly one after completion (proving reconcile
+// recovers it).
+func TestCompleteTask_ReconcilesAgentAuthoredMentionToCompletedAgent(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var runtimeID string
+ if err := testPool.QueryRow(ctx,
+ `SELECT runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,
+ testWorkspaceID).Scan(&runtimeID); err != nil {
+ t.Fatalf("setup: get runtime: %v", err)
+ }
+ // Two workspace-invocable agents: A authors the mention, B is the target
+ // (and the agent whose run completes / reconciles).
+ agentA := createHandlerTestAgent(t, "Reconcile A2A Author A", nil)
+ agentB := createHandlerTestAgent(t, "Reconcile A2A Target B", nil)
+
+ // Issue assigned to B so B's completion is the one that reconciles.
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)
+ VALUES ($1, 'reconcile-a2a-mention fixture', 'in_progress', 'none', $2, 'member', 999007, 0, 'agent', $3)
+ RETURNING id
+ `, testWorkspaceID, testUserID, agentB).Scan(&issueID); err != nil {
+ t.Fatalf("setup: create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE issue_id = $1`, issueID) })
+
+ issue, err := testHandler.Queries.GetIssue(ctx, util.MustParseUUID(issueID))
+ if err != nil {
+ t.Fatalf("setup: load issue: %v", err)
+ }
+
+ // B's trigger comment, created before the run starts.
+ var triggerCommentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)
+ VALUES ($1, $2, 'member', $3, 'initial request', 'comment', now() - interval '10 minutes')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {
+ t.Fatalf("setup: trigger comment: %v", err)
+ }
+
+ // B's task is DISPATCHED (claim response already built, not yet running) —
+ // the state that makes an incoming mention hit the merge-miss + active-task
+ // drop at creation time.
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, created_at, dispatched_at)
+ VALUES ($1, $2, $3, $4, 'dispatched', 0, now() - interval '10 minutes', now() - interval '5 minutes')
+ RETURNING id
+ `, agentB, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: dispatched task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })
+
+ // Agent A posts an explicit @B mention through the real trigger path while
+ // B is dispatched. Insert the row, then drive triggerTasksForComment exactly
+ // as the CreateComment handler would for an agent-authored comment.
+ var mentionCommentID string
+ mention := "[@B](mention://agent/" + agentB + ") please also handle this"
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)
+ VALUES ($1, $2, 'agent', $3, $4, 'comment')
+ RETURNING id
+ `, issueID, testWorkspaceID, agentA, mention).Scan(&mentionCommentID); err != nil {
+ t.Fatalf("setup: agent @B comment: %v", err)
+ }
+ mentionComment, err := testHandler.Queries.GetComment(ctx, util.MustParseUUID(mentionCommentID))
+ if err != nil {
+ t.Fatalf("setup: load mention comment: %v", err)
+ }
+ testHandler.triggerTasksForComment(ctx, issue, mentionComment, nil, "agent", agentA, "", nil)
+
+ // Drop happened: the mention found no queued task to merge into and an
+ // active (dispatched) task exists, so NO fresh queued follow-up was created.
+ if n := queuedTaskCountForAgentIssue(t, issueID, agentB); n != 0 {
+ t.Fatalf("expected the mention to be dropped at creation (0 queued follow-up), got %d", n)
+ }
+
+ // B's task progresses dispatched → running, then completes.
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running', started_at = now() - interval '1 minute' WHERE id = $1`, taskID); err != nil {
+ t.Fatalf("advance task to running: %v", err)
+ }
+ if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {
+ t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Reconcile recovers the dropped mention: exactly one queued follow-up for B.
+ if n := queuedTaskCountForAgentIssue(t, issueID, agentB); n != 1 {
+ t.Fatalf("expected exactly 1 follow-up for B from the agent-authored @B mention after completion, got %d", n)
+ }
+ // A authored the comment but is not its target, so A must not be enqueued.
+ if n := pendingTaskCountForAgentIssue(t, issueID, agentA); n != 0 {
+ t.Fatalf("comment author A must not be enqueued, got %d A task(s)", n)
+ }
+}
+
+// TestCompleteTask_DoesNotReconcilePlainAgentReply guards the anti-loop
+// boundary of MUL-4304 on an agent-assigned issue: an agent-authored comment
+// with NO explicit @mention (a plain reply / acknowledgement) must never earn a
+// follow-up, even though reconcile now considers agent comments. Only explicit
+// @agent/@squad mentions are replayed.
+func TestCompleteTask_DoesNotReconcilePlainAgentReply(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var runtimeID string
+ if err := testPool.QueryRow(ctx,
+ `SELECT runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,
+ testWorkspaceID).Scan(&runtimeID); err != nil {
+ t.Fatalf("setup: get runtime: %v", err)
+ }
+ agentA := createHandlerTestAgent(t, "Reconcile PlainReply Author A", nil)
+ agentB := createHandlerTestAgent(t, "Reconcile PlainReply Target B", nil)
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)
+ VALUES ($1, 'reconcile-plain-agent-reply fixture', 'in_progress', 'none', $2, 'member', 999008, 0, 'agent', $3)
+ RETURNING id
+ `, testWorkspaceID, testUserID, agentB).Scan(&issueID); err != nil {
+ t.Fatalf("setup: create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ var triggerCommentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)
+ VALUES ($1, $2, 'member', $3, 'initial request', 'comment', now() - interval '10 minutes')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {
+ t.Fatalf("setup: trigger comment: %v", err)
+ }
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, created_at, started_at)
+ VALUES ($1, $2, $3, $4, 'running', 0, now() - interval '10 minutes', now() - interval '5 minutes')
+ RETURNING id
+ `, agentB, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: running task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })
+
+ // A plain agent-authored reply during B's run — NO mention of anyone.
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)
+ VALUES ($1, $2, 'agent', $3, 'thanks, looks good to me', 'comment', now() - interval '1 minute')
+ `, issueID, testWorkspaceID, agentA); err != nil {
+ t.Fatalf("setup: plain agent reply: %v", err)
+ }
+
+ if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {
+ t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if n := pendingTaskCountForAgentIssue(t, issueID, agentB); n != 0 {
+ t.Fatalf("a plain agent reply (no mention) must not enqueue a follow-up, got %d B task(s)", n)
+ }
+ if n := pendingTaskCountForAgentIssue(t, issueID, agentA); n != 0 {
+ t.Fatalf("a plain agent reply (no mention) must not enqueue a follow-up, got %d A task(s)", n)
+ }
+}
+
+// TestCompleteTask_DoesNotReconcilePlainWorkerReplyOnSquadIssue is the MUL-4304
+// review must-fix #2 regression test. On a SQUAD-assigned issue,
+// computeCommentAgentTriggers routes a plain worker-agent reply (no mention) to
+// the squad leader via routeAssignedSquadLeaderFallback (Source = issue
+// assignee) — that is the create-time leader→worker→leader coordination path.
+// Reconcile must NOT replay that fallback: it compensates ONLY explicit
+// @agent/@squad mentions (keepExplicitMentionTriggers). So when the squad leader
+// completes a task and a worker's plain reply arrived during the run, no
+// completion-driven follow-up may be enqueued for the leader. Without the
+// explicit-mention filter this test enqueues 1 leader task and fails.
+func TestCompleteTask_DoesNotReconcilePlainWorkerReplyOnSquadIssue(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fx := newSquadCommentTriggerFixture(t)
+ issueID := uuidToString(fx.Issue.ID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)
+ })
+
+ var leaderRuntimeID string
+ if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, fx.LeaderID).Scan(&leaderRuntimeID); err != nil {
+ t.Fatalf("setup: load leader runtime: %v", err)
+ }
+ // A running leader task whose completion drives reconcile.
+ var leaderTaskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, squad_id, priority, created_at, started_at)
+ VALUES ($1, $2, $3, 'running', TRUE, $4, 0, now() - interval '10 minutes', now() - interval '5 minutes')
+ RETURNING id
+ `, fx.LeaderID, leaderRuntimeID, issueID, fx.SquadID).Scan(&leaderTaskID); err != nil {
+ t.Fatalf("setup: leader task: %v", err)
+ }
+
+ // A plain worker-agent reply (no mention) posted during the leader's run.
+ // At create time this WOULD route to the leader via the squad-leader
+ // fallback; reconcile must not replay it.
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)
+ VALUES ($1, $2, 'agent', $3, 'done — pushed the change', 'comment', now() - interval '1 minute')
+ `, issueID, testWorkspaceID, fx.OtherID); err != nil {
+ t.Fatalf("setup: plain worker reply: %v", err)
+ }
+
+ if w := completeTaskViaHandler(t, leaderTaskID, "done"); w.Code != http.StatusOK {
+ t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // The squad-leader fallback is a non-mention route, so reconcile must not
+ // enqueue any follow-up for the leader from a plain worker reply.
+ if n := pendingTaskCountForAgentIssue(t, issueID, fx.LeaderID); n != 0 {
+ t.Fatalf("plain worker reply must not reconcile-wake the squad leader, got %d leader task(s)", n)
+ }
+}
+
// handlerWorkspaceMember inserts a fresh user + workspace member and returns
// the user id (for a second distinct originator).
func handlerWorkspaceMember(t *testing.T, slug string) string {
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 493493e662..ccc6501d21 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2452,8 +2452,20 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A
// a delivered one.
//
// Scope + loop safety:
-// - Only MEMBER comments qualify (agent replies / acknowledgements /
-// self-triggers never do).
+// - MEMBER comments qualify as before, with their full routing. AGENT comments
+// now also qualify, but ONLY through an explicit @agent/@squad mention
+// (keepExplicitMentionTriggers). Every non-mention agent route — the
+// assigned-squad-leader fallback, thread-parent / conversation continuation
+// — is intentionally excluded, so a plain agent reply / acknowledgement
+// earns no follow-up here regardless of issue assignment. That is the
+// anti-loop boundary the old member-only filter protected.
+// This closes MUL-4304: an explicit agent→agent @mention that landed while
+// the target already had a DISPATCHED task is dropped by the create-time
+// enqueue path — merge only folds a comment into a QUEUED task, so a
+// dispatched target hits the merge-miss + active-task `continue` and is
+// deferred here — and was then never replayed because agent comments were
+// excluded. (A target with only a RUNNING/queued task does not hit that
+// drop: queued merges in, running-only takes the normal fresh-enqueue path.)
// - Only comments routing to THE AGENT THAT JUST RAN earn a follow-up here;
// an `@other-agent` comment is left to that agent's own creation-time
// trigger, so a completion never re-wakes an unrelated agent.
@@ -2467,12 +2479,12 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
if task == nil || !task.IssueID.Valid || !task.AgentID.Valid || !task.CreatedAt.Valid {
return
}
- comments, err := h.Queries.ListMemberCommentsForIssueSince(ctx, db.ListMemberCommentsForIssueSinceParams{
+ comments, err := h.Queries.ListReconcilableCommentsForIssueSince(ctx, db.ListReconcilableCommentsForIssueSinceParams{
IssueID: task.IssueID,
Since: task.CreatedAt,
})
if err != nil {
- slog.Warn("reconcile comments on completion: list member comments failed",
+ slog.Warn("reconcile comments on completion: list comments failed",
"issue_id", uuidToString(task.IssueID), "task_id", uuidToString(task.ID), "error", err)
return
}
@@ -2515,14 +2527,37 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
parentComment = &parent
}
}
- // Members are their own originator. Compute what this comment would
- // trigger, then keep ONLY the agent that just completed — never the
- // full fan-out (that would re-wake unrelated `@other-agent` targets).
+ // Compute what this comment would trigger, then keep ONLY the agent
+ // that just completed — never the full fan-out (that would re-wake
+ // unrelated `@other-agent` targets).
+ //
+ // The comment is routed under its OWN author_type. A member is its own
+ // originator. For an agent author, the originator is the human at the
+ // top of that agent's trigger chain (resolved from the comment's source
+ // task); canInvokeAgent judges an agent→agent (A2A) mention by that
+ // originator, not the immediate agent principal (MUL-3963).
+ actorType := c.AuthorType
actorID := uuidToString(c.AuthorID)
- triggers := h.computeCommentAgentTriggers(ctx, issue, c.Content, parentComment, "member", actorID, commentTriggerComputeOptions{
+ originatorUserID := actorID
+ if actorType != "member" {
+ originatorUserID = uuidToString(h.TaskService.ResolveOriginatorFromTriggerComment(ctx, c.ID))
+ }
+ triggers := h.computeCommentAgentTriggers(ctx, issue, c.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
ExcludeTriggerCommentID: c.ID,
- OriginatorUserID: actorID,
+ OriginatorUserID: originatorUserID,
})
+ // For an AGENT author, compensate ONLY explicit @agent/@squad mentions.
+ // computeCommentAgentTriggers can also return the assigned-squad-leader
+ // fallback (Source = issue-assignee) for a plain worker-agent reply on a
+ // squad-assigned issue; that conversational routing is intentionally NOT
+ // replayed here. Restricting to the explicit-mention sources keeps the
+ // invariant unconditional — a plain agent reply / acknowledgement earns
+ // no follow-up regardless of issue assignment — which is the anti-loop
+ // boundary the old member-only filter protected (MUL-4304). Member
+ // comments are unaffected: they keep their full routing.
+ if actorType != "member" {
+ triggers = keepExplicitMentionTriggers(triggers)
+ }
scoped := make([]commentAgentTrigger, 0, 1)
for _, trigger := range triggers {
if uuidToString(trigger.Agent.ID) == agentID {
@@ -2543,8 +2578,30 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
"issue_id", uuidToString(task.IssueID),
"completed_task_id", uuidToString(task.ID),
"agent_id", agentID,
- "undelivered_member_comments", scheduled)
+ "undelivered_comments", scheduled)
+ }
+}
+
+// keepExplicitMentionTriggers filters a computed trigger set down to the ones
+// produced by an EXPLICIT @agent / @squad mention (MUL-4304). It is applied to
+// agent-authored comments during completion reconcile so that only a
+// deliberately-targeted mention earns a replay — the assigned-squad-leader
+// fallback, thread-parent / conversation continuation, and issue-assignee
+// routing (all non-mention sources) are intentionally excluded, so a plain
+// agent reply or acknowledgement never earns a follow-up here. Member comments
+// are never passed through this filter; they keep their full routing.
+func keepExplicitMentionTriggers(triggers []commentAgentTrigger) []commentAgentTrigger {
+ if len(triggers) == 0 {
+ return triggers
+ }
+ filtered := make([]commentAgentTrigger, 0, len(triggers))
+ for _, trigger := range triggers {
+ switch trigger.Source {
+ case commentTriggerSourceMentionAgent, commentTriggerSourceMentionSquadLeader:
+ filtered = append(filtered, trigger)
+ }
}
+ return filtered
}
// buildCoalescedCommentData loads the full detail of each comment that was
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index 0772e7bbb1..503189ad43 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -517,63 +517,6 @@ func (q *Queries) ListCommentsSinceForIssue(ctx context.Context, arg ListComment
return items, nil
}
-const listMemberCommentsForIssueSince = `-- name: ListMemberCommentsForIssueSince :many
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id FROM comment
-WHERE issue_id = $1
- AND author_type = 'member'
- AND created_at > $2
-ORDER BY created_at ASC, id ASC
-`
-
-type ListMemberCommentsForIssueSinceParams struct {
- IssueID pgtype.UUID `json:"issue_id"`
- Since pgtype.Timestamptz `json:"since"`
-}
-
-// MUL-4195 completion reconciliation: every MEMBER-authored comment on an issue
-// created strictly after @since (a run's dispatched_at anchor), oldest first.
-// The reconcile pass replays each undelivered one through the normal trigger
-// pipeline so a single coalesced follow-up run covers all of them, guaranteeing
-// at-least-once processing for deliberate user input that landed after the
-// completing run's claim response was built. Restricted to author_type =
-// 'member' to preserve the anti-loop guarantees (agent replies /
-// acknowledgements / self-triggers never qualify). Ordered ASC so replaying in
-// order lets later comments coalesce onto the follow-up created by the first.
-func (q *Queries) ListMemberCommentsForIssueSince(ctx context.Context, arg ListMemberCommentsForIssueSinceParams) ([]Comment, error) {
- rows, err := q.db.Query(ctx, listMemberCommentsForIssueSince, arg.IssueID, arg.Since)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []Comment{}
- for rows.Next() {
- var i Comment
- if err := rows.Scan(
- &i.ID,
- &i.IssueID,
- &i.AuthorType,
- &i.AuthorID,
- &i.Content,
- &i.Type,
- &i.CreatedAt,
- &i.UpdatedAt,
- &i.ParentID,
- &i.WorkspaceID,
- &i.ResolvedAt,
- &i.ResolvedByType,
- &i.ResolvedByID,
- &i.SourceTaskID,
- ); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
const listRecentThreadCommentsForIssue = `-- name: ListRecentThreadCommentsForIssue :many
WITH RECURSIVE membership(id, root_id, comment_created_at) AS (
-- Each root maps to itself.
@@ -714,6 +657,80 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List
return items, nil
}
+const listReconcilableCommentsForIssueSince = `-- name: ListReconcilableCommentsForIssueSince :many
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id FROM comment
+WHERE issue_id = $1
+ AND author_type IN ('member', 'agent')
+ AND created_at > $2
+ORDER BY created_at ASC, id ASC
+`
+
+type ListReconcilableCommentsForIssueSinceParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ Since pgtype.Timestamptz `json:"since"`
+}
+
+// MUL-4195 / MUL-4304 completion reconciliation: every MEMBER- or AGENT-authored
+// comment on an issue created strictly after @since (the completing run's
+// created_at anchor), oldest first. The reconcile pass replays each undelivered
+// one through the normal trigger pipeline so a single coalesced follow-up run
+// covers all of them, guaranteeing at-least-once processing for input that
+// landed after the completing run's claim response was built.
+//
+// Author-type scope (MUL-4304): originally restricted to author_type = 'member'.
+// That left a gap — an explicit agent→agent @mention (agent A comments
+// `@agent B`) that landed while B already had a DISPATCHED task was dropped by
+// the create-time enqueue path (merge only folds into a QUEUED task, so a
+// dispatched target hits the merge-miss + active-task continue) and then never
+// compensated here, because agent-authored comments were excluded. We now also
+// return 'agent' comments so those explicit mentions can be replayed.
+//
+// This does NOT reopen the anti-loop guarantees the member-only filter was
+// protecting. The reconcile pass runs each returned comment through
+// computeCommentAgentTriggers under its OWN author_type, and for an agent author
+// it then keeps ONLY explicit @agent/@squad mention triggers
+// (keepExplicitMentionTriggers) — the assigned-squad-leader fallback and all
+// other conversational routing are dropped, so a plain agent reply /
+// acknowledgement yields nothing regardless of issue assignment. The reconcile
+// pass further keeps only triggers routing to the agent that just completed, so
+// an agent comment can never fan out to an unrelated agent. Ordered ASC so
+// replaying in order lets later comments coalesce onto the follow-up created by
+// the first.
+func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, arg ListReconcilableCommentsForIssueSinceParams) ([]Comment, error) {
+ rows, err := q.db.Query(ctx, listReconcilableCommentsForIssueSince, arg.IssueID, arg.Since)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Comment{}
+ for rows.Next() {
+ var i Comment
+ if err := rows.Scan(
+ &i.ID,
+ &i.IssueID,
+ &i.AuthorType,
+ &i.AuthorID,
+ &i.Content,
+ &i.Type,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.ParentID,
+ &i.WorkspaceID,
+ &i.ResolvedAt,
+ &i.ResolvedByType,
+ &i.ResolvedByID,
+ &i.SourceTaskID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listRootCommentsForIssue = `-- name: ListRootCommentsForIssue :many
WITH RECURSIVE selected_roots AS (
SELECT c.id, c.created_at
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index 079ff928f6..23d2f35f58 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -329,19 +329,36 @@ WHERE issue_id = @issue_id
ORDER BY created_at DESC
LIMIT 1;
--- name: ListMemberCommentsForIssueSince :many
--- MUL-4195 completion reconciliation: every MEMBER-authored comment on an issue
--- created strictly after @since (a run's dispatched_at anchor), oldest first.
--- The reconcile pass replays each undelivered one through the normal trigger
--- pipeline so a single coalesced follow-up run covers all of them, guaranteeing
--- at-least-once processing for deliberate user input that landed after the
--- completing run's claim response was built. Restricted to author_type =
--- 'member' to preserve the anti-loop guarantees (agent replies /
--- acknowledgements / self-triggers never qualify). Ordered ASC so replaying in
--- order lets later comments coalesce onto the follow-up created by the first.
+-- name: ListReconcilableCommentsForIssueSince :many
+-- MUL-4195 / MUL-4304 completion reconciliation: every MEMBER- or AGENT-authored
+-- comment on an issue created strictly after @since (the completing run's
+-- created_at anchor), oldest first. The reconcile pass replays each undelivered
+-- one through the normal trigger pipeline so a single coalesced follow-up run
+-- covers all of them, guaranteeing at-least-once processing for input that
+-- landed after the completing run's claim response was built.
+--
+-- Author-type scope (MUL-4304): originally restricted to author_type = 'member'.
+-- That left a gap — an explicit agent→agent @mention (agent A comments
+-- `@agent B`) that landed while B already had a DISPATCHED task was dropped by
+-- the create-time enqueue path (merge only folds into a QUEUED task, so a
+-- dispatched target hits the merge-miss + active-task continue) and then never
+-- compensated here, because agent-authored comments were excluded. We now also
+-- return 'agent' comments so those explicit mentions can be replayed.
+--
+-- This does NOT reopen the anti-loop guarantees the member-only filter was
+-- protecting. The reconcile pass runs each returned comment through
+-- computeCommentAgentTriggers under its OWN author_type, and for an agent author
+-- it then keeps ONLY explicit @agent/@squad mention triggers
+-- (keepExplicitMentionTriggers) — the assigned-squad-leader fallback and all
+-- other conversational routing are dropped, so a plain agent reply /
+-- acknowledgement yields nothing regardless of issue assignment. The reconcile
+-- pass further keeps only triggers routing to the agent that just completed, so
+-- an agent comment can never fan out to an unrelated agent. Ordered ASC so
+-- replaying in order lets later comments coalesce onto the follow-up created by
+-- the first.
SELECT * FROM comment
WHERE issue_id = @issue_id
- AND author_type = 'member'
+ AND author_type IN ('member', 'agent')
AND created_at > @since
ORDER BY created_at ASC, id ASC;