Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(comments): remove delayed assignee fallbacks (#8174)
Jiayuan Zhangb5a7ee1e0e75
diff --git a/apps/docs/content/docs/mentioning-agents.mdx b/apps/docs/content/docs/mentioning-agents.mdxindex f46eb16464..cfbad275d5 100644--- a/apps/docs/content/docs/mentioning-agents.mdx+++ b/apps/docs/content/docs/mentioning-agents.mdx@@ -43,7 +43,7 @@ A plain comment (containing no @ at all) is routed by discussion context:When a comment explicitly @-mentions other targets (including members), the assignee fallback no longer applies.-When a reply triggers an agent other than the assignee, Multica schedules a delayed fallback run for the assignee: if the target agent replies within about 5 minutes, the fallback is cancelled automatically; otherwise the assignee starts a run too.+Replies stay with the target agent even while its runtime is offline or busy. Multica does not automatically start the issue assignee after a timeout. To involve another agent, explicitly @-mention it.## Coalescing consecutive commentsdiff --git a/apps/docs/content/docs/mentioning-agents.zh.mdx b/apps/docs/content/docs/mentioning-agents.zh.mdxindex 4c57f51543..755d84d3c5 100644--- a/apps/docs/content/docs/mentioning-agents.zh.mdx+++ b/apps/docs/content/docs/mentioning-agents.zh.mdx@@ -43,7 +43,7 @@ import { Callout } from "fumadocs-ui/components/callout";评论明确 @了其他对象(包括成员)时,不再使用负责人兜底。-回复触发了非负责人的智能体时,Multica 会为负责人安排一次延迟兜底:目标智能体在约 5 分钟内回复,兜底自动取消;否则负责人也会开始一次执行。+回复始终交给目标智能体,即使它的运行时离线或正在忙碌,也不会超时后自动唤醒任务负责人。需要其他智能体参与时,请明确 @提及。## 连续评论的合并diff --git a/e2e/comment-agent-routing.spec.ts b/e2e/comment-agent-routing.spec.tsnew file mode 100644index 0000000000..cc72841fc6--- /dev/null+++ b/e2e/comment-agent-routing.spec.ts@@ -0,0 +1,121 @@+import "./env";++import { expect, test } from "@playwright/test";+import pg from "pg";+import { createTestApi } from "./helpers";++// Routing matrices live in the Go handler tests. This browser regression covers+// the reply composer, real API routing, and historical inline-run visibility.+test("reply stays with the thread agent and hides unused historical fallbacks", async ({ page }, testInfo) => {+ test.setTimeout(120_000);+ const api = await createTestApi();+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ let runtimeId: string | undefined;+ const agentIds: string[] = [];+ try {+ const workspace = (await api.getWorkspaces())[0]!;+ const user = await db.query<{ id: string }>(`SELECT id FROM "user" WHERE email = $1`, [api.getEmail()]);+ const userId = user.rows[0]!.id;+ const runtime = await db.query<{ id: string }>(+ `INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at)+ VALUES ($1, 'Comment routing verification', 'cloud', 'e2e_comment_routing', 'online', 'E2E fixture', '{}'::jsonb, $2, now()) RETURNING id`,+ [workspace.id, userId],+ );+ runtimeId = runtime.rows[0]!.id;+ for (const name of ["Agent A Assignee", "Agent B Thread Owner", "Agent C Cancelled Control"]) {+ const row = await db.query<{ id: string }>(+ `INSERT INTO agent (workspace_id, name, description, instructions, runtime_mode, runtime_config, runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id)+ VALUES ($1, $2, '', '', 'cloud', '{}'::jsonb, $3, 'private', 'private', 1, $4) RETURNING id`,+ [workspace.id, name, runtimeId, userId],+ );+ agentIds.push(row.rows[0]!.id);+ }+ const [agentA, agentB, agentC] = agentIds;+ const issue = await api.createIssue("Verify reply routing and historical cancelled blocks");+ // Seed assignment without triggering an unrelated assignment run.+ await db.query(`UPDATE issue SET assignee_type = 'agent', assignee_id = $1 WHERE id = $2`, [agentA, issue.id]);+ const root = await db.query<{ id: string }>(+ `INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, $4) RETURNING id`,+ [workspace.id, issue.id, userId, `[@Agent B Thread Owner](mention://agent/${agentB}) Please investigate this thread.`],+ );+ const rootId = root.rows[0]!.id;+ const primary = await db.query<{ id: string }>(+ `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, started_at, completed_at)+ VALUES ($1, $2, $3, $4, ARRAY[$4]::uuid[], 'completed', now() - interval '1 minute', now()) RETURNING id`,+ [agentB, runtimeId, issue.id, rootId],+ );+ const primaryId = primary.rows[0]!.id;+ await db.query(+ `INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, parent_id, source_task_id)+ VALUES ($1, $2, 'agent', $3, 'Agent B is following this thread. Please reply here.', $4, $5)`,+ [workspace.id, issue.id, agentB, rootId, primaryId],+ );+ const hiddenIds: string[] = [];+ for (const dispatched of [false, true]) {+ const row = await db.query<{ id: string }>(+ `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, escalation_for_task_id, dispatched_at, completed_at)+ VALUES ($1, $2, $3, $4, 'cancelled', $5, CASE WHEN $6 THEN now() ELSE NULL END, now()) RETURNING id`,+ [agentA, runtimeId, issue.id, rootId, primaryId, dispatched],+ );+ hiddenIds.push(row.rows[0]!.id);+ }+ const control = await db.query<{ id: string }>(+ `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, completed_at)+ VALUES ($1, $2, $3, $4, 'cancelled', now()) RETURNING id`,+ [agentC, runtimeId, issue.id, rootId],+ );+ const controlId = control.rows[0]!.id;+ await page.addInitScript((token) => {+ localStorage.setItem("multica_token", token!);+ localStorage.setItem("multica:chat:isOpen", "false");+ }, api.getToken());+ await page.setViewportSize({ width: 1440, height: 1050 });+ await page.goto(`/${workspace.slug}/issues/${issue.id}`, { waitUntil: "domcontentloaded" });+ await expect(page.getByText("Agent B is following this thread. Please reply here.", { exact: true })).toBeVisible({ timeout: 45_000 });+ await expect(page.locator(`[data-run-id="${controlId}"]`)).toBeVisible();+ for (const id of hiddenIds) await expect(page.locator(`[data-run-id="${id}"]`)).toHaveCount(0);++ await page.getByTestId("reply-composer-shell").first().click();+ const editor = page.locator('.ProseMirror[data-placeholder="Leave a reply..."], .ProseMirror:has([data-placeholder="Leave a reply..."])').first();+ await editor.fill("Please continue, Agent B. The issue remains assigned to Agent A.");+ const posted = page.waitForResponse((response) => response.request().method() === "POST" && response.url().endsWith(`/api/issues/${issue.id}/comments`));+ await page.keyboard.press("ControlOrMeta+Enter");+ const response = await posted;+ expect(response.status()).toBe(201);+ const reply = await response.json();+ const tasks = await db.query<{ id: string; agent_id: string; status: string; escalation_for_task_id: string | null }>(+ `SELECT id, agent_id, status, escalation_for_task_id FROM agent_task_queue WHERE trigger_comment_id = $1`, [reply.id],+ );+ expect(tasks.rows).toHaveLength(1);+ expect(tasks.rows[0]).toMatchObject({ agent_id: agentB, status: "queued", escalation_for_task_id: null });+ await expect(page.locator(`[data-run-id="${tasks.rows[0]!.id}"]`)).toBeVisible();+ for (const id of hiddenIds) await expect(page.locator(`[data-run-id="${id}"]`)).toHaveCount(0);+ await page.screenshot({ path: testInfo.outputPath("thread-reply.png"), fullPage: true });++ // Reload proves persisted history is filtered, not just the live update.+ await page.reload({ waitUntil: "domcontentloaded" });+ await expect(page.locator(`[data-run-id="${tasks.rows[0]!.id}"]`)).toBeVisible({ timeout: 30_000 });+ await expect(page.locator(`[data-run-id="${controlId}"]`)).toBeVisible();+ for (const id of hiddenIds) await expect(page.locator(`[data-run-id="${id}"]`)).toHaveCount(0);++ await page.getByTestId("comment-composer-shell").click();+ await page.locator('.ProseMirror[data-placeholder="Leave a comment..."], .ProseMirror:has([data-placeholder="Leave a comment..."])').first().fill("A separate top-level request for the assignee.");+ const topLevelPosted = page.waitForResponse((res) => res.request().method() === "POST" && res.url().endsWith(`/api/issues/${issue.id}/comments`));+ await page.keyboard.press("ControlOrMeta+Enter");+ const topLevelResponse = await topLevelPosted;+ expect(topLevelResponse.status()).toBe(201);+ const topLevel = await topLevelResponse.json();+ const topTasks = await db.query<{ id: string; agent_id: string }>(`SELECT id, agent_id FROM agent_task_queue WHERE trigger_comment_id = $1`, [topLevel.id]);+ expect(topTasks.rows).toHaveLength(1);+ expect(topTasks.rows[0]!.agent_id).toBe(agentA);+ await expect(page.locator(`[data-run-id="${topTasks.rows[0]!.id}"]`)).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath("top-level-assignee.png"), fullPage: true });+ } finally {+ await api.cleanup();+ if (agentIds.length) await db.query(`DELETE FROM agent WHERE id = ANY($1::uuid[])`, [agentIds]);+ if (runtimeId) await db.query(`DELETE FROM agent_runtime WHERE id = $1`, [runtimeId]);+ await db.end();+ }+});diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex e04bba57e9..32f5392ba3 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -10,6 +10,7 @@ import ("log/slog""net/http""regexp"+ "slices""strings""time""unicode/utf8"@@ -747,6 +748,18 @@ type TaskAgentData struct {RuntimeConfig json.RawMessage `json:"runtime_config,omitempty"`}+// visibleTaskHistory omits unused assignee fallbacks created by older versions.+// Dispatch only begins preparation, so a fallback cancelled before StartTask+// is still unused. Keep started fallbacks and ordinary cancellations visible,+// and retain the underlying scheduling records for audit.+func visibleTaskHistory(tasks []db.AgentTaskQueue) []db.AgentTaskQueue {+ return slices.DeleteFunc(tasks, func(task db.AgentTaskQueue) bool {+ return task.EscalationForTaskID.Valid &&+ !task.StartedAt.Valid &&+ (task.Status == "deferred" || task.Status == "cancelled")+ })+}+// taskToResponse maps a queue row to its wire shape. workspaceID is threaded// in because the row itself doesn't carry one (workspace lives on the agent// / issue / chat session) — we ask the caller to resolve it once and pass it@@ -2573,6 +2586,7 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {return}+ tasks = visibleTaskHistory(tasks)resp := make([]AgentTaskResponse, len(tasks))var taskIDs []pgtype.UUIDif includeUsage {diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 0990309ba6..db7f772740 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1499,39 +1499,11 @@ const (commentTriggerSourceConversation commentAgentTriggerSource = "conversation_continuation")-const defaultCommentRoutingEscalationDelay = 5 * time.Minute--func (h *Handler) commentRoutingEscalationDelay(ctx context.Context, workspaceID pgtype.UUID) time.Duration {- ws, err := h.Queries.GetWorkspace(ctx, workspaceID)- if err != nil || len(ws.Settings) == 0 {- return defaultCommentRoutingEscalationDelay- }-- var settings struct {- CommentRouting struct {- EscalationSeconds *int `json:"escalation_seconds"`- } `json:"comment_routing"`- }- if err := json.Unmarshal(ws.Settings, &settings); err != nil || settings.CommentRouting.EscalationSeconds == nil {- return defaultCommentRoutingEscalationDelay- }- if *settings.CommentRouting.EscalationSeconds <= 0 {- return 0- }- return time.Duration(*settings.CommentRouting.EscalationSeconds) * time.Second-}--type commentEscalationFallback struct {- Agent db.Agent- Squad *db.Squad-}-type commentAgentTrigger struct {- Agent db.Agent- Source commentAgentTriggerSource- Squad *db.Squad- EscalationFallback *commentEscalationFallback- AlreadyPending bool+ Agent db.Agent+ Source commentAgentTriggerSource+ Squad *db.Squad+ AlreadyPending bool}type commentTriggerComputeOptions struct {@@ -1902,9 +1874,6 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {// the agent task path (TaskService.createAgentComment) — both reply paths// must keep the resolved root in sync.h.TaskService.AutoUnresolveThreadOnReply(r.Context(), rootComment, uuidToString(issue.WorkspaceID), authorType, authorID)- if authorType == "agent" {- h.TaskService.CancelDeferredEscalationsForIssueAgent(r.Context(), issue.ID, comment.AuthorID)- }originatorUserID := h.invokeOriginatorFromRequest(r, authorType, authorID)// The comment is already saved; a blocked mention must not fail the whole@@ -2032,15 +2001,6 @@ type commentEnqueueResult struct {// target's outcome. queued / coalesced / deferred are success-shaped (the run// was handled, no duplicate task); only a real enqueue failure is blocked.func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, triggers []commentAgentTrigger) map[string]commentEnqueueResult {- var escalationDelay time.Duration- escalationDelayLoaded := false- getEscalationDelay := func() time.Duration {- if !escalationDelayLoaded {- escalationDelay = h.commentRoutingEscalationDelay(ctx, issue.WorkspaceID)- escalationDelayLoaded = true- }- return escalationDelay- }results := make(map[string]commentEnqueueResult, len(triggers))record := func(trigger commentAgentTrigger, status DispatchStatus, reason DispatchReasonCode) {execSquadID := ""@@ -2050,7 +2010,7 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issuresults[uuidToString(trigger.Agent.ID)] = commentEnqueueResult{status: status, reason: reason, execSquadID: execSquadID}}for _, trigger := range triggers {- status, reason := h.resolveCommentTriggerEnqueue(ctx, issue, trigger, triggerCommentID, getEscalationDelay)+ status, reason := h.resolveCommentTriggerEnqueue(ctx, issue, trigger, triggerCommentID)record(trigger, status, reason)}return results@@ -2092,7 +2052,7 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu// A duplicate that cannot yet be resolved re-loops (bounded by maxAttempts); on// genuine non-convergence it returns a truthful internal_error, never a fabricated// deferred that would silently drop the comment.-func (h *Handler) resolveCommentTriggerEnqueue(ctx context.Context, issue db.Issue, trigger commentAgentTrigger, triggerCommentID pgtype.UUID, getEscalationDelay func() time.Duration) (DispatchStatus, DispatchReasonCode) {+func (h *Handler) resolveCommentTriggerEnqueue(ctx context.Context, issue db.Issue, trigger commentAgentTrigger, triggerCommentID pgtype.UUID) (DispatchStatus, DispatchReasonCode) {pending := trigger.AlreadyPendinglostRace := false// Resolve the reviewed HEAD lazily and at most once — the common@@ -2178,7 +2138,7 @@ func (h *Handler) resolveCommentTriggerEnqueue(ctx context.Context, issue db.Iss// no-blocker case; we simply never PROMISE it.)}}- if err := h.enqueueSingleCommentTrigger(ctx, issue, triggerCommentID, trigger, getEscalationDelay); err != nil {+ if err := h.enqueueSingleCommentTrigger(ctx, issue, triggerCommentID, trigger); err != nil {// Lost the enqueue race: a sibling task for this (issue, agent) now// exists. Re-resolve as pending so the next attempt folds this// comment into that sibling (queued) or durably registers it@@ -2504,7 +2464,6 @@ func (h *Handler) registerPlannedCommentForActiveTask(ctx context.Context, issue// shape today's schema has no safe place to park, and closing it needs a durable// obligation record rather than an in-request hand-off.func (h *Handler) propagateUncoveredCommentObligation(ctx context.Context, issue db.Issue, trigger commentAgentTrigger, commentID pgtype.UUID, headSha pgtype.Text) bool {- noEscalation := func() time.Duration { return 0 }const maxAttempts = 3for attempt := 0; attempt < maxAttempts; attempt++ {registered, err := h.registerPlannedCommentForActiveTask(ctx, issue, trigger.Agent.ID, commentID, pgtype.Text{})@@ -2518,7 +2477,7 @@ func (h *Handler) propagateUncoveredCommentObligation(ctx context.Context, issueif h.mergeCommentIntoPendingTask(ctx, issue, trigger, commentID, headSha) == commentMergeSucceeded {return true}- err = h.enqueueSingleCommentTrigger(ctx, issue, commentID, trigger, noEscalation)+ err = h.enqueueSingleCommentTrigger(ctx, issue, commentID, trigger)if err == nil {return true}@@ -2549,10 +2508,9 @@ func logCommentEnqueueFailure(msg string, err error, attrs ...any) {// Split out of enqueueCommentAgentTriggers so the merge-not-drop path// (MUL-4195) can fall back to it when a pending task vanished mid-flight.// enqueueSingleCommentTrigger enqueues one resolved trigger and returns the-// PRIMARY enqueue error (nil on success) so the caller can surface a-// trigger_outcome (MUL-4525 §2). Secondary work (the deferred escalation-// fallback) stays best-effort logged and does not affect the returned error.-func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, trigger commentAgentTrigger, getEscalationDelay func() time.Duration) error {+// enqueue error (nil on success) so the caller can surface a+// trigger_outcome (MUL-4525 §2).+func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, trigger commentAgentTrigger) error {switch trigger.Source {case commentTriggerSourceIssueAssignee:if trigger.Squad != nil {@@ -2584,7 +2542,6 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issureturn err}case commentTriggerSourceThreadParent, commentTriggerSourceConversation:- var task db.AgentTaskQueuevar err error// Squad is set on these two sources only when the routing already// proved a leader role to continue: the thread root's prior task for@@ -2592,9 +2549,9 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu// for the thread-parent path. Gating on the source as well would keep// the thread-parent path demoted for no reason (MUL-7006).if trigger.Squad != nil {- task, err = h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID)+ _, err = h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID)} else {- task, err = h.TaskService.EnqueueTaskForThreadParent(ctx, issue, trigger.Agent.ID, triggerCommentID)+ _, err = h.TaskService.EnqueueTaskForThreadParent(ctx, issue, trigger.Agent.ID, triggerCommentID)}if err != nil {logCommentEnqueueFailure("enqueue routed comment agent task failed", err,@@ -2603,20 +2560,6 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu"source", trigger.Source)return err}- if trigger.EscalationFallback == nil || getEscalationDelay() <= 0 {- return nil- }- var squadID pgtype.UUID- if trigger.EscalationFallback.Squad != nil {- squadID = trigger.EscalationFallback.Squad.ID- }- if _, err := h.TaskService.EnqueueDeferredAssigneeFallback(ctx, issue, trigger.EscalationFallback.Agent.ID, squadID, task.ID, triggerCommentID, time.Now().Add(getEscalationDelay())); err != nil {- slog.Warn("enqueue deferred assignee fallback failed",- "issue_id", uuidToString(issue.ID),- "primary_agent_id", uuidToString(trigger.Agent.ID),- "fallback_agent_id", uuidToString(trigger.EscalationFallback.Agent.ID),- "error", err)- }}return nil}@@ -2689,13 +2632,6 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issuif !ok {return nil, nil}- if fallback, ok := h.routeAssigneeFallback(ctx, issue, actorType, actorID, opts); ok &&- uuidToString(fallback.Agent.ID) != uuidToString(trigger.Agent.ID) {- trigger.EscalationFallback = &commentEscalationFallback{- Agent: fallback.Agent,- Squad: fallback.Squad,- }- }return []commentAgentTrigger{trigger}, nil}@@ -2705,15 +2641,6 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issuif len(triggers) == 0 {return nil, nil}- if len(triggers) == 1 {- if fallback, ok := h.routeAssigneeFallback(ctx, issue, actorType, actorID, opts); ok &&- uuidToString(fallback.Agent.ID) != uuidToString(triggers[0].Agent.ID) {- triggers[0].EscalationFallback = &commentEscalationFallback{- Agent: fallback.Agent,- Squad: fallback.Squad,- }- }- }return triggers, nil}// A plain member-to-member reply must not start the issue assignee justdiff --git a/server/internal/handler/comment_trigger_preview_test.go b/server/internal/handler/comment_trigger_preview_test.goindex b1c9bfb941..9e0fa71ce3 100644--- a/server/internal/handler/comment_trigger_preview_test.go+++ b/server/internal/handler/comment_trigger_preview_test.go@@ -7,9 +7,8 @@ import ("net/http""net/http/httptest""testing"- "time"- "github.com/multica-ai/multica/server/internal/util"+ "github.com/multica-ai/multica/server/internal/testutil")func createCommentTriggerPreviewIssue(t *testing.T, title string, assigneeType, assigneeID string) string {@@ -573,309 +572,66 @@ func TestPreviewCommentTriggers_MemberMentionSuppressesAssigneeFallback(t *testi}}-func TestCreateComment_ThreadParentQueuesParentAndPromotesDeferredFallback(t *testing.T) {+func TestCreateComment_ThreadReplyDoesNotEscalateToAssignee(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")}- ctx := context.Background()-- assigneeID := createHandlerTestAgent(t, "Thread Parent Assignee", nil)- parentAgentID := createHandlerTestAgent(t, "Thread Parent Owner", nil)- issueID := createCommentTriggerPreviewIssue(t, "thread parent deferred fallback", "agent", assigneeID)-- var parentCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)- VALUES ($1, $2, 'agent', $3, 'I am handling this')- RETURNING id- `, testWorkspaceID, issueID, parentAgentID).Scan(&parentCommentID); err != nil {- t.Fatalf("insert parent agent comment: %v", err)- }-- replyContent := "can you follow up here?"- preview := previewCommentTriggersForTest(t, issueID, CommentTriggerPreviewRequest{- Content: replyContent,- ParentID: &parentCommentID,- })- requirePreviewAgents(t, preview, parentAgentID)- if preview.Agents[0].Source != string(commentTriggerSourceThreadParent) {- t.Fatalf("preview source = %q, want %q", preview.Agents[0].Source, commentTriggerSourceThreadParent)- }-- replyID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{- "content": replyContent,- "parent_id": parentCommentID,- })- if got := countQueuedCommentTriggerTasks(t, issueID, parentAgentID); got != 1 {- t.Fatalf("parent agent queued tasks = %d, want 1", got)- }- if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {- t.Fatalf("assignee queued tasks before timeout = %d, want 0", got)- }-- var primaryTaskID string- if err := testPool.QueryRow(ctx, `- SELECT id FROM agent_task_queue- WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'- `, issueID, parentAgentID).Scan(&primaryTaskID); err != nil {- t.Fatalf("load primary task: %v", err)- }-- var fallbackTaskID, escalationForTaskID, triggerCommentID string- var fireAt time.Time- if err := testPool.QueryRow(ctx, `- SELECT id, escalation_for_task_id, trigger_comment_id, fire_at- FROM agent_task_queue- WHERE issue_id = $1 AND agent_id = $2 AND status = 'deferred'- `, issueID, assigneeID).Scan(&fallbackTaskID, &escalationForTaskID, &triggerCommentID, &fireAt); err != nil {- t.Fatalf("load deferred fallback task: %v", err)- }- if escalationForTaskID != primaryTaskID {- t.Fatalf("deferred fallback escalation_for_task_id = %s, want %s", escalationForTaskID, primaryTaskID)- }- if triggerCommentID != replyID {- t.Fatalf("deferred fallback trigger_comment_id = %s, want %s", triggerCommentID, replyID)- }- if fireAt.Before(time.Now().Add(4*time.Minute)) || fireAt.After(time.Now().Add(6*time.Minute)) {- t.Fatalf("deferred fallback fire_at = %s, want about 5 minutes from now", fireAt.Format(time.RFC3339))- }-- if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET fire_at = now() - interval '1 second' WHERE id = $1`, fallbackTaskID); err != nil {- t.Fatalf("make deferred fallback due: %v", err)- }- if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, util.MustParseUUID(testRuntimeID)); err != nil {- t.Fatalf("promote due deferred fallback: %v", err)- }- if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 1 {- t.Fatalf("assignee queued tasks after timeout promotion = %d, want 1", got)- }-}--func TestCreateComment_ThreadParentSkipsDeferredFallbackWhenParentIsAssignee(t *testing.T) {- if testHandler == nil || testPool == nil {- t.Skip("database not available")- }- ctx := context.Background()-- assigneeID := createHandlerTestAgent(t, "Thread Parent Same Assignee", nil)- issueID := createCommentTriggerPreviewIssue(t, "thread parent same as assignee", "agent", assigneeID)-- var parentCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)- VALUES ($1, $2, 'agent', $3, 'I am handling this')- RETURNING id- `, testWorkspaceID, issueID, assigneeID).Scan(&parentCommentID); err != nil {- t.Fatalf("insert parent agent comment: %v", err)- }-- postCommentForTriggerPreviewTest(t, issueID, map[string]any{- "content": "can you follow up here?",- "parent_id": parentCommentID,- })- if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 1 {- t.Fatalf("parent assignee queued tasks = %d, want 1", got)- }- if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "deferred"); got != 0 {- t.Fatalf("deferred fallback for same parent assignee = %d, want 0", got)- }-}--func TestCreateComment_ThreadParentEscalationCanBeDisabled(t *testing.T) {- if testHandler == nil || testPool == nil {- t.Skip("database not available")- }- ctx := context.Background()-- var previousSettings string- if err := testPool.QueryRow(ctx,- `SELECT COALESCE(settings, '{}'::jsonb)::text FROM workspace WHERE id = $1`,- testWorkspaceID,- ).Scan(&previousSettings); err != nil {- t.Fatalf("load workspace settings: %v", err)- }- if _, err := testPool.Exec(ctx,- `UPDATE workspace SET settings = '{"comment_routing":{"escalation_seconds":0}}'::jsonb WHERE id = $1`,- testWorkspaceID,- ); err != nil {- t.Fatalf("disable comment routing escalation: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `UPDATE workspace SET settings = $1::jsonb WHERE id = $2`, previousSettings, testWorkspaceID)- })-- assigneeID := createHandlerTestAgent(t, "Thread Parent Disabled Assignee", nil)- parentAgentID := createHandlerTestAgent(t, "Thread Parent Disabled Owner", nil)- issueID := createCommentTriggerPreviewIssue(t, "thread parent disabled fallback", "agent", assigneeID)-- var parentCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)- VALUES ($1, $2, 'agent', $3, 'I am handling this')- RETURNING id- `, testWorkspaceID, issueID, parentAgentID).Scan(&parentCommentID); err != nil {- t.Fatalf("insert parent agent comment: %v", err)- }-- postCommentForTriggerPreviewTest(t, issueID, map[string]any{- "content": "can you follow up here?",- "parent_id": parentCommentID,- })- if got := countQueuedCommentTriggerTasks(t, issueID, parentAgentID); got != 1 {- t.Fatalf("parent agent queued tasks = %d, want 1", got)- }- if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "deferred"); got != 0 {- t.Fatalf("disabled deferred assignee fallback = %d, want 0", got)- }-}--func TestCreateComment_ParentAgentReplyCancelsPromotedFallbackBeforeClaim(t *testing.T) {- if testHandler == nil || testPool == nil {- t.Skip("database not available")- }- ctx := context.Background()-- assigneeID := createHandlerTestAgent(t, "Thread Parent Cancel Assignee", nil)- parentAgentID := createHandlerTestAgent(t, "Thread Parent Cancel Owner", nil)- issueID := createCommentTriggerPreviewIssue(t, "thread parent deferred cancel", "agent", assigneeID)-- var parentCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)- VALUES ($1, $2, 'agent', $3, 'I am handling this')- RETURNING id- `, testWorkspaceID, issueID, parentAgentID).Scan(&parentCommentID); err != nil {- t.Fatalf("insert parent agent comment: %v", err)- }-- memberReplyID := postCommentForTriggerPreviewTest(t, issueID, map[string]any{- "content": "can you follow up here?",- "parent_id": parentCommentID,- })- if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "deferred"); got != 1 {- t.Fatalf("deferred assignee fallback before parent ack = %d, want 1", got)- }-- var primaryTaskID, fallbackTaskID string- if err := testPool.QueryRow(ctx, `- SELECT id FROM agent_task_queue- WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'- `, issueID, parentAgentID).Scan(&primaryTaskID); err != nil {- t.Fatalf("load primary task: %v", err)- }- if err := testPool.QueryRow(ctx, `- UPDATE agent_task_queue- SET fire_at = now() - interval '1 second'- WHERE issue_id = $1 AND agent_id = $2 AND status = 'deferred'- RETURNING id- `, issueID, assigneeID).Scan(&fallbackTaskID); err != nil {- t.Fatalf("make deferred fallback due: %v", err)- }- if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, util.MustParseUUID(testRuntimeID)); err != nil {- t.Fatalf("promote due deferred fallback: %v", err)- }- if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 1 {- t.Fatalf("queued assignee fallback before parent ack = %d, want 1", got)- }-- w := httptest.NewRecorder()- r := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{- "content": "acknowledged",- "parent_id": memberReplyID,- })- r = withURLParam(r, "id", issueID)- r.Header.Set("X-Agent-ID", parentAgentID)- r.Header.Set("X-Task-ID", primaryTaskID)- testHandler.CreateComment(w, r)- if w.Code != http.StatusCreated {- t.Fatalf("agent ack comment: expected 201, got %d: %s", w.Code, w.Body.String())- }-- if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "deferred"); got != 0 {- t.Fatalf("deferred assignee fallback after parent ack = %d, want 0", got)- }- if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {- t.Fatalf("queued assignee fallback after parent ack = %d, want 0", got)- }- if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "cancelled"); got != 1 {- t.Fatalf("cancelled assignee fallback after parent ack = %d, want 1", got)- }- claimed, err := testHandler.TaskService.ClaimTask(ctx, util.MustParseUUID(assigneeID))- if err != nil {- t.Fatalf("claim assignee fallback after parent ack: %v", err)- }- if claimed != nil {- t.Fatalf("assignee claimed cancelled fallback %s after parent ack; fallback task was %s", util.UUIDToString(claimed.ID), fallbackTaskID)- }-}--func TestStartTaskCancelsPromotedFallbackBeforeAssigneeCanClaim(t *testing.T) {- if testHandler == nil || testPool == nil {- t.Skip("database not available")- }- ctx := context.Background()-- assigneeID := createHandlerTestAgent(t, "Thread Parent Start Cancel Assignee", nil)- parentAgentID := createHandlerTestAgent(t, "Thread Parent Start Cancel Owner", nil)- issueID := createCommentTriggerPreviewIssue(t, "thread parent start cancels fallback", "agent", assigneeID)-- var parentCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)- VALUES ($1, $2, 'agent', $3, 'I am handling this')- RETURNING id- `, testWorkspaceID, issueID, parentAgentID).Scan(&parentCommentID); err != nil {- t.Fatalf("insert parent agent comment: %v", err)- }-- postCommentForTriggerPreviewTest(t, issueID, map[string]any{- "content": "can you follow up here?",- "parent_id": parentCommentID,- })- if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "deferred"); got != 1 {- t.Fatalf("deferred assignee fallback before start = %d, want 1", got)- }-- primary, err := testHandler.TaskService.ClaimTask(ctx, util.MustParseUUID(parentAgentID))- if err != nil {- t.Fatalf("claim parent task: %v", err)- }- if primary == nil {- t.Fatal("claim parent task returned nil")- }-- var fallbackTaskID string- if err := testPool.QueryRow(ctx, `- UPDATE agent_task_queue- SET fire_at = now() - interval '1 second'- WHERE issue_id = $1 AND agent_id = $2 AND status = 'deferred'- RETURNING id- `, issueID, assigneeID).Scan(&fallbackTaskID); err != nil {- t.Fatalf("make deferred fallback due: %v", err)- }- if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, util.MustParseUUID(testRuntimeID)); err != nil {- t.Fatalf("promote due deferred fallback: %v", err)- }- if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 1 {- t.Fatalf("queued assignee fallback before parent start = %d, want 1", got)- }-- if _, err := testHandler.TaskService.StartTask(ctx, primary.ID); err != nil {- t.Fatalf("start parent task: %v", err)- }-- if got := countQueuedCommentTriggerTasks(t, issueID, assigneeID); got != 0 {- t.Fatalf("queued assignee fallback after parent start = %d, want 0", got)- }- if got := countCommentTriggerTasksWithStatus(t, issueID, assigneeID, "cancelled"); got != 1 {- t.Fatalf("cancelled assignee fallback after parent start = %d, want 1", got)- }- claimed, err := testHandler.TaskService.ClaimTask(ctx, util.MustParseUUID(assigneeID))- if err != nil {- t.Fatalf("claim assignee fallback after parent start: %v", err)- }- if claimed != nil {- t.Fatalf("assignee claimed cancelled fallback %s after parent start; fallback task was %s", util.UUIDToString(claimed.ID), fallbackTaskID)+ for _, tc := range []struct {+ name string+ memberRoot bool+ squadAssignee bool+ sameAssignee bool+ }{+ {name: "direct agent reply"},+ {name: "member root owner", memberRoot: true},+ {name: "direct reply with squad assignee", squadAssignee: true},+ {name: "root owner with squad assignee", memberRoot: true, squadAssignee: true},+ {name: "reply to assignee", sameAssignee: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ ctx := context.Background()+ ownerID := createHandlerTestAgent(t, "Thread Owner", nil)+ assigneeID := ownerID+ if !tc.sameAssignee {+ assigneeID = createHandlerTestAgent(t, "Issue Assignee", nil)+ }+ assigneeType := "agent"+ if tc.squadAssignee {+ assigneeID = dbfx.Squad(t, "Issue Squad", assigneeID)+ assigneeType = "squad"+ }+ issueID := dbfx.Issue(t, "thread reply", testutil.Cols{"assignee_type": assigneeType, "assignee_id": assigneeID})+ parentID := ""+ if tc.memberRoot {+ parentID = dbfx.Comment(t, issueID, fmt.Sprintf("[@Owner](mention://agent/%s) please investigate", ownerID))+ } else {+ parentID = dbfx.Comment(t, issueID, "I am handling this", testutil.Cols{"author_type": "agent", "author_id": ownerID})+ }+ body := map[string]any{"content": "please follow up", "parent_id": parentID}+ requirePreviewAgents(t, previewCommentTriggersForTest(t, issueID, body), ownerID)+ replyID := postCommentForTriggerPreviewTest(t, issueID, body)+ // Read raw rows so hiding unused fallbacks in history cannot satisfy this assertion.+ tasks, err := testHandler.Queries.ListTasksByIssue(ctx, parseUUID(issueID))+ if err != nil {+ t.Fatal(err)+ }+ if len(tasks) != 1 || uuidToString(tasks[0].AgentID) != ownerID || uuidToString(tasks[0].TriggerCommentID) != replyID {+ t.Fatalf("reply must create only the thread owner's task, got %+v", tasks)+ }+ primary, err := testHandler.TaskService.ClaimTask(ctx, parseUUID(ownerID))+ if err != nil {+ t.Fatal(err)+ }+ if primary == nil {+ t.Fatal("thread owner task was not claimable")+ }+ if _, err := testHandler.TaskService.StartTask(ctx, primary.ID); err != nil {+ t.Fatal(err)+ }+ if got, want := taskIDs(runsRequest(t, issueID, "")), sortedCopy(uuidToString(primary.ID)); !sameIDs(got, want) {+ t.Fatalf("reply history = %v, want only the thread owner's run %v", got, want)+ }+ })}}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex c7004e81be..2ea9e6fb36 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -5197,6 +5197,7 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {return}+ tasks = visibleTaskHistory(tasks)resp := make([]AgentTaskResponse, len(tasks))for i, t := range tasks {resp[i] = taskToResponse(t, workspaceID)diff --git a/server/internal/handler/fail_task_successor_test.go b/server/internal/handler/fail_task_successor_test.goindex e7460fe259..e5f458b1ad 100644--- a/server/internal/handler/fail_task_successor_test.go+++ b/server/internal/handler/fail_task_successor_test.go@@ -322,23 +322,18 @@ func TestPromoteDueDeferred_CancelsSupersededRetry(t *testing.T) {}}-// TestPromoteDueDeferred_LeavesNonRetryDeferredRowsAlone bounds the cancellation-// above. Assignee-fallback escalations are deferred rows that are SUPPOSED to-// coexist with an active primary task — they own their own fire_at lifecycle and-// exist precisely to fire when the primary goes quiet. Cancelling those would-// silently disable escalation, so the sweep is scoped to auto-retry clones.-//-// The index fence still applies to them: they stay deferred while the slot is-// occupied rather than colliding on promotion.+// TestPromoteDueDeferred_LeavesNonRetryDeferredRowsAlone keeps the superseded+// retry sweep scoped to auto-retry clones. Other scheduled tasks still wait for+// their queue slot without being cancelled.func TestPromoteDueDeferred_LeavesNonRetryDeferredRowsAlone(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")}ctx := context.Background()- runtimeID := dbfx.Runtime(t, "promote-escalation-runtime")- agentID := dbfx.Agent(t, "promote-escalation-agent", runtimeID)- issueID := dbfx.Issue(t, "escalation survives an active primary", testutil.Cols{+ runtimeID := dbfx.Runtime(t, "promote-scheduled-runtime")+ agentID := dbfx.Agent(t, "promote-scheduled-agent", runtimeID)+ issueID := dbfx.Issue(t, "scheduled task waits for its queue slot", testutil.Cols{"assignee_type": "agent","assignee_id": agentID,})@@ -349,19 +344,18 @@ func TestPromoteDueDeferred_LeavesNonRetryDeferredRowsAlone(t *testing.T) {primaryID := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "runtime_id": runtimeID, "status": "queued",})- escalationID := dbfx.Task(t, agentID, testutil.Cols{- "issue_id": issueID,- "runtime_id": runtimeID,- "status": "deferred",- "fire_at": testutil.Raw("now() - interval '1 minute'"),- "escalation_for_task_id": primaryID,+ scheduledID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "deferred",+ "fire_at": testutil.Raw("now() - interval '1 minute'"),})if err := testHandler.TaskService.PromoteDueDeferredTasksForRuntime(ctx, parseUUID(runtimeID)); err != nil {t.Fatalf("promotion: %v", err)}- if got := taskStatusByID(t, escalationID); got != "deferred" {- t.Fatalf("an escalation must be neither cancelled nor promoted into an occupied slot, got %q", got)+ if got := taskStatusByID(t, scheduledID); got != "deferred" {+ t.Fatalf("a scheduled task must be neither cancelled nor promoted into an occupied slot, got %q", got)}if got := taskStatusByID(t, primaryID); got != "queued" {t.Fatalf("primary must be untouched, got %q", got)diff --git a/server/internal/handler/task_runs_scope_test.go b/server/internal/handler/task_runs_scope_test.goindex eac49e54be..e4d8dae249 100644--- a/server/internal/handler/task_runs_scope_test.go+++ b/server/internal/handler/task_runs_scope_test.go@@ -1,7 +1,9 @@package handlerimport (+ "context""net/http"+ "os""sort""testing"@@ -131,6 +133,189 @@ func TestListTasksByIssueDefaultsToFullHistory(t *testing.T) {}}+func TestTaskHistoryOmitsUnusedAssigneeFallbacks(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ agentID := createHandlerTestAgent(t, "FallbackHistoryAgent", []byte("[]"))+ issueID := dbfx.Issue(t, "fallback history")+ runtimeID := handlerTestRuntimeID(t)+ primaryID := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "status": "completed", "runtime_id": runtimeID})+ want := []string{primaryID}+ for _, tc := range []struct {+ name string+ status string+ fallback bool+ dispatched bool+ started bool+ visible bool+ }{+ {name: "inert fallback", status: "deferred", fallback: true},+ {name: "unused cancelled fallback", status: "cancelled", fallback: true},+ {name: "ordinary cancellation", status: "cancelled", visible: true},+ {name: "ordinary deferred task", status: "deferred", visible: true},+ {name: "promoted fallback", status: "queued", fallback: true, visible: true},+ {name: "dispatched unused cancellation", status: "cancelled", fallback: true, dispatched: true},+ {name: "ordinary dispatched cancellation", status: "cancelled", dispatched: true, visible: true},+ {name: "started cancellation", status: "cancelled", fallback: true, started: true, visible: true},+ {name: "failed fallback", status: "failed", fallback: true, visible: true},+ {name: "completed fallback", status: "completed", fallback: true, visible: true},+ } {+ cols := testutil.Cols{"issue_id": issueID, "status": tc.status, "trigger_summary": tc.name, "runtime_id": runtimeID}+ if tc.fallback {+ cols["escalation_for_task_id"] = primaryID+ }+ if tc.dispatched {+ cols["dispatched_at"] = testutil.Raw("now()")+ }+ if tc.started {+ cols["started_at"] = testutil.Raw("now()")+ }+ id := dbfx.Task(t, agentID, cols)+ if tc.visible {+ want = append(want, id)+ }+ }+ sort.Strings(want)+ if got := taskIDs(runsRequest(t, issueID, "")); !sameIDs(got, want) {+ t.Errorf("issue history = %v, want %v (omit only unused assignee fallbacks)", got, want)+ }+ var agentRuns []AgentTaskResponse+ testutil.Call(t, testHandler.ListAgentTasks, withURLParam(+ newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks?include_usage=true", nil), "id", agentID,+ )).Want(http.StatusOK).JSON(&agentRuns)+ if got := taskIDs(agentRuns); !sameIDs(got, want) {+ t.Errorf("agent history = %v, want %v (same visibility as issue history)", got, want)+ }+}++func TestCancelCommentAssigneeFallbacksMigration(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ agentID := createHandlerTestAgent(t, "RetiredFallbackAgent", []byte("[]"))+ idleAgentID := createHandlerTestAgent(t, "UnusedFallbackAgent", []byte("[]"))+ idleIssueID := dbfx.Issue(t, "only unused fallback")+ idlePrimaryID := dbfx.Task(t, agentID, testutil.Cols{"issue_id": idleIssueID, "runtime_id": handlerTestRuntimeID(t), "status": "completed"})+ idleFallbackID := dbfx.Task(t, idleAgentID, testutil.Cols{+ "issue_id": idleIssueID, "runtime_id": handlerTestRuntimeID(t), "status": "dispatched",+ "dispatched_at": testutil.Raw("now()"), "escalation_for_task_id": idlePrimaryID,+ })+ if _, err := testPool.Exec(context.Background(), `UPDATE agent SET status = 'working' WHERE id IN ($1, $2)`, agentID, idleAgentID); err != nil {+ t.Fatal(err)+ }+ want := map[string]string{}+ want[idleFallbackID] = "cancelled"+ retryIssueID := dbfx.Issue(t, "unused fallback retry lineage")+ retryPrimaryID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": retryIssueID, "runtime_id": handlerTestRuntimeID(t), "status": "completed",+ })+ startedFallbackID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": retryIssueID, "runtime_id": handlerTestRuntimeID(t), "status": "failed",+ "started_at": testutil.Raw("now() - interval '2 minutes'"), "completed_at": testutil.Raw("now() - interval '1 minute'"),+ "escalation_for_task_id": retryPrimaryID,+ })+ startedRetryID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": retryIssueID, "runtime_id": handlerTestRuntimeID(t), "status": "failed",+ "started_at": testutil.Raw("now() - interval '1 minute'"), "completed_at": testutil.Raw("now()"),+ "parent_task_id": startedFallbackID, "retry_of_task_id": startedFallbackID,+ })+ pendingRetryID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": retryIssueID, "runtime_id": handlerTestRuntimeID(t), "status": "deferred",+ "fire_at": testutil.Raw("now() + interval '1 minute'"),+ "parent_task_id": startedRetryID, "retry_of_task_id": startedRetryID,+ })+ manualRerunID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": retryIssueID, "runtime_id": handlerTestRuntimeID(t), "status": "queued",+ "rerun_of_task_id": startedFallbackID,+ })+ mergedIssueID := dbfx.Issue(t, "fallback with merged comment")+ mergedPrimaryID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": mergedIssueID, "runtime_id": handlerTestRuntimeID(t), "status": "completed",+ })+ mergedOriginalCommentID := dbfx.Comment(t, mergedIssueID, "original fallback trigger")+ mergedTriggerCommentID := dbfx.Comment(t, mergedIssueID, "explicit assignee mention")+ mergedFallbackID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": mergedIssueID, "runtime_id": handlerTestRuntimeID(t), "status": "queued",+ "escalation_for_task_id": mergedPrimaryID, "trigger_comment_id": mergedTriggerCommentID,+ })+ dbfx.Exec(t, `UPDATE agent_task_queue SET coalesced_comment_ids = ARRAY[$2::uuid] WHERE id = $1`,+ mergedFallbackID, mergedOriginalCommentID)+ want[retryPrimaryID] = "completed"+ want[startedFallbackID] = "failed"+ want[startedRetryID] = "failed"+ want[pendingRetryID] = "cancelled"+ want[manualRerunID] = "queued"+ want[mergedPrimaryID] = "completed"+ want[mergedFallbackID] = "queued"+ for _, tc := range []struct {+ status string+ fallback bool+ started bool+ want string+ }{+ {status: "deferred", fallback: true, want: "cancelled"},+ {status: "queued", fallback: true, want: "cancelled"},+ {status: "dispatched", fallback: true, want: "cancelled"},+ {status: "waiting_local_directory", fallback: true, want: "cancelled"},+ {status: "running", fallback: true, started: true, want: "running"},+ {status: "completed", fallback: true, started: true, want: "completed"},+ {status: "failed", fallback: true, want: "failed"},+ {status: "cancelled", fallback: true, want: "cancelled"},+ {status: "deferred", want: "deferred"},+ {status: "queued", want: "queued"},+ } {+ issueID := dbfx.Issue(t, "retired fallback")+ primaryID := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "runtime_id": handlerTestRuntimeID(t), "status": "completed"})+ want[primaryID] = "completed"+ cols := testutil.Cols{"issue_id": issueID, "runtime_id": handlerTestRuntimeID(t), "status": tc.status}+ if tc.fallback {+ cols["escalation_for_task_id"] = primaryID+ }+ if tc.started {+ cols["started_at"] = testutil.Raw("now()")+ }+ want[dbfx.Task(t, agentID, cols)] = tc.want+ }+ sql, err := os.ReadFile("../../migrations/456_cancel_comment_assignee_fallbacks.up.sql")+ if err != nil {+ t.Fatal(err)+ }+ for range 2 {+ if _, err := testPool.Exec(context.Background(), string(sql)); err != nil {+ t.Fatal(err)+ }+ for id, status := range want {+ if got := taskStatusByID(t, id); got != status {+ t.Errorf("task %s status = %s, want %s", id, got, status)+ }+ }+ var retryFallbackID *string+ if err := testPool.QueryRow(context.Background(),+ `SELECT escalation_for_task_id FROM agent_task_queue WHERE id = $1`, pendingRetryID,+ ).Scan(&retryFallbackID); err != nil {+ t.Fatal(err)+ }+ if retryFallbackID == nil || *retryFallbackID != retryPrimaryID {+ t.Errorf("pending fallback retry escalation_for_task_id = %v, want %s", retryFallbackID, retryPrimaryID)+ }+ for _, id := range taskIDs(runsRequest(t, retryIssueID, "")) {+ if id == pendingRetryID {+ t.Errorf("cancelled fallback retry %s must be hidden from issue history", id)+ }+ }+ for id, wantStatus := range map[string]string{agentID: "working", idleAgentID: "idle"} {+ agent, err := testHandler.Queries.GetAgent(context.Background(), parseUUID(id))+ if err != nil {+ t.Fatal(err)+ }+ if agent.Status != wantStatus {+ t.Errorf("agent %s status = %s, want %s after retiring unused fallbacks", id, agent.Status, wantStatus)+ }+ }+ }+}+// active=true is the cheap "is an agent on this right now" read. It must drop// terminal runs and keep the whole in-flight set — including queued, which is// about to touch the same code even though it cannot answer you yet.diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex 5f7a103792..2d6c592eb0 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -263,6 +263,14 @@ multica issue runs <issue-id> --active --output json # in-flight runs on thimultica issue runs <issue-id> --siblings --output json # ...and across the sub-issue family```+Comment replies stay with the directly replied-to agent or the thread owner;+they never schedule a delayed run for the issue assignee. Waiting for an offline+or busy agent does not change the recipient. Explicitly @-mention another agent to+involve it. New top-level comments without a target still route to the assignee.+Issue and agent run history omit unused assignee fallbacks from older versions;+cancelled fallbacks are hidden even if dispatched, provided execution never+started. Ordinary cancellations and fallbacks that started remain visible.+`--active` drops the execution history and returns only `queued` / `dispatched`/ `running` / `waiting_local_directory` runs. `--siblings` widens the same readto the issue's family — its parent (or itself, when it has no parent) plus everydiff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 7355355dae..36711856b6 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1472,76 +1472,6 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issreturn task, nil}-// EnqueueDeferredAssigneeFallback creates an inert task that becomes claimable-// only after PromoteDueDeferredTasksForRuntime flips it from deferred to queued.-func (s *TaskService) EnqueueDeferredAssigneeFallback(ctx context.Context, issue db.Issue, agentID, squadID pgtype.UUID, escalationForTaskID pgtype.UUID, triggerCommentID pgtype.UUID, fireAt time.Time) (db.AgentTaskQueue, error) {- agent, err := s.Queries.GetAgent(ctx, agentID)- if err != nil {- slog.Error("deferred fallback enqueue failed: agent not found", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)- return db.AgentTaskQueue{}, fmt.Errorf("load agent: %w", err)- }- if agent.ArchivedAt.Valid {- slog.Debug("deferred fallback enqueue skipped: agent is archived", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))- return db.AgentTaskQueue{}, fmt.Errorf("agent is archived")- }- if !agent.RuntimeID.Valid {- slog.Error("deferred fallback enqueue failed: agent has no runtime", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))- return db.AgentTaskQueue{}, fmt.Errorf("agent has no runtime")- }-- // The fallback assignee is reacting to the same trigger comment as the primary- // routed task, so resolve attribution from that comment (member author →- // direct_human; agent author → comment_source chain) and stamp it at creation.- // Promotion later only flips status, so stamping here keeps the eventual run- // off the NULL-source bypass (MUL-4302 §2). Overlay is intentionally left for- // the existing promotion path — this change is attribution-only. No direct- // actor here: the fallback is comment-routed, so attribution rides the comment.- attr := s.attributionForIssueTask(ctx, issue, triggerCommentID, attribution.SourceCommentSource, pgtype.UUID{})- // No precise human resolved → owner_fallback (accountable = agent owner), or- // refuse if the workspace is fail-closed (MUL-4302 §3.5).- attr, err = s.applyAttributionFallback(ctx, attr, agent)- if err != nil {- slog.Warn("deferred fallback enqueue refused: attribution fail-closed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))- return db.AgentTaskQueue{}, err- }- attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)- isLeader := squadID.Valid- task, err := s.Queries.CreateDeferredAgentTask(ctx, db.CreateDeferredAgentTaskParams{- ID: dbid.NewV7(),- AgentID: agentID,- RuntimeID: agent.RuntimeID,- IssueID: issue.ID,- Priority: priorityToInt(issue.Priority),- TriggerCommentID: triggerCommentID,- TriggerSummary: s.buildCommentTriggerSummary(ctx, issue.WorkspaceID, triggerCommentID),- IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},- SquadID: squadID,- EscalationForTaskID: escalationForTaskID,- FireAt: pgtype.Timestamptz{Time: fireAt, Valid: true},- OriginatorUserID: attr.UserID,- AccountableUserID: attr.AccountableUserID,- OriginatorSource: attrSource,- DelegatedFromTaskID: attrDelegatedFrom,- TriggerEvidenceKind: attrEvidenceKind,- TriggerEvidenceRefID: attrEvidenceRef,- })- if err != nil {- slog.Error("deferred fallback enqueue failed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)- return db.AgentTaskQueue{}, fmt.Errorf("create deferred task: %w", err)- }-- slog.Info("deferred fallback task enqueued",- "task_id", util.UUIDToString(task.ID),- "issue_id", util.UUIDToString(issue.ID),- "agent_id", util.UUIDToString(agentID),- "fire_at", fireAt.UTC().Format(time.RFC3339),- )- // Refresh the daemon's durable deferred schedule after the insert commits.- // An empty task ID means "claim to refresh state", not "this task is ready".- s.notifyRuntimeMayHaveWork(task.RuntimeID, "")- return task, nil-}-// QuickCreateContext is the JSON payload stored on a quick-create task's// context column. The daemon detects this variant via Type == "quick_create"// and switches to the quick-create prompt template; the completion path@@ -3888,7 +3818,7 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgreturn nil, fmt.Errorf("promote deferred tasks: %w", err)}for _, task := range promoted {- slog.Info("deferred fallback task promoted (batch)",+ slog.Info("deferred task promoted (batch)","task_id", util.UUIDToString(task.ID),"runtime_id", util.UUIDToString(task.RuntimeID),"agent_id", util.UUIDToString(task.AgentID),@@ -4082,7 +4012,7 @@ func (s *TaskService) PromoteDueDeferredTasksForRuntime(ctx context.Context, runreturn fmt.Errorf("promote due deferred tasks: %w", err)}for _, task := range tasks {- slog.Info("deferred fallback task promoted",+ slog.Info("deferred task promoted","task_id", util.UUIDToString(task.ID),"runtime_id", util.UUIDToString(runtimeID),"agent_id", util.UUIDToString(task.AgentID),@@ -4124,7 +4054,6 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Agreturn nil, fmt.Errorf("start task: %w", err)}s.forgetTaskReclaim(task)- s.cancelDeferredEscalationsForTask(ctx, task.ID)slog.Info("task started", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))s.captureTaskStarted(ctx, task)@@ -4143,43 +4072,6 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Agreturn &task, nil}-func (s *TaskService) cancelDeferredEscalationsForTask(ctx context.Context, taskID pgtype.UUID) {- cancelled, err := s.Queries.CancelDeferredEscalationsForTask(ctx, taskID)- if err != nil {- slog.Warn("cancel deferred escalations for task failed", "task_id", util.UUIDToString(taskID), "error", err)- return- }- for _, task := range cancelled {- slog.Info("deferred fallback task cancelled",- "task_id", util.UUIDToString(task.ID),- "primary_task_id", util.UUIDToString(taskID),- "reason", "primary_acknowledged",- )- }-}--func (s *TaskService) CancelDeferredEscalationsForIssueAgent(ctx context.Context, issueID, agentID pgtype.UUID) {- cancelled, err := s.Queries.CancelDeferredEscalationsForIssueAgent(ctx, db.CancelDeferredEscalationsForIssueAgentParams{- IssueID: issueID,- AgentID: agentID,- })- if err != nil {- slog.Warn("cancel deferred escalations for issue agent failed",- "issue_id", util.UUIDToString(issueID),- "agent_id", util.UUIDToString(agentID),- "error", err)- return- }- for _, task := range cancelled {- slog.Info("deferred fallback task cancelled",- "task_id", util.UUIDToString(task.ID),- "issue_id", util.UUIDToString(issueID),- "agent_id", util.UUIDToString(agentID),- "reason", "agent_comment_acknowledged",- )- }-}-// ExtendTaskPrepareLease keeps a claimed-but-not-started task protected while// the daemon resolves cached inputs and prepares the execution environment.func (s *TaskService) ExtendTaskPrepareLease(ctx context.Context, taskID, runtimeID pgtype.UUID) (*db.AgentTaskQueue, error) {@@ -7252,7 +7144,6 @@ func (s *TaskService) createAgentComment(ctx context.Context, issueID, agentID preturn}comment := created.Comment()- s.CancelDeferredEscalationsForIssueAgent(ctx, issueID, agentID)commentFields := commentEventFields(comment)commentFields["revision"] = comment.Revisions.Bus.Publish(events.Event{diff --git a/server/internal/service/task_notify_test.go b/server/internal/service/task_notify_test.goindex 642a8bb12b..76ceb27862 100644--- a/server/internal/service/task_notify_test.go+++ b/server/internal/service/task_notify_test.go@@ -6,7 +6,6 @@ import ("time""github.com/jackc/pgx/v5/pgtype"- "github.com/multica-ai/multica/server/internal/testutil""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -30,43 +29,6 @@ func TestTaskClaimableWaitSecondsExcludesDeferredDelay(t *testing.T) {}}-func TestEnqueueDeferredAssigneeFallbackRefreshesRuntimeSchedule(t *testing.T) {- pool := newResolveOriginatorPool(t)- ctx := context.Background()- q := db.New(pool)- workspaceID, userID, agentID, issueID := seedAttributionFixture(t, pool)- fx := testutil.New(pool, workspaceID, userID)- triggerCommentID := fx.Comment(t, issueID, "fallback trigger")- agent, err := q.GetAgent(ctx, util.MustParseUUID(agentID))- if err != nil {- t.Fatalf("GetAgent: %v", err)- }- primaryTaskID := fx.Task(t, agentID, testutil.Cols{- "runtime_id": util.UUIDToString(agent.RuntimeID),- "issue_id": issueID,- "status": "running",- "trigger_comment_id": triggerCommentID,- })- issue, err := q.GetIssue(ctx, util.MustParseUUID(issueID))- if err != nil {- t.Fatalf("GetIssue: %v", err)- }- wakeup := &stubWakeup{}- svc := &TaskService{Queries: q, TxStarter: pool, Wakeup: wakeup}-- task, err := svc.EnqueueDeferredAssigneeFallback(ctx, issue, util.MustParseUUID(agentID), pgtype.UUID{}, util.MustParseUUID(primaryTaskID), util.MustParseUUID(triggerCommentID), time.Now().Add(time.Minute))- if err != nil {- t.Fatalf("EnqueueDeferredAssigneeFallback: %v", err)- }- fx.Cleanup(t, `DELETE FROM agent_task_queue WHERE id = $1`, task.ID)- if task.Status != "deferred" || len(wakeup.calls) != 1 {- t.Fatalf("fallback task/status wakeups = %q/%+v, want deferred with one schedule refresh", task.Status, wakeup.calls)- }- if wakeup.calls[0].runtimeID != util.UUIDToString(task.RuntimeID) || wakeup.calls[0].taskID != "" {- t.Fatalf("fallback schedule wakeup = %+v, want runtime %s without task id", wakeup.calls[0], util.UUIDToString(task.RuntimeID))- }-}-// stubWakeup records every call so the test can assert that notify// reaches the daemon hub and carries the right runtime / task IDs.type stubWakeup struct {diff --git a/server/migrations/456_cancel_comment_assignee_fallbacks.down.sql b/server/migrations/456_cancel_comment_assignee_fallbacks.down.sqlnew file mode 100644index 0000000000..84bb2f9c95--- /dev/null+++ b/server/migrations/456_cancel_comment_assignee_fallbacks.down.sql@@ -0,0 +1,2 @@+-- Cancellation is irreversible: rollback must not resurrect stale replies.+SELECT 1;diff --git a/server/migrations/456_cancel_comment_assignee_fallbacks.up.sql b/server/migrations/456_cancel_comment_assignee_fallbacks.up.sqlnew file mode 100644index 0000000000..c9f2ec3637--- /dev/null+++ b/server/migrations/456_cancel_comment_assignee_fallbacks.up.sql@@ -0,0 +1,63 @@+-- Comment replies no longer escalate to the issue assignee. Retire old+-- fallback tasks and their automatic retries that have not started; preserve+-- running tasks, completed history, and user-requested reruns.+-- Stop old API instances before running this one-time cleanup: they can still+-- enqueue new fallback rows after it finishes. The Helm Recreate deployment+-- and migrate-before-server entrypoint provide this ordering.+WITH RECURSIVE fallback_lineage AS (+ SELECT task.id AS task_id,+ task.escalation_for_task_id,+ ARRAY[task.id] AS path+ FROM agent_task_queue task+ WHERE task.escalation_for_task_id IS NOT NULL+ -- CreateDeferredAgentTask never set retry_of_task_id. Excluding retry+ -- descendants backfilled by an earlier idempotent run keeps one root per+ -- lineage instead of rediscovering every suffix as a separate tree.+ AND task.retry_of_task_id IS NULL++ UNION ALL++ -- CreateRetryTask stores both links to the same immediate parent but does+ -- not copy escalation_for_task_id. Following the indexed parent_task_id+ -- finds descendants without scanning the whole queue; retry_of_task_id+ -- keeps user-requested reruns outside this cleanup.+ SELECT retry.id,+ lineage.escalation_for_task_id,+ lineage.path || retry.id+ FROM fallback_lineage lineage+ JOIN agent_task_queue retry+ ON retry.parent_task_id = lineage.task_id+ AND retry.retry_of_task_id = lineage.task_id+ -- Stored retry links should be acyclic, but corrupt historical data must+ -- not make a startup migration recurse forever.+ WHERE NOT retry.id = ANY(lineage.path)+), cancelled AS (+ UPDATE agent_task_queue task+ SET status = 'cancelled',+ completed_at = now(),+ prepare_lease_expires_at = NULL,+ escalation_for_task_id = fallback_lineage.escalation_for_task_id+ FROM fallback_lineage+ WHERE task.id = fallback_lineage.task_id+ AND task.started_at IS NULL+ -- An unstarted fallback may have absorbed newer comments while queued.+ -- Preserve it so those merged instructions still receive their run.+ AND cardinality(task.coalesced_comment_ids) = 0+ AND task.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')+ RETURNING task.id, task.agent_id+), desired AS (+ SELECT DISTINCT cancelled.agent_id,+ CASE WHEN EXISTS (+ SELECT 1 FROM agent_task_queue task+ WHERE task.agent_id = cancelled.agent_id+ AND task.status IN ('dispatched', 'running')+ -- Data-modifying CTEs share a snapshot. Exclude the returned+ -- rows explicitly rather than reading their old task status.+ AND NOT EXISTS (SELECT 1 FROM cancelled c WHERE c.id = task.id)+ ) THEN 'working' ELSE 'idle' END AS status+ FROM cancelled+)+UPDATE agent+SET status = desired.status, updated_at = now()+FROM desired+WHERE agent.id = desired.agent_id AND agent.status IS DISTINCT FROM desired.status;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex b2ff477a13..90e83dedda 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -936,243 +936,6 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerCreturn items, nil}-const cancelDeferredEscalationsForIssueAgent = `-- name: CancelDeferredEscalationsForIssueAgent :many-WITH cancelled AS (- UPDATE agent_task_queue fallback- SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL- FROM agent_task_queue primary_task- WHERE fallback.escalation_for_task_id = primary_task.id- AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')- AND primary_task.issue_id = $1- AND primary_task.agent_id = $2- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.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, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id, fallback.quick_actions_disabled, fallback.regenerate_quick_actions_for, fallback.branch_name, fallback.durable_work_dir, fallback.channel_context_revision, fallback.comment_thread_id-)-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, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id FROM cancelled-`--type CancelDeferredEscalationsForIssueAgentParams struct {- IssueID pgtype.UUID `json:"issue_id"`- AgentID pgtype.UUID `json:"agent_id"`-}--type CancelDeferredEscalationsForIssueAgentRow struct {- ID pgtype.UUID `json:"id"`- AgentID pgtype.UUID `json:"agent_id"`- IssueID pgtype.UUID `json:"issue_id"`- Status string `json:"status"`- Priority int32 `json:"priority"`- DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`- StartedAt pgtype.Timestamptz `json:"started_at"`- CompletedAt pgtype.Timestamptz `json:"completed_at"`- Result []byte `json:"result"`- Error pgtype.Text `json:"error"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- Context []byte `json:"context"`- RuntimeID pgtype.UUID `json:"runtime_id"`- SessionID pgtype.Text `json:"session_id"`- WorkDir pgtype.Text `json:"work_dir"`- TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`- ChatSessionID pgtype.UUID `json:"chat_session_id"`- AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`- Attempt int32 `json:"attempt"`- MaxAttempts int32 `json:"max_attempts"`- ParentTaskID pgtype.UUID `json:"parent_task_id"`- FailureReason pgtype.Text `json:"failure_reason"`- TriggerSummary pgtype.Text `json:"trigger_summary"`- ForceFreshSession bool `json:"force_fresh_session"`- IsLeaderTask bool `json:"is_leader_task"`- WaitReason pgtype.Text `json:"wait_reason"`- InitiatorUserID pgtype.UUID `json:"initiator_user_id"`- HandoffNote pgtype.Text `json:"handoff_note"`- PrepareLeaseExpiresAt pgtype.Timestamptz `json:"prepare_lease_expires_at"`- SquadID pgtype.UUID `json:"squad_id"`- RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`- EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`- FireAt pgtype.Timestamptz `json:"fire_at"`- OriginatorUserID pgtype.UUID `json:"originator_user_id"`- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`- CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`- DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`- ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`- ChatFinalizeDeferredAt pgtype.Timestamptz `json:"chat_finalize_deferred_at"`- OriginatorSource pgtype.Text `json:"originator_source"`- DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`- RetryOfTaskID pgtype.UUID `json:"retry_of_task_id"`- RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`- RuleVersionID pgtype.UUID `json:"rule_version_id"`- TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`- TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`- AccountableUserID pgtype.UUID `json:"accountable_user_id"`- SessionRolloutMissing bool `json:"session_rollout_missing"`- RetiredSessionID pgtype.Text `json:"retired_session_id"`- QuickActionsDisabled bool `json:"quick_actions_disabled"`- RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`- BranchName pgtype.Text `json:"branch_name"`- DurableWorkDir pgtype.Text `json:"durable_work_dir"`- ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`- CommentThreadID pgtype.UUID `json:"comment_thread_id"`-}--func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {- rows, err := q.db.Query(ctx, cancelDeferredEscalationsForIssueAgent, arg.IssueID, arg.AgentID)- if err != nil {- return nil, err- }- defer rows.Close()- items := []CancelDeferredEscalationsForIssueAgentRow{}- for rows.Next() {- var i CancelDeferredEscalationsForIssueAgentRow- if err := rows.Scan(- &i.ID,- &i.AgentID,- &i.IssueID,- &i.Status,- &i.Priority,- &i.DispatchedAt,- &i.StartedAt,- &i.CompletedAt,- &i.Result,- &i.Error,- &i.CreatedAt,- &i.Context,- &i.RuntimeID,- &i.SessionID,- &i.WorkDir,- &i.TriggerCommentID,- &i.ChatSessionID,- &i.AutopilotRunID,- &i.Attempt,- &i.MaxAttempts,- &i.ParentTaskID,- &i.FailureReason,- &i.TriggerSummary,- &i.ForceFreshSession,- &i.IsLeaderTask,- &i.WaitReason,- &i.InitiatorUserID,- &i.HandoffNote,- &i.PrepareLeaseExpiresAt,- &i.SquadID,- &i.RuntimeMcpOverlay,- &i.EscalationForTaskID,- &i.FireAt,- &i.OriginatorUserID,- &i.RuntimeConnectedApps,- &i.CoalescedCommentIds,- &i.DeliveredCommentIds,- &i.ChatInputTaskID,- &i.ChatFinalizeDeferredAt,- &i.OriginatorSource,- &i.DelegatedFromTaskID,- &i.RetryOfTaskID,- &i.RerunOfTaskID,- &i.RuleVersionID,- &i.TriggerEvidenceKind,- &i.TriggerEvidenceRefID,- &i.AccountableUserID,- &i.SessionRolloutMissing,- &i.RetiredSessionID,- &i.QuickActionsDisabled,- &i.RegenerateQuickActionsFor,- &i.BranchName,- &i.DurableWorkDir,- &i.ChannelContextRevision,- &i.CommentThreadID,- ); err != nil {- return nil, err- }- items = append(items, i)- }- if err := rows.Err(); err != nil {- return nil, err- }- return items, nil-}--const cancelDeferredEscalationsForTask = `-- name: CancelDeferredEscalationsForTask :many-UPDATE agent_task_queue-SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL-WHERE escalation_for_task_id = $1- AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id-`--func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {- rows, err := q.db.Query(ctx, cancelDeferredEscalationsForTask, escalationForTaskID)- if err != nil {- return nil, err- }- defer rows.Close()- items := []AgentTaskQueue{}- for rows.Next() {- var i AgentTaskQueue- if err := rows.Scan(- &i.ID,- &i.AgentID,- &i.IssueID,- &i.Status,- &i.Priority,- &i.DispatchedAt,- &i.StartedAt,- &i.CompletedAt,- &i.Result,- &i.Error,- &i.CreatedAt,- &i.Context,- &i.RuntimeID,- &i.SessionID,- &i.WorkDir,- &i.TriggerCommentID,- &i.ChatSessionID,- &i.AutopilotRunID,- &i.Attempt,- &i.MaxAttempts,- &i.ParentTaskID,- &i.FailureReason,- &i.TriggerSummary,- &i.ForceFreshSession,- &i.IsLeaderTask,- &i.WaitReason,- &i.InitiatorUserID,- &i.HandoffNote,- &i.PrepareLeaseExpiresAt,- &i.SquadID,- &i.RuntimeMcpOverlay,- &i.EscalationForTaskID,- &i.FireAt,- &i.OriginatorUserID,- &i.RuntimeConnectedApps,- &i.CoalescedCommentIds,- &i.DeliveredCommentIds,- &i.ChatInputTaskID,- &i.ChatFinalizeDeferredAt,- &i.OriginatorSource,- &i.DelegatedFromTaskID,- &i.RetryOfTaskID,- &i.RerunOfTaskID,- &i.RuleVersionID,- &i.TriggerEvidenceKind,- &i.TriggerEvidenceRefID,- &i.AccountableUserID,- &i.SessionRolloutMissing,- &i.RetiredSessionID,- &i.QuickActionsDisabled,- &i.RegenerateQuickActionsFor,- &i.BranchName,- &i.DurableWorkDir,- &i.ChannelContextRevision,- &i.CommentThreadID,- ); err != nil {- return nil, err- }- items = append(items, i)- }- if err := rows.Err(); err != nil {- return nil, err- }- return items, nil-}-const cancelPendingTasksByIssueAndAgent = `-- name: CancelPendingTasksByIssueAndAgent :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL@@ -1563,7 +1326,6 @@ WHERE r.runtime_id = ANY($1::uuid[])AND r.status = 'deferred'AND r.issue_id IS NOT NULLAND r.retry_of_task_id IS NOT NULL- AND r.escalation_for_task_id IS NULLAND COALESCE(r.context->>'channel_issue_media_pending', '') <> 'true'AND EXISTS (SELECT 1 FROM agent_task_queue successor@@ -1591,8 +1353,6 @@ RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, c//// Scope is deliberately tight:// - retry_of_task_id IS NOT NULL — only auto-retry clones, never a fresh run.-// - escalation_for_task_id IS NULL — assignee-fallback escalations own their-// fire_at lifecycle and are SUPPOSED to coexist with an active primary.// - channel-media pending rows are excluded for the same reason: that deferred// row is the issue's own task waiting on media, not a superseded retry.// - issue_id IS NOT NULL — chat / quick-create tasks have no slot semantics.@@ -2558,151 +2318,6 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParamsreturn i, err}-const createDeferredAgentTask = `-- name: CreateDeferredAgentTask :one-INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,- trigger_summary, is_leader_task, squad_id, escalation_for_task_id, fire_at,- originator_user_id, accountable_user_id, originator_source,- delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id,- id-)-SELECT- $4, $5, $6, 'deferred', $7,- $8,- $9,- COALESCE($10::boolean, FALSE),- $11,- $12,- $13,- $14,- $15,- $16,- $17,- $18,- $19,- COALESCE($20::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, $3, $2)-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, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id-`--type CreateDeferredAgentTaskParams struct {- PAgentID pgtype.UUID `json:"p_agent_id"`- PRuntimeID pgtype.UUID `json:"p_runtime_id"`- PIssueID pgtype.UUID `json:"p_issue_id"`- AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`- IssueID pgtype.UUID `json:"issue_id"`- Priority int32 `json:"priority"`- TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`- TriggerSummary pgtype.Text `json:"trigger_summary"`- IsLeaderTask pgtype.Bool `json:"is_leader_task"`- SquadID pgtype.UUID `json:"squad_id"`- EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`- FireAt pgtype.Timestamptz `json:"fire_at"`- OriginatorUserID pgtype.UUID `json:"originator_user_id"`- AccountableUserID pgtype.UUID `json:"accountable_user_id"`- OriginatorSource pgtype.Text `json:"originator_source"`- DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`- TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`- TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`- ID pgtype.UUID `json:"id"`-}--// Fenced against workspace teardown: lock_task_owner_rows (migration 284)-// locks the owners' workspace rows in the writer's own transaction and returns-// false once they are gone, so this statement writes no row instead of stranding-// a task in a workspace that has just been deleted (MUL-5999).-// Deferred tasks are inert until PromoteDueDeferredTasksForRuntime flips them-// to queued. Used for comment-routing escalation: a thread-owner primary task-// gets a delayed assignee fallback without waking both agents at t=0.-// Attribution is resolved and stamped at creation (not at promotion), from the-// same trigger comment as the primary task, so the fallback assignee's run-// carries a non-NULL source and evidence rather than bypassing attribution-// (MUL-4302 §2).-func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferredAgentTaskParams) (AgentTaskQueue, error) {- row := q.db.QueryRow(ctx, createDeferredAgentTask,- arg.PAgentID,- arg.PRuntimeID,- arg.PIssueID,- arg.AgentID,- arg.RuntimeID,- arg.IssueID,- arg.Priority,- arg.TriggerCommentID,- arg.TriggerSummary,- arg.IsLeaderTask,- arg.SquadID,- arg.EscalationForTaskID,- arg.FireAt,- arg.OriginatorUserID,- arg.AccountableUserID,- arg.OriginatorSource,- arg.DelegatedFromTaskID,- arg.TriggerEvidenceKind,- arg.TriggerEvidenceRefID,- arg.ID,- )- 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,- &i.ChatInputTaskID,- &i.ChatFinalizeDeferredAt,- &i.OriginatorSource,- &i.DelegatedFromTaskID,- &i.RetryOfTaskID,- &i.RerunOfTaskID,- &i.RuleVersionID,- &i.TriggerEvidenceKind,- &i.TriggerEvidenceRefID,- &i.AccountableUserID,- &i.SessionRolloutMissing,- &i.RetiredSessionID,- &i.QuickActionsDisabled,- &i.RegenerateQuickActionsFor,- &i.BranchName,- &i.DurableWorkDir,- &i.ChannelContextRevision,- &i.CommentThreadID,- )- return i, err-}-const createDeferredChannelIssueTask = `-- name: CreateDeferredChannelIssueTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 10ab9740da..826b8e4297 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -425,43 +425,6 @@ SELECTWHERE lock_task_owner_rows($1, NULL, $2)RETURNING *;--- name: CreateDeferredAgentTask :one--- Fenced against workspace teardown: lock_task_owner_rows (migration 284)--- locks the owners' workspace rows in the writer's own transaction and returns--- false once they are gone, so this statement writes no row instead of stranding--- a task in a workspace that has just been deleted (MUL-5999).--- Deferred tasks are inert until PromoteDueDeferredTasksForRuntime flips them--- to queued. Used for comment-routing escalation: a thread-owner primary task--- gets a delayed assignee fallback without waking both agents at t=0.--- Attribution is resolved and stamped at creation (not at promotion), from the--- same trigger comment as the primary task, so the fallback assignee's run--- carries a non-NULL source and evidence rather than bypassing attribution--- (MUL-4302 §2).-INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,- trigger_summary, is_leader_task, squad_id, escalation_for_task_id, fire_at,- originator_user_id, accountable_user_id, originator_source,- delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id,- id-)-SELECT- @agent_id, @runtime_id, @issue_id, 'deferred', @priority,- sqlc.narg(trigger_comment_id),- sqlc.narg(trigger_summary),- COALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),- sqlc.narg(squad_id),- @escalation_for_task_id,- @fire_at,- sqlc.narg(originator_user_id),- sqlc.narg(accountable_user_id),- sqlc.narg(originator_source),- sqlc.narg(delegated_from_task_id),- sqlc.narg(trigger_evidence_kind),- sqlc.narg(trigger_evidence_ref_id),- COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())-WHERE lock_task_owner_rows($1, $3, $2)-RETURNING *;--- name: LinkTaskToIssue :exec-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)-- locks the owners' workspace rows in the writer's own transaction and returns@@ -2262,8 +2225,6 @@ ORDER BY atq.priority DESC, atq.created_at ASC;---- Scope is deliberately tight:-- * retry_of_task_id IS NOT NULL — only auto-retry clones, never a fresh run.--- * escalation_for_task_id IS NULL — assignee-fallback escalations own their--- fire_at lifecycle and are SUPPOSED to coexist with an active primary.-- * channel-media pending rows are excluded for the same reason: that deferred-- row is the issue's own task waiting on media, not a superseded retry.-- * issue_id IS NOT NULL — chat / quick-create tasks have no slot semantics.@@ -2277,7 +2238,6 @@ WHERE r.runtime_id = ANY(@runtime_ids::uuid[])AND r.status = 'deferred'AND r.issue_id IS NOT NULLAND r.retry_of_task_id IS NOT NULL- AND r.escalation_for_task_id IS NULLAND COALESCE(r.context->>'channel_issue_media_pending', '') <> 'true'AND EXISTS (SELECT 1 FROM agent_task_queue successor@@ -2449,26 +2409,6 @@ SET status = 'queued'WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)RETURNING *;--- name: CancelDeferredEscalationsForTask :many-UPDATE agent_task_queue-SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL-WHERE escalation_for_task_id = $1- AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')-RETURNING *;---- name: CancelDeferredEscalationsForIssueAgent :many-WITH cancelled AS (- UPDATE agent_task_queue fallback- SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL- FROM agent_task_queue primary_task- WHERE fallback.escalation_for_task_id = primary_task.id- AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')- AND primary_task.issue_id = @issue_id- AND primary_task.agent_id = @agent_id- RETURNING fallback.*-)-SELECT * FROM cancelled;--- name: ListActiveTasksByIssue :many-- Backs the issue-detail "agent live" banner. Includes 'queued' so the-- banner shows up the moment a task is enqueued — not only after a runtime