Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(comments): guarantee at-least-once processing of user comments (MUL-4195) (#5068)
Multica Eve75695a2e4084
diff --git a/server/cmd/server/comment_at_least_once_test.go b/server/cmd/server/comment_at_least_once_test.gonew file mode 100644index 0000000000..680ea3edff--- /dev/null+++ b/server/cmd/server/comment_at_least_once_test.go@@ -0,0 +1,410 @@+package main++import (+ "context"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// coalescedCommentIDs returns the coalesced_comment_ids of the most recent+// not-yet-started task for an issue, as text ids.+func coalescedCommentIDs(t *testing.T, issueID string) []string {+ t.Helper()+ var ids []string+ err := testPool.QueryRow(context.Background(),+ `SELECT COALESCE(array_agg(c::text), '{}')+ FROM (+ SELECT unnest(coalesced_comment_ids) AS c+ FROM (+ SELECT coalesced_comment_ids+ FROM agent_task_queue+ WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'waiting_local_directory', 'deferred')+ ORDER BY created_at DESC+ LIMIT 1+ ) t+ ) s`,+ issueID).Scan(&ids)+ if err != nil {+ t.Fatalf("failed to read coalesced_comment_ids: %v", err)+ }+ return ids+}++func containsID(ids []string, want string) bool {+ for _, id := range ids {+ if id == want {+ return true+ }+ }+ return false+}++// TestConsecutiveCommentsMergeNotDropped is the MUL-4195 regression test.+//+// Before the fix, a second/third comment posted while the agent already had a+// queued task was silently DROPPED by the HasPendingTaskForIssueAndAgent dedup:+// only the first comment survived and the later instructions were lost. The fix+// folds each new comment into the pending task instead — still one task (no+// concurrent runs), but every deliberate comment is preserved: the trigger is+// repointed to the newest comment and the earlier ones are recorded in+// coalesced_comment_ids so the single run must address them all.+func TestConsecutiveCommentsMergeNotDropped(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ agentID := getAgentID(t)+ issueID := createIssueAssignedToAgent(t, "Merge-not-drop test", agentID)+ clearTasks(t, issueID) // drop the assignment task so we start clean+ t.Cleanup(func() {+ clearTasks(t, issueID)+ resp := authRequest(t, "DELETE", "/api/issues/"+issueID, nil)+ resp.Body.Close()+ })++ // Three deliberate comments in a row, before any run starts.+ cidA := postComment(t, issueID, "First instruction", nil)+ cidB := postComment(t, issueID, "Second, correcting the first", nil)+ cidC := postComment(t, issueID, "Third, one more detail", nil)++ // Still exactly one task: we bound concurrency to one run per (issue,agent).+ if n := countPendingTasksForAgent(t, issueID, agentID); n != 1 {+ t.Fatalf("expected exactly 1 pending task after 3 comments, got %d", n)+ }++ // The trigger points at the NEWEST comment so the injected prompt shows the+ // latest deliberate instruction.+ if got := latestTriggerCommentID(t, issueID); got != cidC {+ t.Errorf("expected trigger_comment_id to be repointed to newest comment %s, got %s", cidC, got)+ }++ // The earlier comments are preserved (not dropped) as coalesced comments.+ coalesced := coalescedCommentIDs(t, issueID)+ if !containsID(coalesced, cidA) {+ t.Errorf("expected coalesced_comment_ids to preserve first comment %s; got %v", cidA, coalesced)+ }+ if !containsID(coalesced, cidB) {+ t.Errorf("expected coalesced_comment_ids to preserve second comment %s; got %v", cidB, coalesced)+ }+ // The current trigger must not also appear in the coalesced set.+ if containsID(coalesced, cidC) {+ t.Errorf("newest comment %s should be the trigger, not a coalesced entry; got %v", cidC, coalesced)+ }+}++// TestGetLatestMemberCommentForIssueSince pins the completion-reconciliation+// query (MUL-4195): it must surface member comments newer than the run's+// started_at anchor and ignore agent-authored comments (the anti-loop rule).+func TestGetLatestMemberCommentForIssueSince(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ queries := db.New(testPool)++ agentID := getAgentID(t)+ issueID := createIssue(t, "Reconcile query test")+ t.Cleanup(func() {+ resp := authRequest(t, "DELETE", "/api/issues/"+issueID, nil)+ resp.Body.Close()+ })++ anchor := time.Now()+ // A member comment BEFORE the anchor — must not qualify.+ insertCommentAt(t, issueID, "member", testUserID, "old member comment", anchor.Add(-10*time.Minute))+ // An agent comment AFTER the anchor — must be ignored (loop safety).+ insertCommentAt(t, issueID, "agent", agentID, "agent reply after start", anchor.Add(2*time.Minute))++ pgAnchor := pgtype.Timestamptz{Time: anchor, Valid: true}+ pgIssue := toPgUUID(t, issueID)++ // With only an older member comment and a newer agent comment, nothing+ // qualifies → ErrNoRows (no spurious follow-up).+ if _, err := queries.GetLatestMemberCommentForIssueSince(ctx, db.GetLatestMemberCommentForIssueSinceParams{+ IssueID: pgIssue,+ Since: pgAnchor,+ }); err != pgx.ErrNoRows {+ t.Fatalf("expected pgx.ErrNoRows when only an agent comment is newer, got %v", err)+ }++ // Now a member comment AFTER the anchor — this is the deliberate input that+ // must earn a follow-up.+ wantID := insertCommentAt(t, issueID, "member", testUserID, "new member instruction", anchor.Add(5*time.Minute))+ got, err := queries.GetLatestMemberCommentForIssueSince(ctx, db.GetLatestMemberCommentForIssueSinceParams{+ IssueID: pgIssue,+ Since: pgAnchor,+ })+ if err != nil {+ t.Fatalf("expected the newer member comment, got error %v", err)+ }+ if pgUUIDToText(got.ID) != wantID {+ t.Errorf("expected latest member comment %s, got %s", wantID, pgUUIDToText(got.ID))+ }+}++// insertCommentAt inserts a comment with an explicit created_at and author, and+// returns its id. Used to construct precise before/after-anchor scenarios.+func insertCommentAt(t *testing.T, issueID, authorType, authorID, content string, at time.Time) string {+ t.Helper()+ var id string+ err := testPool.QueryRow(context.Background(), `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, 'comment', $6, $6)+ RETURNING id::text+ `, issueID, testWorkspaceID, authorType, authorID, content, at).Scan(&id)+ if err != nil {+ t.Fatalf("insertCommentAt: %v", err)+ }+ return id+}++func toPgUUID(t *testing.T, s string) pgtype.UUID {+ t.Helper()+ var u pgtype.UUID+ if err := u.Scan(s); err != nil {+ t.Fatalf("parse uuid %q: %v", s, err)+ }+ return u+}++func pgUUIDToText(u pgtype.UUID) string {+ v, err := u.Value()+ if err != nil || v == nil {+ return ""+ }+ s, _ := v.(string)+ return s+}++// TestMergeCommentIntoPendingTask_RecomputesOriginatorAndSkipsDispatched is the+// MUL-4195 second-round regression test for the merge query. It pins two+// properties:+//+// - Recompute-on-merge (review must-fix #1): folding a DIFFERENT member's+// comment into a queued task re-stamps originator_user_id (and would+// re-stamp the overlay) to the new comment's originator, so the single+// coalescing run carries the latest instruction's identity instead of the+// original user's — and the comment is never dropped. The earlier gate+// returned ErrNoRows here, which then hit the one-pending-per-(issue,agent)+// unique index on the fresh-enqueue fallback and silently lost the comment.+// - Pre-claim-only target (review must-fix #2): a DISPATCHED task is never a+// merge target (its claim response is already built), so merging returns+// ErrNoRows and the comment is left to completion reconciliation.+func TestMergeCommentIntoPendingTask_RecomputesOriginatorAndSkipsDispatched(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ queries := db.New(testPool)++ agentID := getAgentID(t)+ issueID := createIssueAssignedToAgent(t, "Merge recompute test", agentID)+ clearTasks(t, issueID) // drop the assignment task so we start clean+ t.Cleanup(func() {+ clearTasks(t, issueID)+ resp := authRequest(t, "DELETE", "/api/issues/"+issueID, nil)+ resp.Body.Close()+ })++ now := time.Now()+ cidA := insertCommentAt(t, issueID, "member", testUserID, "first, from originator A", now.Add(-2*time.Minute))+ cidB := insertCommentAt(t, issueID, "member", testUserID, "second, folds in", now.Add(-1*time.Minute))++ // A second member to act as a DIFFERENT originator.+ otherUserID := createWorkspaceMember(t, "merge-recompute-other")++ var runtimeID string+ if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {+ t.Fatalf("load runtime: %v", err)+ }+ // Seed a queued task originated by testUserID and triggered by cidA.+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, originator_user_id)+ VALUES ($1, $2, $3, $4, 'queued', 0, $5)+ `, agentID, runtimeID, issueID, cidA, testUserID); err != nil {+ t.Fatalf("seed queued task: %v", err)+ }++ pgIssue := toPgUUID(t, issueID)+ pgAgent := toPgUUID(t, agentID)++ // A DIFFERENT originator (userB) now MERGES (no gate): trigger repointed to+ // cidB, originator re-stamped to userB, cidA preserved as coalesced.+ if _, err := queries.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{+ IssueID: pgIssue,+ AgentID: pgAgent,+ NewTriggerCommentID: toPgUUID(t, cidB),+ NewOriginatorUserID: toPgUUID(t, otherUserID),+ NewTriggerSummary: pgtype.Text{String: "second, folds in", Valid: true},+ }); err != nil {+ t.Fatalf("recompute merge should succeed for a different originator, got %v", err)+ }+ if got := latestTriggerCommentID(t, issueID); got != cidB {+ t.Errorf("merge must repoint the trigger to %s, got %s", cidB, got)+ }+ if ids := coalescedCommentIDs(t, issueID); !containsID(ids, cidA) {+ t.Errorf("merge must preserve %s as coalesced, got %v", cidA, ids)+ }+ if got := taskOriginator(t, issueID, agentID); got != otherUserID {+ t.Errorf("merge must re-stamp originator to the new comment's originator %s, got %s", otherUserID, got)+ }++ // Now flip the task to 'dispatched' and confirm a further comment is NOT a+ // merge target — its claim response is already built, so merging would+ // falsely mark an undelivered comment as delivered (must-fix #2).+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE issue_id = $1`, issueID); err != nil {+ t.Fatalf("flip task to dispatched: %v", err)+ }+ cidC := insertCommentAt(t, issueID, "member", testUserID, "third, arrives after dispatch", now)+ if _, err := queries.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{+ IssueID: pgIssue,+ AgentID: pgAgent,+ NewTriggerCommentID: toPgUUID(t, cidC),+ NewOriginatorUserID: toPgUUID(t, testUserID),+ NewTriggerSummary: pgtype.Text{String: "third", Valid: true},+ }); err != pgx.ErrNoRows {+ t.Fatalf("merge into a dispatched task must return pgx.ErrNoRows, got %v", err)+ }+}++// createWorkspaceMember inserts a fresh user + workspace member and returns the+// user id, for tests that need a second distinct originator.+func createWorkspaceMember(t *testing.T, slug string) string {+ t.Helper()+ ctx := context.Background()+ var userID string+ email := slug + "-" + time.Now().Format("150405.000000") + "@example.test"+ if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,+ "Merge Test "+slug, email).Scan(&userID); err != nil {+ t.Fatalf("create user: %v", err)+ }+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'admin')`,+ testWorkspaceID, userID); err != nil {+ t.Fatalf("create member: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM member WHERE user_id = $1`, userID)+ testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)+ })+ return userID+}++// taskOriginator returns originator_user_id (as text) of the most recent task+// for (issue, agent).+func taskOriginator(t *testing.T, issueID, agentID string) string {+ t.Helper()+ var originator string+ if err := testPool.QueryRow(context.Background(), `+ SELECT COALESCE(originator_user_id::text, '')+ FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2+ ORDER BY created_at DESC+ LIMIT 1+ `, issueID, agentID).Scan(&originator); err != nil {+ t.Fatalf("read task originator: %v", err)+ }+ return originator+}++// TestMergeCommentIntoPendingTask_TargetsQueuedNotDeferred is the MUL-4195+// round-4 regression test. When a `(issue, agent)` pair has BOTH an older+// queued task (the run about to be claimed) and a newer deferred+// assignee-fallback task, a new comment's merge must land on the QUEUED task —+// the one that will actually run next — not the newer deferred fallback. An+// earlier `status IN ('queued','deferred') ORDER BY created_at DESC` target+// picked the deferred row, so the comment missed the imminent run and the+// deferred fallback could later promote into a duplicate. The merge now matches+// `status = 'queued'` only; the deferred row is left to its own escalation+// lifecycle.+func TestMergeCommentIntoPendingTask_TargetsQueuedNotDeferred(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ queries := db.New(testPool)++ agentID := getAgentID(t)+ issueID := createIssueAssignedToAgent(t, "Merge target queued-vs-deferred test", agentID)+ clearTasks(t, issueID)+ t.Cleanup(func() {+ clearTasks(t, issueID)+ resp := authRequest(t, "DELETE", "/api/issues/"+issueID, nil)+ resp.Body.Close()+ })++ now := time.Now()+ cidQueued := insertCommentAt(t, issueID, "member", testUserID, "queued task trigger", now.Add(-3*time.Minute))+ cidDeferred := insertCommentAt(t, issueID, "member", testUserID, "deferred fallback trigger", now.Add(-2*time.Minute))+ cidNew := insertCommentAt(t, issueID, "member", testUserID, "new comment, must fold into queued", now.Add(-1*time.Minute))++ var runtimeID string+ if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {+ t.Fatalf("load runtime: %v", err)+ }++ // Older queued task (the imminent run) ...+ var queuedTaskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, created_at)+ VALUES ($1, $2, $3, $4, 'queued', 0, now() - interval '3 minutes')+ RETURNING id+ `, agentID, runtimeID, issueID, cidQueued).Scan(&queuedTaskID); err != nil {+ t.Fatalf("seed queued task: %v", err)+ }+ // ... and a NEWER deferred assignee-fallback task for the same (issue, agent).+ var deferredTaskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, created_at, fire_at)+ VALUES ($1, $2, $3, $4, 'deferred', 0, now() - interval '2 minutes', now() + interval '5 minutes')+ RETURNING id+ `, agentID, runtimeID, issueID, cidDeferred).Scan(&deferredTaskID); err != nil {+ t.Fatalf("seed deferred task: %v", err)+ }++ row, err := queries.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{+ IssueID: toPgUUID(t, issueID),+ AgentID: toPgUUID(t, agentID),+ NewTriggerCommentID: toPgUUID(t, cidNew),+ NewOriginatorUserID: toPgUUID(t, testUserID),+ NewTriggerSummary: pgtype.Text{String: "new comment", Valid: true},+ })+ if err != nil {+ t.Fatalf("merge should target the queued task, got %v", err)+ }+ // The merge must have hit the QUEUED task, not the deferred one.+ if got := pgUUIDToText(row.ID); got != queuedTaskID {+ t.Fatalf("merge must target the queued task %s, got %s", queuedTaskID, got)+ }++ // Queued task: trigger repointed to the new comment, old trigger coalesced.+ var queuedTrigger string+ var queuedCoalesced []string+ if err := testPool.QueryRow(ctx, `+ SELECT trigger_comment_id::text, coalesced_comment_ids::text[] FROM agent_task_queue WHERE id = $1+ `, queuedTaskID).Scan(&queuedTrigger, &queuedCoalesced); err != nil {+ t.Fatalf("read queued task: %v", err)+ }+ if queuedTrigger != cidNew {+ t.Errorf("queued task trigger must be repointed to %s, got %s", cidNew, queuedTrigger)+ }+ if !containsID(queuedCoalesced, cidQueued) {+ t.Errorf("queued task must coalesce its old trigger %s, got %v", cidQueued, queuedCoalesced)+ }++ // Deferred fallback must be UNTOUCHED (still its own trigger, still deferred).+ var deferredTrigger, deferredStatus string+ if err := testPool.QueryRow(ctx, `+ SELECT trigger_comment_id::text, status FROM agent_task_queue WHERE id = $1+ `, deferredTaskID).Scan(&deferredTrigger, &deferredStatus); err != nil {+ t.Fatalf("read deferred task: %v", err)+ }+ if deferredTrigger != cidDeferred {+ t.Errorf("deferred fallback trigger must be untouched (%s), got %s", cidDeferred, deferredTrigger)+ }+ if deferredStatus != "deferred" {+ t.Errorf("deferred fallback status must stay 'deferred', got %s", deferredStatus)+ }+}diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex 9d469cfba9..f61d0a75fb 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -158,6 +158,44 @@ func buildCommentPrompt(task Task, provider string) string {}fmt.Fprintf(&b, "[NEW COMMENT] %s just left a new comment. Focus on THIS comment — do not confuse it with previous ones:\n\n", authorLabel)fmt.Fprintf(&b, "> %s\n\n", task.TriggerCommentContent)+ // MUL-4195: comments that arrived before this run started were folded+ // into it rather than dropped. The trigger above is the newest; the+ // agent must ALSO address these earlier ones so no deliberate user+ // instruction is silently lost. Prefer the embedded detail so the agent+ // does not have to guess which thread each folded comment lives in+ // (they may span multiple threads — review should-fix #3); fall back to+ // a thread-agnostic issue-wide fetch hint for old servers that only send+ // the ids.+ if len(task.CoalescedComments) > 0 {+ fmt.Fprintf(&b, "This run also covers %d earlier comment(s) posted before it started — you must read and address them too, not just the one above. They may be in different threads, so each is reproduced here with its own thread:\n\n", len(task.CoalescedComments))+ for _, cc := range task.CoalescedComments {+ authorLabel := "A user"+ if cc.AuthorType == "agent" {+ name := cc.AuthorName+ if name == "" {+ name = "another agent"+ }+ authorLabel = fmt.Sprintf("Another agent (%s)", name)+ } else if cc.AuthorName != "" {+ authorLabel = cc.AuthorName+ }+ fmt.Fprintf(&b, "- comment %s", cc.ID)+ if cc.CreatedAt != "" {+ fmt.Fprintf(&b, " (%s, %s)", authorLabel, cc.CreatedAt)+ } else {+ fmt.Fprintf(&b, " (%s)", authorLabel)+ }+ if cc.ThreadID != "" {+ fmt.Fprintf(&b, " [thread %s]", cc.ThreadID)+ }+ b.WriteString(":\n")+ fmt.Fprintf(&b, " > %s\n", strings.ReplaceAll(strings.TrimSpace(cc.Content), "\n", "\n > "))+ }+ fmt.Fprintf(&b, "\nIf you need the surrounding discussion for any of them, fetch its thread with `multica issue comment list %s --thread <thread-id> --tail 30 --output json` using the thread id shown above.\n\n", task.IssueID)+ } else if len(task.CoalescedCommentIDs) > 0 {+ fmt.Fprintf(&b, "This run also covers %d earlier comment(s) posted before it started — you must read and address them too, not just the one above: %s. These may be in DIFFERENT threads, so do not assume they share the triggering thread; fetch each by pulling the issue-wide discussion with `multica issue comment list %s --recent 30 --output json` (expand with `--full` if a thread is folded) and locate the ids above.\n\n",+ len(task.CoalescedCommentIDs), strings.Join(task.CoalescedCommentIDs, ", "), task.IssueID)+ }if task.TriggerAuthorType == "agent" {b.WriteString("⚠️ The triggering comment was posted by another agent. Decide whether a reply is warranted. If you produced actual work this turn (investigated, fixed something, answered a real question), post the result as a normal reply — that is NOT a noise comment, and the standard rule that final results must be delivered via comment still applies. If the triggering comment was a pure acknowledgment, thanks, or sign-off AND you produced no work this turn, do NOT reply — and do NOT post a comment saying 'No reply needed' or similar. Simply exit with no output. Silence is the preferred way to end agent-to-agent threads. If you do reply, do not @mention the other agent as a sign-off (that re-triggers them and starts a loop).\n\n")}diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.goindex 8117821d39..9b60ede261 100644--- a/server/internal/daemon/prompt_test.go+++ b/server/internal/daemon/prompt_test.go@@ -601,3 +601,78 @@ func TestBuildPromptResumedNoDeltaDoesNotForceThreadRead(t *testing.T) {t.Errorf("resumed/no-delta prompt must not use the cold-start forced-read wording, got:\n%s", out)}}++// TestBuildCommentPromptCoalescedCrossThread pins MUL-4195 review should-fix #3:+// when a run coalesces comments that span MULTIPLE threads, the prompt must+// embed each folded comment's content with its OWN thread id instead of+// claiming they all live in the triggering thread. The earlier version told the+// agent "they are in the triggering thread" and handed a single `--thread`+// command — wrong (and lossy) when the folded comments came from different+// threads.+func TestBuildCommentPromptCoalescedCrossThread(t *testing.T) {+ task := Task{+ IssueID: "issue-xthread-1",+ TriggerCommentID: "trigger-newest",+ TriggerThreadID: "thread-root-A",+ TriggerCommentContent: "latest instruction",+ TriggerAuthorType: "member",+ CoalescedCommentIDs: []string{"c-old-1", "c-old-2"},+ CoalescedComments: []CoalescedCommentData{+ {ID: "c-old-1", ThreadID: "thread-root-A", AuthorType: "member", AuthorName: "Alice", Content: "first earlier comment", CreatedAt: "2026-07-08T01:00:00Z"},+ {ID: "c-old-2", ThreadID: "thread-root-B", AuthorType: "member", AuthorName: "Bob", Content: "comment in a different thread", CreatedAt: "2026-07-08T02:00:00Z"},+ },+ }+ out := BuildPrompt(task, "claude")++ // The stale same-thread assumption must be gone.+ if strings.Contains(out, "they are in the triggering thread") {+ t.Errorf("prompt must not assume coalesced comments share the triggering thread, got:\n%s", out)+ }+ // Each folded comment's content is embedded directly, so the agent never+ // has to guess which thread to read to find it.+ for _, want := range []string{"first earlier comment", "comment in a different thread"} {+ if !strings.Contains(out, want) {+ t.Errorf("prompt must embed coalesced comment content %q, got:\n%s", want, out)+ }+ }+ // Each distinct thread id is surfaced so a follow-up fetch targets the+ // right thread — including the OTHER thread (B), not just the trigger's.+ for _, want := range []string{"thread-root-A", "thread-root-B"} {+ if !strings.Contains(out, want) {+ t.Errorf("prompt must surface coalesced comment thread id %q, got:\n%s", want, out)+ }+ }+ // Both coalesced comment ids remain referenced.+ for _, id := range []string{"c-old-1", "c-old-2"} {+ if !strings.Contains(out, id) {+ t.Errorf("prompt must reference coalesced comment id %s, got:\n%s", id, out)+ }+ }+}++// TestBuildCommentPromptCoalescedIDsOnlyFallback pins the old-server fallback:+// when only coalesced ids are shipped (no embedded detail), the prompt must+// still NOT assume a shared thread and must point at an issue-wide fetch.+func TestBuildCommentPromptCoalescedIDsOnlyFallback(t *testing.T) {+ task := Task{+ IssueID: "issue-fallback-1",+ TriggerCommentID: "trigger-newest",+ TriggerThreadID: "thread-root-A",+ TriggerCommentContent: "latest instruction",+ TriggerAuthorType: "member",+ CoalescedCommentIDs: []string{"c-old-1", "c-old-2"},+ }+ out := BuildPrompt(task, "claude")++ if strings.Contains(out, "they are in the triggering thread") {+ t.Errorf("id-only fallback must not assume a shared thread, got:\n%s", out)+ }+ if !strings.Contains(out, "--recent 30") {+ t.Errorf("id-only fallback must point at an issue-wide fetch (--recent 30), got:\n%s", out)+ }+ for _, id := range []string{"c-old-1", "c-old-2"} {+ if !strings.Contains(out, id) {+ t.Errorf("id-only fallback must reference coalesced comment id %s, got:\n%s", id, out)+ }+ }+}diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex 4168b6de2c..00b459d677 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -71,6 +71,8 @@ type Task struct {PriorSessionID string `json:"prior_session_id,omitempty"` // Claude session ID from a previous task on this issuePriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on this issueTriggerCommentID string `json:"trigger_comment_id,omitempty"` // comment that triggered this task+ CoalescedCommentIDs []string `json:"coalesced_comment_ids,omitempty"` // MUL-4195: earlier comments folded into this run while it was still queued; the agent must address these in addition to the (newest) triggering comment. Empty for old servers / non-merged runs+ CoalescedComments []CoalescedCommentData `json:"coalesced_comments,omitempty"` // MUL-4195: full detail of the folded comments (thread_id/author/created_at/content) so the prompt can address each without assuming a shared thread. Empty for old servers / non-merged runsTriggerThreadID string `json:"trigger_thread_id,omitempty"` // root comment ID for the triggering thread; falls back to trigger_comment_id on old serversTriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering commentTriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind for the triggering comment@@ -139,6 +141,19 @@ type ChatAttachmentMeta struct {ContentType string `json:"content_type,omitempty"`}+// CoalescedCommentData mirrors the server-side struct (handler.CoalescedCommentData):+// the full detail of a comment folded into this run while it was still queued+// (MUL-4195). The prompt embeds each one directly so the agent addresses every+// folded comment without assuming they all live in the triggering thread.+type CoalescedCommentData struct {+ ID string `json:"id"`+ ThreadID string `json:"thread_id,omitempty"`+ AuthorType string `json:"author_type,omitempty"`+ AuthorName string `json:"author_name,omitempty"`+ Content string `json:"content"`+ CreatedAt string `json:"created_at,omitempty"`+}+// AgentData holds agent details returned by the claim endpoint.type AgentData struct {ID string `json:"id"`diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex f0362de491..e1e51665f0 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -310,6 +310,8 @@ type AgentTaskResponse struct {// WorkDir directly; newer UIs should prefer RelativeWorkDir.RelativeWorkDir string `json:"relative_work_dir,omitempty"`TriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this task+ CoalescedCommentIDs []string `json:"coalesced_comment_ids,omitempty"` // MUL-4195: earlier comments folded into this run when it had not yet started, so a single run still covers every deliberate comment; trigger_comment_id is the newest. Surfaced so the UI can show which comments a run covered. omitempty so old clients ignore it+ CoalescedComments []CoalescedCommentData `json:"coalesced_comments,omitempty"` // MUL-4195: full detail (thread_id/author/created_at/content) of the folded comments, so the daemon prompt can address each without assuming they share the triggering thread. omitempty so old clients ignore itTriggerThreadID string `json:"trigger_thread_id,omitempty"` // root comment ID for the triggering threadTriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering commentTriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletes@@ -385,6 +387,25 @@ type ChatAttachmentMeta struct {ContentType string `json:"content_type,omitempty"`}+// CoalescedCommentData carries the full detail of a comment that was folded+// into a not-yet-started run (MUL-4195) so the daemon can embed it directly in+// the prompt. The earlier merge path only shipped comment IDs plus a+// "they are in the triggering thread" hint, which is WRONG when the folded+// comments span multiple threads (an issue's assignee can be triggered from+// different threads). Shipping thread_id / author / created_at / content lets+// the prompt address each folded comment without assuming a single thread or+// relying on a `--recent N` window that may not cover them all. The mirror+// struct on the daemon side lives in internal/daemon/types.go with the same+// JSON field names.+type CoalescedCommentData struct {+ ID string `json:"id"`+ ThreadID string `json:"thread_id,omitempty"`+ AuthorType string `json:"author_type,omitempty"`+ AuthorName string `json:"author_name,omitempty"`+ Content string `json:"content"`+ CreatedAt string `json:"created_at,omitempty"`+}+// TaskAgentData holds agent info included in claim responses so the daemon// can set up the execution environment (branch naming, skill files, instructions).type TaskAgentData struct {@@ -430,29 +451,30 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {handoffNote = t.HandoffNote.String}return AgentTaskResponse{- ID: uuidToString(t.ID),- AgentID: uuidToString(t.AgentID),- RuntimeID: uuidToString(t.RuntimeID),- IssueID: uuidToString(t.IssueID),- WorkspaceID: workspaceID,- Status: t.Status,- Priority: t.Priority,- DispatchedAt: timestampToPtr(t.DispatchedAt),- StartedAt: timestampToPtr(t.StartedAt),- CompletedAt: timestampToPtr(t.CompletedAt),- Result: result,- Error: textToPtr(t.Error),- FailureReason: failureReason,- Attempt: t.Attempt,- MaxAttempts: t.MaxAttempts,- ParentTaskID: uuidToPtr(t.ParentTaskID),- IsLeaderTask: t.IsLeaderTask,- CreatedAt: timestampToString(t.CreatedAt),- TriggerCommentID: uuidToPtr(t.TriggerCommentID),- TriggerSummary: textToPtr(t.TriggerSummary),- HandoffNote: handoffNote,- WorkDir: workDir,- RelativeWorkDir: relativeWorkDir(workDir, workspaceID, uuidToString(t.ID)),+ ID: uuidToString(t.ID),+ AgentID: uuidToString(t.AgentID),+ RuntimeID: uuidToString(t.RuntimeID),+ IssueID: uuidToString(t.IssueID),+ WorkspaceID: workspaceID,+ Status: t.Status,+ Priority: t.Priority,+ DispatchedAt: timestampToPtr(t.DispatchedAt),+ StartedAt: timestampToPtr(t.StartedAt),+ CompletedAt: timestampToPtr(t.CompletedAt),+ Result: result,+ Error: textToPtr(t.Error),+ FailureReason: failureReason,+ Attempt: t.Attempt,+ MaxAttempts: t.MaxAttempts,+ ParentTaskID: uuidToPtr(t.ParentTaskID),+ IsLeaderTask: t.IsLeaderTask,+ CreatedAt: timestampToString(t.CreatedAt),+ TriggerCommentID: uuidToPtr(t.TriggerCommentID),+ CoalescedCommentIDs: uuidsToStrings(t.CoalescedCommentIds),+ TriggerSummary: textToPtr(t.TriggerSummary),+ HandoffNote: handoffNote,+ WorkDir: workDir,+ RelativeWorkDir: relativeWorkDir(workDir, workspaceID, uuidToString(t.ID)),// Surface task source so the UI can distinguish issue-linked tasks// from chat-spawned or autopilot-spawned ones; all three may arrive// with issue_id = "" once a task has no linked issue.diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 33d73b6438..10534a1980 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1397,67 +1397,180 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu}for _, trigger := range triggers {if trigger.AlreadyPending {- continue- }- switch trigger.Source {- case commentTriggerSourceIssueAssignee:- if trigger.Squad != nil {- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {- slog.Warn("enqueue squad leader task failed",- "issue_id", uuidToString(issue.ID),- "squad_id", uuidToString(trigger.Squad.ID),- "leader_id", uuidToString(trigger.Agent.ID),- "error", err)- }- continue- }- if _, err := h.TaskService.EnqueueTaskForIssue(ctx, issue, triggerCommentID); err != nil {- slog.Warn("enqueue agent task on comment failed", "issue_id", uuidToString(issue.ID), "error", err)- }- case commentTriggerSourceMentionSquadLeader:- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {- slog.Warn("enqueue squad leader mention task failed",- "issue_id", uuidToString(issue.ID),- "agent_id", uuidToString(trigger.Agent.ID),- "error", err)- }- case commentTriggerSourceMentionAgent:- if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, trigger.Agent.ID, triggerCommentID); err != nil {- slog.Warn("enqueue mention agent task failed",- "issue_id", uuidToString(issue.ID),- "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)+ // MUL-4195: a queued/dispatched task for this (issue, agent)+ // already exists. Historically we DROPPED the comment here, losing+ // the user's follow-up instruction. Instead try to fold it into the+ // queued (not-yet-claimed) task so a single run still covers every+ // comment, re-stamping the run's originator/overlay to the new+ // comment (mergeCommentIntoPendingTask).+ if h.mergeCommentIntoPendingTask(ctx, issue, trigger, triggerCommentID) {continue}- if trigger.EscalationFallback == nil || getEscalationDelay() <= 0 {+ // The merge found no queued task to fold into: the existing task+ // is already dispatched/running (its claim response is built), or+ // the queued row was just claimed. We must NOT enqueue a+ // fresh queued task in that case — a dispatched sibling would trip+ // the idx_one_pending_task_per_issue_agent unique index (dropping+ // the comment again) and even where the index allows it we'd risk a+ // duplicate concurrent run. When an active task exists, its+ // completion reconcile (reconcileCommentsOnCompletion) is what+ // guarantees this comment earns a bounded follow-up. Only when NO+ // active task exists is a fresh enqueue both safe and necessary.+ if h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, trigger.Agent.ID) {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",+ }+ h.enqueueSingleCommentTrigger(ctx, issue, triggerCommentID, trigger, getEscalationDelay)+ }+}++// hasActiveTaskForIssueAndAgent reports whether the (issue, agent) pair has any+// non-terminal task whose completion will drive completion reconciliation. Used+// by the comment enqueue path to decide, after a merge miss, between deferring+// to reconcile (an active task exists) and enqueuing a fresh follow-up (none+// does). Fail-closed: on a DB error we return true so the caller does NOT+// enqueue a possibly-colliding duplicate — worst case the comment is caught by+// reconcile rather than double-run.+func (h *Handler) hasActiveTaskForIssueAndAgent(ctx context.Context, issueID, agentID pgtype.UUID) bool {+ active, err := h.Queries.HasActiveTaskForIssueAndAgent(ctx, db.HasActiveTaskForIssueAndAgentParams{+ IssueID: issueID,+ AgentID: agentID,+ })+ if err != nil {+ slog.Warn("has active task for issue+agent check failed",+ "issue_id", uuidToString(issueID), "agent_id", uuidToString(agentID), "error", err)+ return true+ }+ return active+}++// mergeCommentIntoPendingTask folds a newly-arrived comment into an existing+// not-yet-started task for (issue, agent) instead of dropping it (MUL-4195).+// Returns true when the comment was HANDLED — either merged, or a non-fatal DB+// error we deliberately do not convert into a duplicate task. Returns false+// only when no pending task exists anymore (pgx.ErrNoRows: it was+// claimed/started between the dedup check and now), so the caller enqueues a+// fresh task and the deliberate comment is never lost.+//+// The merge is GATED on the originator being unchanged (MUL-4195 review+// mergeCommentIntoPendingTask folds a newly-arrived comment into the existing+// QUEUED (not-yet-claimed) task for (issue, agent) instead of dropping it+// (MUL-4195). Returns true when the comment was handled (merged, or a+// non-fatal DB error we deliberately do not turn into a duplicate). Returns+// false only when no queued task exists to merge into (pgx.ErrNoRows) — the+// existing task is already dispatched/running, or was just claimed — in which+// case the caller decides between deferring to completion reconcile and a fresh+// enqueue.+//+// Recompute-on-merge (MUL-4195 review must-fix #1): the run's+// originator_user_id, runtime_mcp_overlay and runtime_connected_apps are+// re-stamped to the NEW trigger comment's originator, and trigger_summary is+// refreshed. This is what lets a different member's comment safely fold into a+// task another member created: the single coalescing run then carries the+// latest instruction's originator and the matching connected-app overlay,+// instead of answering the new comment under the original user's capabilities+// and audit identity. It also replaces the earlier originator gate + fresh+// fallback, which could not create a second pending task anyway (the+// one-pending-per-(issue,agent) unique index) and so silently dropped the+// mismatched-originator comment.+func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issue, trigger commentAgentTrigger, newTriggerCommentID pgtype.UUID) bool {+ originator := h.TaskService.ResolveOriginatorFromTriggerComment(ctx, newTriggerCommentID)+ overlay, connectedApps := h.TaskService.BuildRuntimeMCPOverlayForMerge(ctx, originator, trigger.Agent)+ row, err := h.Queries.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{+ IssueID: issue.ID,+ AgentID: trigger.Agent.ID,+ NewTriggerCommentID: newTriggerCommentID,+ NewOriginatorUserID: originator,+ NewTriggerSummary: h.TaskService.BuildCommentTriggerSummary(ctx, newTriggerCommentID),+ NewRuntimeMcpOverlay: overlay,+ NewRuntimeConnectedApps: connectedApps,+ })+ if err != nil {+ if isNotFound(err) {+ // No pre-claim (queued/deferred) task to merge into. The caller+ // defers to completion reconcile when an active task exists, or+ // enqueues fresh when none does.+ return false+ }+ // Unknown error: the pending task most likely still exists, so do NOT+ // risk enqueuing a duplicate. Log and treat as handled.+ slog.Warn("merge comment into pending task failed",+ "issue_id", uuidToString(issue.ID),+ "agent_id", uuidToString(trigger.Agent.ID),+ "error", err)+ return true+ }+ slog.Info("merged comment into pending task",+ "task_id", uuidToString(row.ID),+ "issue_id", uuidToString(issue.ID),+ "agent_id", uuidToString(trigger.Agent.ID),+ "new_trigger_comment_id", uuidToString(newTriggerCommentID),+ "coalesced_count", len(row.CoalescedCommentIds))+ return true+}++// enqueueSingleCommentTrigger creates a fresh task for one computed trigger.+// Split out of enqueueCommentAgentTriggers so the merge-not-drop path+// (MUL-4195) can fall back to it when a pending task vanished mid-flight.+func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, trigger commentAgentTrigger, getEscalationDelay func() time.Duration) {+ switch trigger.Source {+ case commentTriggerSourceIssueAssignee:+ if trigger.Squad != nil {+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {+ slog.Warn("enqueue squad leader task failed","issue_id", uuidToString(issue.ID),- "primary_agent_id", uuidToString(trigger.Agent.ID),- "fallback_agent_id", uuidToString(trigger.EscalationFallback.Agent.ID),+ "squad_id", uuidToString(trigger.Squad.ID),+ "leader_id", uuidToString(trigger.Agent.ID),"error", err)}+ return+ }+ if _, err := h.TaskService.EnqueueTaskForIssue(ctx, issue, triggerCommentID); err != nil {+ slog.Warn("enqueue agent task on comment failed", "issue_id", uuidToString(issue.ID), "error", err)+ }+ case commentTriggerSourceMentionSquadLeader:+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {+ slog.Warn("enqueue squad leader mention task failed",+ "issue_id", uuidToString(issue.ID),+ "agent_id", uuidToString(trigger.Agent.ID),+ "error", err)+ }+ case commentTriggerSourceMentionAgent:+ if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, trigger.Agent.ID, triggerCommentID); err != nil {+ slog.Warn("enqueue mention agent task failed",+ "issue_id", uuidToString(issue.ID),+ "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)+ return+ }+ if trigger.EscalationFallback == nil || getEscalationDelay() <= 0 {+ return+ }+ 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(getEscalationDelay())); 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)}}}diff --git a/server/internal/handler/comment_reconcile_test.go b/server/internal/handler/comment_reconcile_test.gonew file mode 100644index 0000000000..e67798c136--- /dev/null+++ b/server/internal/handler/comment_reconcile_test.go@@ -0,0 +1,530 @@+package handler++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// completeTaskViaHandler drives the daemon CompleteTask endpoint for taskID.+func completeTaskViaHandler(t *testing.T, taskID, output string) *httptest.ResponseRecorder {+ t.Helper()+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",+ map[string]any{"output": output},+ testWorkspaceID, "legit-daemon")+ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("taskId", taskID)+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))+ testHandler.CompleteTask(w, req)+ return w+}++// pendingTaskCountForAgentIssue counts claimable (queued/dispatched) tasks for+// an (issue, agent) pair.+func pendingTaskCountForAgentIssue(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 IN ('queued', 'dispatched')`,+ issueID, agentID).Scan(&n); err != nil {+ t.Fatalf("count pending 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+// run instead of being silently lost.+func TestCompleteTask_ReconcilesMemberCommentPostedDuringRun(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var agentID, runtimeID string+ if err := testPool.QueryRow(ctx,+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,+ testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {+ t.Fatalf("setup: get agent: %v", err)+ }++ // Issue assigned to the agent so a plain member comment routes to it.+ 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-e2e fixture', 'in_progress', 'none', $2, 'member', 999001, 0, 'agent', $3)+ RETURNING id+ `, testWorkspaceID, testUserID, agentID).Scan(&issueID); err != nil {+ t.Fatalf("setup: create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })++ // 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)+ }++ // A running task whose started_at is in the past.+ 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+ `, agentID, 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 deliberate member comment that arrived DURING the run (after started_at).+ if _, err := testPool.Exec(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)+ VALUES ($1, $2, 'member', $3, 'wait, also handle this', 'comment', now() - interval '1 minute')+ `, issueID, testWorkspaceID, testUserID); err != nil {+ t.Fatalf("setup: mid-run member comment: %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())+ }++ // A follow-up run must now be queued for the agent.+ if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {+ t.Fatalf("expected exactly 1 follow-up task after reconciliation, got %d", n)+ }+}++// TestCompleteTask_NoReconcileWhenNoNewMemberComment guards against spurious+// follow-ups: when no member comment arrived after the run started, completion+// must not enqueue any new task.+func TestCompleteTask_NoReconcileWhenNoNewMemberComment(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var agentID, runtimeID string+ if err := testPool.QueryRow(ctx,+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,+ testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {+ t.Fatalf("setup: get agent: %v", err)+ }++ 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-negative fixture', 'in_progress', 'none', $2, 'member', 999002, 0, 'agent', $3)+ RETURNING id+ `, testWorkspaceID, testUserID, agentID).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, 'the only 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+ `, agentID, 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) })++ 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, agentID); n != 0 {+ t.Fatalf("expected no follow-up task when no new member comment, got %d", n)+ }+}++// TestCompleteTask_DoesNotReTriggerOtherAgentMentionedDuringRun is the MUL-4195+// review must-fix #2 regression test. Agent A is running on an issue when a+// member posts a comment that @-mentions a DIFFERENT agent B. B is triggered at+// comment-creation time (not exercised here). When A's run completes, the+// completion reconcile must NOT replay that comment through the full trigger+// pipeline and spawn a SECOND B run — reconcile is scoped to the agent that+// just ran (A). Before the fix, reconcile fanned the latest member comment out+// to every routed agent, so completing A re-woke B (and any other agent the+// comment mentioned), breaking the bounded-follow-up guarantee.+func TestCompleteTask_DoesNotReTriggerOtherAgentMentionedDuringRun(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var agentA, runtimeID string+ if err := testPool.QueryRow(ctx,+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,+ testWorkspaceID).Scan(&agentA, &runtimeID); err != nil {+ t.Fatalf("setup: get agent A: %v", err)+ }+ // A second, workspace-invocable agent that a member can @mention.+ agentB := createHandlerTestAgent(t, "Reconcile Other Agent B", nil)++ // Issue assigned to A so A'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-other-agent fixture', 'in_progress', 'none', $2, 'member', 999003, 0, 'agent', $3)+ RETURNING id+ `, testWorkspaceID, testUserID, agentA).Scan(&issueID); err != nil {+ t.Fatalf("setup: create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })++ // A'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)+ }++ // A running task for A whose started_at is in the past.+ 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+ `, agentA, 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 member comment posted DURING A's run that @-mentions agent B.+ mention := "[@B](mention://agent/" + agentB + ") please take a look"+ if _, err := testPool.Exec(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)+ VALUES ($1, $2, 'member', $3, $4, 'comment', now() - interval '1 minute')+ `, issueID, testWorkspaceID, testUserID, mention); err != nil {+ t.Fatalf("setup: mid-run @B comment: %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())+ }++ // The @B comment routes to B, not A, so scoping reconcile to A means+ // NEITHER agent gets a completion-driven follow-up. B in particular must+ // not be re-woken by A's completion.+ if n := pendingTaskCountForAgentIssue(t, issueID, agentB); n != 0 {+ t.Fatalf("agent B must not be re-triggered by agent A's completion, got %d B task(s)", n)+ }+ if n := pendingTaskCountForAgentIssue(t, issueID, agentA); n != 0 {+ t.Fatalf("agent A must not enqueue a follow-up for a comment addressed to B, got %d A 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 {+ t.Helper()+ ctx := context.Background()+ var userID string+ email := slug + "-" + time.Now().Format("150405.000000") + "@example.test"+ if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,+ "Reconcile Test "+slug, email).Scan(&userID); err != nil {+ t.Fatalf("create user: %v", err)+ }+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'admin')`,+ testWorkspaceID, userID); err != nil {+ t.Fatalf("create member: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM member WHERE user_id = $1`, userID)+ testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)+ })+ return userID+}++// TestConsecutiveCommentsDifferentOriginatorsFullEnqueuePath is the MUL-4195+// second-round must-fix #1 regression test, driving the FULL handler enqueue+// path (computeCommentAgentTriggers → enqueueCommentAgentTriggers → merge), not+// just the SQL. Member A's comment creates a queued task; member B (a different+// originator) then comments before the run starts. The earlier build returned+// ErrNoRows from the originator gate and fell through to a fresh enqueue that+// tripped the one-pending-per-(issue,agent) unique index, silently dropping B's+// comment. With recompute-on-merge, B's comment folds into the single task:+// still one task (no drop, no collision), trigger repointed to B, originator+// re-stamped to B, and A's comment preserved as coalesced.+func TestConsecutiveCommentsDifferentOriginatorsFullEnqueuePath(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var agentID string+ if err := testPool.QueryRow(ctx,+ `SELECT id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL ORDER BY created_at ASC LIMIT 1`,+ testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("setup: get agent: %v", err)+ }+ userB := handlerWorkspaceMember(t, "originatorB")++ 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, 'diff-originator fixture', 'in_progress', 'none', $2, 'member', 999004, 0, 'agent', $3)+ RETURNING id+ `, testWorkspaceID, testUserID, agentID).Scan(&issueID); err != nil {+ t.Fatalf("setup: create issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)+ testPool.Exec(ctx, `DELETE FROM comment WHERE issue_id = $1`, issueID)+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)+ })++ issue, err := testHandler.Queries.GetIssue(ctx, util.MustParseUUID(issueID))+ if err != nil {+ t.Fatalf("load issue: %v", err)+ }++ insertMemberComment := func(authorID, content string) db.Comment {+ t.Helper()+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)+ VALUES ($1, $2, 'member', $3, $4, 'comment') RETURNING id+ `, issueID, testWorkspaceID, authorID, content).Scan(&id); err != nil {+ t.Fatalf("insert comment: %v", err)+ }+ c, err := testHandler.Queries.GetComment(ctx, util.MustParseUUID(id))+ if err != nil {+ t.Fatalf("load comment: %v", err)+ }+ return c+ }++ // A's comment → creates the queued task (originator A).+ cA := insertMemberComment(testUserID, "first, from A")+ testHandler.triggerTasksForComment(ctx, issue, cA, nil, "member", testUserID, testUserID, nil)+ if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {+ t.Fatalf("after A's comment expected exactly 1 queued task, got %d", n)+ }++ // B's comment (different originator) before start → must fold in, NOT drop.+ cB := insertMemberComment(userB, "second, from B — different user")+ testHandler.triggerTasksForComment(ctx, issue, cB, nil, "member", userB, userB, nil)++ // Still exactly one task (bounded concurrency, no unique-index collision).+ if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {+ t.Fatalf("after B's comment expected still exactly 1 task (folded in, not dropped/duplicated), got %d", n)+ }+ // Trigger repointed to B, originator re-stamped to B, A coalesced.+ trigger, originator, coalesced := taskTriggerOriginatorCoalesced(t, issueID, agentID)+ if trigger != uuidToString(cB.ID) {+ t.Errorf("expected trigger repointed to B's comment %s, got %s", uuidToString(cB.ID), trigger)+ }+ if originator != userB {+ t.Errorf("expected originator re-stamped to B (%s), got %s", userB, originator)+ }+ if !containsUUID(coalesced, uuidToString(cA.ID)) {+ t.Errorf("expected A's comment %s preserved as coalesced, got %v", uuidToString(cA.ID), coalesced)+ }+}++// TestCompleteTask_ReconcilesDispatchedWindowComment is the MUL-4195+// second-round must-fix #2 regression test. A member comment that lands AFTER+// the claim response was built (after dispatched_at) but BEFORE StartTask+// (before started_at) must still earn a follow-up. The earlier reconcile+// anchored on started_at and missed this window; anchoring on dispatched_at+// catches it.+func TestCompleteTask_ReconcilesDispatchedWindowComment(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var agentID, runtimeID string+ if err := testPool.QueryRow(ctx,+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,+ testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {+ t.Fatalf("setup: get agent: %v", err)+ }++ 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, 'dispatched-window fixture', 'in_progress', 'none', $2, 'member', 999005, 0, 'agent', $3)+ RETURNING id+ `, testWorkspaceID, testUserID, agentID).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)+ }++ // Running task: dispatched 5m ago, started 2m ago. The claim response was+ // built at dispatch.+ 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, started_at)+ VALUES ($1, $2, $3, $4, 'running', 0, now() - interval '10 minutes', now() - interval '5 minutes', now() - interval '2 minutes')+ RETURNING id+ `, agentID, 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 member comment in the dispatch→start window: after dispatched_at+ // (5m ago), before started_at (2m ago). A started_at anchor would miss it.+ if _, err := testPool.Exec(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)+ VALUES ($1, $2, 'member', $3, 'squeezed in before start', 'comment', now() - interval '3 minutes')+ `, issueID, testWorkspaceID, testUserID); err != nil {+ t.Fatalf("setup: dispatch-window comment: %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, agentID); n != 1 {+ t.Fatalf("expected exactly 1 follow-up for the dispatch-window comment, got %d", n)+ }+}++// taskTriggerOriginatorCoalesced returns (trigger_comment_id, originator_user_id,+// coalesced_comment_ids) as text for the most recent task of (issue, agent).+func taskTriggerOriginatorCoalesced(t *testing.T, issueID, agentID string) (string, string, []string) {+ t.Helper()+ var trigger, originator string+ var coalesced []string+ if err := testPool.QueryRow(context.Background(), `+ SELECT COALESCE(trigger_comment_id::text, ''),+ COALESCE(originator_user_id::text, ''),+ coalesced_comment_ids::text[]+ FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2+ ORDER BY created_at DESC+ LIMIT 1+ `, issueID, agentID).Scan(&trigger, &originator, &coalesced); err != nil {+ t.Fatalf("read task trigger/originator/coalesced: %v", err)+ }+ return trigger, originator, coalesced+}++func containsUUID(ids []string, want string) bool {+ for _, id := range ids {+ if id == want {+ return true+ }+ }+ return false+}++// TestCompleteTask_ReconcilesPreDispatchMergeRaceComment is the MUL-4195+// round-3 must-fix regression test. A member comment is created while the task+// is still queued, but its merge loses the race to the daemon claiming the task+// (queued→dispatched); the merge then finds no pre-claim row and the enqueue+// path defers to reconcile. The comment's created_at is BEFORE dispatched_at,+// so a dispatched_at-anchored reconcile would skip it and it would vanish. The+// created_at anchor + delivered-set exclusion must catch it — while NOT+// re-firing a comment that WAS delivered as a pre-claim coalesced entry.+func TestCompleteTask_ReconcilesPreDispatchMergeRaceComment(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var agentID, runtimeID string+ if err := testPool.QueryRow(ctx,+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,+ testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {+ t.Fatalf("setup: get agent: %v", err)+ }++ 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, 'pre-dispatch race fixture', 'in_progress', 'none', $2, 'member', 999006, 0, 'agent', $3)+ RETURNING id+ `, testWorkspaceID, testUserID, agentID).Scan(&issueID); err != nil {+ t.Fatalf("setup: create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })++ // Timeline: task created 10m ago; the run's trigger 10m ago; a delivered+ // pre-claim coalesced comment 8m ago; the RACE comment 7m ago (still before+ // dispatch); dispatched 6m ago; started 5m ago.+ insertComment := func(content, age string) string {+ t.Helper()+ var id 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, $4, 'comment', now() - $5::interval) RETURNING id+ `, issueID, testWorkspaceID, testUserID, content, age).Scan(&id); err != nil {+ t.Fatalf("insert comment: %v", err)+ }+ return id+ }+ triggerCommentID := insertComment("initial request", "10 minutes")+ deliveredCoalescedID := insertComment("folded in while queued (delivered)", "8 minutes")+ raceCommentID := insertComment("posted before dispatch, merge lost the race", "7 minutes")++ // The running task: created before every comment window, with the delivered+ // comment recorded in coalesced_comment_ids, dispatched after the race+ // comment, started later still.+ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue+ (agent_id, runtime_id, issue_id, trigger_comment_id, coalesced_comment_ids, status, priority, created_at, dispatched_at, started_at)+ VALUES ($1, $2, $3, $4, ARRAY[$5::uuid], 'running', 0,+ now() - interval '10 minutes', now() - interval '6 minutes', now() - interval '5 minutes')+ RETURNING id+ `, agentID, runtimeID, issueID, triggerCommentID, deliveredCoalescedID).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) })++ if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {+ t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ // Exactly one follow-up, and it must be for the RACE comment — the+ // delivered coalesced comment must be excluded (not re-fired).+ if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {+ t.Fatalf("expected exactly 1 follow-up for the pre-dispatch race comment, got %d", n)+ }+ trigger, _, coalesced := taskTriggerOriginatorCoalesced(t, issueID, agentID)+ if trigger != raceCommentID {+ t.Errorf("follow-up trigger must be the race comment %s, got %s", raceCommentID, trigger)+ }+ if containsUUID(coalesced, deliveredCoalescedID) || trigger == deliveredCoalescedID {+ t.Errorf("the already-delivered coalesced comment %s must be excluded from the follow-up, got trigger=%s coalesced=%v",+ deliveredCoalescedID, trigger, coalesced)+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 63960e9014..546978c36d 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1606,6 +1606,14 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {}}+ // MUL-4195: surface comments that were folded into this run while it+ // was still queued so the daemon can steer the agent to read them all.+ resp.CoalescedCommentIDs = uuidsToStrings(task.CoalescedCommentIds)+ // Embed the folded comments' full detail (thread/author/created_at/+ // content) so the prompt can address each one without assuming they+ // share the triggering thread (MUL-4195 review should-fix #3).+ resp.CoalescedComments = h.buildCoalescedCommentData(r.Context(), task.CoalescedCommentIds)+// Fetch the triggering comment content so the daemon can embed it// directly in the agent prompt (prevents the agent from ignoring comments// when stale output files exist in a reused workdir). Also surface the@@ -2362,6 +2370,14 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {h.emitIssueExecutedOnFirstCompletion(r, task)+ // MUL-4195: guarantee at-least-once processing. If a member posted a+ // deliberate comment while this run was executing (or one was merged into+ // it after its context was built), schedule a single follow-up so the+ // input is never silently dropped. Loop-safe: member-authored only, capped+ // by the existing per-(issue, agent) dedup, and terminating because the+ // triggering comment always predates the follow-up run's started_at.+ h.reconcileCommentsOnCompletion(r.Context(), task)+// Best-effort revoke of any agent task token minted at claim time.// The token would naturally expire at the 24h watermark and is also// cascaded on agent_task deletion, but eagerly deleting it on@@ -2418,6 +2434,176 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A))}+// reconcileCommentsOnCompletion closes the at-least-once gap for member+// comments a completing run did NOT deliver (MUL-4195).+//+// The merge path (mergeCommentIntoPendingTask) folds a comment into a task only+// while it is still PRE-CLAIM (queued/deferred), so trigger_comment_id plus+// coalesced_comment_ids is EXACTLY the set the run's claim response carried —+// its "delivered set". Anything a member posted during this run's lifetime that+// is NOT in that set was never delivered and must earn a follow-up.+//+// Anchor = created_at + delivered-set exclusion, NOT a dispatch/start timestamp+// (MUL-4195 review round-3 must-fix). A timestamp anchor cannot tell a+// delivered comment from an undelivered one, and there is a race it structurally+// misses: a comment created while the task was still queued, but whose merge+// lost the race to the daemon claiming the task (queued→dispatched) — the merge+// then finds no pre-claim row (ErrNoRows), the enqueue path defers to reconcile,+// yet the comment's created_at is BEFORE dispatched_at, so a dispatched_at+// anchor would skip it and it would vanish. Anchoring on the task's own+// created_at reaches back over the whole run, and excluding the delivered set+// (trigger + coalesced) is what prevents re-firing comments the run actually+// received. Together they catch the pre-dispatch merge-race comment, the+// dispatch→start comment, and the during-run comment, while never double-firing+// a delivered one.+//+// Scope + loop safety:+// - Only MEMBER comments qualify (agent replies / acknowledgements /+// self-triggers never do).+// - 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.+// - Every undelivered qualifying comment is replayed through the normal+// enqueue path in chronological order, so they coalesce into a SINGLE+// follow-up task (the first enqueues it, the rest merge in). Bounded to one+// run, and terminating: the follow-up's own created_at is later than all of+// these comments and its delivered set will contain them, so its completion+// finds nothing to re-schedule.+func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.AgentTaskQueue) {+ if task == nil || !task.IssueID.Valid || !task.AgentID.Valid || !task.CreatedAt.Valid {+ return+ }+ comments, err := h.Queries.ListMemberCommentsForIssueSince(ctx, db.ListMemberCommentsForIssueSinceParams{+ IssueID: task.IssueID,+ Since: task.CreatedAt,+ })+ if err != nil {+ slog.Warn("reconcile comments on completion: list member comments failed",+ "issue_id", uuidToString(task.IssueID), "task_id", uuidToString(task.ID), "error", err)+ return+ }+ if len(comments) == 0 {+ return+ }+ // The delivered set: everything this run's claim response actually carried.+ // Because merges only ever touch pre-claim rows, this is exactly+ // trigger_comment_id ∪ coalesced_comment_ids. Any member comment since the+ // task was created that is NOT in here was never delivered to the run.+ delivered := make(map[string]struct{}, len(task.CoalescedCommentIds)+1)+ if task.TriggerCommentID.Valid {+ delivered[uuidToString(task.TriggerCommentID)] = struct{}{}+ }+ for _, id := range task.CoalescedCommentIds {+ if id.Valid {+ delivered[uuidToString(id)] = struct{}{}+ }+ }+ issue, err := h.Queries.GetIssue(ctx, task.IssueID)+ if err != nil {+ slog.Warn("reconcile comments on completion: load issue failed",+ "issue_id", uuidToString(task.IssueID), "error", err)+ return+ }+ agentID := uuidToString(task.AgentID)+ scheduled := 0+ for i := range comments {+ c := comments[i]+ if _, ok := delivered[uuidToString(c.ID)]; ok {+ // Already delivered to this run (trigger or pre-claim coalesced).+ continue+ }+ if isNoteComment(c.Content) {+ continue+ }+ var parentComment *db.Comment+ if c.ParentID.Valid {+ if parent, err := h.Queries.GetComment(ctx, c.ParentID); err == nil {+ 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).+ actorID := uuidToString(c.AuthorID)+ triggers := h.computeCommentAgentTriggers(ctx, issue, c.Content, parentComment, "member", actorID, commentTriggerComputeOptions{+ ExcludeTriggerCommentID: c.ID,+ OriginatorUserID: actorID,+ })+ scoped := make([]commentAgentTrigger, 0, 1)+ for _, trigger := range triggers {+ if uuidToString(trigger.Agent.ID) == agentID {+ scoped = append(scoped, trigger)+ }+ }+ if len(scoped) == 0 {+ continue+ }+ // The first qualifying comment enqueues the follow-up task; later ones+ // find it AlreadyPending and merge in, so all undelivered comments end+ // up covered by a single bounded run.+ h.enqueueCommentAgentTriggers(ctx, issue, c.ID, scoped)+ scheduled+++ }+ if scheduled > 0 {+ slog.Info("reconcile comments on completion: scheduled follow-up",+ "issue_id", uuidToString(task.IssueID),+ "completed_task_id", uuidToString(task.ID),+ "agent_id", agentID,+ "undelivered_member_comments", scheduled)+ }+}++// buildCoalescedCommentData loads the full detail of each comment that was+// folded into a not-yet-started run (MUL-4195) so the claim response can embed+// them and the prompt can address each without assuming they share the+// triggering thread (review should-fix #3). Thread id follows the same rule as+// the triggering comment (parent id when the comment is a reply, else the+// comment's own id). Missing comments (deleted / wrong workspace) are skipped+// rather than failing the claim. The set is bounded by how many comments a user+// fires before a run starts, so the per-comment lookups stay cheap.+func (h *Handler) buildCoalescedCommentData(ctx context.Context, ids []pgtype.UUID) []CoalescedCommentData {+ if len(ids) == 0 {+ return nil+ }+ out := make([]CoalescedCommentData, 0, len(ids))+ for _, id := range ids {+ if !id.Valid {+ continue+ }+ comment, err := h.Queries.GetComment(ctx, id)+ if err != nil {+ continue+ }+ data := CoalescedCommentData{+ ID: uuidToString(comment.ID),+ ThreadID: uuidToString(comment.ID),+ AuthorType: comment.AuthorType,+ Content: comment.Content,+ CreatedAt: timestampToString(comment.CreatedAt),+ }+ if comment.ParentID.Valid {+ data.ThreadID = uuidToString(comment.ParentID)+ }+ if comment.AuthorID.Valid {+ switch comment.AuthorType {+ case "agent":+ if a, err := h.Queries.GetAgent(ctx, comment.AuthorID); err == nil {+ data.AuthorName = a.Name+ }+ case "member":+ if u, err := h.Queries.GetUser(ctx, comment.AuthorID); err == nil {+ data.AuthorName = u.Name+ }+ }+ }+ out = append(out, data)+ }+ if len(out) == 0 {+ return nil+ }+ return out+}+// ReportTaskUsage stores per-task token usage. Called independently of// complete/fail so usage is captured even when tasks fail or are blocked.type TaskUsagePayload struct {diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 8a39ad2a0f..0088e3c838 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -348,9 +348,29 @@ func timestampToString(t pgtype.Timestamptz) string { return util.TimestampToStrfunc timestampToPtr(t pgtype.Timestamptz) *string { return util.TimestampToPtr(t) }func dateToPtr(d pgtype.Date) *string { return util.DateToPtr(d) }func uuidToPtr(u pgtype.UUID) *string { return util.UUIDToPtr(u) }-func int8ToPtr(v pgtype.Int8) *int64 { return util.Int8ToPtr(v) }-func int4ToPtr(v pgtype.Int4) *int32 { return util.Int4ToPtr(v) }-func ptrToInt4(v *int32) pgtype.Int4 { return util.PtrToInt4(v) }++// uuidsToStrings maps a UUID array column to string ids, skipping NULL/invalid+// entries. Returns nil (not an empty slice) when there is nothing to emit so+// `omitempty` JSON fields drop out cleanly (MUL-4195).+func uuidsToStrings(us []pgtype.UUID) []string {+ if len(us) == 0 {+ return nil+ }+ out := make([]string, 0, len(us))+ for _, u := range us {+ if u.Valid {+ out = append(out, uuidToString(u))+ }+ }+ if len(out) == 0 {+ return nil+ }+ return out+}++func int8ToPtr(v pgtype.Int8) *int64 { return util.Int8ToPtr(v) }+func int4ToPtr(v pgtype.Int4) *int32 { return util.Int4ToPtr(v) }+func ptrToInt4(v *int32) pgtype.Int4 { return util.PtrToInt4(v) }// parseUUIDOrBadRequest validates a UUID string sourced from user input// (URL params, request body, headers). On invalid input it writes a 400diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 5fd5ba0622..03a8302cc7 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -144,6 +144,34 @@ func (s *TaskService) buildCommentTriggerSummary(ctx context.Context, commentIDreturn pgtype.Text{String: summary, Valid: true}}+// ResolveOriginatorFromTriggerComment is the exported wrapper used by the+// comment-merge path (MUL-4195) to compute the top-of-chain human originator+// for a newly-arrived comment, so a merge can be gated on the originator being+// unchanged. See resolveOriginatorFromTriggerComment for the chain rules.+func (s *TaskService) ResolveOriginatorFromTriggerComment(ctx context.Context, commentID pgtype.UUID) pgtype.UUID {+ return s.resolveOriginatorFromTriggerComment(ctx, commentID)+}++// BuildCommentTriggerSummary is the exported wrapper used by the comment-merge+// path (MUL-4195) to refresh a coalesced task's trigger_summary to the newest+// trigger comment's snapshot.+func (s *TaskService) BuildCommentTriggerSummary(ctx context.Context, commentID pgtype.UUID) pgtype.Text {+ return s.buildCommentTriggerSummary(ctx, commentID)+}++// BuildRuntimeMCPOverlayForMerge recomputes the Composio MCP overlay ++// connected-app metadata for (originatorUserID, agent), used when a merge+// re-stamps a coalesced task's originator (MUL-4195 review must-fix #1). The+// overlay is a pure function of (originator, agent); re-stamping it alongside+// originator_user_id keeps the coalescing run's connected-app capabilities and+// audit attribution consistent with the latest trigger comment's originator+// instead of the task's original one. Fails soft to empty (same as the enqueue+// path) so a transient Composio hiccup never blocks the merge.+func (s *TaskService) BuildRuntimeMCPOverlayForMerge(ctx context.Context, originatorUserID pgtype.UUID, agent db.Agent) (overlay, connectedApps []byte) {+ data := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)+ return data.Overlay, data.ConnectedApps+}+func NewTaskService(q *db.Queries, tx TxStarter, hub *realtime.Hub, bus *events.Bus, wakeups ...TaskWakeupNotifier) *TaskService {var wakeup TaskWakeupNotifierif len(wakeups) > 0 {diff --git a/server/migrations/145_agent_task_coalesced_comments.down.sql b/server/migrations/145_agent_task_coalesced_comments.down.sqlnew file mode 100644index 0000000000..cdca084059--- /dev/null+++ b/server/migrations/145_agent_task_coalesced_comments.down.sql@@ -0,0 +1 @@+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS coalesced_comment_ids;diff --git a/server/migrations/145_agent_task_coalesced_comments.up.sql b/server/migrations/145_agent_task_coalesced_comments.up.sqlnew file mode 100644index 0000000000..e3ed30b414--- /dev/null+++ b/server/migrations/145_agent_task_coalesced_comments.up.sql@@ -0,0 +1,20 @@+-- Guarantee at-least-once processing of user comments (MUL-4195).+--+-- Historically a new comment that arrived while an agent already had a+-- queued/dispatched task for the same (issue, agent) was silently DROPPED by+-- the HasPendingTaskForIssueAndAgent dedup: only the first comment's+-- trigger_comment_id survived, and the follow-up instruction was lost with no+-- visible trace. That is a correctness bug for comments, which — unlike chat —+-- are deliberate, addressed, persisted user input that must never vanish.+--+-- coalesced_comment_ids records the comments that were FOLDED INTO a+-- not-yet-started task instead of being dropped. The task's trigger_comment_id+-- is repointed to the newest comment (so the injected prompt shows the latest+-- deliberate instruction) while this array preserves every earlier comment the+-- single run must still address. It is also surfaced on the task API so the UI+-- can show exactly which comments a run covered.+--+-- Default '{}' (empty array, never NULL) so existing rows and every non-merge+-- enqueue path keep working untouched.+ALTER TABLE agent_task_queue+ ADD COLUMN coalesced_comment_ids UUID[] NOT NULL DEFAULT '{}';diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 4b6f4c8356..ee41864fb6 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -184,7 +184,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :oneUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {@@ -226,6 +226,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -234,7 +235,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`// Bulk-cancel every active (queued/dispatched/running) task for an agent.@@ -287,6 +288,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -302,7 +304,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :mUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`// Cancels active tasks belonging to a chat session. Called from@@ -355,6 +357,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -370,7 +373,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`// Cancels every active task on the issue and returns the affected rows so the@@ -423,6 +426,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -438,7 +442,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgenUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type CancelAgentTasksByIssueAndAgentParams struct {@@ -495,6 +499,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -510,7 +515,7 @@ const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerCommUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`// Cancels active tasks whose trigger is the given comment. Called when a@@ -563,6 +568,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -583,9 +589,9 @@ WITH cancelled AS (AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')AND primary_task.issue_id = $1AND 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.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps+ 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.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids)-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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps FROM cancelled+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids FROM cancelled`type CancelDeferredEscalationsForIssueAgentParams struct {@@ -629,6 +635,7 @@ type CancelDeferredEscalationsForIssueAgentRow struct {FireAt pgtype.Timestamptz `json:"fire_at"`OriginatorUserID pgtype.UUID `json:"originator_user_id"`RuntimeConnectedApps []byte `json:"runtime_connected_apps"`+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`}func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {@@ -676,6 +683,7 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -692,7 +700,7 @@ UPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE escalation_for_task_id = $1AND 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {@@ -740,6 +748,7 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -780,7 +789,7 @@ WHERE id = (LIMIT 1FOR 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type ClaimAgentTaskParams struct {@@ -836,6 +845,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -967,7 +977,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :oneUPDATE agent_task_queueSET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4, prepare_lease_expires_at = NULLWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type CompleteAgentTaskParams struct {@@ -1021,6 +1031,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -1147,7 +1158,7 @@ VALUES ($13,$14)-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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type CreateAgentTaskParams struct {@@ -1228,6 +1239,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -1246,7 +1258,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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type CreateDeferredAgentTaskParams struct {@@ -1315,6 +1327,7 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -1330,7 +1343,7 @@ VALUES ($6,$7)-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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type CreateQuickCreateTaskParams struct {@@ -1393,6 +1406,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -1419,7 +1433,7 @@ SELECT$3FROM agent_task_queue pWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type CreateRetryTaskParams struct {@@ -1484,6 +1498,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -1507,7 +1522,7 @@ FROM victims vWHERE t.id = v.idAND 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, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps+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.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids`type ExpireStaleQueuedTasksParams struct {@@ -1583,6 +1598,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -1601,7 +1617,7 @@ WHERE id = $1AND runtime_id = $2AND 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type ExtendAgentTaskPrepareLeaseParams struct {@@ -1653,6 +1669,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -1667,7 +1684,7 @@ SET status = 'failed',work_dir = COALESCE($5, work_dir),prepare_lease_expires_at = NULLWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type FailAgentTaskParams struct {@@ -1732,6 +1749,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -1756,7 +1774,7 @@ WHERE (AND r.last_seen_at >= now() - make_interval(secs => $3::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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type FailStaleTasksParams struct {@@ -1847,6 +1865,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -1976,7 +1995,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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids FROM agent_task_queueWHERE id = $1`@@ -2019,12 +2038,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)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, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps 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.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE atq.id = $1 AND a.workspace_id = $2`@@ -2080,6 +2100,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -2318,6 +2339,33 @@ func (q *Queries) HasActiveTaskForIssue(ctx context.Context, issueID pgtype.UUIDreturn has_active, err}+const hasActiveTaskForIssueAndAgent = `-- name: HasActiveTaskForIssueAndAgent :one+SELECT count(*) > 0 AS has_active FROM agent_task_queue+WHERE issue_id = $1 AND agent_id = $2+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+`++type HasActiveTaskForIssueAndAgentParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+}++// MUL-4195: true when the (issue, agent) pair has any non-terminal task in a+// state whose completion will run completion reconciliation — queued,+// dispatched, running, or waiting_local_directory. Used by the comment enqueue+// path: when a merge into a pre-claim task fails (the task is already+// dispatched/running, or a mismatched pre-claim task exists), a fresh queued+// INSERT would collide with idx_one_pending_task_per_issue_agent AND would risk+// a duplicate run. Instead the caller relies on that active task's completion+// reconcile to schedule the guaranteed follow-up, and only enqueues fresh when+// NO active task exists.+func (q *Queries) HasActiveTaskForIssueAndAgent(ctx context.Context, arg HasActiveTaskForIssueAndAgentParams) (bool, error) {+ row := q.db.QueryRow(ctx, hasActiveTaskForIssueAndAgent, arg.IssueID, arg.AgentID)+ var has_active bool+ err := row.Scan(&has_active)+ return has_active, err+}+const hasPendingTaskForIssue = `-- name: HasPendingTaskForIssue :oneSELECT count(*) > 0 AS has_pending FROM agent_task_queueWHERE issue_id = $1 AND status IN ('queued', 'dispatched')@@ -2540,7 +2588,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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids FROM agent_task_queueWHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')ORDER BY created_at DESC`@@ -2595,6 +2643,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -2607,7 +2656,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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids FROM agent_task_queueWHERE agent_id = $1ORDER BY created_at DESC`@@ -2657,6 +2706,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -2771,7 +2821,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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids FROM agent_task_queueWHERE runtime_id = $1 AND status IN ('queued', 'dispatched')ORDER BY priority DESC, created_at ASC`@@ -2821,6 +2871,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -2833,7 +2884,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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids FROM agent_task_queueWHERE runtime_id = $1 AND status = 'queued'ORDER BY priority DESC, created_at ASC`@@ -2891,6 +2942,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -2903,7 +2955,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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids FROM agent_task_queueWHERE issue_id = $1ORDER BY created_at DESC`@@ -2953,6 +3005,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -2965,15 +3018,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, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps 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.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1AND 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, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps 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.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps+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.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids 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.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_idsFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1@@ -3045,6 +3098,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -3062,7 +3116,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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type MarkAgentTaskWaitingLocalDirectoryParams struct {@@ -3119,7 +3173,104 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ )+ return i, err+}++const mergeCommentIntoPendingTask = `-- name: MergeCommentIntoPendingTask :one+UPDATE agent_task_queue+SET coalesced_comment_ids = (+ SELECT COALESCE(array_agg(DISTINCT e), '{}')+ FROM unnest(array_append(coalesced_comment_ids, trigger_comment_id)) AS e+ WHERE e IS NOT NULL AND e <> $1::uuid+ ),+ trigger_comment_id = $1::uuid,+ trigger_summary = COALESCE($2, trigger_summary),+ originator_user_id = $3::uuid,+ runtime_mcp_overlay = $4,+ runtime_connected_apps = $5+WHERE id = (+ SELECT t.id FROM agent_task_queue t+ WHERE t.issue_id = $6+ AND t.agent_id = $7+ AND t.status = 'queued'+ ORDER BY t.created_at DESC+ LIMIT 1+)+RETURNING id, coalesced_comment_ids+`++type MergeCommentIntoPendingTaskParams struct {+ NewTriggerCommentID pgtype.UUID `json:"new_trigger_comment_id"`+ NewTriggerSummary pgtype.Text `json:"new_trigger_summary"`+ NewOriginatorUserID pgtype.UUID `json:"new_originator_user_id"`+ NewRuntimeMcpOverlay []byte `json:"new_runtime_mcp_overlay"`+ NewRuntimeConnectedApps []byte `json:"new_runtime_connected_apps"`+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+}++type MergeCommentIntoPendingTaskRow struct {+ ID pgtype.UUID `json:"id"`+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`+}++// MUL-4195: fold a newly-arrived comment into an existing task for (issue,+// agent) that has NOT yet been claimed, instead of letting the+// HasPendingTaskForIssueAndAgent dedup silently DROP it. The task's prior+// trigger_comment_id becomes a coalesced ("also cover") comment and+// @new_trigger_comment_id becomes the new trigger, so the injected prompt shows+// the latest deliberate instruction while the single run is still told to+// address every folded comment.+//+// Target is restricted to the single 'queued' task on purpose (MUL-4195 review+// rounds 2–4). This merge is only reached when HasPendingTaskForIssueAndAgent+// matched a 'queued'/'dispatched' task, and 'dispatched' is deliberately NOT a+// target: a dispatched / waiting_local_directory / running task has already had+// its claim response (with its coalesced_comment_ids) built and shipped, so+// folding a comment in afterward would mark an undelivered comment as delivered;+// those are handled by completion reconciliation instead. 'deferred' is also NOT+// a target: a deferred row is an assignee-fallback escalation with its own+// fire_at/promotion lifecycle, and it never sets AlreadyPending+// (HasPendingTaskForIssueAndAgent only looks at queued/dispatched). If a newer+// deferred fallback and an older queued task coexisted, a status-IN target would+// pick the deferred one by created_at and steal the coalescing target away from+// the queued run that is actually about to be claimed — so we match ONLY the+// queued row (the idx_one_pending_task_per_issue_agent unique index guarantees+// at most one). Because merges only ever touch that pre-claim queued row,+// coalesced_comment_ids == the set the run actually received.+//+// Recompute-on-merge (MUL-4195 review must-fix #1): originator_user_id,+// runtime_mcp_overlay and runtime_connected_apps are re-stamped to the NEW+// trigger comment's originator (computed by the caller). Earlier this only+// repointed the trigger and kept the old originator's overlay/attribution, so a+// run answering user B's comment could execute under user A's connected-app+// capabilities and audit identity. Re-stamping means the single coalescing run+// carries the latest deliberate instruction's originator and the matching+// overlay — no cross-user capability bleed, no stale attribution. This also+// removes the previous originator gate + fresh-enqueue fallback, which could not+// create a second task anyway (the idx_one_pending_task_per_issue_agent unique+// index allows only one queued/dispatched task per (issue, agent)) and therefore+// silently dropped the mismatched-originator comment.+//+// Returns pgx.ErrNoRows when no queued task exists (it was claimed/started+// between the dedup check and this call, or the only task is already+// dispatched/running). The caller must NOT blindly enqueue a fresh task in that+// case — a dispatched sibling would trip the unique index — it defers to+// completion reconciliation unless no active task exists at all.+func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeCommentIntoPendingTaskParams) (MergeCommentIntoPendingTaskRow, error) {+ row := q.db.QueryRow(ctx, mergeCommentIntoPendingTask,+ arg.NewTriggerCommentID,+ arg.NewTriggerSummary,+ arg.NewOriginatorUserID,+ arg.NewRuntimeMcpOverlay,+ arg.NewRuntimeConnectedApps,+ arg.IssueID,+ arg.AgentID,)+ var i MergeCommentIntoPendingTaskRow+ err := row.Scan(&i.ID, &i.CoalescedCommentIds)return i, err}@@ -3129,7 +3280,7 @@ SET status = 'queued'WHERE runtime_id = $1AND 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {@@ -3177,6 +3328,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtime&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -3203,7 +3355,7 @@ WHERE id = (LIMIT 1FOR 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type ReclaimStaleDispatchedTaskForRuntimeParams struct {@@ -3256,6 +3408,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -3269,7 +3422,7 @@ SET status = 'failed',wait_reason = NULL,prepare_lease_expires_at = NULLWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`// Called by the daemon at startup. Atomically fails any dispatched/running/@@ -3323,6 +3476,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -3422,7 +3576,7 @@ SET status = 'running',wait_reason = NULL,prepare_lease_expires_at = NULLWHERE 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`// Transitions a task to running. Accepts either 'dispatched' (the normal@@ -3470,6 +3624,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 073a007c95..4183087985 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -222,7 +222,7 @@ const createAutopilotTask = `-- name: CreateAutopilotTask :oneINSERT 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type CreateAutopilotTaskParams struct {@@ -281,6 +281,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex c877515e29..3112fce485 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -124,7 +124,7 @@ VALUES ($8,$9)-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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type CreateChatTaskParams struct {@@ -188,6 +188,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,)return i, err}@@ -798,9 +799,8 @@ FOR UPDATE// their FK check after we commit the delete.func (q *Queries) LockChatSessionForDelete(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {row := q.db.QueryRow(ctx, lockChatSessionForDelete, id)- var id_2 pgtype.UUID- err := row.Scan(&id_2)- return id_2, err+ err := row.Scan(&id)+ return id, err}const markChatSessionRead = `-- name: MarkChatSessionRead :execdiff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex 46ded661f8..0772e7bbb1 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -276,6 +276,51 @@ func (q *Queries) GetCommentInWorkspace(ctx context.Context, arg GetCommentInWorreturn i, err}+const getLatestMemberCommentForIssueSince = `-- name: GetLatestMemberCommentForIssueSince :one+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 DESC+LIMIT 1+`++type GetLatestMemberCommentForIssueSinceParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ Since pgtype.Timestamptz `json:"since"`+}++// MUL-4195 completion reconciliation: the newest MEMBER-authored comment on an+// issue created strictly after @since (a run's started_at). Used when a task+// completes to detect deliberate user input that landed while the agent was+// busy — or that was merged into the running task after its context was+// already built — so a single follow-up run can be scheduled for it. Restricted+// to author_type = 'member' on purpose: only human input earns the guaranteed+// follow-up, which preserves the existing anti-loop guarantees (agent replies,+// acknowledgements, and self-triggers never qualify). Returns pgx.ErrNoRows+// when nothing newer exists, i.e. the run already covered the latest input.+func (q *Queries) GetLatestMemberCommentForIssueSince(ctx context.Context, arg GetLatestMemberCommentForIssueSinceParams) (Comment, error) {+ row := q.db.QueryRow(ctx, getLatestMemberCommentForIssueSince, arg.IssueID, arg.Since)+ var i Comment+ err := row.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,+ )+ return i, err+}+const getThreadRoot = `-- name: GetThreadRoot :oneWITH RECURSIVE root_of AS (SELECT c.id, c.parent_id@@ -472,6 +517,63 @@ func (q *Queries) ListCommentsSinceForIssue(ctx context.Context, arg ListCommentreturn 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 :manyWITH RECURSIVE membership(id, root_id, comment_created_at) AS (-- Each root maps to itself.diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex d7d3b543c3..b0ad168c32 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -124,7 +124,8 @@ type AgentTaskQueue struct {// Top-of-chain human originator for this run. For human-triggered tasks (comment by a member, chat, quick-create) equals that member. For agent-fanout tasks inherited from the parent task's originator_user_id via comment.source_task_id. NULL when no human is in the chain (autopilot, system-driven). Used by canInvokeAgent to judge A2A by the originator; the Composio overlay now follows invocation permission and uses the agent owner's connection, so this is audit/attribution + A2A gating, NOT a Composio owner==originator gate (MUL-3963).OriginatorUserID pgtype.UUID `json:"originator_user_id"`// Non-secret per-task connected app metadata corresponding to runtime_mcp_overlay, used by the daemon brief to tell agents which app capabilities are mounted. Cleared with runtime_mcp_overlay after task completion.- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`}type Attachment struct {diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 219acbeea0..8d1fb1d808 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -16,7 +16,7 @@ UPDATE agent_task_queueSET 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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`type CancelAgentTasksByRuntimeOrAgentParams struct {@@ -83,6 +83,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}@@ -202,7 +203,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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps+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, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids`// Marks dispatched/running/waiting_local_directory tasks as failed when@@ -253,6 +254,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ&i.FireAt,&i.OriginatorUserID,&i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex c6a62a31bf..d37faee61b 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -730,6 +730,85 @@ WHERE issue_id = @issue_idOR context->>'head_sha' = sqlc.narg('head_sha')::text);+-- name: MergeCommentIntoPendingTask :one+-- MUL-4195: fold a newly-arrived comment into an existing task for (issue,+-- agent) that has NOT yet been claimed, instead of letting the+-- HasPendingTaskForIssueAndAgent dedup silently DROP it. The task's prior+-- trigger_comment_id becomes a coalesced ("also cover") comment and+-- @new_trigger_comment_id becomes the new trigger, so the injected prompt shows+-- the latest deliberate instruction while the single run is still told to+-- address every folded comment.+--+-- Target is restricted to the single 'queued' task on purpose (MUL-4195 review+-- rounds 2–4). This merge is only reached when HasPendingTaskForIssueAndAgent+-- matched a 'queued'/'dispatched' task, and 'dispatched' is deliberately NOT a+-- target: a dispatched / waiting_local_directory / running task has already had+-- its claim response (with its coalesced_comment_ids) built and shipped, so+-- folding a comment in afterward would mark an undelivered comment as delivered;+-- those are handled by completion reconciliation instead. 'deferred' is also NOT+-- a target: a deferred row is an assignee-fallback escalation with its own+-- fire_at/promotion lifecycle, and it never sets AlreadyPending+-- (HasPendingTaskForIssueAndAgent only looks at queued/dispatched). If a newer+-- deferred fallback and an older queued task coexisted, a status-IN target would+-- pick the deferred one by created_at and steal the coalescing target away from+-- the queued run that is actually about to be claimed — so we match ONLY the+-- queued row (the idx_one_pending_task_per_issue_agent unique index guarantees+-- at most one). Because merges only ever touch that pre-claim queued row,+-- coalesced_comment_ids == the set the run actually received.+--+-- Recompute-on-merge (MUL-4195 review must-fix #1): originator_user_id,+-- runtime_mcp_overlay and runtime_connected_apps are re-stamped to the NEW+-- trigger comment's originator (computed by the caller). Earlier this only+-- repointed the trigger and kept the old originator's overlay/attribution, so a+-- run answering user B's comment could execute under user A's connected-app+-- capabilities and audit identity. Re-stamping means the single coalescing run+-- carries the latest deliberate instruction's originator and the matching+-- overlay — no cross-user capability bleed, no stale attribution. This also+-- removes the previous originator gate + fresh-enqueue fallback, which could not+-- create a second task anyway (the idx_one_pending_task_per_issue_agent unique+-- index allows only one queued/dispatched task per (issue, agent)) and therefore+-- silently dropped the mismatched-originator comment.+--+-- Returns pgx.ErrNoRows when no queued task exists (it was claimed/started+-- between the dedup check and this call, or the only task is already+-- dispatched/running). The caller must NOT blindly enqueue a fresh task in that+-- case — a dispatched sibling would trip the unique index — it defers to+-- completion reconciliation unless no active task exists at all.+UPDATE agent_task_queue+SET coalesced_comment_ids = (+ SELECT COALESCE(array_agg(DISTINCT e), '{}')+ FROM unnest(array_append(coalesced_comment_ids, trigger_comment_id)) AS e+ WHERE e IS NOT NULL AND e <> @new_trigger_comment_id::uuid+ ),+ trigger_comment_id = @new_trigger_comment_id::uuid,+ trigger_summary = COALESCE(sqlc.narg('new_trigger_summary'), trigger_summary),+ originator_user_id = sqlc.narg('new_originator_user_id')::uuid,+ runtime_mcp_overlay = sqlc.narg('new_runtime_mcp_overlay'),+ runtime_connected_apps = sqlc.narg('new_runtime_connected_apps')+WHERE id = (+ SELECT t.id FROM agent_task_queue t+ WHERE t.issue_id = @issue_id+ AND t.agent_id = @agent_id+ AND t.status = 'queued'+ ORDER BY t.created_at DESC+ LIMIT 1+)+RETURNING id, coalesced_comment_ids;++-- name: HasActiveTaskForIssueAndAgent :one+-- MUL-4195: true when the (issue, agent) pair has any non-terminal task in a+-- state whose completion will run completion reconciliation — queued,+-- dispatched, running, or waiting_local_directory. Used by the comment enqueue+-- path: when a merge into a pre-claim task fails (the task is already+-- dispatched/running, or a mismatched pre-claim task exists), a fresh queued+-- INSERT would collide with idx_one_pending_task_per_issue_agent AND would risk+-- a duplicate run. Instead the caller relies on that active task's completion+-- reconcile to schedule the guaranteed follow-up, and only enqueues fresh when+-- NO active task exists.+SELECT count(*) > 0 AS has_active FROM agent_task_queue+WHERE issue_id = $1 AND agent_id = $2+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory');+-- name: GetLatestTaskRoleForIssueAndAgent :one-- Returns the role markers from the agent's most recent task on this issue.-- Used by the squad-leader self-trigger guard to tell apart leader tasks,diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex a18dd38eb9..079ff928f6 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -312,6 +312,39 @@ WHERE issue_id = @issue_idAND id <> @anchor_idAND NOT (author_type = 'agent' AND author_id = @author_id);+-- name: GetLatestMemberCommentForIssueSince :one+-- MUL-4195 completion reconciliation: the newest MEMBER-authored comment on an+-- issue created strictly after @since (a run's started_at). Used when a task+-- completes to detect deliberate user input that landed while the agent was+-- busy — or that was merged into the running task after its context was+-- already built — so a single follow-up run can be scheduled for it. Restricted+-- to author_type = 'member' on purpose: only human input earns the guaranteed+-- follow-up, which preserves the existing anti-loop guarantees (agent replies,+-- acknowledgements, and self-triggers never qualify). Returns pgx.ErrNoRows+-- when nothing newer exists, i.e. the run already covered the latest input.+SELECT * FROM comment+WHERE issue_id = @issue_id+ AND author_type = 'member'+ AND created_at > @since+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.+SELECT * FROM comment+WHERE issue_id = @issue_id+ AND author_type = 'member'+ AND created_at > @since+ORDER BY created_at ASC, id ASC;+-- name: GetComment :oneSELECT * FROM commentWHERE id = $1;