Skip to content

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

Go

fix(tasks): preserve merged comment delivery (#5192)

Multica Evebf161f2f9c16
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 8d46f62404..a1bdf2d126 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -33,6 +33,75 @@ describe("ApiClient", () => {
}
});
+ it("preserves planned and delivered comment coverage from issue task runs", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify([
+ {
+ id: "task-1",
+ status: "queued",
+ trigger_comment_id: "comment-3",
+ coalesced_comment_ids: ["comment-1", "comment-2"],
+ delivered_comment_ids: ["comment-1", "comment-2", "comment-3"],
+ },
+ ]),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ ),
+ );
+
+ const client = new ApiClient("https://api.example.test");
+ const tasks = await client.listTasksByIssue("issue-1");
+
+ expect(tasks[0]?.trigger_comment_id).toBe("comment-3");
+ expect(tasks[0]?.coalesced_comment_ids).toEqual([
+ "comment-1",
+ "comment-2",
+ ]);
+ expect(tasks[0]?.delivered_comment_ids).toEqual([
+ "comment-1",
+ "comment-2",
+ "comment-3",
+ ]);
+ });
+
+ it("keeps task runs when optional comment coverage is malformed", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify([
+ {
+ id: "task-1",
+ status: "queued",
+ coalesced_comment_ids: ["comment-1", 2],
+ delivered_comment_ids: "not-an-array",
+ },
+ {
+ id: "task-2",
+ status: "completed",
+ delivered_comment_ids: ["comment-2", "comment-3"],
+ },
+ ]),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ ),
+ );
+
+ const client = new ApiClient("https://api.example.test");
+ const tasks = await client.listTasksByIssue("issue-1");
+
+ expect(tasks).toHaveLength(2);
+ expect(tasks[0]?.coalesced_comment_ids).toBeUndefined();
+ expect(tasks[0]?.delivered_comment_ids).toBeUndefined();
+ expect(tasks[1]?.delivered_comment_ids).toEqual([
+ "comment-2",
+ "comment-3",
+ ]);
+ });
+
it("uses the expected HTTP contract for autopilot endpoints", async () => {
const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(
new Response(JSON.stringify({ autopilots: [], runs: [], total: 0 }), {
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 0189a64d33..ac0ef1bd42 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -147,6 +147,7 @@ import { createRequestId } from "../utils";
import { getCurrentSlug } from "../platform/workspace-storage";
import { parseWithFallback } from "./schema";
import {
+ AgentTaskListSchema,
AgentTemplateSchema,
AgentTemplateSummaryListSchema,
AttachmentResponseSchema,
@@ -1469,7 +1470,10 @@ export class ApiClient {
}
async listTasksByIssue(issueId: string): Promise<AgentTask[]> {
- return this.fetch(`/api/issues/${issueId}/task-runs`);
+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/task-runs`);
+ return parseWithFallback<AgentTask[]>(raw, AgentTaskListSchema, [], {
+ endpoint: "GET /api/issues/:id/task-runs",
+ });
}
async getIssueUsage(issueId: string): Promise<IssueUsageSummary> {
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 12d275a381..370b588044 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
AppConfigSchema,
+ AgentTaskListSchema,
DashboardAgentRunTimeListSchema,
DashboardUsageByAgentListSchema,
DashboardUsageDailyListSchema,
@@ -188,6 +189,74 @@ describe("TimelineEntriesSchema", () => {
});
});
+describe("AgentTaskListSchema", () => {
+ const task = {
+ id: "task-1",
+ agent_id: "agent-1",
+ runtime_id: "runtime-1",
+ issue_id: "issue-1",
+ status: "queued",
+ priority: 0,
+ dispatched_at: null,
+ started_at: null,
+ completed_at: null,
+ result: null,
+ error: null,
+ created_at: "2026-07-10T00:00:00Z",
+ trigger_comment_id: "comment-3",
+ };
+
+ it("preserves planned and delivered comment IDs for a task run", () => {
+ const parsed = AgentTaskListSchema.parse([
+ {
+ ...task,
+ coalesced_comment_ids: ["comment-1", "comment-2"],
+ delivered_comment_ids: ["comment-1", "comment-2", "comment-3"],
+ },
+ ]);
+
+ expect(parsed[0]?.trigger_comment_id).toBe("comment-3");
+ expect(parsed[0]?.coalesced_comment_ids).toEqual([
+ "comment-1",
+ "comment-2",
+ ]);
+ expect(parsed[0]?.delivered_comment_ids).toEqual([
+ "comment-1",
+ "comment-2",
+ "comment-3",
+ ]);
+ });
+
+ it("accepts task payloads from older backends without comment coverage", () => {
+ const parsed = AgentTaskListSchema.parse([task]);
+ expect(parsed[0]?.coalesced_comment_ids).toBeUndefined();
+ expect(parsed[0]?.delivered_comment_ids).toBeUndefined();
+ });
+
+ it("degrades malformed optional coverage without dropping task rows", () => {
+ const parsed = AgentTaskListSchema.parse([
+ {
+ ...task,
+ coalesced_comment_ids: ["comment-1", 2],
+ delivered_comment_ids: "not-an-array",
+ },
+ {
+ ...task,
+ id: "task-2",
+ delivered_comment_ids: ["comment-2", "comment-3"],
+ },
+ ]);
+
+ expect(parsed).toHaveLength(2);
+ expect(parsed[0]?.coalesced_comment_ids).toBeUndefined();
+ expect(parsed[0]?.delivered_comment_ids).toBeUndefined();
+ expect(parsed[1]?.delivered_comment_ids).toEqual([
+ "comment-2",
+ "comment-3",
+ ]);
+ });
+});
+
describe("CreateFeedbackResponseSchema", () => {
const ENDPOINT = { endpoint: "POST /api/feedback" };
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 3932adcc3d..bf9608d649 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -523,15 +523,19 @@ const RuntimeUsageByHourSchema = z.object({
export const RuntimeUsageByHourListSchema = z.array(RuntimeUsageByHourSchema);
// ---------------------------------------------------------------------------
-// Task cancellation (`POST /api/tasks/:id/cancel`)
-//
-// This response is consumed directly by chat recovery. The embedded task
-// object stays loose so daemon/runtime fields can drift, but the optional
-// `cancelled_chat_message` payload must be well-formed before the UI deletes
-// a message from cache or restores text into the input.
+// Agent task responses. The base object stays loose so daemon/runtime fields
+// can drift while task-list consumers still validate the fields they render.
// ---------------------------------------------------------------------------
-const AgentTaskResponseSchema = z.object({
+const OptionalStringArraySchema = z.preprocess(
+ (value) =>
+ Array.isArray(value) && value.every((item) => typeof item === "string")
+ ? value
+ : undefined,
+ z.array(z.string()).optional(),
+);
+
+export const AgentTaskSchema = z.object({
id: z.string(),
agent_id: z.string().default(""),
runtime_id: z.string().default(""),
@@ -550,6 +554,11 @@ const AgentTaskResponseSchema = z.object({
parent_task_id: z.string().optional(),
attempt: z.number().optional(),
trigger_comment_id: z.string().optional(),
+ // Coverage is additive display metadata. A mixed-version or partially
+ // upgraded server must not make one malformed optional field erase the
+ // entire execution log, so degrade that field to "absent" independently.
+ coalesced_comment_ids: OptionalStringArraySchema,
+ delivered_comment_ids: OptionalStringArraySchema,
trigger_summary: z.string().optional(),
handoff_note: z.string().optional(),
kind: z.string().optional(),
@@ -557,6 +566,11 @@ const AgentTaskResponseSchema = z.object({
relative_work_dir: z.string().optional(),
}).loose();
+export const AgentTaskListSchema = z.array(AgentTaskSchema);
+
+// Task cancellation (`POST /api/tasks/:id/cancel`) is consumed directly by
+// chat recovery. Its optional message payload must be well-formed before the
+// UI deletes a message from cache or restores text into the input.
const CancelledChatMessageSchema = z.object({
chat_session_id: z.string(),
message_id: z.string(),
@@ -567,7 +581,7 @@ const CancelledChatMessageSchema = z.object({
attachments: z.array(AttachmentSchema).optional(),
}).loose();
-export const CancelTaskResponseSchema = AgentTaskResponseSchema.extend({
+export const CancelTaskResponseSchema = AgentTaskSchema.extend({
cancelled_chat_message: CancelledChatMessageSchema.nullish()
.transform((value) => value ?? undefined),
}).loose();
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 7dde88a439..2207957df1 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -236,6 +236,21 @@ export interface AgentTask {
attempt?: number;
/** Set when an issue comment triggered this task (@mention or assignee comment). */
trigger_comment_id?: string;
+ /**
+ * Earlier comment IDs folded into this run before it was claimed. This does
+ * not include `trigger_comment_id`, which remains the run's newest trigger.
+ * Their unique union is the queued coverage plan; claimed-task consumers
+ * should prefer `delivered_comment_ids` when that receipt is present. Omitted
+ * by older backends and for runs that were not merged.
+ */
+ coalesced_comment_ids?: string[];
+ /**
+ * Comment IDs actually embedded in the task's latest claim response. Once a
+ * task has left queued state this is the authoritative coverage receipt.
+ * Omitted by older backends, where consumers may fall back to the planned
+ * trigger/coalesced union; an explicitly empty array is still authoritative.
+ */
+ delivered_comment_ids?: string[];
/**
* Canonical short description of what triggered this task — snapshot
* taken at creation time. For comment-triggered tasks it's the
diff --git a/packages/views/issues/components/execution-log-section.test.tsx b/packages/views/issues/components/execution-log-section.test.tsx
index 988892df48..286fd582e3 100644
--- a/packages/views/issues/components/execution-log-section.test.tsx
+++ b/packages/views/issues/components/execution-log-section.test.tsx
@@ -27,7 +27,7 @@ vi.mock("./terminate-task-confirm-dialog", () => ({
TerminateTaskConfirmDialog: () => null,
}));
-import { ActiveTaskRow } from "./execution-log-section";
+import { ActiveTaskRow, TaskCommentCoverage } from "./execution-log-section";
function makeTask(overrides: Partial<AgentTask> = {}): AgentTask {
return {
@@ -61,11 +61,20 @@ afterEach(() => {
describe("ActiveTaskRow", () => {
it("renders running status as elapsed time only", () => {
- renderWithI18n(<ActiveTaskRow task={makeTask()} issueId="issue-1" />);
+ renderWithI18n(
+ <ActiveTaskRow
+ task={makeTask({
+ trigger_comment_id: "comment-3",
+ coalesced_comment_ids: ["comment-1", "comment-2"],
+ })}
+ issueId="issue-1"
+ />,
+ );
expect(screen.getByText("5m 04s")).toBeInTheDocument();
expect(screen.queryByText(/events?/i)).not.toBeInTheDocument();
expect(screen.getByText("Started from comment")).toBeInTheDocument();
+ expect(screen.getByText("Includes 3 comments")).toBeInTheDocument();
expect(screen.getByText("View transcript")).toBeInTheDocument();
expect(mockState.taskMessagesOptions).not.toHaveBeenCalled();
});
@@ -87,3 +96,123 @@ describe("ActiveTaskRow", () => {
);
});
});
+
+describe("TaskCommentCoverage", () => {
+ it.each<AgentTask["status"]>([
+ "queued",
+ "dispatched",
+ "waiting_local_directory",
+ "running",
+ "completed",
+ "failed",
+ ])("shows merged comment coverage for %s tasks", (status) => {
+ renderWithI18n(
+ <TaskCommentCoverage
+ task={makeTask({
+ status,
+ trigger_comment_id: "comment-3",
+ coalesced_comment_ids: ["comment-1", "comment-2"],
+ delivered_comment_ids:
+ status === "queued"
+ ? undefined
+ : ["comment-1", "comment-2", "comment-3"],
+ })}
+ />,
+ );
+
+ expect(screen.getByText("Includes 3 comments")).toBeInTheDocument();
+ });
+
+ it("uses the unique planned union for queued tasks", () => {
+ renderWithI18n(
+ <TaskCommentCoverage
+ task={makeTask({
+ status: "queued",
+ trigger_comment_id: "comment-2",
+ coalesced_comment_ids: ["comment-1", "comment-2", "comment-1"],
+ delivered_comment_ids: ["comment-1"],
+ })}
+ />,
+ );
+
+ expect(screen.getByText("Includes 2 comments")).toBeInTheDocument();
+ expect(screen.queryByText("Includes 4 comments")).not.toBeInTheDocument();
+ });
+
+ it("prefers the actual delivery receipt after a task is claimed", () => {
+ renderWithI18n(
+ <TaskCommentCoverage
+ task={makeTask({
+ trigger_comment_id: "comment-3",
+ coalesced_comment_ids: ["comment-1", "comment-2"],
+ delivered_comment_ids: ["comment-1", "comment-2", "comment-2"],
+ })}
+ />,
+ );
+
+ expect(screen.getByText("Includes 2 comments")).toBeInTheDocument();
+ expect(screen.queryByText("Includes 3 comments")).not.toBeInTheDocument();
+ });
+
+ it("falls back to planned coverage for legacy claimed-task rows", () => {
+ renderWithI18n(
+ <TaskCommentCoverage
+ task={makeTask({
+ trigger_comment_id: "comment-3",
+ coalesced_comment_ids: ["comment-1", "comment-2"],
+ })}
+ />,
+ );
+
+ expect(screen.getByText("Includes 3 comments")).toBeInTheDocument();
+ });
+
+ it("treats an explicitly empty delivery receipt as authoritative", () => {
+ renderWithI18n(
+ <TaskCommentCoverage
+ task={makeTask({
+ trigger_comment_id: "comment-3",
+ coalesced_comment_ids: ["comment-1", "comment-2"],
+ delivered_comment_ids: [],
+ })}
+ />,
+ );
+
+ expect(screen.queryByText(/Includes \d+ comments?/)).not.toBeInTheDocument();
+ });
+
+ it("stays hidden for one comment but shows a cancelled task receipt", () => {
+ const { rerender } = renderWithI18n(
+ <TaskCommentCoverage
+ task={makeTask({ trigger_comment_id: "comment-1" })}
+ />,
+ );
+ expect(screen.queryByText(/Includes \d+ comments?/)).not.toBeInTheDocument();
+
+ rerender(
+ <TaskCommentCoverage
+ task={makeTask({
+ status: "cancelled",
+ trigger_comment_id: "comment-2",
+ coalesced_comment_ids: ["comment-1"],
+ delivered_comment_ids: ["comment-1", "comment-2"],
+ })}
+ />,
+ );
+ expect(screen.getByText("Includes 2 comments")).toBeInTheDocument();
+ });
+
+ it("renders the Chinese comment count", () => {
+ renderWithI18n(
+ <TaskCommentCoverage
+ task={makeTask({
+ trigger_comment_id: "comment-3",
+ coalesced_comment_ids: ["comment-1", "comment-2"],
+ })}
+ />,
+ { locale: "zh-Hans" },
+ );
+
+ expect(screen.getByText("包含 3 条评论")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsx
index c217fb1f43..1dbc5d0765 100644
--- a/packages/views/issues/components/execution-log-section.tsx
+++ b/packages/views/issues/components/execution-log-section.tsx
@@ -305,6 +305,7 @@ export function ActiveTaskRow({
return (
<RowShell task={task}>
<TriggerText text={trigger} />
+ <TaskCommentCoverage task={task} />
<RowStatus title={label}>
{task.status === "running" ? (
<>
@@ -398,6 +399,7 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {
return (
<RowShell task={task}>
<TriggerText text={trigger} />
+ <TaskCommentCoverage task={task} />
<RowStatus title={failureLabel ?? label}>
<TaskStatusIcon status={task.status} />
<span className="sr-only">{failureLabel ?? label}</span>
@@ -462,6 +464,49 @@ function TriggerText({ text }: { text: string }) {
return <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">{text}</span>;
}
+function supportsCommentCoverage(status: AgentTask["status"]): boolean {
+ switch (status) {
+ case "queued":
+ case "dispatched":
+ case "waiting_local_directory":
+ case "running":
+ case "completed":
+ case "failed":
+ case "cancelled":
+ return true;
+ default:
+ return false;
+ }
+}
+
+export function TaskCommentCoverage({ task }: { task: AgentTask }) {
+ const { t } = useT("issues");
+ if (!supportsCommentCoverage(task.status)) return null;
+
+ // Queued rows show the planned coverage: coalesced_comment_ids deliberately
+ // excludes the newest trigger. Once claimed, prefer the server's actual
+ // delivery receipt. Only legacy rows where that field is absent fall back to
+ // the plan; an explicit [] means the claim delivered no comments.
+ const plannedCommentIds = [
+ task.trigger_comment_id,
+ ...(task.coalesced_comment_ids ?? []),
+ ];
+ const coverageIds =
+ task.status !== "queued" && task.delivered_comment_ids !== undefined
+ ? task.delivered_comment_ids
+ : plannedCommentIds;
+ const commentIds = new Set(
+ coverageIds.filter((id): id is string => Boolean(id)),
+ );
+ if (commentIds.size <= 1) return null;
+
+ return (
+ <span className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground">
+ {t(($) => $.execution_log.included_comments, { count: commentIds.size })}
+ </span>
+ );
+}
+
function RowStatus({
children,
title,
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index d126bf3331..a1b1a2f0a1 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -381,6 +381,8 @@
"trigger_comment": "Comment trigger",
"trigger_initial": "Initial run",
"trigger_handoff_prefix": "Handoff: ",
+ "included_comments_one": "Includes {{count}} comment",
+ "included_comments_other": "Includes {{count}} comments",
"status_queued": "Queued",
"status_dispatched": "Starting",
"status_waiting_local_directory": "Waiting for local directory",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 945399f26f..6ba19cdab1 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -365,6 +365,7 @@
"trigger_comment": "コメントトリガー",
"trigger_initial": "初回実行",
"trigger_handoff_prefix": "引き継ぎ:",
+ "included_comments_other": "{{count}} 件のコメントを含む",
"status_queued": "待機中",
"status_dispatched": "開始中",
"status_waiting_local_directory": "ローカルディレクトリ待機中",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index b212b2c49e..308b879ea3 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -365,6 +365,7 @@
"trigger_comment": "댓글 트리거",
"trigger_initial": "초기 실행",
"trigger_handoff_prefix": "인계: ",
+ "included_comments_other": "댓글 {{count}}개 포함",
"status_queued": "대기 중",
"status_dispatched": "시작 중",
"status_waiting_local_directory": "로컬 디렉터리 대기 중",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index c9b10701a7..99fecd510b 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -365,6 +365,7 @@
"trigger_comment": "评论触发",
"trigger_initial": "首次运行",
"trigger_handoff_prefix": "交接:",
+ "included_comments_other": "包含 {{count}} 条评论",
"status_queued": "排队中",
"status_dispatched": "启动中",
"status_waiting_local_directory": "等待本地目录释放",
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 6722d77875..2336859849 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -166,7 +166,10 @@ func (c *Client) setIdentityHeaders(req *http.Request) {
if c.os != "" {
req.Header.Set("X-Client-OS", c.os)
}
- req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilitySkillBundlesV1)
+ req.Header.Set("X-Client-Capabilities", strings.Join([]string{
+ protocol.DaemonCapabilitySkillBundlesV1,
+ protocol.DaemonCapabilityCoalescedCommentsV1,
+ }, ","))
}
// SetToken sets the auth token for authenticated requests.
diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.go
index e38d5e8dab..7878d09b22 100644
--- a/server/internal/daemon/client_test.go
+++ b/server/internal/daemon/client_test.go
@@ -7,9 +7,12 @@ import (
"net/http"
"net/http/httptest"
"runtime"
+ "strings"
"sync/atomic"
"testing"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
func TestClient_IdentityHeaders_PostJSON(t *testing.T) {
@@ -26,6 +29,18 @@ func TestClient_IdentityHeaders_PostJSON(t *testing.T) {
if got := r.Header.Get("Authorization"); got != "Bearer tok" {
t.Errorf("expected Authorization Bearer tok, got %q", got)
}
+ capabilities := make(map[string]bool)
+ for _, capability := range strings.Split(r.Header.Get("X-Client-Capabilities"), ",") {
+ capabilities[strings.TrimSpace(capability)] = true
+ }
+ for _, want := range []string{
+ protocol.DaemonCapabilitySkillBundlesV1,
+ protocol.DaemonCapabilityCoalescedCommentsV1,
+ } {
+ if !capabilities[want] {
+ t.Errorf("X-Client-Capabilities missing %q: %v", want, capabilities)
+ }
+ }
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"ok": "1"})
}))
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index e1e51665f0..6065170ab6 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -312,6 +312,7 @@ type AgentTaskResponse struct {
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 it
+ DeliveredCommentIDs []string `json:"delivered_comment_ids"` // always present: [] is an authoritative empty receipt, while field absence identifies responses from legacy servers
TriggerThreadID string `json:"trigger_thread_id,omitempty"` // root comment ID for the triggering thread
TriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering comment
TriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletes
@@ -471,6 +472,7 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {
CreatedAt: timestampToString(t.CreatedAt),
TriggerCommentID: uuidToPtr(t.TriggerCommentID),
CoalescedCommentIDs: uuidsToStrings(t.CoalescedCommentIds),
+ DeliveredCommentIDs: uuidStringsOrEmpty(t.DeliveredCommentIds),
TriggerSummary: textToPtr(t.TriggerSummary),
HandoffNote: handoffNote,
WorkDir: workDir,
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index b9de6290cc..b675b6ab86 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"log/slog"
"net/http"
+ "sort"
"strconv"
"strings"
"time"
@@ -2047,6 +2048,23 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
// NOTE: See CreateComment — Markdown is sanitized at render/edit time, not here.
oldContent := existing.Content
+ var triggerIssue *db.Issue
+ var cancelled []db.AgentTaskQueue
+ if oldContent != req.Content {
+ issue, err := h.Queries.GetIssue(r.Context(), existing.IssueID)
+ if err != nil {
+ slog.Warn("load issue for edit post-processing failed", "issue_id", uuidToString(existing.IssueID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to load issue")
+ return
+ }
+ triggerIssue = &issue
+ cancelled, err = h.TaskService.CancelTasksByTriggerComment(r.Context(), existing.ID)
+ if err != nil {
+ slog.Warn("cancel tasks for edited comment failed", "comment_id", uuidToString(existing.ID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to prepare comment edit")
+ return
+ }
+ }
comment, err := h.Queries.UpdateComment(r.Context(), db.UpdateCommentParams{
ID: commentUUID,
@@ -2054,9 +2072,30 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
})
if err != nil {
slog.Warn("update comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
+ if triggerIssue != nil {
+ // Cancellation committed but the edit did not. Restore the complete
+ // original batch, including the still-valid unchanged comment.
+ h.retriggerCancelledTaskSurvivors(r.Context(), *triggerIssue, cancelled, pgtype.UUID{})
+ }
writeError(w, http.StatusInternalServerError, "failed to update comment")
return
}
+ retriggerEditedComment := func() {
+ if oldContent == comment.Content {
+ return
+ }
+ issue := *triggerIssue
+ var parentComment *db.Comment
+ if existing.ParentID.Valid {
+ parent, err := h.Queries.GetComment(r.Context(), existing.ParentID)
+ if err == nil {
+ parentComment = &parent
+ }
+ }
+
+ h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, existing.ID)
+ h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), suppressAgentIDs)
+ }
// Replace the comment attachment set when a modern client sends
// attachment_ids. Older clients omit the field; in that case preserve the
@@ -2068,6 +2107,10 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
AttachmentIds: attachmentIDs,
}); err != nil {
slog.Error("failed to replace comment attachments", "error", err)
+ // UpdateComment already committed the new body. Even though attachment
+ // replacement failed, repair task routing for that persisted edit so a
+ // dispatched run cannot permanently keep the old comment version.
+ retriggerEditedComment()
writeError(w, http.StatusInternalServerError, "failed to update attachments")
return
}
@@ -2081,26 +2124,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
slog.Info("comment updated", append(logger.RequestAttrs(r), "comment_id", commentId)...)
h.publish(protocol.EventCommentUpdated, workspaceID, actorType, actorID, map[string]any{"comment": resp})
- if oldContent != comment.Content {
- if err := h.TaskService.CancelTasksByTriggerComment(r.Context(), existing.ID); err != nil {
- slog.Warn("cancel tasks for edited comment failed", "comment_id", uuidToString(existing.ID), "error", err)
- }
-
- issue, err := h.Queries.GetIssue(r.Context(), existing.IssueID)
- if err != nil {
- slog.Warn("load issue for edit post-processing failed", "issue_id", uuidToString(existing.IssueID), "error", err)
- } else {
- var parentComment *db.Comment
- if existing.ParentID.Valid {
- parent, err := h.Queries.GetComment(r.Context(), existing.ParentID)
- if err == nil {
- parentComment = &parent
- }
- }
-
- h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), suppressAgentIDs)
- }
- }
+ retriggerEditedComment()
writeJSON(w, http.StatusOK, resp)
}
@@ -2145,16 +2169,23 @@ func (h *Handler) DeleteComment(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusForbidden, "only comment author or admin can delete")
return
}
+ issue, err := h.Queries.GetIssue(r.Context(), comment.IssueID)
+ if err != nil {
+ slog.Warn("load issue for delete post-processing failed", "issue_id", uuidToString(comment.IssueID), "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to load issue")
+ return
+ }
// Collect attachment URLs before CASCADE delete removes them.
attachmentURLs, _ := h.Queries.ListAttachmentURLsByCommentID(r.Context(), comment.ID)
- // Cancel any active tasks triggered by this comment so the agent does not
- // run with the now-deleted content already embedded in its prompt. Must
+ // Cancel any active task whose planned batch contains this comment so the
+ // agent does not run with the now-deleted content already embedded. Must
// run before DeleteComment because the FK ON DELETE SET NULL would
// otherwise nullify trigger_comment_id and orphan those tasks in queued.
- if err := h.TaskService.CancelTasksByTriggerComment(r.Context(), comment.ID); err != nil {
- slog.Warn("cancel tasks for deleted trigger comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
+ cancelled, cancelErr := h.TaskService.CancelTasksByTriggerComment(r.Context(), comment.ID)
+ if cancelErr != nil {
+ slog.Warn("cancel tasks for deleted trigger comment failed", append(logger.RequestAttrs(r), "error", cancelErr, "comment_id", commentId)...)
}
if err := h.Queries.DeleteComment(r.Context(), db.DeleteCommentParams{
@@ -2162,6 +2193,10 @@ func (h *Handler) DeleteComment(w http.ResponseWriter, r *http.Request) {
WorkspaceID: comment.WorkspaceID,
}); err != nil {
slog.Warn("delete comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
+ // Cancellation already committed but deletion did not. The comment is
+ // still valid, so rebuild the complete cancelled batch (including this
+ // trigger) before returning the storage error.
+ h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, pgtype.UUID{})
writeError(w, http.StatusInternalServerError, "failed to delete comment")
return
}
@@ -2172,9 +2207,95 @@ func (h *Handler) DeleteComment(w http.ResponseWriter, r *http.Request) {
"comment_id": uuidToString(comment.ID),
"issue_id": uuidToString(comment.IssueID),
})
+ h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, comment.ID)
w.WriteHeader(http.StatusNoContent)
}
+// retriggerCancelledTaskSurvivors repairs the surviving inputs from a
+// batch containing a comment that was edited or deleted. Cancellation releases
+// the one-pending-task constraint; every other comment is replayed through the
+// normal authorization/routing path, scoped to the agent whose task carried
+// it. Chronological replay makes those survivors coalesce back into one batch
+// and lets the latest real comment restamp originator + connected-app context.
+func (h *Handler) retriggerCancelledTaskSurvivors(ctx context.Context, issue db.Issue, cancelled []db.AgentTaskQueue, excludedCommentID pgtype.UUID) {
+ if len(cancelled) == 0 {
+ return
+ }
+ targetsByComment := make(map[string]map[string]pgtype.UUID)
+ for _, task := range cancelled {
+ if !task.AgentID.Valid {
+ continue
+ }
+ plannedCommentIDs := append([]pgtype.UUID{}, task.CoalescedCommentIds...)
+ if task.TriggerCommentID.Valid {
+ plannedCommentIDs = append(plannedCommentIDs, task.TriggerCommentID)
+ }
+ for _, commentID := range plannedCommentIDs {
+ if !commentID.Valid || (excludedCommentID.Valid && commentID == excludedCommentID) {
+ continue
+ }
+ commentKey := uuidToString(commentID)
+ if targetsByComment[commentKey] == nil {
+ targetsByComment[commentKey] = make(map[string]pgtype.UUID)
+ }
+ targetsByComment[commentKey][uuidToString(task.AgentID)] = task.AgentID
+ }
+ }
+
+ comments := make([]db.Comment, 0, len(targetsByComment))
+ for commentID := range targetsByComment {
+ comment, err := h.Queries.GetComment(ctx, parseUUID(commentID))
+ if err != nil {
+ slog.Warn("retrigger cancelled comment batch: load survivor failed",
+ "issue_id", uuidToString(issue.ID), "comment_id", commentID, "error", err)
+ continue
+ }
+ if comment.IssueID != issue.ID {
+ continue
+ }
+ comments = append(comments, comment)
+ }
+ sort.Slice(comments, func(i, j int) bool {
+ if !comments[i].CreatedAt.Time.Equal(comments[j].CreatedAt.Time) {
+ return comments[i].CreatedAt.Time.Before(comments[j].CreatedAt.Time)
+ }
+ return uuidToString(comments[i].ID) < uuidToString(comments[j].ID)
+ })
+
+ for i := range comments {
+ comment := comments[i]
+ if isNoteComment(comment.Content) {
+ continue
+ }
+ var parentComment *db.Comment
+ if comment.ParentID.Valid {
+ if parent, err := h.Queries.GetComment(ctx, comment.ParentID); err == nil {
+ parentComment = &parent
+ }
+ }
+ actorType := comment.AuthorType
+ actorID := uuidToString(comment.AuthorID)
+ originatorUserID := actorID
+ if actorType != "member" {
+ originatorUserID = uuidToString(h.TaskService.ResolveOriginatorFromTriggerComment(ctx, issue.WorkspaceID, comment.ID))
+ }
+ triggers := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
+ ExcludeTriggerCommentID: comment.ID,
+ OriginatorUserID: originatorUserID,
+ })
+ targets := targetsByComment[uuidToString(comment.ID)]
+ scoped := make([]commentAgentTrigger, 0, len(targets))
+ for _, trigger := range triggers {
+ if _, ok := targets[uuidToString(trigger.Agent.ID)]; ok {
+ scoped = append(scoped, trigger)
+ }
+ }
+ if len(scoped) > 0 {
+ h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, scoped)
+ }
+ }
+}
+
// loadCommentForActor resolves a {commentId} URL param to a comment in the
// caller's workspace. Returns the comment, the workspace UUID, the actor
// identity, and ok. Resolve / unresolve handlers share this scaffolding so the
diff --git a/server/internal/handler/comment_reconcile_test.go b/server/internal/handler/comment_reconcile_test.go
index 574466f51c..f2dfa444c6 100644
--- a/server/internal/handler/comment_reconcile_test.go
+++ b/server/internal/handler/comment_reconcile_test.go
@@ -4,6 +4,7 @@ import (
"context"
"net/http"
"net/http/httptest"
+ "slices"
"testing"
"time"
@@ -94,8 +95,8 @@ func TestCompleteTask_ReconcilesMemberCommentPostedDuringRun(t *testing.T) {
// 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')
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at)
+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], '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)
@@ -157,8 +158,8 @@ func TestCompleteTask_NoReconcileWhenNoNewMemberComment(t *testing.T) {
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')
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at)
+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], '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)
@@ -222,8 +223,8 @@ func TestCompleteTask_DoesNotReTriggerOtherAgentMentionedDuringRun(t *testing.T)
// 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')
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at)
+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], '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)
@@ -323,8 +324,8 @@ func TestCompleteTask_ReconcilesAgentAuthoredMentionToCompletedAgent(t *testing.
// drop at creation time.
var taskID string
if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, created_at, dispatched_at)
- VALUES ($1, $2, $3, $4, 'dispatched', 0, now() - interval '10 minutes', now() - interval '5 minutes')
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, dispatched_at)
+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'dispatched', 0, now() - interval '10 minutes', now() - interval '5 minutes')
RETURNING id
`, agentB, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {
t.Fatalf("setup: dispatched task: %v", err)
@@ -414,8 +415,8 @@ func TestCompleteTask_DoesNotReconcilePlainAgentReply(t *testing.T) {
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')
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at)
+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '5 minutes')
RETURNING id
`, agentB, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {
t.Fatalf("setup: running task: %v", err)
@@ -650,8 +651,8 @@ func TestCompleteTask_ReconcilesDispatchedWindowComment(t *testing.T) {
// 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')
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, dispatched_at, started_at)
+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], '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)
@@ -760,8 +761,8 @@ func TestCompleteTask_ReconcilesPreDispatchMergeRaceComment(t *testing.T) {
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,
+ (agent_id, runtime_id, issue_id, trigger_comment_id, coalesced_comment_ids, delivered_comment_ids, status, priority, created_at, dispatched_at, started_at)
+ VALUES ($1, $2, $3, $4, ARRAY[$5::uuid], ARRAY[$4::uuid, $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 {
@@ -787,3 +788,95 @@ func TestCompleteTask_ReconcilesPreDispatchMergeRaceComment(t *testing.T) {
deliveredCoalescedID, trigger, coalesced)
}
}
+
+// TestCompleteTask_ReconcilesPlannedButUndeliveredComments pins the distinction
+// between the enqueue plan and the claim receipt. The planned comments predate
+// the task (as they do on an auto-retry), so the planned-id query branch is the
+// only way completion can recover payload-overflow or legacy-undelivered input.
+func TestCompleteTask_ReconcilesPlannedButUndeliveredComments(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ tests := []struct {
+ name string
+ deliveredOldCount int
+ wantFollowup int
+ }{
+ {name: "partial receipt replays only omitted suffix", deliveredOldCount: 1, wantFollowup: 1},
+ {name: "legacy trigger-only receipt replays whole coalesced batch", deliveredOldCount: 0, wantFollowup: 2},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Planned undelivered runtime "+tc.name)
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Planned undelivered agent "+tc.name)
+ if _, err := testPool.Exec(ctx, `
+ UPDATE issue
+ SET assignee_type = 'agent', assignee_id = $2
+ WHERE id = $1
+ `, issueID, agentID); err != nil {
+ t.Fatalf("assign issue: %v", err)
+ }
+
+ 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
+ }
+ old1 := insertComment("planned old one", "10 minutes")
+ old2 := insertComment("planned old two", "9 minutes")
+ trigger := insertComment("planned trigger", "8 minutes")
+ delivered := []string{trigger}
+ if tc.deliveredOldCount > 0 {
+ delivered = append([]string{old1}, delivered...)
+ }
+
+ 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, delivered_comment_ids,
+ status, priority, created_at, dispatched_at, started_at
+ )
+ VALUES (
+ $1, $2, $3, $4,
+ ARRAY[$5::uuid, $6::uuid], $7::uuid[],
+ 'running', 0, now() - interval '5 minutes', now() - interval '4 minutes', now() - interval '3 minutes'
+ )
+ RETURNING id
+ `, agentID, runtimeID, issueID, trigger, old1, old2, delivered).Scan(&taskID); err != nil {
+ t.Fatalf("insert running task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `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 != 1 {
+ t.Fatalf("expected one bounded follow-up, got %d", n)
+ }
+ followupTrigger, _, followupCoalesced := taskTriggerOriginatorCoalesced(t, issueID, agentID)
+ covered := append([]string{}, followupCoalesced...)
+ covered = append(covered, followupTrigger)
+ slices.Sort(covered)
+ want := []string{old2}
+ if tc.wantFollowup == 2 {
+ want = []string{old1, old2}
+ }
+ slices.Sort(want)
+ if !slices.Equal(covered, want) {
+ t.Fatalf("follow-up coverage = %v, want %v", covered, want)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 30372b5ee4..02d55a57a3 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1356,6 +1356,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
return
}
runtimeWorkspaceID := uuidToString(runtime.WorkspaceID)
+ supportsCoalescedComments := requestHasDaemonCapability(r, protocol.DaemonCapabilityCoalescedCommentsV1)
authMs = time.Since(start).Milliseconds()
claimStart := time.Now()
@@ -1373,12 +1374,64 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
outcome = "no_task"
return
}
+ if !task.TriggerCommentID.Valid && len(task.CoalescedCommentIds) > 0 {
+ // A legacy edit/delete race can leave a plan whose trigger FK was
+ // cleared while its user-scoped MCP overlay still belongs to the deleted
+ // author. Never dispatch it as a generic assignment: that prompt reads
+ // issue history and would still expose the stale user's capabilities.
+ // Cancel the stale row and replay every survivor through normal routing,
+ // which recomputes originator and connected-app context.
+ if !task.IssueID.Valid {
+ outcome = "error_stale_comment_plan"
+ writeError(w, http.StatusInternalServerError, "comment task has no issue")
+ return
+ }
+ issue, loadErr := h.Queries.GetIssue(r.Context(), task.IssueID)
+ if loadErr != nil {
+ outcome = "error_stale_comment_plan"
+ writeError(w, http.StatusInternalServerError, "failed to repair stale comment task")
+ return
+ }
+ if uuidToString(issue.WorkspaceID) != runtimeWorkspaceID {
+ outcome = "error_workspace"
+ if _, cancelErr := h.TaskService.CancelTask(r.Context(), task.ID); cancelErr != nil {
+ slog.Error("task claim: cancel stale cross-workspace task failed",
+ "task_id", uuidToString(task.ID), "error", cancelErr)
+ }
+ writeError(w, http.StatusInternalServerError, "task workspace isolation check failed")
+ return
+ }
+ cancelled, cancelErr := h.TaskService.CancelTask(r.Context(), task.ID)
+ if cancelErr != nil {
+ outcome = "error_stale_comment_plan"
+ writeError(w, http.StatusInternalServerError, "failed to repair stale comment task")
+ return
+ }
+ h.retriggerCancelledTaskSurvivors(r.Context(), issue, []db.AgentTaskQueue{*cancelled}, pgtype.UUID{})
+ outcome = "repaired_stale_comment_plan"
+ payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": nil})
+ return
+ }
outcome = "claimed"
buildStart = time.Now()
// Build response with fresh agent data (name + skills + custom_env + custom_args).
resp := taskToResponse(*task, runtimeWorkspaceID)
+ // Empty-but-non-nil so pgx persists '{}' rather than NULL for tasks without
+ // comment input. Comment tasks replace this with the ids actually embedded
+ // in the capability-aware response built below.
+ deliveredCommentIDs := []pgtype.UUID{}
+ commentBackedTask := task.TriggerCommentID.Valid || len(task.CoalescedCommentIds) > 0
+ requeueFailedClaim := func(reason string) {
+ if _, err := h.TaskService.RequeueTaskAfterClaimFailure(r.Context(), *task); err != nil {
+ slog.Error("task claim: failed to requeue after finalization error",
+ "task_id", uuidToString(task.ID),
+ "reason", reason,
+ "error", err,
+ )
+ }
+ }
composioMCPEnabled := h.composioMCPAppsEnabled(r.Context())
if composioMCPEnabled {
resp.ConnectedApps = parseRuntimeConnectedAppsForClaim(task.RuntimeConnectedApps, task.ID)
@@ -1600,13 +1653,59 @@ 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(), runtime.WorkspaceID, task.CoalescedCommentIds)
+ // Load every planned input as one chronological, de-duplicated set.
+ // The trigger is included here so the delivery receipt can only contain
+ // comments whose body we successfully embedded. Missing/deleted rows are
+ // intentionally absent and remain eligible for reconciliation. A stable
+ // payload budget always keeps the primary trigger, then admits an oldest-
+ // first prefix of additional comments; overflow is reconciled later.
+ // Workspace-scoped load (MUL-4252) so a foreign comment UUID resolves to
+ // "missing" instead of leaking another tenant's text into the prompt.
+ plannedCommentIDs := append([]pgtype.UUID{}, task.CoalescedCommentIds...)
+ if task.TriggerCommentID.Valid {
+ plannedCommentIDs = append(plannedCommentIDs, task.TriggerCommentID)
+ }
+ loadedComments := h.buildCoalescedCommentData(r.Context(), runtime.WorkspaceID, plannedCommentIDs)
+ triggerCommentID := uuidToString(task.TriggerCommentID)
+ var deliveredComments []CoalescedCommentData
+ triggerLoaded := false
+ for _, comment := range loadedComments {
+ if comment.ID == triggerCommentID {
+ triggerLoaded = true
+ break
+ }
+ }
+ if task.TriggerCommentID.Valid && triggerLoaded {
+ deliveredComments = selectCommentDelivery(
+ loadedComments,
+ triggerCommentID,
+ !supportsCoalescedComments,
+ maxClaimCommentPayloadBytes,
+ )
+ }
+ // If the persisted trigger body cannot be loaded, fail closed on comment
+ // coverage for this claim. The trigger snapshot CAS below also rejects a
+ // concurrent edit/delete that changes the FK after this read.
+ deliveredCommentIDs = commentDataIDs(deliveredComments)
+ // taskToResponse exposes the enqueue plan to UI task-list callers. A
+ // daemon claim must instead advertise only the structured ids actually
+ // present in this payload, especially when the delivery budget truncates.
+ resp.CoalescedCommentIDs = nil
+ for _, comment := range deliveredComments {
+ if comment.ID == triggerCommentID {
+ // Populate the actual payload from the same successful read that
+ // earned the receipt. The richer GetComment lookup below resolves
+ // initiator ids and count hints, but a transient second-read failure
+ // must never acknowledge a body that was not embedded.
+ resp.TriggerCommentContent = comment.Content
+ resp.TriggerThreadID = comment.ThreadID
+ resp.TriggerAuthorType = comment.AuthorType
+ resp.TriggerAuthorName = comment.AuthorName
+ continue
+ }
+ resp.CoalescedCommentIDs = append(resp.CoalescedCommentIDs, comment.ID)
+ resp.CoalescedComments = append(resp.CoalescedComments, comment)
+ }
// Fetch the triggering comment content so the daemon can embed it
// directly in the agent prompt (prevents the agent from ignoring comments
@@ -1614,13 +1713,14 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
// comment author's kind and display name so the agent knows whether it
// was triggered by a human or by another agent — a signal used by the
// harness instructions to avoid mention loops between agents.
- if task.TriggerCommentID.Valid {
+ effectiveTriggerUUID := task.TriggerCommentID
+ if effectiveTriggerUUID.Valid {
// Scope by the runtime's workspace so a task row carrying a foreign
// comment UUID can never pull another workspace's comment text into
// this agent's prompt. The task's issue workspace is asserted equal
// to runtime.WorkspaceID below, so this is the right tenant (MUL-4252).
if comment, err := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{
- ID: task.TriggerCommentID,
+ ID: effectiveTriggerUUID,
WorkspaceID: runtime.WorkspaceID,
}); err == nil {
resp.TriggerCommentContent = comment.Content
@@ -1672,7 +1772,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
IssueID: comment.IssueID,
}); err == nil && startedAt.Valid {
if cnt, err := h.Queries.CountNewCommentsSince(r.Context(), db.CountNewCommentsSinceParams{
- AnchorID: task.TriggerCommentID,
+ AnchorID: effectiveTriggerUUID,
IssueID: comment.IssueID,
WorkspaceID: comment.WorkspaceID,
Since: startedAt,
@@ -1685,6 +1785,24 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
}
}
+ if !supportsCoalescedComments {
+ // Legacy daemons ignore the structured coalesced fields. Fold every
+ // successfully loaded comment into the one trigger field they already
+ // understand, then hide the structured fields to avoid duplicate prompt
+ // sections in intermediate daemons that understand them but do not yet
+ // advertise the capability.
+ if len(resp.CoalescedComments) > 0 || (resp.TriggerCommentContent == "" && len(deliveredComments) > 0) {
+ resp.TriggerCommentContent = formatLegacyCommentBundle(deliveredComments)
+ }
+ resp.CoalescedCommentIDs = nil
+ resp.CoalescedComments = nil
+ } else if resp.TriggerCommentContent == "" && len(deliveredComments) > 0 {
+ // A deleted newest trigger must not suppress the structured earlier
+ // comments: buildCommentPrompt renders them inside its trigger-content
+ // branch. The missing id itself is not acknowledged in the receipt.
+ resp.TriggerCommentContent = "The newest triggering comment is no longer available. Address every earlier comment included below."
+ }
+
// Look up the prior session for this (agent, issue) pair so the daemon
// can resume the Claude Code conversation context.
//
@@ -2063,24 +2181,33 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
outcome = "error_token"
slog.Error("task claim: failed to generate agent task token",
"task_id", uuidToString(task.ID), "error", terr)
+ requeueFailedClaim("token_generation")
writeError(w, http.StatusInternalServerError, "failed to mint task token")
return
}
- if _, terr := h.Queries.CreateTaskToken(r.Context(), db.CreateTaskTokenParams{
+ receipt, ferr := h.TaskService.FinalizeTaskClaim(r.Context(), *task, db.CreateTaskTokenParams{
TokenHash: auth.HashToken(tokenStr),
TaskID: task.ID,
AgentID: task.AgentID,
WorkspaceID: parseUUID(resp.WorkspaceID),
UserID: runtime.OwnerID,
ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},
- }); terr != nil {
- outcome = "error_token"
- slog.Error("task claim: failed to persist agent task token",
- "task_id", uuidToString(task.ID), "error", terr)
- writeError(w, http.StatusInternalServerError, "failed to persist task token")
+ }, deliveredCommentIDs, commentBackedTask)
+ if ferr != nil {
+ outcome = "error_claim_finalize"
+ slog.Error("task claim: failed to finalize token and comment delivery receipt",
+ "task_id", uuidToString(task.ID), "error", ferr)
+ // FinalizeTaskClaim is transactional, so its newly generated token is
+ // rolled back with the receipt. Never delete by task here: a stale
+ // reclaim can race the original daemon starting, and broad revocation
+ // would invalidate that already-authorized execution.
+ requeueFailedClaim("token_and_delivery_receipt")
+ writeError(w, http.StatusInternalServerError, "failed to finalize task claim")
return
}
resp.AuthToken = tokenStr
+ task.DeliveredCommentIds = receipt
+ resp.DeliveredCommentIDs = uuidStringsOrEmpty(receipt)
slog.Info("task claimed by runtime", "task_id", uuidToString(task.ID), "runtime_id", runtimeID, "agent_id", uuidToString(task.AgentID), "prior_session", resp.PriorSessionID)
if resp.Agent != nil && len(resp.Agent.Skills) > 0 {
@@ -2439,10 +2566,11 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A
// 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.
+// while it is still PRE-CLAIM (queued/deferred). Those planned ids are not
+// proof of delivery: older daemons ignore structured coalesced fields, and a
+// referenced comment can be deleted before claim. Claim therefore records the
+// ids it actually embedded in delivered_comment_ids. Anything posted during
+// this run's lifetime that is NOT in that receipt 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
@@ -2453,8 +2581,8 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A
// 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
+// 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.
//
@@ -2486,9 +2614,14 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
if task == nil || !task.IssueID.Valid || !task.AgentID.Valid || !task.CreatedAt.Valid {
return
}
+ plannedCommentIDs := append([]pgtype.UUID{}, task.CoalescedCommentIds...)
+ if task.TriggerCommentID.Valid {
+ plannedCommentIDs = append(plannedCommentIDs, task.TriggerCommentID)
+ }
comments, err := h.Queries.ListReconcilableCommentsForIssueSince(ctx, db.ListReconcilableCommentsForIssueSinceParams{
- IssueID: task.IssueID,
- Since: task.CreatedAt,
+ IssueID: task.IssueID,
+ Since: task.CreatedAt,
+ PlannedCommentIds: plannedCommentIDs,
})
if err != nil {
slog.Warn("reconcile comments on completion: list comments failed",
@@ -2498,15 +2631,11 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
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 {
+ // The delivered set is the claim-time receipt, not the enqueue-time plan.
+ // Legacy tasks backfill only the primary trigger, deliberately replaying
+ // coalesced inputs that their daemon may have ignored.
+ delivered := make(map[string]struct{}, len(task.DeliveredCommentIds))
+ for _, id := range task.DeliveredCommentIds {
if id.Valid {
delivered[uuidToString(id)] = struct{}{}
}
@@ -2630,10 +2759,16 @@ func (h *Handler) buildCoalescedCommentData(ctx context.Context, workspaceID pgt
return nil
}
out := make([]CoalescedCommentData, 0, len(ids))
+ seen := make(map[string]struct{}, len(ids))
for _, id := range ids {
if !id.Valid {
continue
}
+ idString := uuidToString(id)
+ if _, ok := seen[idString]; ok {
+ continue
+ }
+ seen[idString] = struct{}{}
// Workspace-scoped so a foreign comment UUID resolves to "missing"
// (skipped) instead of leaking another tenant's text into the prompt
// (MUL-4252). Matches this function's documented skip-on-missing rule.
@@ -2671,9 +2806,157 @@ func (h *Handler) buildCoalescedCommentData(ctx context.Context, workspaceID pgt
if len(out) == 0 {
return nil
}
+ sort.Slice(out, func(i, j int) bool {
+ left, leftErr := time.Parse(time.RFC3339Nano, out[i].CreatedAt)
+ right, rightErr := time.Parse(time.RFC3339Nano, out[j].CreatedAt)
+ if leftErr == nil && rightErr == nil && !left.Equal(right) {
+ return left.Before(right)
+ }
+ if out[i].CreatedAt != out[j].CreatedAt {
+ return out[i].CreatedAt < out[j].CreatedAt
+ }
+ return out[i].ID < out[j].ID
+ })
return out
}
+func commentDataIDs(comments []CoalescedCommentData) []pgtype.UUID {
+ if len(comments) == 0 {
+ return []pgtype.UUID{}
+ }
+ ids := make([]pgtype.UUID, 0, len(comments))
+ for _, comment := range comments {
+ ids = append(ids, parseUUID(comment.ID))
+ }
+ return ids
+}
+
+const maxClaimCommentPayloadBytes = 512 << 10 // 512 KiB of comment input per claim
+
+// selectCommentDelivery applies a deterministic budget to comment input. The
+// primary trigger is mandatory when it still exists, even when that single
+// comment exceeds the budget; one comment must never become unclaimable. Extra
+// comments are admitted as an oldest-first prefix, so overflow remains a stable
+// suffix for completion reconciliation and cannot starve across retries.
+func selectCommentDelivery(comments []CoalescedCommentData, triggerID string, legacy bool, limit int) []CoalescedCommentData {
+ if len(comments) == 0 {
+ return nil
+ }
+ mandatoryID := triggerID
+ mandatoryFound := false
+ for _, comment := range comments {
+ if comment.ID == mandatoryID {
+ mandatoryFound = true
+ break
+ }
+ }
+ if !mandatoryFound {
+ // The planned trigger may have been deleted. Keep the newest available
+ // comment so the claim still makes progress and reconcile can pick up the
+ // remainder.
+ mandatoryID = comments[len(comments)-1].ID
+ }
+
+ selected := map[string]struct{}{mandatoryID: {}}
+ used := commentDeliveryBaseSize(legacy) + commentDeliveryEntrySize(commentByID(comments, mandatoryID), legacy)
+ for _, comment := range comments {
+ if comment.ID == mandatoryID {
+ continue
+ }
+ cost := commentDeliveryEntrySize(comment, legacy)
+ if limit > 0 && used+cost > limit {
+ break
+ }
+ selected[comment.ID] = struct{}{}
+ used += cost
+ }
+
+ out := make([]CoalescedCommentData, 0, len(selected))
+ for _, comment := range comments {
+ if _, ok := selected[comment.ID]; ok {
+ out = append(out, comment)
+ }
+ }
+ return out
+}
+
+func commentByID(comments []CoalescedCommentData, id string) CoalescedCommentData {
+ for _, comment := range comments {
+ if comment.ID == id {
+ return comment
+ }
+ }
+ return CoalescedCommentData{}
+}
+
+func commentDeliveryBaseSize(legacy bool) int {
+ if legacy {
+ return escapedJSONStringContentSize(legacyCommentBundleHeader)
+ }
+ return 2 // JSON array brackets
+}
+
+func commentDeliveryEntrySize(comment CoalescedCommentData, legacy bool) int {
+ if legacy {
+ return escapedJSONStringContentSize(formatLegacyCommentEntry(comment))
+ }
+ encoded, err := json.Marshal(comment)
+ if err != nil {
+ return maxClaimCommentPayloadBytes + 1
+ }
+ return len(encoded) + 1 // comma between JSON array entries
+}
+
+func escapedJSONStringContentSize(value string) int {
+ encoded, err := json.Marshal(value)
+ if err != nil || len(encoded) < 2 {
+ return maxClaimCommentPayloadBytes + 1
+ }
+ // json.Marshal adds the surrounding string quotes. The remaining bytes
+ // match the escaping cost paid when the legacy bundle is nested in the
+ // claim response.
+ return len(encoded) - 2
+}
+
+const legacyCommentBundleHeader = "This run covers multiple distinct issue comments. Address every comment below in chronological order; do not treat this bundle as one rewritten comment.\n"
+
+// formatLegacyCommentBundle carries every planned comment through the one
+// field understood by daemons that predate coalesced-comments-v1. Delimiters,
+// ids and thread ids keep distinct instructions attributable and fetchable.
+func formatLegacyCommentBundle(comments []CoalescedCommentData) string {
+ if len(comments) == 0 {
+ return ""
+ }
+ var b strings.Builder
+ b.WriteString(legacyCommentBundleHeader)
+ for _, comment := range comments {
+ b.WriteString(formatLegacyCommentEntry(comment))
+ }
+ return strings.TrimSpace(b.String())
+}
+
+func formatLegacyCommentEntry(comment CoalescedCommentData) string {
+ var b strings.Builder
+ fmt.Fprintf(&b, "\n--- comment %s", comment.ID)
+ if comment.ThreadID != "" {
+ fmt.Fprintf(&b, " [thread %s]", comment.ThreadID)
+ }
+ if comment.AuthorType != "" || comment.AuthorName != "" {
+ fmt.Fprintf(&b, " [author %s", comment.AuthorType)
+ if comment.AuthorName != "" {
+ fmt.Fprintf(&b, ": %s", comment.AuthorName)
+ }
+ b.WriteString("]")
+ }
+ if comment.CreatedAt != "" {
+ fmt.Fprintf(&b, " [created %s]", comment.CreatedAt)
+ }
+ b.WriteString(" ---\n")
+ b.WriteString(comment.Content)
+ fmt.Fprintf(&b, "\n--- end comment %s ---\n", comment.ID)
+ return b.String()
+}
+
// 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/daemon_comment_delivery_test.go b/server/internal/handler/daemon_comment_delivery_test.go
new file mode 100644
index 0000000000..ebd8b339c8
--- /dev/null
+++ b/server/internal/handler/daemon_comment_delivery_test.go
@@ -0,0 +1,973 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func TestRequestHasDaemonCapability(t *testing.T) {
+ tests := []struct {
+ name string
+ header string
+ want bool
+ }{
+ {name: "absent"},
+ {name: "exact", header: protocol.DaemonCapabilityCoalescedCommentsV1, want: true},
+ {name: "comma separated and trimmed", header: "skill-bundles-v1, coalesced-comments-v1 ", want: true},
+ {name: "substring", header: "xcoalesced-comments-v1", want: false},
+ {name: "case sensitive", header: "Coalesced-Comments-V1", want: false},
+ {name: "unknown", header: "future-comments-v2", want: false},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPost, "/claim", nil)
+ if tc.header != "" {
+ req.Header.Set("X-Client-Capabilities", tc.header)
+ }
+ if got := requestHasDaemonCapability(req, protocol.DaemonCapabilityCoalescedCommentsV1); got != tc.want {
+ t.Fatalf("requestHasDaemonCapability(%q) = %v, want %v", tc.header, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestSelectCommentDelivery_BudgetKeepsTriggerAndStablePrefix(t *testing.T) {
+ comments := []CoalescedCommentData{
+ {ID: "00000000-0000-0000-0000-000000000001", Content: "oldest"},
+ {ID: "00000000-0000-0000-0000-000000000002", Content: "overflow"},
+ {ID: "00000000-0000-0000-0000-000000000003", Content: "trigger"},
+ }
+ triggerID := comments[2].ID
+ limit := commentDeliveryBaseSize(false) +
+ commentDeliveryEntrySize(comments[2], false) +
+ commentDeliveryEntrySize(comments[0], false)
+
+ selected := selectCommentDelivery(comments, triggerID, false, limit)
+ got := make([]string, 0, len(selected))
+ for _, comment := range selected {
+ got = append(got, comment.ID)
+ }
+ want := []string{comments[0].ID, comments[2].ID}
+ if !slices.Equal(got, want) {
+ t.Fatalf("selected ids = %v, want stable prefix + trigger %v", got, want)
+ }
+}
+
+func TestFormatLegacyCommentBundle_PreservesBodiesAndOrder(t *testing.T) {
+ comments := []CoalescedCommentData{
+ {ID: "00000000-0000-0000-0000-000000000001", ThreadID: "thread-a", AuthorType: "member", AuthorName: "A", Content: " first body\n", CreatedAt: "2026-07-10T01:00:00Z"},
+ {ID: "00000000-0000-0000-0000-000000000002", ThreadID: "thread-b", AuthorType: "agent", AuthorName: "B", Content: "second body", CreatedAt: "2026-07-10T02:00:00Z"},
+ }
+ bundle := formatLegacyCommentBundle(comments)
+ for _, want := range []string{comments[0].ID, comments[1].ID, "thread-a", "thread-b", "member: A", "agent: B", comments[0].Content, comments[1].Content} {
+ if !strings.Contains(bundle, want) {
+ t.Fatalf("legacy bundle missing %q:\n%s", want, bundle)
+ }
+ }
+ if strings.Index(bundle, comments[0].ID) > strings.Index(bundle, comments[1].ID) {
+ t.Fatalf("legacy bundle is not chronological:\n%s", bundle)
+ }
+}
+
+func TestCommentDeliveryEntrySize_AccountsForLegacyJSONEscaping(t *testing.T) {
+ comment := CoalescedCommentData{
+ ID: "00000000-0000-0000-0000-000000000001",
+ Content: `quotes " backslashes \\ and html <>&`,
+ }
+ raw := len(formatLegacyCommentEntry(comment))
+ if got := commentDeliveryEntrySize(comment, true); got <= raw {
+ t.Fatalf("legacy escaped size = %d, want greater than raw size %d", got, raw)
+ }
+}
+
+type commentDeliveryFixture struct {
+ runtimeID string
+ agentID string
+ issueID string
+ taskID string
+ commentID []string
+ threadID []string
+ content []string
+}
+
+type failNthBegin struct {
+ delegate *pgxpool.Pool
+ failAt int
+ calls int
+}
+
+type failDeleteCommentDB struct {
+ delegate db.DBTX
+}
+
+func (f *failDeleteCommentDB) Exec(ctx context.Context, query string, args ...interface{}) (pgconn.CommandTag, error) {
+ if strings.Contains(query, "-- name: DeleteComment") {
+ return pgconn.CommandTag{}, errors.New("injected comment deletion failure")
+ }
+ return f.delegate.Exec(ctx, query, args...)
+}
+
+func (f *failDeleteCommentDB) Query(ctx context.Context, query string, args ...interface{}) (pgx.Rows, error) {
+ return f.delegate.Query(ctx, query, args...)
+}
+
+func (f *failDeleteCommentDB) QueryRow(ctx context.Context, query string, args ...interface{}) pgx.Row {
+ return f.delegate.QueryRow(ctx, query, args...)
+}
+
+func (f *failNthBegin) Begin(ctx context.Context) (pgx.Tx, error) {
+ f.calls++
+ if f.calls == f.failAt {
+ return nil, errors.New("injected claim finalization transaction failure")
+ }
+ return f.delegate.Begin(ctx)
+}
+
+func createCommentDeliveryFixture(t *testing.T, label string) commentDeliveryFixture {
+ t.Helper()
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, label+" runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, label+" agent")
+
+ contents := []string{"first cross-thread instruction", "second instruction", "latest instruction"}
+ ids := make([]string, 3)
+ 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() - interval '3 minutes')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID, contents[0]).Scan(&ids[0]); err != nil {
+ t.Fatalf("insert first comment: %v", err)
+ }
+ 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() - interval '2 minutes')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID, contents[1]).Scan(&ids[1]); err != nil {
+ t.Fatalf("insert second comment: %v", err)
+ }
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, created_at)
+ VALUES ($1, $2, 'member', $3, $4, 'comment', $5, now() - interval '1 minute')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID, contents[2], ids[1]).Scan(&ids[2]); err != nil {
+ t.Fatalf("insert trigger comment: %v", err)
+ }
+
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority,
+ trigger_comment_id, coalesced_comment_ids
+ )
+ VALUES ($1, $2, $3, 'queued', 0, $4, ARRAY[$5::uuid, $6::uuid])
+ RETURNING id
+ `, agentID, runtimeID, issueID, ids[2], ids[1], ids[0]).Scan(&taskID); err != nil {
+ t.Fatalf("insert comment delivery task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ return commentDeliveryFixture{
+ runtimeID: runtimeID,
+ agentID: agentID,
+ issueID: issueID,
+ taskID: taskID,
+ commentID: ids,
+ threadID: []string{ids[0], ids[1], ids[1]},
+ content: contents,
+ }
+}
+
+func claimCommentDeliveryFixture(t *testing.T, fixture commentDeliveryFixture, capabilities string) AgentTaskResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+fixture.runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "comment-delivery-matrix")
+ if capabilities != "" {
+ req.Header.Set("X-Client-Capabilities", capabilities)
+ }
+ req = withURLParam(req, "runtimeId", fixture.runtimeID)
+ testHandler.ClaimTaskByRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var response struct {
+ Task *AgentTaskResponse `json:"task"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode claim response: %v", err)
+ }
+ if response.Task == nil {
+ t.Fatalf("claim returned no task: %s", w.Body.String())
+ }
+ return *response.Task
+}
+
+func deliveredCommentIDsForTask(t *testing.T, taskID string) []string {
+ t.Helper()
+ var ids []string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT delivered_comment_ids::text[]
+ FROM agent_task_queue
+ WHERE id = $1
+ `, taskID).Scan(&ids); err != nil {
+ t.Fatalf("load delivered comment ids: %v", err)
+ }
+ return ids
+}
+
+func TestClaimTaskByRuntime_CoalescedDeliveryMatrix(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ t.Run("legacy daemon receives one compatible bundle", func(t *testing.T) {
+ fixture := createCommentDeliveryFixture(t, "Legacy comment delivery")
+ task := claimCommentDeliveryFixture(t, fixture, protocol.DaemonCapabilitySkillBundlesV1)
+
+ // A v0.3.41-shaped decoder knows only this old comment field. All input
+ // must still be available through it; structured fields are deliberately
+ // absent to avoid duplicate rendering in intermediate clients.
+ wire, err := json.Marshal(map[string]any{"task": task})
+ if err != nil {
+ t.Fatalf("marshal legacy-shaped response: %v", err)
+ }
+ var legacy struct {
+ Task struct {
+ TriggerCommentContent string `json:"trigger_comment_content"`
+ } `json:"task"`
+ }
+ if err := json.Unmarshal(wire, &legacy); err != nil {
+ t.Fatalf("legacy decode: %v", err)
+ }
+ for i := range fixture.commentID {
+ for _, want := range []string{fixture.commentID[i], fixture.threadID[i], fixture.content[i]} {
+ if !strings.Contains(legacy.Task.TriggerCommentContent, want) {
+ t.Fatalf("legacy trigger bundle missing %q:\n%s", want, legacy.Task.TriggerCommentContent)
+ }
+ }
+ }
+ if len(task.CoalescedComments) != 0 || len(task.CoalescedCommentIDs) != 0 {
+ t.Fatalf("legacy claim leaked structured coalesced fields: ids=%v comments=%v", task.CoalescedCommentIDs, task.CoalescedComments)
+ }
+ if !slices.Equal(deliveredCommentIDsForTask(t, fixture.taskID), fixture.commentID) {
+ t.Fatalf("legacy receipt does not match embedded comments")
+ }
+ })
+
+ t.Run("capable daemon receives ordered structured comments", func(t *testing.T) {
+ fixture := createCommentDeliveryFixture(t, "Structured comment delivery")
+ capabilities := protocol.DaemonCapabilitySkillBundlesV1 + "," + protocol.DaemonCapabilityCoalescedCommentsV1
+ task := claimCommentDeliveryFixture(t, fixture, capabilities)
+
+ if task.TriggerCommentContent != fixture.content[2] {
+ t.Fatalf("trigger content = %q, want %q", task.TriggerCommentContent, fixture.content[2])
+ }
+ if !slices.Equal(task.CoalescedCommentIDs, fixture.commentID[:2]) {
+ t.Fatalf("structured ids = %v, want %v", task.CoalescedCommentIDs, fixture.commentID[:2])
+ }
+ if len(task.CoalescedComments) != 2 {
+ t.Fatalf("structured comments = %d, want 2", len(task.CoalescedComments))
+ }
+ for i, comment := range task.CoalescedComments {
+ if comment.ID != fixture.commentID[i] || comment.ThreadID != fixture.threadID[i] || comment.Content != fixture.content[i] {
+ t.Fatalf("structured comment[%d] = %+v", i, comment)
+ }
+ }
+ if !slices.Equal(task.DeliveredCommentIDs, fixture.commentID) {
+ t.Fatalf("response receipt = %v, want %v", task.DeliveredCommentIDs, fixture.commentID)
+ }
+ if !slices.Equal(deliveredCommentIDsForTask(t, fixture.taskID), fixture.commentID) {
+ t.Fatalf("database receipt does not match embedded comments")
+ }
+
+ if _, err := testHandler.TaskService.StartTask(context.Background(), parseUUID(fixture.taskID)); err != nil {
+ t.Fatalf("start claimed task: %v", err)
+ }
+ if w := completeTaskViaHandler(t, fixture.taskID, "done"); w.Code != http.StatusOK {
+ t.Fatalf("complete claimed task: %d %s", w.Code, w.Body.String())
+ }
+ if n := pendingTaskCountForAgentIssue(t, fixture.issueID, fixture.agentID); n != 0 {
+ t.Fatalf("full receipt produced %d follow-up tasks, want 0", n)
+ }
+ })
+}
+
+func TestClaimTaskByRuntime_CoalescedOnlyStaleTaskDoesNotReuseDeletedTriggerCapabilities(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Deleted trigger stale claim")
+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
+ t.Fatalf("assign stale-claim issue: %v", err)
+ }
+ if _, err := testPool.Exec(context.Background(), `DELETE FROM comment WHERE id = $1`, fixture.commentID[2]); err != nil {
+ t.Fatalf("delete trigger directly: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+fixture.runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "stale-comment-plan-repair")
+ req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityCoalescedCommentsV1)
+ req = withURLParam(req, "runtimeId", fixture.runtimeID)
+ testHandler.ClaimTaskByRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("repair stale claim: got %d: %s", w.Code, w.Body.String())
+ }
+ var response struct {
+ Task *AgentTaskResponse `json:"task"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode stale-plan repair response: %v", err)
+ }
+ if response.Task != nil {
+ t.Fatalf("stale plan was dispatched instead of repaired: %+v", response.Task)
+ }
+ assertRepairedCommentBatch(t, fixture, fixture.commentID[1], fixture.commentID[:1])
+}
+
+func TestUpdateComment_RequeuesSurvivingCoalescedBatch(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Edited trigger batch repair")
+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
+ t.Fatalf("assign edited-trigger issue: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest(http.MethodPut, "/api/comments/"+fixture.commentID[2], map[string]any{
+ "content": "edited latest instruction",
+ })
+ req = withURLParam(req, "commentId", fixture.commentID[2])
+ testHandler.UpdateComment(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateComment: got %d: %s", w.Code, w.Body.String())
+ }
+
+ assertRepairedCommentBatch(t, fixture, fixture.commentID[2], fixture.commentID[:2])
+}
+
+func TestDeleteComment_RequeuesSurvivingCoalescedBatch(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Deleted trigger batch repair")
+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
+ t.Fatalf("assign deleted-trigger issue: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest(http.MethodDelete, "/api/comments/"+fixture.commentID[2], nil)
+ req = withURLParam(req, "commentId", fixture.commentID[2])
+ testHandler.DeleteComment(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteComment: got %d: %s", w.Code, w.Body.String())
+ }
+
+ assertRepairedCommentBatch(t, fixture, fixture.commentID[1], fixture.commentID[:1])
+ var deletedCount int
+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM comment WHERE id = $1`, fixture.commentID[2]).Scan(&deletedCount); err != nil {
+ t.Fatalf("check deleted trigger: %v", err)
+ }
+ if deletedCount != 0 {
+ t.Fatalf("deleted trigger still exists")
+ }
+}
+
+func TestUpdateComment_CancelsAndRequeuesWhenEditedInputIsCoalesced(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Edited coalesced input repair")
+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
+ t.Fatalf("assign edited-coalesced issue: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest(http.MethodPut, "/api/comments/"+fixture.commentID[0], map[string]any{
+ "content": "edited earlier instruction",
+ })
+ req = withURLParam(req, "commentId", fixture.commentID[0])
+ testHandler.UpdateComment(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateComment: got %d: %s", w.Code, w.Body.String())
+ }
+
+ assertRepairedCommentBatch(t, fixture, fixture.commentID[0], fixture.commentID[1:])
+}
+
+func TestDeleteComment_CancelsAndRequeuesWhenDeletedInputIsCoalesced(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Deleted coalesced input repair")
+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
+ t.Fatalf("assign deleted-coalesced issue: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest(http.MethodDelete, "/api/comments/"+fixture.commentID[0], nil)
+ req = withURLParam(req, "commentId", fixture.commentID[0])
+ testHandler.DeleteComment(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteComment: got %d: %s", w.Code, w.Body.String())
+ }
+
+ assertRepairedCommentBatch(t, fixture, fixture.commentID[2], fixture.commentID[1:2])
+}
+
+func TestDeleteComment_FailureRestoresCancelledCompleteBatch(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Failed deletion batch repair")
+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
+ t.Fatalf("assign failed-delete issue: %v", err)
+ }
+
+ failingHandler := *testHandler
+ failingHandler.Queries = db.New(&failDeleteCommentDB{delegate: testPool})
+ w := httptest.NewRecorder()
+ req := newRequest(http.MethodDelete, "/api/comments/"+fixture.commentID[2], nil)
+ req = withURLParam(req, "commentId", fixture.commentID[2])
+ failingHandler.DeleteComment(w, req)
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("DeleteComment failure: got %d: %s", w.Code, w.Body.String())
+ }
+
+ var existing int
+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM comment WHERE id = $1`, fixture.commentID[2]).Scan(&existing); err != nil {
+ t.Fatalf("check trigger after failed delete: %v", err)
+ }
+ if existing != 1 {
+ t.Fatalf("failed delete unexpectedly removed trigger")
+ }
+ assertRepairedCommentBatch(t, fixture, fixture.commentID[2], fixture.commentID[:2])
+}
+
+func assertRepairedCommentBatch(t *testing.T, fixture commentDeliveryFixture, wantTrigger string, wantCoalesced []string) {
+ t.Helper()
+ var originalStatus string
+ if err := testPool.QueryRow(context.Background(), `SELECT status FROM agent_task_queue WHERE id = $1`, fixture.taskID).Scan(&originalStatus); err != nil {
+ t.Fatalf("load original task: %v", err)
+ }
+ if originalStatus != "cancelled" {
+ t.Fatalf("original task status = %s, want cancelled", originalStatus)
+ }
+
+ var trigger string
+ var coalesced, delivered []string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT trigger_comment_id::text, coalesced_comment_ids::text[], delivered_comment_ids::text[]
+ FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, fixture.issueID, fixture.agentID).Scan(&trigger, &coalesced, &delivered); err != nil {
+ t.Fatalf("load repaired task: %v", err)
+ }
+ if trigger != wantTrigger {
+ t.Fatalf("repaired trigger = %s, want %s", trigger, wantTrigger)
+ }
+ gotCoalesced := append([]string{}, coalesced...)
+ want := append([]string{}, wantCoalesced...)
+ slices.Sort(gotCoalesced)
+ slices.Sort(want)
+ if !slices.Equal(gotCoalesced, want) {
+ t.Fatalf("repaired coalesced ids = %v, want %v", gotCoalesced, want)
+ }
+ if len(delivered) != 0 {
+ t.Fatalf("repaired batch inherited receipt: %v", delivered)
+ }
+}
+
+func TestBuildCoalescedCommentData_SortsEqualTimestampsByID(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Comment delivery tie order")
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE comment
+ SET created_at = TIMESTAMPTZ '2026-07-10 01:00:00+00'
+ WHERE id = ANY($1::uuid[])
+ `, fixture.commentID[:2]); err != nil {
+ t.Fatalf("set equal comment timestamps: %v", err)
+ }
+ ids := []pgtype.UUID{
+ util.MustParseUUID(fixture.commentID[1]),
+ util.MustParseUUID(fixture.commentID[0]),
+ }
+ comments := testHandler.buildCoalescedCommentData(context.Background(), util.MustParseUUID(testWorkspaceID), ids)
+ want := append([]string{}, fixture.commentID[:2]...)
+ slices.Sort(want)
+ got := []string{comments[0].ID, comments[1].ID}
+ if !slices.Equal(got, want) {
+ t.Fatalf("equal-timestamp order = %v, want id order %v", got, want)
+ }
+}
+
+func TestClaimTaskByRuntime_PayloadOverflowReceiptsOnlyEmbeddedPrefix(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Comment payload overflow")
+ oversized := strings.Repeat("x", maxClaimCommentPayloadBytes+1024)
+ if _, err := testPool.Exec(context.Background(), `UPDATE comment SET content = $2 WHERE id = $1`, fixture.commentID[0], oversized); err != nil {
+ t.Fatalf("make first coalesced comment oversized: %v", err)
+ }
+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
+ t.Fatalf("assign overflow issue: %v", err)
+ }
+
+ task := claimCommentDeliveryFixture(t, fixture, protocol.DaemonCapabilityCoalescedCommentsV1)
+ if !slices.Equal(task.DeliveredCommentIDs, []string{fixture.commentID[2]}) {
+ t.Fatalf("overflow receipt = %v, want primary trigger only", task.DeliveredCommentIDs)
+ }
+ if len(task.CoalescedComments) != 0 || len(task.CoalescedCommentIDs) != 0 {
+ t.Fatalf("overflow claim embedded comments beyond stable boundary: ids=%v comments=%d", task.CoalescedCommentIDs, len(task.CoalescedComments))
+ }
+
+ if _, err := testHandler.TaskService.StartTask(context.Background(), parseUUID(fixture.taskID)); err != nil {
+ t.Fatalf("start overflow task: %v", err)
+ }
+ if w := completeTaskViaHandler(t, fixture.taskID, "done"); w.Code != http.StatusOK {
+ t.Fatalf("complete overflow task: %d %s", w.Code, w.Body.String())
+ }
+ if n := pendingTaskCountForAgentIssue(t, fixture.issueID, fixture.agentID); n != 1 {
+ t.Fatalf("overflow should create one bounded follow-up, got %d", n)
+ }
+ followupTrigger, _, followupCoalesced := taskTriggerOriginatorCoalesced(t, fixture.issueID, fixture.agentID)
+ covered := append([]string{}, followupCoalesced...)
+ covered = append(covered, followupTrigger)
+ slices.Sort(covered)
+ want := append([]string{}, fixture.commentID[:2]...)
+ slices.Sort(want)
+ if !slices.Equal(covered, want) {
+ t.Fatalf("overflow follow-up coverage = %v, want omitted suffix %v", covered, want)
+ }
+}
+
+func TestClaimTaskByRuntime_StaleReclaimReplacesDeliveryReceipt(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Stale comment receipt reclaim")
+ first := claimCommentDeliveryFixture(t, fixture, protocol.DaemonCapabilityCoalescedCommentsV1)
+ if !slices.Equal(first.DeliveredCommentIDs, fixture.commentID) {
+ t.Fatalf("first receipt = %v, want all comments", first.DeliveredCommentIDs)
+ }
+
+ oversized := strings.Repeat("x", maxClaimCommentPayloadBytes+1024)
+ if _, err := testPool.Exec(context.Background(), `UPDATE comment SET content = $2 WHERE id = $1`, fixture.commentID[0], oversized); err != nil {
+ t.Fatalf("make reclaimed comment oversized: %v", err)
+ }
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE agent_task_queue
+ SET dispatched_at = now() - interval '2 minutes', prepare_lease_expires_at = NULL
+ WHERE id = $1
+ `, fixture.taskID); err != nil {
+ t.Fatalf("prepare stale receipt reclaim: %v", err)
+ }
+
+ reclaimed := claimCommentDeliveryFixture(t, fixture, protocol.DaemonCapabilityCoalescedCommentsV1)
+ want := []string{fixture.commentID[2]}
+ if !slices.Equal(reclaimed.DeliveredCommentIDs, want) {
+ t.Fatalf("reclaimed response receipt = %v, want replacement %v", reclaimed.DeliveredCommentIDs, want)
+ }
+ if got := deliveredCommentIDsForTask(t, fixture.taskID); !slices.Equal(got, want) {
+ t.Fatalf("reclaimed database receipt = %v, want replacement %v", got, want)
+ }
+}
+
+func TestCreateRetryTask_PreservesCommentPlanAndResetsReceipt(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Comment retry runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Comment retry agent")
+
+ commentIDs := make([]string, 3)
+ for i := range commentIDs {
+ 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, testUserID, "retry comment").Scan(&commentIDs[i]); err != nil {
+ t.Fatalf("insert retry comment: %v", err)
+ }
+ }
+
+ var parentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority,
+ trigger_comment_id, coalesced_comment_ids, delivered_comment_ids,
+ attempt, max_attempts, failure_reason
+ )
+ VALUES (
+ $1, $2, $3, 'failed', 0,
+ $4, ARRAY[$5::uuid, $6::uuid], ARRAY[$4::uuid, $5::uuid, $6::uuid],
+ 1, 3, 'timeout'
+ )
+ RETURNING id
+ `, agentID, runtimeID, issueID, commentIDs[2], commentIDs[0], commentIDs[1]).Scan(&parentID); err != nil {
+ t.Fatalf("insert retry parent: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ child, err := testHandler.Queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{ID: util.MustParseUUID(parentID)})
+ if err != nil {
+ t.Fatalf("CreateRetryTask: %v", err)
+ }
+ if got := uuidToString(child.TriggerCommentID); got != commentIDs[2] {
+ t.Fatalf("child trigger = %s, want %s", got, commentIDs[2])
+ }
+ gotCoalesced := uuidsToStrings(child.CoalescedCommentIds)
+ wantCoalesced := commentIDs[:2]
+ slices.Sort(gotCoalesced)
+ slices.Sort(wantCoalesced)
+ if !slices.Equal(gotCoalesced, wantCoalesced) {
+ t.Fatalf("child coalesced ids = %v, want %v", gotCoalesced, wantCoalesced)
+ }
+ if len(child.DeliveredCommentIds) != 0 {
+ t.Fatalf("retry child inherited delivery receipt: %v", uuidsToStrings(child.DeliveredCommentIds))
+ }
+}
+
+func TestRerunIssue_PreservesSourceCommentPlanAndResetsReceipt(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Comment manual rerun runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Comment manual rerun agent")
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, issueID, agentID); err != nil {
+ t.Fatalf("assign rerun issue: %v", err)
+ }
+
+ commentIDs := make([]string, 3)
+ for i := range commentIDs {
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)
+ VALUES ($1, $2, 'member', $3, 'manual rerun comment', 'comment')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID).Scan(&commentIDs[i]); err != nil {
+ t.Fatalf("insert manual rerun comment: %v", err)
+ }
+ }
+
+ var sourceID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority,
+ trigger_comment_id, coalesced_comment_ids, delivered_comment_ids,
+ started_at, completed_at
+ )
+ VALUES (
+ $1, $2, $3, 'completed', 0,
+ $4, ARRAY[$5::uuid, $6::uuid], ARRAY[$4::uuid, $5::uuid, $6::uuid],
+ now() - interval '2 minutes', now() - interval '1 minute'
+ )
+ RETURNING id
+ `, agentID, runtimeID, issueID, commentIDs[2], commentIDs[0], commentIDs[1]).Scan(&sourceID); err != nil {
+ t.Fatalf("insert manual rerun source: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+
+ rerun, err := testHandler.TaskService.RerunIssue(ctx, util.MustParseUUID(issueID), util.MustParseUUID(sourceID), pgtype.UUID{})
+ if err != nil {
+ t.Fatalf("RerunIssue: %v", err)
+ }
+ if got := uuidToString(rerun.TriggerCommentID); got != commentIDs[2] {
+ t.Fatalf("rerun trigger = %s, want %s", got, commentIDs[2])
+ }
+ gotCoalesced := uuidsToStrings(rerun.CoalescedCommentIds)
+ wantCoalesced := append([]string{}, commentIDs[:2]...)
+ slices.Sort(gotCoalesced)
+ slices.Sort(wantCoalesced)
+ if !slices.Equal(gotCoalesced, wantCoalesced) {
+ t.Fatalf("rerun coalesced ids = %v, want %v", gotCoalesced, wantCoalesced)
+ }
+ if len(rerun.DeliveredCommentIds) != 0 {
+ t.Fatalf("manual rerun inherited receipt: %v", uuidsToStrings(rerun.DeliveredCommentIds))
+ }
+}
+
+func TestRerunIssue_PromotesNewestSurvivorAfterSourceTriggerDeleted(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fixture := createCommentDeliveryFixture(t, "Deleted trigger manual rerun")
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID); err != nil {
+ t.Fatalf("assign deleted-trigger rerun issue: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue
+ SET status = 'completed', started_at = now() - interval '2 minutes', completed_at = now() - interval '1 minute'
+ WHERE id = $1
+ `, fixture.taskID); err != nil {
+ t.Fatalf("complete deleted-trigger rerun source: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, fixture.commentID[2]); err != nil {
+ t.Fatalf("delete rerun source trigger: %v", err)
+ }
+
+ rerun, err := testHandler.TaskService.RerunIssue(ctx, parseUUID(fixture.issueID), parseUUID(fixture.taskID), pgtype.UUID{})
+ if err != nil {
+ t.Fatalf("RerunIssue: %v", err)
+ }
+ if got := uuidToString(rerun.TriggerCommentID); got != fixture.commentID[1] {
+ t.Fatalf("rerun promoted trigger = %s, want newest survivor %s", got, fixture.commentID[1])
+ }
+ if got := uuidsToStrings(rerun.CoalescedCommentIds); !slices.Equal(got, []string{fixture.commentID[0]}) {
+ t.Fatalf("rerun survivor plan = %v, want [%s]", got, fixture.commentID[0])
+ }
+ if len(rerun.DeliveredCommentIds) != 0 {
+ t.Fatalf("rerun inherited delivery receipt: %v", uuidsToStrings(rerun.DeliveredCommentIds))
+ }
+ if got := uuidToString(rerun.OriginatorUserID); got != testUserID {
+ t.Fatalf("rerun originator = %s, want promoted comment author %s", got, testUserID)
+ }
+}
+
+func TestSetTaskDeliveredCommentIDs_CASAndSubset(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Delivery receipt CAS runtime")
+ otherRuntimeID := createClaimReclaimRuntime(t, ctx, "Delivery receipt CAS other runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Delivery receipt CAS agent")
+
+ commentIDs := make([]string, 2)
+ for i := range commentIDs {
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)
+ VALUES ($1, $2, 'member', $3, 'receipt CAS comment', 'comment')
+ RETURNING id
+ `, issueID, testWorkspaceID, testUserID).Scan(&commentIDs[i]); err != nil {
+ t.Fatalf("insert receipt CAS comment: %v", err)
+ }
+ }
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority, dispatched_at,
+ trigger_comment_id, coalesced_comment_ids
+ )
+ VALUES ($1, $2, $3, 'dispatched', 0, now(), $4, ARRAY[$5::uuid])
+ RETURNING id
+ `, agentID, runtimeID, issueID, commentIDs[1], commentIDs[0]).Scan(&taskID); err != nil {
+ t.Fatalf("insert receipt CAS task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ })
+ task, err := testHandler.Queries.GetAgentTask(ctx, util.MustParseUUID(taskID))
+ if err != nil {
+ t.Fatalf("GetAgentTask: %v", err)
+ }
+
+ params := db.SetTaskDeliveredCommentIDsParams{
+ DeliveredCommentIds: []pgtype.UUID{util.MustParseUUID(commentIDs[1])},
+ TaskID: task.ID,
+ RuntimeID: task.RuntimeID,
+ DispatchedAt: task.DispatchedAt,
+ ExpectedTriggerCommentID: task.TriggerCommentID,
+ }
+ if got, err := testHandler.Queries.SetTaskDeliveredCommentIDs(ctx, params); err != nil || len(got) != 1 {
+ t.Fatalf("valid receipt = %v, %v; want one id", got, err)
+ }
+ params.DeliveredCommentIds = []pgtype.UUID{}
+ if got, err := testHandler.Queries.SetTaskDeliveredCommentIDs(ctx, params); err != nil || len(got) != 0 {
+ t.Fatalf("empty receipt = %v, %v; want authoritative empty array", got, err)
+ }
+
+ params.DeliveredCommentIds = []pgtype.UUID{util.MustParseUUID("00000000-0000-0000-0000-000000000099")}
+ if _, err := testHandler.Queries.SetTaskDeliveredCommentIDs(ctx, params); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("foreign receipt id error = %v, want pgx.ErrNoRows", err)
+ }
+ params.DeliveredCommentIds = []pgtype.UUID{util.MustParseUUID(commentIDs[1])}
+ params.RuntimeID = util.MustParseUUID(otherRuntimeID)
+ if _, err := testHandler.Queries.SetTaskDeliveredCommentIDs(ctx, params); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("wrong runtime error = %v, want pgx.ErrNoRows", err)
+ }
+ params.RuntimeID = task.RuntimeID
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running', started_at = now() WHERE id = $1`, taskID); err != nil {
+ t.Fatalf("mark task running: %v", err)
+ }
+ if _, err := testHandler.Queries.SetTaskDeliveredCommentIDs(ctx, params); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("running task receipt error = %v, want pgx.ErrNoRows", err)
+ }
+}
+
+func TestClaimTaskByRuntime_FinalizationFailureRequeuesImmediately(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Claim finalization failure")
+ priorTokenHash := "prior-valid-token-" + fixture.taskID
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at)
+ VALUES ($1, $2, $3, $4, $5, now() + interval '1 hour')
+ `, priorTokenHash, fixture.taskID, fixture.agentID, testWorkspaceID, testUserID); err != nil {
+ t.Fatalf("insert prior task token: %v", err)
+ }
+
+ failingHandler := *testHandler
+ // Inject a failing transaction starter without copying TaskService by value:
+ // it embeds a sync.Mutex (go vet rejects the copy) and a value copy would also
+ // split the analytics-cache lock from the map it guards. Swap the field on the
+ // shared service and restore it when the test ends. failingHandler shares the
+ // same *TaskService pointer, so it observes the failing starter.
+ originalTxStarter := testHandler.TaskService.TxStarter
+ testHandler.TaskService.TxStarter = &failNthBegin{delegate: testPool, failAt: 2}
+ defer func() { testHandler.TaskService.TxStarter = originalTxStarter }()
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+fixture.runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "comment-delivery-finalize-failure")
+ req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityCoalescedCommentsV1)
+ req = withURLParam(req, "runtimeId", fixture.runtimeID)
+ failingHandler.ClaimTaskByRuntime(w, req)
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("failed finalization status = %d, want 500: %s", w.Code, w.Body.String())
+ }
+ if strings.Contains(w.Body.String(), "auth_token") || strings.Contains(w.Body.String(), `"task"`) {
+ t.Fatalf("failed claim leaked a task payload: %s", w.Body.String())
+ }
+
+ var status string
+ var dispatched bool
+ var delivered []string
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT status, dispatched_at IS NOT NULL, delivered_comment_ids::text[]
+ FROM agent_task_queue
+ WHERE id = $1
+ `, fixture.taskID).Scan(&status, &dispatched, &delivered); err != nil {
+ t.Fatalf("load requeued task: %v", err)
+ }
+ if status != "queued" || dispatched || len(delivered) != 0 {
+ t.Fatalf("failed claim state = status=%s dispatched=%v delivered=%v; want queued/false/[]", status, dispatched, delivered)
+ }
+ var tokens int
+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM task_token WHERE task_id = $1`, fixture.taskID).Scan(&tokens); err != nil {
+ t.Fatalf("count task tokens: %v", err)
+ }
+ if tokens != 1 {
+ t.Fatalf("failed claim left %d task token(s), want only the prior valid token", tokens)
+ }
+ var priorStillExists bool
+ if err := testPool.QueryRow(context.Background(), `SELECT EXISTS(SELECT 1 FROM task_token WHERE token_hash = $1)`, priorTokenHash).Scan(&priorStillExists); err != nil {
+ t.Fatalf("check prior task token: %v", err)
+ }
+ if !priorStillExists {
+ t.Fatalf("failed reclaim revoked an earlier execution's valid token")
+ }
+
+ // No 90-second stale-dispatch delay: the very next normal poll can claim
+ // the same complete batch and earn a receipt.
+ task := claimCommentDeliveryFixture(t, fixture, protocol.DaemonCapabilityCoalescedCommentsV1)
+ if task.ID != fixture.taskID {
+ t.Fatalf("immediate retry claimed task %s, want %s", task.ID, fixture.taskID)
+ }
+ if !slices.Equal(task.DeliveredCommentIDs, fixture.commentID) {
+ t.Fatalf("immediate retry receipt = %v, want %v", task.DeliveredCommentIDs, fixture.commentID)
+ }
+}
+
+func TestFinalizeTaskClaim_ReceiptCASFailureRollsBackInsertedToken(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fixture := createCommentDeliveryFixture(t, "Claim receipt rollback")
+ task, err := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(fixture.runtimeID))
+ if err != nil || task == nil {
+ t.Fatalf("claim fixture task: task=%v err=%v", task, err)
+ }
+ tokenHash := "rolled-back-token-" + fixture.taskID
+ _, err = testHandler.TaskService.FinalizeTaskClaim(ctx, *task, db.CreateTaskTokenParams{
+ TokenHash: tokenHash,
+ TaskID: task.ID,
+ AgentID: task.AgentID,
+ WorkspaceID: parseUUID(testWorkspaceID),
+ UserID: parseUUID(testUserID),
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
+ }, []pgtype.UUID{parseUUID("00000000-0000-0000-0000-000000000099")}, true)
+ if err == nil {
+ t.Fatalf("FinalizeTaskClaim accepted an out-of-plan receipt")
+ }
+ var tokenCount int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM task_token WHERE token_hash = $1`, tokenHash).Scan(&tokenCount); err != nil {
+ t.Fatalf("count rolled-back token: %v", err)
+ }
+ if tokenCount != 0 {
+ t.Fatalf("receipt CAS failure committed %d generated token(s)", tokenCount)
+ }
+ if got := deliveredCommentIDsForTask(t, fixture.taskID); len(got) != 0 {
+ t.Fatalf("receipt CAS failure advanced receipt: %v", got)
+ }
+}
+
+func TestFinalizeTaskClaim_TriggerDeletedAfterClaimRejectsStaleProvenance(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ fixture := createCommentDeliveryFixture(t, "Claim trigger deletion race")
+ task, err := testHandler.TaskService.ClaimTaskForRuntime(ctx, parseUUID(fixture.runtimeID))
+ if err != nil || task == nil {
+ t.Fatalf("claim fixture task: task=%v err=%v", task, err)
+ }
+ if !task.TriggerCommentID.Valid {
+ t.Fatalf("claim snapshot unexpectedly lacks trigger")
+ }
+ if _, err := testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, fixture.commentID[2]); err != nil {
+ t.Fatalf("delete trigger after claim snapshot: %v", err)
+ }
+
+ tokenHash := "deleted-trigger-race-token-" + fixture.taskID
+ _, err = testHandler.TaskService.FinalizeTaskClaim(ctx, *task, db.CreateTaskTokenParams{
+ TokenHash: tokenHash,
+ TaskID: task.ID,
+ AgentID: task.AgentID,
+ WorkspaceID: parseUUID(testWorkspaceID),
+ UserID: parseUUID(testUserID),
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
+ }, []pgtype.UUID{parseUUID(fixture.commentID[0]), parseUUID(fixture.commentID[1])}, true)
+ if err == nil {
+ t.Fatalf("FinalizeTaskClaim accepted a receipt after persisted trigger changed")
+ }
+ var tokenCount int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM task_token WHERE token_hash = $1`, tokenHash).Scan(&tokenCount); err != nil {
+ t.Fatalf("count stale-provenance token: %v", err)
+ }
+ if tokenCount != 0 {
+ t.Fatalf("stale trigger race committed %d generated token(s)", tokenCount)
+ }
+ if got := deliveredCommentIDsForTask(t, fixture.taskID); len(got) != 0 {
+ t.Fatalf("stale trigger race advanced receipt: %v", got)
+ }
+}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index a387df997c..fde3df44c2 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -369,6 +369,18 @@ func uuidsToStrings(us []pgtype.UUID) []string {
return out
}
+// uuidStringsOrEmpty preserves the distinction between a modern, authoritative
+// empty UUID-array value (`[]`) and a field omitted by a legacy server. Delivery
+// receipts use this so clients never mistake zero delivered comments for an
+// unknown receipt and fall back to the enqueue-time plan.
+func uuidStringsOrEmpty(us []pgtype.UUID) []string {
+ out := uuidsToStrings(us)
+ if out == nil {
+ return []string{}
+ }
+ 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) }
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index fa99b20dc0..dfcf99cb21 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -710,6 +710,10 @@ func (s *TaskService) ResolveIssueReviewSHAParam(ctx context.Context, issueID pg
}
func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
+ return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, nil, forceFreshSession, handoffNote)
+}
+
+func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
if !issue.AssigneeID.Valid {
slog.Error("task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "error", "issue has no assignee")
return db.AgentTaskQueue{}, fmt.Errorf("issue has no assignee")
@@ -737,6 +741,7 @@ func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, trig
IssueID: issue.ID,
Priority: priorityToInt(issue.Priority),
TriggerCommentID: triggerCommentID,
+ CoalescedCommentIds: coalescedCommentIDs,
TriggerSummary: s.buildCommentTriggerSummary(ctx, issue.WorkspaceID, triggerCommentID),
ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},
HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},
@@ -805,6 +810,10 @@ func (s *TaskService) EnqueueTaskForSquadLeaderWithHandoff(ctx context.Context,
}
func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, nil, isLeader, squadID, forceFreshSession, handoffNote)
+}
+
+func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
agent, err := s.Queries.GetAgent(ctx, agentID)
if err != nil {
slog.Error("mention task enqueue failed: agent not found", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)
@@ -827,6 +836,7 @@ func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, ag
IssueID: issue.ID,
Priority: priorityToInt(issue.Priority),
TriggerCommentID: triggerCommentID,
+ CoalescedCommentIds: coalescedCommentIDs,
TriggerSummary: s.buildCommentTriggerSummary(ctx, issue.WorkspaceID, triggerCommentID),
IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},
ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},
@@ -1147,23 +1157,21 @@ func (s *TaskService) CancelTasksForAgent(ctx context.Context, agentID pgtype.UU
return cancelled, nil
}
-// CancelTasksByTriggerComment cancels active tasks whose trigger is the given
-// comment. Called from DeleteComment so an agent does not run with the
-// now-deleted content already embedded in its prompt. Must be invoked BEFORE
-// the comment row is deleted because the FK ON DELETE SET NULL would
-// otherwise nullify trigger_comment_id and we'd lose the ability to find
-// the affected tasks.
-func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentID pgtype.UUID) error {
+// CancelTasksByTriggerComment cancels active tasks whose planned comment batch
+// contains the given edited/deleted comment. The historical method name is
+// retained for call-site stability. It must run before deletion clears the
+// trigger FK; the returned rows let the handler re-route every surviving input.
+func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentID pgtype.UUID) ([]db.AgentTaskQueue, error) {
cancelled, err := s.Queries.CancelAgentTasksByTriggerComment(ctx, commentID)
if err != nil {
- return err
+ return nil, err
}
for _, t := range cancelled {
s.captureTaskCancelled(ctx, t)
s.ReconcileAgentStatus(ctx, t.AgentID)
s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
}
- return nil
+ return cancelled, nil
}
// BroadcastCancelledTasks reconciles each affected agent's status and emits
@@ -1501,6 +1509,68 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.
return claimed, nil
}
+// FinalizeTaskClaim atomically persists the task-scoped token and, for a
+// comment-backed task, the exact comment ids embedded in the response. The
+// handler must call this only after the full payload has been built and before
+// writing any response bytes. A failure rolls both writes back so the claim can
+// be safely returned to the queue.
+func (s *TaskService) FinalizeTaskClaim(
+ ctx context.Context,
+ task db.AgentTaskQueue,
+ token db.CreateTaskTokenParams,
+ deliveredCommentIDs []pgtype.UUID,
+ recordCommentReceipt bool,
+) ([]pgtype.UUID, error) {
+ receipt := task.DeliveredCommentIds
+ err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ if _, err := qtx.CreateTaskToken(ctx, token); err != nil {
+ return fmt.Errorf("create task token: %w", err)
+ }
+ if !recordCommentReceipt {
+ return nil
+ }
+ persisted, err := qtx.SetTaskDeliveredCommentIDs(ctx, db.SetTaskDeliveredCommentIDsParams{
+ DeliveredCommentIds: deliveredCommentIDs,
+ TaskID: task.ID,
+ RuntimeID: task.RuntimeID,
+ DispatchedAt: task.DispatchedAt,
+ ExpectedTriggerCommentID: task.TriggerCommentID,
+ })
+ if err != nil {
+ return fmt.Errorf("set delivered comment ids: %w", err)
+ }
+ receipt = persisted
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return receipt, nil
+}
+
+// RequeueTaskAfterClaimFailure immediately releases an exact dispatched claim
+// whose payload finalization failed before the HTTP response was written. The
+// SQL CAS includes dispatched_at so a late handler cannot roll back a newer
+// reclaim. This is not a fresh enqueue: do not duplicate queued analytics.
+func (s *TaskService) RequeueTaskAfterClaimFailure(ctx context.Context, task db.AgentTaskQueue) (*db.AgentTaskQueue, error) {
+ requeued, err := s.Queries.RequeueAgentTaskAfterClaimFailure(ctx, db.RequeueAgentTaskAfterClaimFailureParams{
+ TaskID: task.ID,
+ RuntimeID: task.RuntimeID,
+ DispatchedAt: task.DispatchedAt,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("requeue task after claim failure: %w", err)
+ }
+ s.ReconcileAgentStatus(ctx, requeued.AgentID)
+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, requeued)
+ s.notifyTaskAvailable(requeued)
+ slog.Info("task requeued after claim finalization failure",
+ "task_id", util.UUIDToString(requeued.ID),
+ "runtime_id", util.UUIDToString(requeued.RuntimeID),
+ )
+ return &requeued, nil
+}
+
func (s *TaskService) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) error {
tasks, err := s.Queries.PromoteDueDeferredTasksForRuntime(ctx, runtimeID)
if err != nil {
@@ -2091,9 +2161,10 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
// Determine the target agent for the rerun.
var (
- agentID pgtype.UUID
- isLeader bool
- squadID pgtype.UUID
+ agentID pgtype.UUID
+ isLeader bool
+ squadID pgtype.UUID
+ coalescedCommentIDs []pgtype.UUID
)
if sourceTaskID.Valid {
sourceTask, err := s.Queries.GetAgentTask(ctx, sourceTaskID)
@@ -2115,8 +2186,16 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
// TriggerCommentID) and the rerun degrades into a generic issue
// run that has lost the original comment context. Only override
// when the caller didn't pass one explicitly.
- if !triggerCommentID.Valid && sourceTask.TriggerCommentID.Valid {
- triggerCommentID = sourceTask.TriggerCommentID
+ if !triggerCommentID.Valid {
+ coalescedCommentIDs = append([]pgtype.UUID{}, sourceTask.CoalescedCommentIds...)
+ if sourceTask.TriggerCommentID.Valid {
+ triggerCommentID = sourceTask.TriggerCommentID
+ } else if len(coalescedCommentIDs) > 0 {
+ triggerCommentID, coalescedCommentIDs, err = s.promoteNewestSurvivingComment(ctx, coalescedCommentIDs)
+ if err != nil {
+ return nil, fmt.Errorf("repair source comment plan: %w", err)
+ }
+ }
}
} else {
switch {
@@ -2153,7 +2232,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
}
- task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, isLeader, squadID)
+ task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID)
if err != nil {
return nil, err
}
@@ -2168,18 +2247,68 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
return &task, nil
}
+// promoteNewestSurvivingComment repairs a manual rerun whose original trigger
+// was deleted (the FK clears trigger_comment_id while the UUID-array plan
+// survives). Promoting before enqueue lets the normal enqueue path recompute
+// originator and user-scoped connected-app capabilities from the real comment,
+// rather than carrying the deleted trigger's stale security context.
+func (s *TaskService) promoteNewestSurvivingComment(ctx context.Context, ids []pgtype.UUID) (pgtype.UUID, []pgtype.UUID, error) {
+ type survivingComment struct {
+ id pgtype.UUID
+ createdAt time.Time
+ }
+ survivors := make([]survivingComment, 0, len(ids))
+ seen := make(map[string]struct{}, len(ids))
+ for _, id := range ids {
+ if !id.Valid {
+ continue
+ }
+ key := util.UUIDToString(id)
+ if _, ok := seen[key]; ok {
+ continue
+ }
+ seen[key] = struct{}{}
+ comment, err := s.Queries.GetComment(ctx, id)
+ if errors.Is(err, pgx.ErrNoRows) {
+ continue
+ }
+ if err != nil {
+ return pgtype.UUID{}, nil, err
+ }
+ survivors = append(survivors, survivingComment{id: comment.ID, createdAt: comment.CreatedAt.Time})
+ }
+ if len(survivors) == 0 {
+ return pgtype.UUID{}, nil, nil
+ }
+ newest := 0
+ for i := 1; i < len(survivors); i++ {
+ if survivors[i].createdAt.After(survivors[newest].createdAt) ||
+ (survivors[i].createdAt.Equal(survivors[newest].createdAt) &&
+ util.UUIDToString(survivors[i].id) > util.UUIDToString(survivors[newest].id)) {
+ newest = i
+ }
+ }
+ remaining := make([]pgtype.UUID, 0, len(survivors)-1)
+ for i, comment := range survivors {
+ if i != newest {
+ remaining = append(remaining, comment.id)
+ }
+ }
+ return survivors[newest].id, remaining, nil
+}
+
// enqueueRerunTask enqueues a fresh task for the given agent on the issue.
// When the target agent is the issue's single-agent assignee we use the
// assignee-driven path (enqueueIssueTask) so the issue-assignee bookkeeping
// stays in sync; otherwise (squad member, prior assignee that has since been
// reassigned, mention agent) we use the mention path with the same
// force_fresh_session=true contract.
-func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, squadID pgtype.UUID) (db.AgentTaskQueue, error) {
+func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID) (db.AgentTaskQueue, error) {
if issue.AssigneeType.String == "agent" && issue.AssigneeID.Valid &&
util.UUIDToString(issue.AssigneeID) == util.UUIDToString(agentID) {
- return s.enqueueIssueTask(ctx, issue, triggerCommentID, true, "")
+ return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, coalescedCommentIDs, true, "")
}
- return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, isLeader, squadID, true, "")
+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "")
}
// HandleFailedTasks runs the post-failure side effects for a batch of
diff --git a/server/migrations/157_agent_task_delivered_comments.down.sql b/server/migrations/157_agent_task_delivered_comments.down.sql
new file mode 100644
index 0000000000..5a497fbf89
--- /dev/null
+++ b/server/migrations/157_agent_task_delivered_comments.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS delivered_comment_ids;
diff --git a/server/migrations/157_agent_task_delivered_comments.up.sql b/server/migrations/157_agent_task_delivered_comments.up.sql
new file mode 100644
index 0000000000..1144cb1f4c
--- /dev/null
+++ b/server/migrations/157_agent_task_delivered_comments.up.sql
@@ -0,0 +1,17 @@
+-- Record the comment ids that were actually embedded in a daemon claim.
+--
+-- coalesced_comment_ids is the enqueue plan, not proof of delivery: daemons
+-- predating coalesced-comments-v1 ignore the structured fields. Keeping a
+-- separate delivered set lets completion reconciliation replay every comment
+-- that the claiming daemon did not receive.
+ALTER TABLE agent_task_queue
+ ADD COLUMN IF NOT EXISTS delivered_comment_ids UUID[] NOT NULL DEFAULT '{}';
+
+-- Active tasks created before this migration always received their primary
+-- trigger through trigger_comment_content. We deliberately do not backfill
+-- coalesced ids: an older daemon may have ignored them, and a duplicate replay
+-- is safer than silently losing a deliberate instruction.
+UPDATE agent_task_queue
+SET delivered_comment_ids = ARRAY[trigger_comment_id]
+WHERE trigger_comment_id IS NOT NULL
+ AND status IN ('dispatched', 'running', 'waiting_local_directory');
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index ee41864fb6..ac81712c63 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 :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', '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, coalesced_comment_ids
+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, delivered_comment_ids
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -227,6 +227,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -235,7 +236,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', '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, coalesced_comment_ids
+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, delivered_comment_ids
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -289,6 +290,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -304,7 +306,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', '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, coalesced_comment_ids
+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, delivered_comment_ids
`
// Cancels active tasks belonging to a chat session. Called from
@@ -358,6 +360,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -373,7 +376,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', '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, coalesced_comment_ids
+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, delivered_comment_ids
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -427,6 +430,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -442,7 +446,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgen
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', '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, coalesced_comment_ids
+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, delivered_comment_ids
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -500,6 +504,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -514,15 +519,15 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
const cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerComment :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
-WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', '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, coalesced_comment_ids
+WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
+ 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, coalesced_comment_ids, delivered_comment_ids
`
-// Cancels active tasks whose trigger is the given comment. Called when a
-// comment is deleted so the agent does not run with the now-deleted content
-// already embedded in its prompt. Must run BEFORE the comment row is deleted
-// because the FK ON DELETE SET NULL would otherwise nullify trigger_comment_id
-// and we'd lose the ability to find the affected tasks.
+// Cancels active tasks whose planned batch contains the edited/deleted comment.
+// The body may already have been embedded as either the primary trigger or a
+// coalesced input; cancellation prevents an agent from acting on a stale or
+// deleted version. Must run before deletion clears trigger_comment_id.
func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerCommentID pgtype.UUID) ([]AgentTaskQueue, error) {
rows, err := q.db.Query(ctx, cancelAgentTasksByTriggerComment, triggerCommentID)
if err != nil {
@@ -569,6 +574,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -589,9 +595,9 @@ WITH cancelled AS (
AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
AND primary_task.issue_id = $1
AND primary_task.agent_id = $2
- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids
+ 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, fallback.delivered_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, coalesced_comment_ids 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, delivered_comment_ids FROM cancelled
`
type CancelDeferredEscalationsForIssueAgentParams struct {
@@ -636,6 +642,7 @@ type CancelDeferredEscalationsForIssueAgentRow struct {
OriginatorUserID pgtype.UUID `json:"originator_user_id"`
RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
+ DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
}
func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {
@@ -684,6 +691,7 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -700,7 +708,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE escalation_for_task_id = $1
AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -749,6 +757,7 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -789,7 +798,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
type ClaimAgentTaskParams struct {
@@ -846,6 +855,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -977,7 +987,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :one
UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4, prepare_lease_expires_at = NULL
WHERE id = $1 AND status = 'running'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
type CompleteAgentTaskParams struct {
@@ -1032,6 +1042,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -1139,43 +1150,45 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent
const createAgentTask = `-- name: CreateAgentTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
- trigger_summary, force_fresh_session, is_leader_task, handoff_note,
+ coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,
squad_id, context, originator_user_id, runtime_mcp_overlay, runtime_connected_apps
)
VALUES (
$1, $2, $3, 'queued', $4, $5,
- $6,
- COALESCE($7::boolean, FALSE),
+ COALESCE($6::uuid[], '{}'),
+ $7,
COALESCE($8::boolean, FALSE),
- $9,
+ COALESCE($9::boolean, FALSE),
$10,
+ $11,
CASE
- WHEN COALESCE($11::text, '') <> ''
- THEN jsonb_build_object('head_sha', $11::text)
+ WHEN COALESCE($12::text, '') <> ''
+ THEN jsonb_build_object('head_sha', $12::text)
ELSE NULL
END,
- $12,
$13,
- $14
+ $14,
+ $15
)
-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
+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, delivered_comment_ids
`
type CreateAgentTaskParams struct {
- AgentID pgtype.UUID `json:"agent_id"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- Priority int32 `json:"priority"`
- TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
- TriggerSummary pgtype.Text `json:"trigger_summary"`
- ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
- IsLeaderTask pgtype.Bool `json:"is_leader_task"`
- HandoffNote pgtype.Text `json:"handoff_note"`
- SquadID pgtype.UUID `json:"squad_id"`
- HeadSha pgtype.Text `json:"head_sha"`
- OriginatorUserID pgtype.UUID `json:"originator_user_id"`
- RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Priority int32 `json:"priority"`
+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
+ IsLeaderTask pgtype.Bool `json:"is_leader_task"`
+ HandoffNote pgtype.Text `json:"handoff_note"`
+ SquadID pgtype.UUID `json:"squad_id"`
+ HeadSha pgtype.Text `json:"head_sha"`
+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
}
// head_sha stamps the commit under review into the task's context JSONB so the
@@ -1192,6 +1205,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
arg.IssueID,
arg.Priority,
arg.TriggerCommentID,
+ arg.CoalescedCommentIds,
arg.TriggerSummary,
arg.ForceFreshSession,
arg.IsLeaderTask,
@@ -1240,6 +1254,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -1258,7 +1273,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, coalesced_comment_ids
+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, delivered_comment_ids
`
type CreateDeferredAgentTaskParams struct {
@@ -1328,6 +1343,7 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -1343,7 +1359,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, coalesced_comment_ids
+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, delivered_comment_ids
`
type CreateQuickCreateTaskParams struct {
@@ -1407,6 +1423,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -1414,14 +1431,14 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
const createRetryTask = `-- name: CreateRetryTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
- status, priority, trigger_comment_id, trigger_summary, context,
+ status, priority, trigger_comment_id, coalesced_comment_ids, trigger_summary, context,
session_id, work_dir,
attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task,
squad_id, originator_user_id, runtime_mcp_overlay, runtime_connected_apps
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
- 'queued', p.priority, p.trigger_comment_id, p.trigger_summary, p.context,
+ 'queued', p.priority, p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.session_id END,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,
p.attempt + 1, p.max_attempts, p.id,
@@ -1433,7 +1450,7 @@ SELECT
$3
FROM agent_task_queue p
WHERE p.id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
type CreateRetryTaskParams struct {
@@ -1448,11 +1465,11 @@ type CreateRetryTaskParams struct {
// retried as fresh sessions so the child does not inherit a stuck agent
// conversation. Keep the CASE WHEN predicates in sync with
// resumeUnsafeFailureReason and the resume lookup blacklists. attempt is
-// incremented; max_attempts, trigger_comment_id, is_leader_task, and squad_id
-// are inherited so the retried task keeps the same squad-role provenance as its
-// parent and the self-trigger guard in shouldEnqueueSquadLeaderOnComment
-// continues to recognise it as a leader task. Inheriting squad_id also keeps
-// the squad-leader briefing injection working across retries.
+// incremented; max_attempts, trigger_comment_id, coalesced_comment_ids,
+// is_leader_task, and squad_id are inherited so the retried task receives the
+// parent's complete planned comment batch and keeps the same squad-role
+// provenance. delivered_comment_ids intentionally stays at its '{}' default:
+// the child must earn its own delivery receipt at claim time.
//
// originator_user_id is inherited so the Composio overlay decision sees the
// same top-of-chain human across the retry: the user behind the original
@@ -1499,6 +1516,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -1522,7 +1540,7 @@ FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
AND t.created_at < now() - make_interval(secs => $1::double precision)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids
+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, t.delivered_comment_ids
`
type ExpireStaleQueuedTasksParams struct {
@@ -1599,6 +1617,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -1617,7 +1636,7 @@ WHERE id = $1
AND runtime_id = $2
AND status IN ('dispatched', 'waiting_local_directory')
AND started_at IS NULL
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -1670,6 +1689,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -1684,7 +1704,7 @@ SET status = 'failed',
work_dir = COALESCE($5, work_dir),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
type FailAgentTaskParams struct {
@@ -1750,6 +1770,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -1774,7 +1795,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, coalesced_comment_ids
+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, delivered_comment_ids
`
type FailStaleTasksParams struct {
@@ -1866,6 +1887,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -1995,7 +2017,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, coalesced_comment_ids 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, delivered_comment_ids FROM agent_task_queue
WHERE id = $1
`
@@ -2039,12 +2061,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
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, atq.coalesced_comment_ids 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, atq.delivered_comment_ids FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -2101,6 +2124,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -2588,7 +2612,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, coalesced_comment_ids 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, delivered_comment_ids FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -2644,6 +2668,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -2656,7 +2681,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, coalesced_comment_ids 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, delivered_comment_ids FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -2707,6 +2732,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -2821,7 +2847,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, coalesced_comment_ids 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, delivered_comment_ids FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -2872,6 +2898,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -2884,7 +2911,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, coalesced_comment_ids 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, delivered_comment_ids FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -2943,6 +2970,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -2955,7 +2983,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, coalesced_comment_ids 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, delivered_comment_ids FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -3006,6 +3034,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -3018,15 +3047,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, atq.coalesced_comment_ids 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, atq.delivered_comment_ids FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
UNION ALL
-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, 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_ids
+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, t.delivered_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_ids, atq.delivered_comment_ids
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
@@ -3099,6 +3128,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -3116,7 +3146,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, coalesced_comment_ids
+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, delivered_comment_ids
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -3174,6 +3204,7 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -3228,9 +3259,9 @@ type MergeCommentIntoPendingTaskRow struct {
// 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
+// its claim response built. Folding afterward would add a planned id that is
+// absent from that response's delivered_comment_ids receipt; completion
+// reconciliation handles it 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
@@ -3238,8 +3269,8 @@ type MergeCommentIntoPendingTaskRow struct {
// 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.
+// at most one). coalesced_comment_ids remains the pre-claim plan; the claim
+// path records the actual embedded subset in delivered_comment_ids.
//
// 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
@@ -3280,7 +3311,7 @@ SET status = 'queued'
WHERE runtime_id = $1
AND status = 'deferred'
AND fire_at <= now()
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -3329,6 +3360,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtime
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -3355,7 +3387,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -3409,6 +3441,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -3422,7 +3455,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -3477,6 +3510,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -3531,6 +3565,76 @@ func (q *Queries) RefreshAgentStatusFromTasks(ctx context.Context, id pgtype.UUI
return i, err
}
+const requeueAgentTaskAfterClaimFailure = `-- name: RequeueAgentTaskAfterClaimFailure :one
+UPDATE agent_task_queue
+SET status = 'queued',
+ dispatched_at = NULL,
+ prepare_lease_expires_at = NULL,
+ delivered_comment_ids = '{}'
+WHERE id = $1
+ AND runtime_id = $2
+ AND status = 'dispatched'
+ AND started_at IS NULL
+ AND dispatched_at = $3
+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, delivered_comment_ids
+`
+
+type RequeueAgentTaskAfterClaimFailureParams struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
+}
+
+// Claim finalization (task token + optional comment receipt) failed before any
+// response bytes were written. Return only that exact claim generation to the
+// queue so another poll can retry immediately instead of waiting for stale
+// dispatch recovery. The dispatched_at CAS prevents an old handler from
+// rolling back a newer reclaim.
+func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg RequeueAgentTaskAfterClaimFailureParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, requeueAgentTaskAfterClaimFailure, arg.TaskID, arg.RuntimeID, arg.DispatchedAt)
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ )
+ return i, err
+}
+
const restoreAgent = `-- name: RestoreAgent :one
UPDATE agent SET archived_at = NULL, archived_by = NULL, updated_at = now()
WHERE id = $1
@@ -3569,6 +3673,53 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erro
return i, err
}
+const setTaskDeliveredCommentIDs = `-- name: SetTaskDeliveredCommentIDs :one
+UPDATE agent_task_queue
+SET delivered_comment_ids = $1::uuid[]
+WHERE id = $2
+ AND runtime_id = $3
+ AND status = 'dispatched'
+ AND started_at IS NULL
+ AND dispatched_at = $4
+ AND trigger_comment_id IS NOT DISTINCT FROM $5::uuid
+ AND NOT EXISTS (
+ SELECT 1
+ FROM unnest($1::uuid[]) AS delivered(id)
+ WHERE delivered.id IS NULL
+ OR (
+ delivered.id IS DISTINCT FROM trigger_comment_id
+ AND NOT (delivered.id = ANY(coalesced_comment_ids))
+ )
+ )
+RETURNING delivered_comment_ids
+`
+
+type SetTaskDeliveredCommentIDsParams struct {
+ DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
+ TaskID pgtype.UUID `json:"task_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
+ ExpectedTriggerCommentID pgtype.UUID `json:"expected_trigger_comment_id"`
+}
+
+// Replace (rather than append to) the delivery receipt for this claim. A stale
+// dispatched task may be reclaimed by a daemon with different capabilities,
+// so only the ids embedded in the newest response count as delivered. The CAS
+// keeps a stale handler from writing after execution starts, and the subset
+// guard prevents acknowledging an id outside the task's enqueue-time plan.
+func (q *Queries) SetTaskDeliveredCommentIDs(ctx context.Context, arg SetTaskDeliveredCommentIDsParams) ([]pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, setTaskDeliveredCommentIDs,
+ arg.DeliveredCommentIds,
+ arg.TaskID,
+ arg.RuntimeID,
+ arg.DispatchedAt,
+ arg.ExpectedTriggerCommentID,
+ )
+ var delivered_comment_ids []pgtype.UUID
+ err := row.Scan(&delivered_comment_ids)
+ return delivered_comment_ids, err
+}
+
const startAgentTask = `-- name: StartAgentTask :one
UPDATE agent_task_queue
SET status = 'running',
@@ -3576,7 +3727,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -3625,6 +3776,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 4183087985..1155d8f94e 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 :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)
VALUES ($1, $2, NULL, 'queued', $3, $4, $5)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
type CreateAutopilotTaskParams struct {
@@ -282,6 +282,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 2d6326b5ab..7b5f0a9f00 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -125,7 +125,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, coalesced_comment_ids
+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, delivered_comment_ids
`
type CreateChatTaskParams struct {
@@ -190,6 +190,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
)
return i, err
}
@@ -806,9 +807,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 :exec
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index 503189ad43..a831d734f1 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -661,21 +661,26 @@ const listReconcilableCommentsForIssueSince = `-- name: ListReconcilableComments
SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id FROM comment
WHERE issue_id = $1
AND author_type IN ('member', 'agent')
- AND created_at > $2
+ AND (
+ created_at > $2
+ OR id = ANY($3::uuid[])
+ )
ORDER BY created_at ASC, id ASC
`
type ListReconcilableCommentsForIssueSinceParams struct {
- IssueID pgtype.UUID `json:"issue_id"`
- Since pgtype.Timestamptz `json:"since"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Since pgtype.Timestamptz `json:"since"`
+ PlannedCommentIds []pgtype.UUID `json:"planned_comment_ids"`
}
// MUL-4195 / MUL-4304 completion reconciliation: every MEMBER- or AGENT-authored
// comment on an issue created strictly after @since (the completing run's
-// created_at anchor), oldest first. The reconcile pass replays each undelivered
-// one through the normal trigger pipeline so a single coalesced follow-up run
-// covers all of them, guaranteeing at-least-once processing for input that
-// landed after the completing run's claim response was built.
+// created_at anchor), plus every id in its planned trigger/coalesced batch.
+// Planned ids matter for retry children because their input comments predate
+// the child's created_at; if one could not be embedded at claim time it still
+// needs reconciliation. The handler excludes only delivered_comment_ids, then
+// replays the remainder through the normal trigger pipeline oldest first.
//
// Author-type scope (MUL-4304): originally restricted to author_type = 'member'.
// That left a gap — an explicit agent→agent @mention (agent A comments
@@ -697,7 +702,7 @@ type ListReconcilableCommentsForIssueSinceParams struct {
// replaying in order lets later comments coalesce onto the follow-up created by
// the first.
func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, arg ListReconcilableCommentsForIssueSinceParams) ([]Comment, error) {
- rows, err := q.db.Query(ctx, listReconcilableCommentsForIssueSince, arg.IssueID, arg.Since)
+ rows, err := q.db.Query(ctx, listReconcilableCommentsForIssueSince, arg.IssueID, arg.Since, arg.PlannedCommentIds)
if err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index b6204b0008..3e6b20b93f 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -126,6 +126,7 @@ type AgentTaskQueue struct {
// 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"`
CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
+ DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
}
type Attachment struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 8d1fb1d808..070087890f 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids
+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, delivered_comment_ids
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -84,6 +84,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
@@ -203,7 +204,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, coalesced_comment_ids
+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, delivered_comment_ids
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -255,6 +256,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.OriginatorUserID,
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index d37faee61b..324bfa8f44 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -169,11 +169,12 @@ ORDER BY created_at DESC;
-- key rides harmlessly alongside.
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
- trigger_summary, force_fresh_session, is_leader_task, handoff_note,
+ coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,
squad_id, context, originator_user_id, runtime_mcp_overlay, runtime_connected_apps
)
VALUES (
$1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),
+ COALESCE(sqlc.narg(coalesced_comment_ids)::uuid[], '{}'),
sqlc.narg(trigger_summary),
COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),
COALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),
@@ -242,11 +243,11 @@ WHERE id = $1 AND issue_id IS NULL;
-- retried as fresh sessions so the child does not inherit a stuck agent
-- conversation. Keep the CASE WHEN predicates in sync with
-- resumeUnsafeFailureReason and the resume lookup blacklists. attempt is
--- incremented; max_attempts, trigger_comment_id, is_leader_task, and squad_id
--- are inherited so the retried task keeps the same squad-role provenance as its
--- parent and the self-trigger guard in shouldEnqueueSquadLeaderOnComment
--- continues to recognise it as a leader task. Inheriting squad_id also keeps
--- the squad-leader briefing injection working across retries.
+-- incremented; max_attempts, trigger_comment_id, coalesced_comment_ids,
+-- is_leader_task, and squad_id are inherited so the retried task receives the
+-- parent's complete planned comment batch and keeps the same squad-role
+-- provenance. delivered_comment_ids intentionally stays at its '{}' default:
+-- the child must earn its own delivery receipt at claim time.
--
-- originator_user_id is inherited so the Composio overlay decision sees the
-- same top-of-chain human across the retry: the user behind the original
@@ -255,14 +256,14 @@ WHERE id = $1 AND issue_id IS NULL;
-- carried for A2A/audit, not as an originator == agent.owner_id gate.
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
- status, priority, trigger_comment_id, trigger_summary, context,
+ status, priority, trigger_comment_id, coalesced_comment_ids, trigger_summary, context,
session_id, work_dir,
attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task,
squad_id, originator_user_id, runtime_mcp_overlay, runtime_connected_apps
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
- 'queued', p.priority, p.trigger_comment_id, p.trigger_summary, p.context,
+ 'queued', p.priority, p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.session_id END,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,
p.attempt + 1, p.max_attempts, p.id,
@@ -309,14 +310,14 @@ WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_l
RETURNING *;
-- name: CancelAgentTasksByTriggerComment :many
--- Cancels active tasks whose trigger is the given comment. Called when a
--- comment is deleted so the agent does not run with the now-deleted content
--- already embedded in its prompt. Must run BEFORE the comment row is deleted
--- because the FK ON DELETE SET NULL would otherwise nullify trigger_comment_id
--- and we'd lose the ability to find the affected tasks.
+-- Cancels active tasks whose planned batch contains the edited/deleted comment.
+-- The body may already have been embedded as either the primary trigger or a
+-- coalesced input; cancellation prevents an agent from acting on a stale or
+-- deleted version. Must run before deletion clears trigger_comment_id.
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
-WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
-- name: CancelAgentTasksByChatSession :many
@@ -386,6 +387,49 @@ WHERE id = (
)
RETURNING *;
+-- name: SetTaskDeliveredCommentIDs :one
+-- Replace (rather than append to) the delivery receipt for this claim. A stale
+-- dispatched task may be reclaimed by a daemon with different capabilities,
+-- so only the ids embedded in the newest response count as delivered. The CAS
+-- keeps a stale handler from writing after execution starts, and the subset
+-- guard prevents acknowledging an id outside the task's enqueue-time plan.
+UPDATE agent_task_queue
+SET delivered_comment_ids = @delivered_comment_ids::uuid[]
+WHERE id = @task_id
+ AND runtime_id = @runtime_id
+ AND status = 'dispatched'
+ AND started_at IS NULL
+ AND dispatched_at = @dispatched_at
+ AND trigger_comment_id IS NOT DISTINCT FROM sqlc.narg(expected_trigger_comment_id)::uuid
+ AND NOT EXISTS (
+ SELECT 1
+ FROM unnest(@delivered_comment_ids::uuid[]) AS delivered(id)
+ WHERE delivered.id IS NULL
+ OR (
+ delivered.id IS DISTINCT FROM trigger_comment_id
+ AND NOT (delivered.id = ANY(coalesced_comment_ids))
+ )
+ )
+RETURNING delivered_comment_ids;
+
+-- name: RequeueAgentTaskAfterClaimFailure :one
+-- Claim finalization (task token + optional comment receipt) failed before any
+-- response bytes were written. Return only that exact claim generation to the
+-- queue so another poll can retry immediately instead of waiting for stale
+-- dispatch recovery. The dispatched_at CAS prevents an old handler from
+-- rolling back a newer reclaim.
+UPDATE agent_task_queue
+SET status = 'queued',
+ dispatched_at = NULL,
+ prepare_lease_expires_at = NULL,
+ delivered_comment_ids = '{}'
+WHERE id = @task_id
+ AND runtime_id = @runtime_id
+ AND status = 'dispatched'
+ AND started_at IS NULL
+ AND dispatched_at = @dispatched_at
+RETURNING *;
+
-- name: ReclaimStaleDispatchedTaskForRuntime :one
-- Re-delivers a task whose previous claim likely succeeded server-side but
-- whose response never reached the daemon. The task is still in `dispatched`
@@ -743,9 +787,9 @@ WHERE issue_id = @issue_id
-- 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
+-- its claim response built. Folding afterward would add a planned id that is
+-- absent from that response's delivered_comment_ids receipt; completion
+-- reconciliation handles it 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
@@ -753,8 +797,8 @@ WHERE issue_id = @issue_id
-- 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.
+-- at most one). coalesced_comment_ids remains the pre-claim plan; the claim
+-- path records the actual embedded subset in delivered_comment_ids.
--
-- 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
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index 23d2f35f58..80a75652a7 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -332,10 +332,11 @@ LIMIT 1;
-- name: ListReconcilableCommentsForIssueSince :many
-- MUL-4195 / MUL-4304 completion reconciliation: every MEMBER- or AGENT-authored
-- comment on an issue created strictly after @since (the completing run's
--- created_at anchor), oldest first. The reconcile pass replays each undelivered
--- one through the normal trigger pipeline so a single coalesced follow-up run
--- covers all of them, guaranteeing at-least-once processing for input that
--- landed after the completing run's claim response was built.
+-- created_at anchor), plus every id in its planned trigger/coalesced batch.
+-- Planned ids matter for retry children because their input comments predate
+-- the child's created_at; if one could not be embedded at claim time it still
+-- needs reconciliation. The handler excludes only delivered_comment_ids, then
+-- replays the remainder through the normal trigger pipeline oldest first.
--
-- Author-type scope (MUL-4304): originally restricted to author_type = 'member'.
-- That left a gap — an explicit agent→agent @mention (agent A comments
@@ -359,7 +360,10 @@ LIMIT 1;
SELECT * FROM comment
WHERE issue_id = @issue_id
AND author_type IN ('member', 'agent')
- AND created_at > @since
+ AND (
+ created_at > @since
+ OR id = ANY(@planned_comment_ids::uuid[])
+ )
ORDER BY created_at ASC, id ASC;
-- name: GetComment :one
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index af15a3c47e..08e0f4c279 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -3,7 +3,8 @@ package protocol
import "encoding/json"
const (
- DaemonCapabilitySkillBundlesV1 = "skill-bundles-v1"
+ DaemonCapabilitySkillBundlesV1 = "skill-bundles-v1"
+ DaemonCapabilityCoalescedCommentsV1 = "coalesced-comments-v1"
)
// Message is the envelope for all WebSocket messages.