Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6063: recover terminal delegated task failures (#6844)
Multica Eveafd05ca22175
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 0333ed01fb..095484f889 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -194,6 +194,7 @@ var concurrentIndexCleanups = map[string]string{"333_issue_status_pkey_index": "issue_status_pkey_uidx","335_issue_status_workspace_key_index": "idx_issue_status_workspace_key","336_issue_status_workspace_name_index": "idx_issue_status_workspace_name_active",+ "343_comment_delegated_failure_pending_index": "idx_comment_delegated_failure_pending",}// concurrentDownIndexCleanups covers every migration whose down directiondiff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.goindex 857d80b78b..f42aa160b0 100644--- a/server/cmd/server/runtime_sweeper.go+++ b/server/cmd/server/runtime_sweeper.go@@ -104,6 +104,9 @@ const (chatFinalizeGraceSeconds = 60.0// chatFinalizeBatchSize caps deferred finalizations per tick.chatFinalizeBatchSize = 100+ // delegatedFailureRecoveryBatchSize bounds the durable recovery-outbox+ // replay so a historical backlog cannot monopolise the runtime sweep tick.+ delegatedFailureRecoveryBatchSize = 100)type runtimeGCTxStarter interface {@@ -135,12 +138,35 @@ func runRuntimeSweeper(ctx context.Context, txStarter runtimeGCTxStarter, queriesweepExpiredRuntimeReconnectRetries(ctx, queries, taskSvc, reconnectGrace)sweepStaleTasks(ctx, queries, taskSvc, bus, reconnectGrace)sweepExpiredQueuedTasks(ctx, queries, taskSvc)+ sweepPendingDelegatedFailureRecoveries(ctx, taskSvc)sweepDeferredChatFinalizations(ctx, queries, taskSvc)gcRuntimes(ctx, txStarter, queries, taskSvc.Metrics, bus)}}}+// sweepPendingDelegatedFailureRecoveries retries durable coordinator handoffs+// that were not acquired by an executable task. It runs even when no stale+// task was found in this tick, which is what repairs a recovery dispatch lost+// before a server restart.+func sweepPendingDelegatedFailureRecoveries(ctx context.Context, taskSvc *service.TaskService) {+ result, err := taskSvc.RecoverPendingDelegatedFailures(ctx, delegatedFailureRecoveryBatchSize)+ if err != nil {+ slog.Warn("delegated failure recovery sweeper: replay failed",+ "replayed", result.Replayed,+ "exhausted", result.Exhausted,+ "error", err,+ )+ return+ }+ if result.Replayed > 0 {+ slog.Info("delegated failure recovery sweeper: replayed pending recoveries", "count", result.Replayed)+ }+ if result.Exhausted > 0 {+ slog.Warn("delegated failure recovery sweeper: automatic attempts exhausted", "count", result.Exhausted)+ }+}+// sweepStaleRuntimes marks runtimes offline if they haven't heartbeated. Task// termination is a separate every-tick stage so reconnect grace is measured// independently of the one tick where the runtime first flips offline.diff --git a/server/internal/attribution/attribution.go b/server/internal/attribution/attribution.goindex 78bb575139..3da1b2592b 100644--- a/server/internal/attribution/attribution.go+++ b/server/internal/attribution/attribution.go@@ -99,6 +99,9 @@ const (EvidenceAutopilotRun EvidenceKind = "autopilot_run"EvidenceRuleVersion EvidenceKind = "rule_version"EvidenceRerun EvidenceKind = "rerun"+ // EvidenceDelegatedFailure points at the terminal worker task that handed+ // control back to its source coordinator.+ EvidenceDelegatedFailure EvidenceKind = "delegated_failure"// EvidenceChat points the uniform evidence pair at the chat session that// triggered the run — the chat analogue of autopilot_run/issue_assignment.// The dedicated chat_session_id column still exists for its own consumers;diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex 749167c022..bf2fdad90d 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -294,7 +294,9 @@ func buildCommentPrompt(task Task, provider string) string {b.WriteString(turnModeReply)if task.TriggerCommentContent != "" {authorLabel := "A user"- if task.TriggerAuthorType == "agent" {+ if task.TriggerAuthorType == "system" {+ authorLabel = "The platform"+ } else if task.TriggerAuthorType == "agent" {name := task.TriggerAuthorNameif name == "" {name = "another agent"@@ -315,7 +317,9 @@ func buildCommentPrompt(task Task, provider string) string {fmt.Fprintf(&b, "This run also covers %d earlier comment(s) posted before it started — you must read and address them too, not just the one above. They may be in different threads, so each is reproduced here with its own thread:\n\n", len(task.CoalescedComments))for _, cc := range task.CoalescedComments {authorLabel := "A user"- if cc.AuthorType == "agent" {+ if cc.AuthorType == "system" {+ authorLabel = "The platform"+ } else if cc.AuthorType == "agent" {name := cc.AuthorNameif name == "" {name = "another agent"diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.goindex 319e34938f..4a37390370 100644--- a/server/internal/daemon/prompt_test.go+++ b/server/internal/daemon/prompt_test.go@@ -1242,6 +1242,22 @@ func TestBuildCommentPromptCoalescedCrossThread(t *testing.T) {}}+func TestBuildCommentPromptLabelsDelegatedFailureSignalAsPlatform(t *testing.T) {+ task := Task{+ IssueID: "issue-recovery-1",+ TriggerCommentID: "recovery-comment-1",+ TriggerCommentContent: "Delegated task failed; resume coordination.",+ TriggerAuthorType: "system",+ }+ out := BuildPrompt(task, "codex")+ if !strings.Contains(out, "[NEW COMMENT] The platform just left a new comment") {+ t.Fatalf("system recovery comment was mislabeled in prompt:\n%s", out)+ }+ if strings.Contains(out, "[NEW COMMENT] A user just left a new comment") {+ t.Fatalf("system recovery comment must not be labeled as a user:\n%s", out)+ }+}+// TestBuildCommentPromptCoalescedIDsOnlyFallback pins the old-server fallback:// when only coalesced ids are shipped (no embedded detail), the prompt must// still NOT assume a shared thread, and must reach the ids through a BOUNDEDdiff --git a/server/internal/handler/cancel_task_by_user_test.go b/server/internal/handler/cancel_task_by_user_test.goindex 35b32a94e0..ed75f7e118 100644--- a/server/internal/handler/cancel_task_by_user_test.go+++ b/server/internal/handler/cancel_task_by_user_test.go@@ -617,6 +617,78 @@ func TestCancelTaskByUser_IssueTask_Succeeds(t *testing.T) {}}+func TestCancelTaskByUser_DelegatedFailureRecoveryAcknowledgesSignal(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ agentID := createHandlerTestAgent(t, "CancelRecoveryTaskAgent", []byte("[]"))+ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES ($1, 'cancel-recovery-task', 'in_progress', 'medium', $2, 'member', 92004, 0)+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })++ var sourceTaskID, failedTaskID, recoveryCommentID, recoveryTaskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, completed_at)+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'completed', 0, now())+ RETURNING id+ `, agentID, issueID).Scan(&sourceTaskID); err != nil {+ t.Fatalf("create source task: %v", err)+ }+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, completed_at,+ delegated_from_task_id, trigger_evidence_kind+ )+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'failed', 0, now(), $3, 'comment')+ RETURNING id+ `, agentID, issueID, sourceTaskID).Scan(&failedTaskID); err != nil {+ t.Fatalf("create failed task: %v", err)+ }+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, source_task_id)+ VALUES ($1, $2, 'system', $3, 'resume delegated coordination', 'progress_update', $4)+ RETURNING id+ `, issueID, testWorkspaceID, testUserID, failedTaskID).Scan(&recoveryCommentID); err != nil {+ t.Fatalf("create recovery comment: %v", err)+ }+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,+ trigger_evidence_kind, trigger_evidence_ref_id+ )+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3,+ 'delegated_failure', $4)+ RETURNING id+ `, agentID, issueID, recoveryCommentID, failedTaskID).Scan(&recoveryTaskID); err != nil {+ t.Fatalf("create recovery task: %v", err)+ }++ w := httptest.NewRecorder()+ testHandler.CancelTaskByUser(w, cancelTaskByUserRequest(t, testUserID, recoveryTaskID))+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var status string+ var acknowledged bool+ if err := testPool.QueryRow(ctx, `+ SELECT status, $2::uuid = ANY(delivered_comment_ids)+ FROM agent_task_queue WHERE id = $1+ `, recoveryTaskID, recoveryCommentID).Scan(&status, &acknowledged); err != nil {+ t.Fatalf("read cancelled recovery task: %v", err)+ }+ if status != "cancelled" || !acknowledged {+ t.Fatalf("cancelled recovery status/ack = %q/%v, want cancelled/true", status, acknowledged)+ }+}+// TestCancelTaskByUser_ChatTask_NonCreator_Returns403 preserves chat privacy:// a workspace member who did not start the conversation cannot cancel its task.func TestCancelTaskByUser_ChatTask_NonCreator_Returns403(t *testing.T) {diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex 2fc284e83f..da678ce0fa 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -1823,6 +1823,7 @@ func (h *Handler) CancelTaskByUser(w http.ResponseWriter, r *http.Request) {QueuedOnly: queuedOnly,ExpectedChatSession: expectedSession,QueueAction: queueAction,+ UserInitiated: true,})if errors.Is(err, service.ErrTaskNoLongerQueued) {writeError(w, http.StatusConflict, err.Error())diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 9b1bf16db6..d781494b32 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -3507,6 +3507,20 @@ func (h *Handler) retriggerCancelledTaskSurvivors(ctx context.Context, issue db.if isNoteComment(comment.Content) {continue}+ // Platform recovery comments bypass generic member/agent routing. If+ // editing or deleting another comment cancelled the queued batch that+ // carried one, replay it through the durable delegated-failure path so+ // the cancelled, undelivered task cannot swallow the obligation.+ if service.IsDelegatedFailureRecoveryComment(comment) {+ if err := h.TaskService.DispatchDelegatedFailureRecoveryComment(ctx, comment, pgtype.UUID{}); err != nil {+ slog.Warn("retrigger cancelled comment batch: delegated failure recovery replay failed",+ "issue_id", uuidToString(issue.ID),+ "comment_id", uuidToString(comment.ID),+ "error", err,+ )+ }+ continue+ }var parentComment *db.Commentif comment.ParentID.Valid {if parent, err := h.Queries.GetComment(ctx, comment.ParentID); err == nil {diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 9a296bffd9..83208fdd04 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -3755,6 +3755,24 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Agif isNoteComment(c.Content) {continue}+ // A delegated failure recovery signal is platform-authored and targets+ // the exact source coordinator recorded by the failed task. It bypasses+ // generic comment routing (which deliberately treats system authors as+ // unattributed) and excludes this just-completed task from the coverage+ // check because the signal was planned after claim, not delivered to it.+ if service.IsDelegatedFailureRecoveryComment(c) {+ if err := h.TaskService.DispatchDelegatedFailureRecoveryComment(ctx, c, task.ID); err != nil {+ slog.Warn("reconcile comments on completion: delegated failure recovery replay failed",+ "issue_id", uuidToString(task.IssueID),+ "task_id", uuidToString(task.ID),+ "comment_id", uuidToString(c.ID),+ "error", err,+ )+ } else {+ scheduled+++ }+ continue+ }var parentComment *db.Commentif c.ParentID.Valid {// Scope to the issue's workspace; a comment's parent is always in the@@ -4573,7 +4591,7 @@ func (h *Handler) CancelTask(w http.ResponseWriter, r *http.Request) {return}- task, err := h.TaskService.CancelTask(r.Context(), existing.ID)+ task, err := h.TaskService.CancelTaskByUser(r.Context(), existing.ID)if err != nil {slog.Warn("cancel task failed", "task_id", taskID, "error", err)writeError(w, http.StatusBadRequest, err.Error())diff --git a/server/internal/handler/delegated_failure_recovery_test.go b/server/internal/handler/delegated_failure_recovery_test.gonew file mode 100644index 0000000000..516d372a81--- /dev/null+++ b/server/internal/handler/delegated_failure_recovery_test.go@@ -0,0 +1,124 @@+package handler++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestUpdateComment_RequeuesDelegatedFailureRecoverySurvivor(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ runtimeID := createClaimReclaimRuntime(t, ctx, "delegated recovery cancellation runtime")+ coordinatorID, sourceIssueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "delegated recovery coordinator")+ if _, err := testPool.Exec(ctx, `+ UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, sourceIssueID, coordinatorID); err != nil {+ t.Fatalf("assign source issue: %v", err)+ }++ var workerID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config,+ runtime_id, visibility, max_concurrent_tasks, owner_id+ )+ VALUES ($1, 'delegated recovery worker', '', 'cloud', '{}'::jsonb, $2, 'private', 1, $3)+ RETURNING id`, testWorkspaceID, runtimeID, testUserID).Scan(&workerID); err != nil {+ t.Fatalf("create worker agent: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, workerID) })++ var workerIssueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)+ VALUES (+ $1, 'delegated recovery worker issue', 'in_progress', 'none', $2, 'member',+ (SELECT COALESCE(MAX(number), 82649) + 1 FROM issue WHERE workspace_id = $1),+ 0+ )+ RETURNING id`, testWorkspaceID, testUserID).Scan(&workerIssueID); err != nil {+ t.Fatalf("create worker issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, workerIssueID) })++ var sourceTaskID, failedTaskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority,+ originator_user_id, accountable_user_id, originator_source+ )+ VALUES ($1, $2, $3, 'completed', 0, $4, $4, 'direct_human')+ RETURNING id`, coordinatorID, runtimeID, sourceIssueID, testUserID).Scan(&sourceTaskID); err != nil {+ t.Fatalf("create source task: %v", err)+ }+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority,+ originator_user_id, accountable_user_id, originator_source,+ delegated_from_task_id, trigger_evidence_kind, failure_reason, error, completed_at+ )+ VALUES ($1, $2, $3, 'failed', 0, $4, $4, 'delegation', $5, 'comment',+ 'agent_error.process_failure', 'worker exited', now())+ RETURNING id`, workerID, runtimeID, workerIssueID, testUserID, sourceTaskID).Scan(&failedTaskID); err != nil {+ t.Fatalf("create failed delegated task: %v", err)+ }++ var humanCommentID, recoveryCommentID 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, 'original instruction', 'comment', now() - interval '1 second')+ RETURNING id`, sourceIssueID, testWorkspaceID, testUserID).Scan(&humanCommentID); err != nil {+ t.Fatalf("create human comment: %v", err)+ }+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, source_task_id)+ VALUES ($1, $2, 'system', $3, 'resume delegated coordination', 'progress_update', $4)+ RETURNING id`, sourceIssueID, testWorkspaceID, testUserID, failedTaskID).Scan(&recoveryCommentID); err != nil {+ t.Fatalf("create recovery comment: %v", err)+ }++ var cancelledTaskID 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, originator_user_id,+ accountable_user_id, originator_source+ )+ VALUES ($1, $2, $3, 'queued', 0, $4, ARRAY[$5::uuid], '{}', $6, $6, 'direct_human')+ RETURNING id`, coordinatorID, runtimeID, sourceIssueID, recoveryCommentID, humanCommentID, testUserID).Scan(&cancelledTaskID); err != nil {+ t.Fatalf("create queued coordinator batch: %v", err)+ }+ w := httptest.NewRecorder()+ req := newRequest(http.MethodPut, "/api/comments/"+humanCommentID, map[string]any{+ "content": "edited instruction",+ })+ req = withURLParam(req, "commentId", humanCommentID)+ testHandler.UpdateComment(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateComment: got %d: %s", w.Code, w.Body.String())+ }++ var cancelledStatus string+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, cancelledTaskID).Scan(&cancelledStatus); err != nil {+ t.Fatalf("read cancelled task: %v", err)+ }+ if cancelledStatus != "cancelled" {+ t.Fatalf("original batch status = %q, want cancelled", cancelledStatus)+ }+ var activeTasks int+ var recoveryCovered bool+ if err := testPool.QueryRow(ctx, `+ SELECT count(*), COALESCE(bool_or(trigger_comment_id = $3::uuid OR $3::uuid = ANY(coalesced_comment_ids)), false)+ FROM agent_task_queue+ WHERE agent_id = $1 AND issue_id = $2+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')`, coordinatorID, sourceIssueID, recoveryCommentID).+ Scan(&activeTasks, &recoveryCovered); err != nil {+ t.Fatalf("read rebuilt coordinator task: %v", err)+ }+ if activeTasks != 1 || !recoveryCovered {+ t.Fatalf("rebuilt active tasks/recovery coverage = %d/%v, want 1/true", activeTasks, recoveryCovered)+ }+}diff --git a/server/internal/service/delegated_failure_recovery_test.go b/server/internal/service/delegated_failure_recovery_test.gonew file mode 100644index 0000000000..a528759dfe--- /dev/null+++ b/server/internal/service/delegated_failure_recovery_test.go@@ -0,0 +1,759 @@+package service++import (+ "context"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/attribution"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type delegatedFailureFixture struct {+ pool *pgxpool.Pool+ workspaceID string+ userID string+ issueID string+ workerIssue string+ runtimeID string+ coordinator string+ worker string+ sourceTask string+}++func seedDelegatedFailureFixture(t *testing.T) (*delegatedFailureFixture, *TaskService) {+ t.Helper()+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ workspaceID, userID, coordinatorID, issueID := seedAttributionFixture(t, pool)+ if _, err := pool.Exec(ctx, `UPDATE issue SET status = 'in_progress' WHERE id = $1`, issueID); err != nil {+ t.Fatalf("activate source issue: %v", err)+ }++ var runtimeID string+ if err := pool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, coordinatorID).Scan(&runtimeID); err != nil {+ t.Fatalf("load runtime: %v", err)+ }+ var workerID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, runtime_mode, runtime_config, runtime_id, visibility,+ max_concurrent_tasks, owner_id, instructions, custom_env, custom_args+ )+ VALUES ($1, 'delegated-worker', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3, '', '{}'::jsonb, '[]'::jsonb)+ RETURNING id`, workspaceID, runtimeID, userID).Scan(&workerID); err != nil {+ t.Fatalf("seed worker: %v", err)+ }+ var workerIssueID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, creator_type, creator_id, assignee_type, assignee_id,+ priority, parent_issue_id, number+ )+ VALUES ($1, 'delegated worker issue', 'member', $2, 'agent', $3, 'medium', $4, 2)+ RETURNING id`, workspaceID, userID, workerID, issueID).Scan(&workerIssueID); err != nil {+ t.Fatalf("seed worker issue: %v", err)+ }++ var sourceTaskID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority,+ originator_user_id, accountable_user_id, originator_source+ )+ VALUES ($1, $2, $3, 'completed', 0, $4, $4, 'direct_human')+ RETURNING id`, coordinatorID, runtimeID, issueID, userID).Scan(&sourceTaskID); err != nil {+ t.Fatalf("seed source task: %v", err)+ }++ return &delegatedFailureFixture{+ pool: pool,+ workspaceID: workspaceID,+ userID: userID,+ issueID: issueID,+ workerIssue: workerIssueID,+ runtimeID: runtimeID,+ coordinator: coordinatorID,+ worker: workerID,+ sourceTask: sourceTaskID,+ }, NewTaskService(db.New(pool), pool, nil, events.New())+}++func (f *delegatedFailureFixture) insertWorkerTask(t *testing.T, status, evidenceKind string, attempt, maxAttempts int32) pgtype.UUID {+ t.Helper()+ var taskID pgtype.UUID+ if err := f.pool.QueryRow(context.Background(), `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, attempt, max_attempts,+ originator_user_id, accountable_user_id, originator_source,+ delegated_from_task_id, trigger_evidence_kind+ )+ VALUES ($1, $2, $3, $4, 0, $5, $6, $7, $7, 'delegation', $8, NULLIF($9, ''))+ RETURNING id`, f.worker, f.runtimeID, f.workerIssue, status, attempt, maxAttempts, f.userID, f.sourceTask, evidenceKind).Scan(&taskID); err != nil {+ t.Fatalf("seed worker task: %v", err)+ }+ return taskID+}++func TestFailTaskFinalDelegatedFailureWakesCoordinatorOnce(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "running", "comment", 1, 2)+ secret := "sk-" + strings.Repeat("a", 24)++ failed, err := svc.FailTask(ctx, failedID, "upstream capacity exhausted "+secret, "", "", "", "agent_error.process_failure", false, "")+ if err != nil {+ t.Fatalf("FailTask: %v", err)+ }++ var recoveryCount int+ var recoveryAgent, recoveryIssue, evidenceRef, delegatedFrom string+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*), COALESCE(max(agent_id::text), ''), COALESCE(max(issue_id::text), ''),+ COALESCE(max(trigger_evidence_ref_id::text), ''), COALESCE(max(delegated_from_task_id::text), '')+ FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).+ Scan(&recoveryCount, &recoveryAgent, &recoveryIssue, &evidenceRef, &delegatedFrom); err != nil {+ t.Fatalf("read recovery task: %v", err)+ }+ if recoveryCount != 1 {+ t.Fatalf("recovery task count = %d, want 1", recoveryCount)+ }+ if recoveryAgent != f.coordinator || recoveryIssue != f.issueID {+ t.Fatalf("recovery target = agent %s issue %s, want %s/%s", recoveryAgent, recoveryIssue, f.coordinator, f.issueID)+ }+ if evidenceRef != util.UUIDToString(failedID) || delegatedFrom != util.UUIDToString(failedID) {+ t.Fatalf("recovery lineage = evidence %s delegated_from %s, want failed task %s", evidenceRef, delegatedFrom, util.UUIDToString(failedID))+ }+ var retryCount int+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE parent_task_id = $1`, failedID).Scan(&retryCount); err != nil {+ t.Fatalf("count process-failure retries: %v", err)+ }+ if retryCount != 0 {+ t.Fatalf("process-failure retry count = %d, want 0", retryCount)+ }++ var commentCount int+ var content string+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*), COALESCE(max(content), '') FROM comment+ WHERE issue_id = $1 AND author_type = 'system' AND type = 'progress_update' AND source_task_id = $2`, f.issueID, failedID).+ Scan(&commentCount, &content); err != nil {+ t.Fatalf("read recovery comment: %v", err)+ }+ if commentCount != 1 {+ t.Fatalf("recovery comment count = %d, want 1", commentCount)+ }+ if strings.Contains(content, secret) || !strings.Contains(content, "[REDACTED API KEY]") {+ t.Fatalf("recovery comment did not redact error: %q", content)+ }+ var failedIssueComments int+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FROM comment+ WHERE issue_id = $1 AND type = 'system' AND source_task_id = $2`, f.workerIssue, failedID).Scan(&failedIssueComments); err != nil {+ t.Fatalf("count failed-issue comments: %v", err)+ }+ if failedIssueComments != 1 {+ t.Fatalf("failed-issue comments = %d, want legacy failure comment preserved", failedIssueComments)+ }++ // Replaying the sweeper/direct-failure side effect for the same terminal row+ // must not create another comment or another coordinator run.+ if handled, err := svc.recoverDelegatedTaskFailure(ctx, *failed); err != nil || !handled {+ t.Fatalf("repeat recovery = handled %v err %v, want handled without error", handled, err)+ }+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM comment WHERE issue_id = $1 AND type = 'progress_update' AND source_task_id = $2`, f.issueID, failedID).Scan(&commentCount); err != nil {+ t.Fatalf("recount recovery comments: %v", err)+ }+ if commentCount != 1 {+ t.Fatalf("replayed recovery comment count = %d, want 1", commentCount)+ }+ if _, err := f.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET status = 'failed', completed_at = now(), failure_reason = 'agent_error.process_failure',+ delivered_comment_ids = ARRAY[(+ SELECT id FROM comment+ WHERE type = 'progress_update' AND source_task_id = $1+ LIMIT 1+ )]::uuid[]+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID); err != nil {+ t.Fatalf("fail recovery task: %v", err)+ }+ if handled, err := svc.recoverDelegatedTaskFailure(ctx, *failed); err != nil || !handled {+ t.Fatalf("recovery after terminal recovery task = handled %v err %v", handled, err)+ }+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&recoveryCount); err != nil {+ t.Fatalf("recount recovery tasks: %v", err)+ }+ if recoveryCount != 1 {+ t.Fatalf("delivered terminal recovery was recreated: task count = %d, want 1", recoveryCount)+ }+}++func TestPendingDelegatedFailureSweepRepairsCommittedCommentWithoutTask(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)+ if _, err := f.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET failure_reason = 'agent_error.process_failure', error = 'worker exited', completed_at = now()+ WHERE id = $1`, failedID); err != nil {+ t.Fatalf("stamp failed task: %v", err)+ }+ // The durable outbox starts at the explicit platform comment. Do not+ // retroactively wake arbitrary historical delegated failures that predate+ // this recovery mechanism.+ if result, err := svc.RecoverPendingDelegatedFailures(ctx, 100); err != nil || result != (DelegatedFailureRecoverySweepResult{}) {+ t.Fatalf("pre-comment recovery sweep = %+v, %v; want zero result, nil", result, err)+ }++ // This is the durable intermediate state left when comment creation commits+ // but the first coordinator dispatch fails or the server exits immediately.+ target, created, err := svc.ensureDelegatedFailureRecoveryComment(ctx, failedID)+ if err != nil || target == nil || !created {+ t.Fatalf("ensure recovery comment = target %v created %v err %v", target != nil, created, err)+ }+ var tasksBefore int+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&tasksBefore); err != nil {+ t.Fatalf("count recovery tasks before sweep: %v", err)+ }+ if tasksBefore != 0 {+ t.Fatalf("recovery tasks before sweep = %d, want 0", tasksBefore)+ }++ result, err := svc.RecoverPendingDelegatedFailures(ctx, 100)+ if err != nil || result.Replayed != 1 || result.Exhausted != 0 {+ t.Fatalf("RecoverPendingDelegatedFailures = %+v, %v; want one replay, nil", result, err)+ }+ var comments, tasks int+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM comment WHERE type = 'progress_update' AND source_task_id = $1`, failedID).Scan(&comments); err != nil {+ t.Fatalf("count recovery comments: %v", err)+ }+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&tasks); err != nil {+ t.Fatalf("count recovery tasks after sweep: %v", err)+ }+ if comments != 1 || tasks != 1 {+ t.Fatalf("comments/tasks after sweep = %d/%d, want 1/1", comments, tasks)+ }+ if result, err := svc.RecoverPendingDelegatedFailures(ctx, 100); err != nil || result != (DelegatedFailureRecoverySweepResult{}) {+ t.Fatalf("second recovery sweep = %+v, %v; want zero result, nil", result, err)+ }+}++func TestPendingDelegatedFailureSweepRequeuesTerminalUndeliveredTask(t *testing.T) {+ for _, terminalStatus := range []string{"failed", "cancelled"} {+ t.Run(terminalStatus, func(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)+ if _, err := f.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET failure_reason = 'agent_error.process_failure', error = 'worker exited', completed_at = now()+ WHERE id = $1`, failedID); err != nil {+ t.Fatalf("stamp failed task: %v", err)+ }+ failed, err := svc.Queries.GetAgentTask(ctx, failedID)+ if err != nil {+ t.Fatalf("load failed task: %v", err)+ }+ if handled, err := svc.recoverDelegatedTaskFailure(ctx, failed); err != nil || !handled {+ t.Fatalf("initial recovery = handled %v err %v", handled, err)+ }++ var firstRecoveryID pgtype.UUID+ if err := f.pool.QueryRow(ctx, `+ SELECT id FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&firstRecoveryID); err != nil {+ t.Fatalf("load first recovery task: %v", err)+ }+ if terminalStatus == "cancelled" {+ if _, err := svc.CancelTask(ctx, firstRecoveryID); err != nil {+ t.Fatalf("server-cancel recovery before delivery: %v", err)+ }+ } else if _, err := f.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET status = $2, completed_at = now(), delivered_comment_ids = '{}'+ WHERE id = $1`, firstRecoveryID, terminalStatus); err != nil {+ t.Fatalf("terminalize recovery before delivery: %v", err)+ }++ result, err := svc.RecoverPendingDelegatedFailures(ctx, 100)+ if err != nil || result.Replayed != 1 || result.Exhausted != 0 {+ t.Fatalf("RecoverPendingDelegatedFailures = %+v, %v; want one replay, nil", result, err)+ }+ var active, total int+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FILTER (WHERE status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')),+ count(*)+ FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&active, &total); err != nil {+ t.Fatalf("count recovery tasks: %v", err)+ }+ if active != 1 || total != 2 {+ t.Fatalf("active/total recovery tasks = %d/%d, want 1/2", active, total)+ }+ if result, err := svc.RecoverPendingDelegatedFailures(ctx, 100); err != nil || result != (DelegatedFailureRecoverySweepResult{}) {+ t.Fatalf("second recovery sweep = %+v, %v; want zero result, nil", result, err)+ }+ })+ }+}++func TestUserCancelledDelegatedFailureRecoveryStaysCancelled(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)+ if _, err := f.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET failure_reason = 'agent_error.process_failure', error = 'worker exited', completed_at = now()+ WHERE id = $1`, failedID); err != nil {+ t.Fatalf("stamp failed task: %v", err)+ }+ failed, err := svc.Queries.GetAgentTask(ctx, failedID)+ if err != nil {+ t.Fatalf("load failed task: %v", err)+ }+ if handled, err := svc.recoverDelegatedTaskFailure(ctx, failed); err != nil || !handled {+ t.Fatalf("initial recovery = handled %v err %v", handled, err)+ }++ var recoveryTaskID, recoveryCommentID pgtype.UUID+ if err := f.pool.QueryRow(ctx, `+ SELECT task.id, recovery.id+ FROM agent_task_queue task+ JOIN comment recovery ON recovery.id = task.trigger_comment_id+ WHERE task.trigger_evidence_kind = 'delegated_failure'+ AND task.trigger_evidence_ref_id = $1`, failedID).Scan(&recoveryTaskID, &recoveryCommentID); err != nil {+ t.Fatalf("load recovery task/comment: %v", err)+ }+ cancelled, err := svc.CancelTaskByUser(ctx, recoveryTaskID)+ if err != nil {+ t.Fatalf("CancelTaskByUser: %v", err)+ }+ if cancelled.Status != "cancelled" {+ t.Fatalf("cancelled status = %q, want cancelled", cancelled.Status)+ }++ var acknowledged bool+ if err := f.pool.QueryRow(ctx, `+ SELECT $2::uuid = ANY(delivered_comment_ids)+ FROM agent_task_queue WHERE id = $1`, recoveryTaskID, recoveryCommentID).Scan(&acknowledged); err != nil {+ t.Fatalf("read user-cancel acknowledgement: %v", err)+ }+ if !acknowledged {+ t.Fatal("user cancellation did not terminally acknowledge the recovery signal")+ }+ if result, err := svc.RecoverPendingDelegatedFailures(ctx, 100); err != nil || result != (DelegatedFailureRecoverySweepResult{}) {+ t.Fatalf("recovery sweep after user cancel = %+v, %v; want zero result, nil", result, err)+ }+ var taskCount int+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&taskCount); err != nil {+ t.Fatalf("count recovery tasks: %v", err)+ }+ if taskCount != 1 {+ t.Fatalf("recovery tasks after user cancel = %d, want 1", taskCount)+ }+}++func TestManualRerunKeepsDelegatedFailureRecoveryReplayable(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)+ if _, err := f.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET failure_reason = 'agent_error.process_failure', error = 'worker exited', completed_at = now()+ WHERE id = $1`, failedID); err != nil {+ t.Fatalf("stamp failed task: %v", err)+ }+ failed, err := svc.Queries.GetAgentTask(ctx, failedID)+ if err != nil {+ t.Fatalf("load failed task: %v", err)+ }+ if handled, err := svc.recoverDelegatedTaskFailure(ctx, failed); err != nil || !handled {+ t.Fatalf("initial recovery = handled %v err %v", handled, err)+ }++ var firstRecoveryTaskID, recoveryCommentID pgtype.UUID+ if err := f.pool.QueryRow(ctx, `+ SELECT task.id, recovery.id+ FROM agent_task_queue task+ JOIN comment recovery ON recovery.id = task.trigger_comment_id+ WHERE task.trigger_evidence_kind = 'delegated_failure'+ AND task.trigger_evidence_ref_id = $1`, failedID).Scan(&firstRecoveryTaskID, &recoveryCommentID); err != nil {+ t.Fatalf("load initial recovery task/comment: %v", err)+ }++ rerun, err := svc.RerunIssue(+ ctx,+ util.MustParseUUID(f.issueID),+ util.MustParseUUID(f.sourceTask),+ pgtype.UUID{},+ util.MustParseUUID(f.userID),+ nil,+ )+ if err != nil {+ t.Fatalf("RerunIssue: %v", err)+ }+ var firstStatus string+ var acknowledged bool+ if err := f.pool.QueryRow(ctx, `+ SELECT status, $2::uuid = ANY(delivered_comment_ids)+ FROM agent_task_queue WHERE id = $1`, firstRecoveryTaskID, recoveryCommentID).Scan(&firstStatus, &acknowledged); err != nil {+ t.Fatalf("read rerun-cancelled recovery task: %v", err)+ }+ if firstStatus != "cancelled" || acknowledged {+ t.Fatalf("rerun-cancelled recovery = status %q acknowledged %v, want cancelled and replayable", firstStatus, acknowledged)+ }++ result, err := svc.RecoverPendingDelegatedFailures(ctx, 100)+ if err != nil || result.Replayed != 1 || result.Exhausted != 0 {+ t.Fatalf("recovery sweep after rerun = %+v, %v; want one replay", result, err)+ }+ var rerunTrigger string+ if err := f.pool.QueryRow(ctx, `SELECT COALESCE(trigger_comment_id::text, '') FROM agent_task_queue WHERE id = $1`, rerun.ID).Scan(&rerunTrigger); err != nil {+ t.Fatalf("read rerun trigger: %v", err)+ }+ if rerunTrigger != util.UUIDToString(recoveryCommentID) {+ t.Fatalf("rerun trigger = %q, want recovery comment %s", rerunTrigger, util.UUIDToString(recoveryCommentID))+ }+ var dedicatedRecoveryTasks int+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&dedicatedRecoveryTasks); err != nil {+ t.Fatalf("count dedicated recovery tasks: %v", err)+ }+ if dedicatedRecoveryTasks != 1 {+ t.Fatalf("dedicated recovery task count after rerun = %d, want original cancelled task only", dedicatedRecoveryTasks)+ }+ if result, err := svc.RecoverPendingDelegatedFailures(ctx, 100); err != nil || result != (DelegatedFailureRecoverySweepResult{}) {+ t.Fatalf("second recovery sweep after rerun = %+v, %v; want zero result", result, err)+ }+}++func TestDelegatedFailureRecoveryStopsAfterBoundedUndeliveredAttempts(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)+ if _, err := f.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET failure_reason = 'agent_error.process_failure', error = 'worker exited', completed_at = now()+ WHERE id = $1`, failedID); err != nil {+ t.Fatalf("stamp failed task: %v", err)+ }+ failed, err := svc.Queries.GetAgentTask(ctx, failedID)+ if err != nil {+ t.Fatalf("load failed task: %v", err)+ }+ if handled, err := svc.recoverDelegatedTaskFailure(ctx, failed); err != nil || !handled {+ t.Fatalf("initial recovery = handled %v err %v", handled, err)+ }++ for attempt := 1; attempt <= delegatedFailureRecoveryMaxTaskAttempts; attempt++ {+ var currentTaskID pgtype.UUID+ if err := f.pool.QueryRow(ctx, `+ SELECT id FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure'+ AND trigger_evidence_ref_id = $1+ AND status = 'queued'+ ORDER BY created_at DESC, id DESC+ LIMIT 1`, failedID).Scan(¤tTaskID); err != nil {+ t.Fatalf("load recovery attempt %d: %v", attempt, err)+ }+ if _, err := f.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET status = 'failed', completed_at = now(), failure_reason = 'queued_expired',+ error = 'task expired in queue', delivered_comment_ids = '{}'+ WHERE id = $1`, currentTaskID); err != nil {+ t.Fatalf("fail recovery attempt %d: %v", attempt, err)+ }++ result, err := svc.RecoverPendingDelegatedFailures(ctx, 100)+ if err != nil {+ t.Fatalf("recovery sweep after attempt %d = %+v, %v", attempt, result, err)+ }+ if attempt < delegatedFailureRecoveryMaxTaskAttempts {+ if result.Replayed != 1 || result.Exhausted != 0 {+ t.Fatalf("recovery sweep after attempt %d = %+v, want one replay", attempt, result)+ }+ } else if result.Replayed != 0 || result.Exhausted != 1 {+ t.Fatalf("recovery sweep after final attempt = %+v, want one exhaustion", result)+ }+ var active, total int+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FILTER (WHERE status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')),+ count(*)+ FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&active, &total); err != nil {+ t.Fatalf("count attempt %d tasks: %v", attempt, err)+ }+ wantActive := 1+ wantTotal := attempt + 1+ if attempt == delegatedFailureRecoveryMaxTaskAttempts {+ wantActive = 0+ wantTotal = delegatedFailureRecoveryMaxTaskAttempts+ }+ if active != wantActive || total != wantTotal {+ t.Fatalf("attempt %d active/total = %d/%d, want %d/%d", attempt, active, total, wantActive, wantTotal)+ }+ }++ var exhaustionComments int+ var exhaustionContent string+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*), COALESCE(max(content), '')+ FROM comment+ WHERE issue_id = $1 AND author_type = 'system' AND type = 'system' AND source_task_id = $2`, f.issueID, failedID).+ Scan(&exhaustionComments, &exhaustionContent); err != nil {+ t.Fatalf("read exhaustion comment: %v", err)+ }+ if exhaustionComments != 1 || !strings.Contains(exhaustionContent, "stopped after 3") {+ t.Fatalf("exhaustion comment = count %d content %q, want one visible bounded-stop explanation", exhaustionComments, exhaustionContent)+ }+ var inboxItems int+ var inboxSeverity, inboxBody string+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*), COALESCE(max(severity), ''), COALESCE(max(body), '')+ FROM inbox_item+ WHERE workspace_id = $1+ AND recipient_type = 'member'+ AND recipient_id = $2+ AND issue_id = $3+ AND type = 'task_failed'`, f.workspaceID, f.userID, f.issueID).+ Scan(&inboxItems, &inboxSeverity, &inboxBody); err != nil {+ t.Fatalf("read exhaustion inbox item: %v", err)+ }+ if inboxItems != 1 || inboxSeverity != "action_required" || inboxBody != exhaustionContent {+ t.Fatalf("exhaustion inbox = count %d severity %q body %q, want one action-required copy of explanation", inboxItems, inboxSeverity, inboxBody)+ }+ if result, err := svc.RecoverPendingDelegatedFailures(ctx, 100); err != nil || result != (DelegatedFailureRecoverySweepResult{}) {+ t.Fatalf("post-exhaustion recovery sweep = %+v, %v; want zero result, nil", result, err)+ }+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FROM inbox_item+ WHERE workspace_id = $1 AND recipient_id = $2 AND issue_id = $3+ AND type = 'task_failed'`, f.workspaceID, f.userID, f.issueID).Scan(&inboxItems); err != nil {+ t.Fatalf("recount exhaustion inbox items: %v", err)+ }+ if inboxItems != 1 {+ t.Fatalf("post-exhaustion inbox count = %d, want 1", inboxItems)+ }+ var finalTasks int+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&finalTasks); err != nil {+ t.Fatalf("count final recovery tasks: %v", err)+ }+ if finalTasks != delegatedFailureRecoveryMaxTaskAttempts {+ t.Fatalf("final recovery task count = %d, want %d", finalTasks, delegatedFailureRecoveryMaxTaskAttempts)+ }+}++func TestHandleFailedTasksFinalDelegatedFailureWakesCoordinator(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)+ if _, err := f.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET failure_reason = 'agent_error.process_failure', error = 'worker process exited', completed_at = now()+ WHERE id = $1`, failedID); err != nil {+ t.Fatalf("stamp failed task: %v", err)+ }+ failed, err := svc.Queries.GetAgentTask(ctx, failedID)+ if err != nil {+ t.Fatalf("load failed task: %v", err)+ }++ if retried := svc.HandleFailedTasks(ctx, []db.AgentTaskQueue{failed}); retried != 0 {+ t.Fatalf("HandleFailedTasks retried = %d, want 0", retried)+ }++ var recoveryTasks, recoveryComments int+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&recoveryTasks); err != nil {+ t.Fatalf("count recovery tasks: %v", err)+ }+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM comment WHERE issue_id = $1 AND type = 'progress_update' AND source_task_id = $2`, f.issueID, failedID).Scan(&recoveryComments); err != nil {+ t.Fatalf("count recovery comments: %v", err)+ }+ if recoveryTasks != 1 || recoveryComments != 1 {+ t.Fatalf("sweeper recovery tasks/comments = %d/%d, want 1/1", recoveryTasks, recoveryComments)+ }+}++func TestFailTaskRetryPendingDoesNotWakeCoordinator(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "running", "comment", 1, 2)++ if _, err := svc.FailTask(ctx, failedID, "task timed out", "", "", "", "timeout", false, ""); err != nil {+ t.Fatalf("FailTask: %v", err)+ }++ var retries, recoveries, comments int+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE parent_task_id = $1`, failedID).Scan(&retries); err != nil {+ t.Fatalf("count retries: %v", err)+ }+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&recoveries); err != nil {+ t.Fatalf("count recoveries: %v", err)+ }+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM comment WHERE type = 'progress_update' AND source_task_id = $1`, failedID).Scan(&comments); err != nil {+ t.Fatalf("count recovery comments: %v", err)+ }+ if retries != 1 || recoveries != 0 || comments != 0 {+ t.Fatalf("retry/recovery/comments = %d/%d/%d, want 1/0/0", retries, recoveries, comments)+ }+}++func TestFinalDelegatedFailureMergesIntoPendingCoordinatorTask(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "running", "comment", 1, 2)++ var pendingID pgtype.UUID+ if err := f.pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority,+ originator_user_id, accountable_user_id, originator_source,+ trigger_evidence_kind, trigger_evidence_ref_id+ )+ VALUES ($1, $2, $3, 'queued', 0, $4, $4, 'direct_human', 'issue_assignment', $3)+ RETURNING id`, f.coordinator, f.runtimeID, f.issueID, f.userID).Scan(&pendingID); err != nil {+ t.Fatalf("seed pending coordinator task: %v", err)+ }++ if _, err := svc.FailTask(ctx, failedID, "worker exited", "", "", "", "agent_error.process_failure", false, ""); err != nil {+ t.Fatalf("FailTask: %v", err)+ }++ var triggerID pgtype.UUID+ var evidenceKind string+ if err := f.pool.QueryRow(ctx, `SELECT trigger_comment_id, trigger_evidence_kind FROM agent_task_queue WHERE id = $1`, pendingID).+ Scan(&triggerID, &evidenceKind); err != nil {+ t.Fatalf("read pending coordinator task: %v", err)+ }+ if !triggerID.Valid {+ t.Fatal("pending coordinator task did not receive the recovery comment")+ }+ if evidenceKind != string(attribution.EvidenceIssueAssignment) {+ t.Fatalf("pending task attribution changed to %q, want issue_assignment", evidenceKind)+ }+ var newRecoveryTasks int+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&newRecoveryTasks); err != nil {+ t.Fatalf("count standalone recovery tasks: %v", err)+ }+ if newRecoveryTasks != 0 {+ t.Fatalf("standalone recovery tasks = %d, want 0 after merge", newRecoveryTasks)+ }++ // A second delegated failure while the same coordinator task is still+ // queued must coalesce into that task instead of creating a parallel run.+ secondFailedID := f.insertWorkerTask(t, "running", "comment", 1, 2)+ if _, err := svc.FailTask(ctx, secondFailedID, "second worker exited", "", "", "", "agent_error.process_failure", false, ""); err != nil {+ t.Fatalf("FailTask(second): %v", err)+ }+ var secondCommentID pgtype.UUID+ if err := f.pool.QueryRow(ctx, `SELECT id FROM comment WHERE type = 'progress_update' AND source_task_id = $1`, secondFailedID).Scan(&secondCommentID); err != nil {+ t.Fatalf("load second recovery comment: %v", err)+ }+ var newestTrigger, coversFirst bool+ if err := f.pool.QueryRow(ctx, `+ SELECT trigger_comment_id = $2::uuid, $3::uuid = ANY(coalesced_comment_ids)+ FROM agent_task_queue WHERE id = $1`, pendingID, secondCommentID, triggerID).Scan(&newestTrigger, &coversFirst); err != nil {+ t.Fatalf("read second merged signal: %v", err)+ }+ if !newestTrigger || !coversFirst {+ t.Fatalf("parallel recovery plan = newest trigger %v / prior coalesced %v, want true/true", newestTrigger, coversFirst)+ }+}++func TestDelegatedFailurePlannedBehindDispatchedCoordinatorGetsFollowUp(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "running", "comment", 1, 2)++ var activeID pgtype.UUID+ if err := f.pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, dispatched_at,+ originator_user_id, accountable_user_id, originator_source+ )+ VALUES ($1, $2, $3, 'dispatched', 0, now(), $4, $4, 'direct_human')+ RETURNING id`, f.coordinator, f.runtimeID, f.issueID, f.userID).Scan(&activeID); err != nil {+ t.Fatalf("seed active coordinator task: %v", err)+ }++ if _, err := svc.FailTask(ctx, failedID, "worker exited", "", "", "", "agent_error.process_failure", false, ""); err != nil {+ t.Fatalf("FailTask: %v", err)+ }+ comment, err := svc.Queries.GetDelegatedFailureRecoveryComment(ctx, db.GetDelegatedFailureRecoveryCommentParams{+ IssueID: util.MustParseUUID(f.issueID),+ WorkspaceID: util.MustParseUUID(f.workspaceID),+ SourceTaskID: failedID,+ })+ if err != nil {+ t.Fatalf("load recovery comment: %v", err)+ }+ var planned bool+ if err := f.pool.QueryRow(ctx, `SELECT $2::uuid = ANY(coalesced_comment_ids) FROM agent_task_queue WHERE id = $1`, activeID, comment.ID).Scan(&planned); err != nil {+ t.Fatalf("read active recovery plan: %v", err)+ }+ if !planned {+ t.Fatal("active coordinator task did not record planned recovery input")+ }+ reconcilable, err := svc.Queries.ListReconcilableCommentsForIssueSince(ctx, db.ListReconcilableCommentsForIssueSinceParams{+ IssueID: util.MustParseUUID(f.issueID),+ Since: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},+ PlannedCommentIds: []pgtype.UUID{comment.ID},+ })+ if err != nil {+ t.Fatalf("list reconcilable recovery comments: %v", err)+ }+ if len(reconcilable) != 1 || reconcilable[0].ID != comment.ID {+ t.Fatalf("reconcilable recovery comments = %+v, want only %s", reconcilable, util.UUIDToString(comment.ID))+ }++ if _, err := f.pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, activeID); err != nil {+ t.Fatalf("complete coordinator task: %v", err)+ }+ if err := svc.DispatchDelegatedFailureRecoveryComment(ctx, comment, activeID); err != nil {+ t.Fatalf("replay recovery after completion: %v", err)+ }+ var followUps int+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FROM agent_task_queue+ WHERE agent_id = $1 AND issue_id = $2 AND trigger_evidence_kind = 'delegated_failure'+ AND trigger_evidence_ref_id = $3`, f.coordinator, f.issueID, failedID).Scan(&followUps); err != nil {+ t.Fatalf("count recovery follow-ups: %v", err)+ }+ if followUps != 1 {+ t.Fatalf("recovery follow-ups = %d, want 1", followUps)+ }+}++func TestDelegatedFailureRecoveryTaskDoesNotRecursivelyWake(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ recoveryID := f.insertWorkerTask(t, "running", string(attribution.EvidenceDelegatedFailure), 1, 2)++ if _, err := svc.FailTask(ctx, recoveryID, "recovery failed", "", "", "", "agent_error.process_failure", false, ""); err != nil {+ t.Fatalf("FailTask: %v", err)+ }++ var comments int+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM comment WHERE type = 'progress_update' AND source_task_id = $1`, recoveryID).Scan(&comments); err != nil {+ t.Fatalf("count recursive recovery comments: %v", err)+ }+ if comments != 0 {+ t.Fatalf("recursive recovery comments = %d, want 0", comments)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 6b2efdc2c1..d153fad85b 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -2320,14 +2320,20 @@ type CancelTaskOptions struct {// daemon log the user never sees.ErrorMessage stringFailureReason string+ // UserInitiated distinguishes the issue UI/API cancel action from automatic+ // server repairs. An explicit user cancellation terminally acknowledges any+ // delegated-failure recovery signal planned into the task; automatic+ // cancellations must leave that signal replayable.+ UserInitiated bool}-// CancelTask cancels a single task by ID. It broadcasts a task:cancelled event-// so frontends can update immediately.+// CancelTask cancels a single task by ID for an automatic server path. It does+// not acknowledge delegated-failure recovery inputs; use CancelTaskByUser for+// an explicit issue-task cancellation. It broadcasts a task:cancelled event so+// frontends can update immediately.func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.AgentTaskQueue, error) {- // Every caller of this wrapper cancels a non-chat task — issue/autopilot- // tasks through the issue-scoped endpoint, plus the daemon and sweeper paths- // — so finalizeCancelledChatMessage returns before the gate is even read.+ // Callers of this wrapper are automatic non-chat repair/daemon paths, so+ // finalizeCancelledChatMessage returns before the gate is even read.// Should a chat task ever reach here, there is no client waiting on a// synchronous restore anyway, and the durable path is the only one that can// hand the prompt back at all.@@ -2338,6 +2344,21 @@ func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.Areturn &result.Task, nil}+// CancelTaskByUser is the explicit issue-task cancellation path. Unlike an+// automatic server cancellation, it terminally acknowledges any delegated-+// failure recovery signal carried by the task so the sweeper respects the+// user's decision instead of recreating the task.+func (s *TaskService) CancelTaskByUser(ctx context.Context, taskID pgtype.UUID) (*db.AgentTaskQueue, error) {+ result, err := s.CancelTaskWithResult(ctx, taskID, CancelTaskOptions{+ ClientSupportsDraftRestore: true,+ UserInitiated: true,+ })+ if err != nil {+ return nil, err+ }+ return &result.Task, nil+}+// CancelTaskWithReason cancels a task the SERVER decided to stop, persisting an// actionable reason onto the row. It runs the same full cancellation flow as// CancelTask — audit capture, chat settle, agent status reconcile,@@ -2366,6 +2387,9 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UUopts.ErrorMessage = util.SanitizeTextForPostgres(opts.ErrorMessage)opts.FailureReason = util.SanitizeTextForPostgres(opts.FailureReason)+ if opts.UserInitiated && (opts.ErrorMessage != "" || opts.FailureReason != "") {+ return nil, errors.New("user-initiated cancellation cannot carry a server failure reason")+ }var (task db.AgentTaskQueuecancelledChatMessage *CancelledChatMessageResult@@ -2405,7 +2429,9 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UUcancelled db.AgentTaskQueueerr error)- if opts.ErrorMessage != "" || opts.FailureReason != "" {+ if opts.UserInitiated {+ cancelled, err = qtx.CancelAgentTaskByUser(ctx, taskID)+ } else if opts.ErrorMessage != "" || opts.FailureReason != "" {cancelled, err = qtx.CancelAgentTaskWithReason(ctx, db.CancelAgentTaskWithReasonParams{ID: taskID,Error: pgtype.Text{String: opts.ErrorMessage, Valid: opts.ErrorMessage != ""},@@ -4258,10 +4284,30 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,}}+ // A delegated task that has reached a terminal failure must hand control+ // back to the task that delegated it. This runs only after the existing+ // retry decision: retryable failures keep their current policy and remain+ // silent while a child attempt is pending. The recovery signal is a+ // platform-authored comment on the source task's issue, routed explicitly to+ // that task's agent; recoverDelegatedTaskFailure coalesces it with an+ // existing coordinator run and deduplicates by the failed task id.+ if retried == nil {+ _, recoveryErr := s.recoverDelegatedTaskFailure(ctx, task)+ if recoveryErr != nil {+ slog.Warn("delegated task failure recovery failed",+ "task_id", util.UUIDToString(task.ID),+ "delegated_from_task_id", util.UUIDToString(task.DelegatedFromTaskID),+ "error", recoveryErr,+ )+ }+ }+// Skip the per-failure system comment when we'll immediately retry —// the new task will surface its own status to the user, and we don't// want to spam the issue with "task timed out" messages on every- // daemon hiccup.+ // daemon hiccup. Delegated failures keep this existing failed-issue comment+ // in addition to the coordinator recovery signal, preserving visibility on+ // both sides of a cross-issue handoff.if errMsg != "" && task.IssueID.Valid && retried == nil {s.createAgentComment(ctx, task.IssueID, task.AgentID, redact.Text(errMsg), "system", task.TriggerCommentID, task.ID)}@@ -4666,7 +4712,11 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc}}- // Cancel only the target agent's active/queued tasks on this issue.+ // Cancel only the target agent's active/queued tasks on this issue. A manual+ // rerun is a request to resume the issue, not to dismiss planned recovery+ // signals, so this intentionally stays on the server-cancel query. Any+ // undelivered delegated-failure signal remains an outbox obligation and the+ // sweeper can merge it into the fresh rerun task.cancelled, err := s.Queries.CancelAgentTasksByIssueAndAgent(ctx, db.CancelAgentTasksByIssueAndAgentParams{IssueID: issueID,AgentID: agentID,@@ -4806,6 +4856,15 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTasretriedIssues[util.UUIDToString(t.IssueID)] = true}}+ if !retryPending {+ if _, err := s.recoverDelegatedTaskFailure(ctx, t); err != nil {+ slog.Warn("handle failed tasks: delegated failure recovery failed",+ "task_id", util.UUIDToString(t.ID),+ "delegated_from_task_id", util.UUIDToString(t.DelegatedFromTaskID),+ "error", err,+ )+ }+ }failureReason := "agent_error"if t.FailureReason.Valid && t.FailureReason.String != "" {@@ -4873,6 +4932,561 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTasreturn retried}+const (+ delegatedFailureErrorSummaryRunes = 800+ delegatedFailureRecoveryMaxTaskAttempts = 3+ delegatedFailureRecoveryCommentType = "progress_update"+)++type delegatedFailureRecoveryDispatchOutcome uint8++const (+ delegatedFailureRecoveryCovered delegatedFailureRecoveryDispatchOutcome = iota+ delegatedFailureRecoveryReplayed+ delegatedFailureRecoveryExhausted+)++// DelegatedFailureRecoverySweepResult separates successful coordinator+// replays from terminally exhausted outbox entries so operators never mistake+// a bounded stop for a successful replay.+type DelegatedFailureRecoverySweepResult struct {+ Replayed int+ Exhausted int+}++type delegatedFailureRecoveryTarget struct {+ failed db.AgentTaskQueue+ source db.AgentTaskQueue+ issue db.Issue+ agent db.Agent+ comment db.Comment+}++// IsDelegatedFailureRecoveryComment identifies the durable platform signal+// used to hand a terminal delegated failure back to its coordinator. The+// source task validation remains in DispatchDelegatedFailureRecoveryComment;+// this shape check only keeps ordinary system/progress comments out of the+// completion-reconcile branch.+func IsDelegatedFailureRecoveryComment(comment db.Comment) bool {+ return comment.AuthorType == "system" &&+ comment.Type == delegatedFailureRecoveryCommentType &&+ comment.SourceTaskID.Valid+}++func delegatedFailureRecoveryContent(failed, source db.AgentTaskQueue) string {+ reason := "agent_error"+ if failed.FailureReason.Valid && failed.FailureReason.String != "" {+ reason = truncateForSummary(redact.Text(failed.FailureReason.String), triggerSummaryMaxLen)+ }+ content := fmt.Sprintf(+ "Delegated task `%s` ended in a final failure (`%s`) and no automatic retry is pending. Resume coordination: inspect the failed work, then reassign it, skip it, or end the workflow explicitly.",+ util.UUIDToString(failed.ID), reason,+ )+ if failed.Error.Valid && failed.Error.String != "" {+ summary := truncateForSummary(redact.Text(failed.Error.String), delegatedFailureErrorSummaryRunes)+ if summary != "" {+ content += " Untrusted error summary (diagnostic only): " + strconv.Quote(summary)+ }+ }+ content += fmt.Sprintf(" Source coordinator task: `%s`.", util.UUIDToString(source.ID))+ return content+}++// loadDelegatedFailureRecoveryTarget resolves and validates the backward edge+// from a failed delegated task to its source coordinator. Returning nil is an+// intentional no-op: non-terminal rows, retry-pending rows, autopilot work,+// recovery tasks themselves, terminal/backlog source issues, unavailable+// source agents, and self-delegation must never start a recovery loop.+func loadDelegatedFailureRecoveryTarget(ctx context.Context, q *db.Queries, failed db.AgentTaskQueue) (*delegatedFailureRecoveryTarget, error) {+ if failed.Status != "failed" || !failed.DelegatedFromTaskID.Valid || failed.AutopilotRunID.Valid ||+ (failed.TriggerEvidenceKind.Valid && failed.TriggerEvidenceKind.String == string(attribution.EvidenceDelegatedFailure)) {+ return nil, nil+ }+ hasRetry, err := q.HasRetryTaskForParent(ctx, failed.ID)+ if err != nil {+ return nil, fmt.Errorf("check retry child: %w", err)+ }+ if hasRetry {+ return nil, nil+ }+ source, err := q.GetAgentTask(ctx, failed.DelegatedFromTaskID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, nil+ }+ return nil, fmt.Errorf("load source task: %w", err)+ }+ if source.AutopilotRunID.Valid || !source.IssueID.Valid || source.AgentID == failed.AgentID {+ return nil, nil+ }+ issue, err := q.GetIssue(ctx, source.IssueID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, nil+ }+ return nil, fmt.Errorf("load source issue: %w", err)+ }+ effectiveStatus := issuestatus.Effective(ctx, q, issue.WorkspaceID, issue.Status)+ if effectiveStatus == issuestatus.Done || effectiveStatus == issuestatus.Cancelled || effectiveStatus == issuestatus.Backlog {+ return nil, nil+ }+ agent, err := q.GetAgent(ctx, source.AgentID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, nil+ }+ return nil, fmt.Errorf("load source agent: %w", err)+ }+ if agent.ArchivedAt.Valid || !agent.RuntimeID.Valid || agent.WorkspaceID != issue.WorkspaceID {+ return nil, nil+ }+ return &delegatedFailureRecoveryTarget{failed: failed, source: source, issue: issue, agent: agent}, nil+}++// ensureDelegatedFailureRecoveryComment creates one durable recovery signal+// per failed task. The failed row lock serializes FailTask and sweeper callers;+// the comment itself is platform-authored so it does not create subscriber or+// mention-notification side effects.+func (s *TaskService) ensureDelegatedFailureRecoveryComment(ctx context.Context, failedID pgtype.UUID) (*delegatedFailureRecoveryTarget, bool, error) {+ var target *delegatedFailureRecoveryTarget+ created := false+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {+ failed, err := qtx.GetAgentTaskForDelegatedFailureUpdate(ctx, failedID)+ if err != nil {+ return fmt.Errorf("lock failed task: %w", err)+ }+ target, err = loadDelegatedFailureRecoveryTarget(ctx, qtx, failed)+ if err != nil || target == nil {+ return err+ }+ comment, err := qtx.GetDelegatedFailureRecoveryComment(ctx, db.GetDelegatedFailureRecoveryCommentParams{+ IssueID: target.issue.ID,+ WorkspaceID: target.issue.WorkspaceID,+ SourceTaskID: failed.ID,+ })+ if err == nil {+ target.comment = comment+ return nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return fmt.Errorf("find recovery comment: %w", err)+ }+ comment, err = qtx.CreateComment(ctx, db.CreateCommentParams{+ IssueID: target.issue.ID,+ WorkspaceID: target.issue.WorkspaceID,+ AuthorType: "system",+ AuthorID: pgtype.UUID{Valid: true},+ Content: delegatedFailureRecoveryContent(target.failed, target.source),+ Type: delegatedFailureRecoveryCommentType,+ SourceTaskID: failed.ID,+ })+ if err != nil {+ return fmt.Errorf("create recovery comment: %w", err)+ }+ target.comment = comment+ created = true+ return nil+ }); err != nil {+ return nil, false, err+ }+ if target == nil {+ return nil, false, nil+ }+ if created && s.Bus != nil {+ s.Bus.Publish(events.Event{+ Type: protocol.EventCommentCreated,+ WorkspaceID: util.UUIDToString(target.issue.WorkspaceID),+ ActorType: "system",+ ActorID: "",+ Payload: map[string]any{+ "comment": map[string]any{+ "id": util.UUIDToString(target.comment.ID),+ "issue_id": util.UUIDToString(target.comment.IssueID),+ "author_type": target.comment.AuthorType,+ "author_id": util.UUIDToString(target.comment.AuthorID),+ "content": target.comment.Content,+ "type": target.comment.Type,+ "parent_id": util.UUIDToPtr(target.comment.ParentID),+ "source_task_id": util.UUIDToPtr(target.comment.SourceTaskID),+ "created_at": target.comment.CreatedAt.Time.Format("2006-01-02T15:04:05Z"),+ },+ "issue_title": target.issue.Title,+ "issue_status": target.issue.Status,+ },+ })+ }+ return target, created, nil+}++func delegatedFailureRecoveryExhaustionContent(target *delegatedFailureRecoveryTarget) string {+ return fmt.Sprintf(+ "Automatic recovery for delegated task `%s` stopped after %d coordinator tasks ended before receiving the recovery signal. No more recovery tasks will be created automatically; resume or dismiss the work manually. Source coordinator task: `%s`.",+ util.UUIDToString(target.failed.ID),+ delegatedFailureRecoveryMaxTaskAttempts,+ util.UUIDToString(target.source.ID),+ )+}++func delegatedFailureRecoveryAttribution(target *delegatedFailureRecoveryTarget) (pgtype.UUID, pgtype.UUID) {+ originator := target.failed.OriginatorUserID+ accountable := target.failed.AccountableUserID+ if originator.Valid {+ accountable = originator+ }+ if !originator.Valid && !accountable.Valid {+ originator = target.source.OriginatorUserID+ accountable = target.source.AccountableUserID+ if originator.Valid {+ accountable = originator+ }+ }+ return originator, accountable+}++// exhaustDelegatedFailureRecovery atomically settles the recovery outbox after+// its bounded automatic attempts, creates one visible system explanation, and+// notifies the responsible human. The bool reports whether this caller created+// that terminal outcome. Updating the newest attempt first serializes+// concurrent sweepers; the second caller then observes the explanation written+// by the first and does not report another exhaustion.+func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, target *delegatedFailureRecoveryTarget) (bool, error) {+ var exhaustedComment db.Comment+ var exhaustedInbox db.InboxItem+ created := false+ inboxCreated := false+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {+ if _, err := qtx.AcknowledgeExhaustedDelegatedFailureRecovery(ctx, db.AcknowledgeExhaustedDelegatedFailureRecoveryParams{+ CommentID: target.comment.ID,+ FailedTaskID: target.failed.ID,+ MaxAttempts: delegatedFailureRecoveryMaxTaskAttempts,+ }); err != nil {+ return fmt.Errorf("acknowledge exhausted delegated failure recovery: %w", err)+ }++ comment, err := qtx.GetDelegatedFailureRecoveryExhaustionComment(ctx, db.GetDelegatedFailureRecoveryExhaustionCommentParams{+ IssueID: target.issue.ID,+ WorkspaceID: target.issue.WorkspaceID,+ SourceTaskID: target.failed.ID,+ })+ if err == nil {+ exhaustedComment = comment+ return nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return fmt.Errorf("find delegated failure exhaustion comment: %w", err)+ }++ comment, err = qtx.CreateComment(ctx, db.CreateCommentParams{+ IssueID: target.issue.ID,+ WorkspaceID: target.issue.WorkspaceID,+ AuthorType: "system",+ AuthorID: pgtype.UUID{Valid: true},+ Content: delegatedFailureRecoveryExhaustionContent(target),+ Type: "system",+ SourceTaskID: target.failed.ID,+ })+ if err != nil {+ return fmt.Errorf("create delegated failure exhaustion comment: %w", err)+ }+ exhaustedComment = comment+ created = true++ // Exhaustion deliberately does not @mention the coordinator agent: doing+ // so would enqueue a fourth recovery run and defeat the attempt bound.+ // Instead, create one durable action-required inbox item for the human+ // who originated (or is accountable for) the delegated work.+ _, recipient := delegatedFailureRecoveryAttribution(target)+ if recipient.Valid {+ _, err = qtx.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{+ UserID: recipient,+ WorkspaceID: target.issue.WorkspaceID,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return nil+ }+ if err != nil {+ return fmt.Errorf("validate delegated failure exhaustion recipient: %w", err)+ }++ details, err := json.Marshal(map[string]any{+ "failed_task_id": util.UUIDToString(target.failed.ID),+ "source_task_id": util.UUIDToString(target.source.ID),+ "coordinator_agent_id": util.UUIDToString(target.agent.ID),+ "max_attempts": delegatedFailureRecoveryMaxTaskAttempts,+ })+ if err != nil {+ return fmt.Errorf("encode delegated failure exhaustion details: %w", err)+ }+ exhaustedInbox, err = qtx.CreateInboxItem(ctx, db.CreateInboxItemParams{+ WorkspaceID: target.issue.WorkspaceID,+ RecipientType: "member",+ RecipientID: recipient,+ Type: "task_failed",+ Severity: "action_required",+ IssueID: target.issue.ID,+ Title: target.issue.Title,+ Body: pgtype.Text{String: exhaustedComment.Content, Valid: true},+ ActorType: pgtype.Text{String: "system", Valid: true},+ ActorID: pgtype.UUID{},+ Details: details,+ })+ if err != nil {+ return fmt.Errorf("create delegated failure exhaustion inbox item: %w", err)+ }+ inboxCreated = true+ }+ return nil+ }); err != nil {+ return false, err+ }++ if created && s.Bus != nil {+ s.Bus.Publish(events.Event{+ Type: protocol.EventCommentCreated,+ WorkspaceID: util.UUIDToString(target.issue.WorkspaceID),+ ActorType: "system",+ ActorID: "",+ Payload: map[string]any{+ "comment": map[string]any{+ "id": util.UUIDToString(exhaustedComment.ID),+ "issue_id": util.UUIDToString(exhaustedComment.IssueID),+ "author_type": exhaustedComment.AuthorType,+ "author_id": util.UUIDToString(exhaustedComment.AuthorID),+ "content": exhaustedComment.Content,+ "type": exhaustedComment.Type,+ "parent_id": util.UUIDToPtr(exhaustedComment.ParentID),+ "source_task_id": util.UUIDToPtr(exhaustedComment.SourceTaskID),+ "created_at": exhaustedComment.CreatedAt.Time.Format("2006-01-02T15:04:05Z"),+ },+ "issue_title": target.issue.Title,+ "issue_status": target.issue.Status,+ },+ })+ }+ if inboxCreated && s.Bus != nil {+ s.Bus.Publish(events.Event{+ Type: protocol.EventInboxNew,+ WorkspaceID: util.UUIDToString(target.issue.WorkspaceID),+ ActorType: "system",+ ActorID: "",+ Payload: map[string]any{"item": map[string]any{+ "id": util.UUIDToString(exhaustedInbox.ID),+ "workspace_id": util.UUIDToString(exhaustedInbox.WorkspaceID),+ "recipient_type": exhaustedInbox.RecipientType,+ "recipient_id": util.UUIDToString(exhaustedInbox.RecipientID),+ "type": exhaustedInbox.Type,+ "severity": exhaustedInbox.Severity,+ "issue_id": util.UUIDToPtr(exhaustedInbox.IssueID),+ "title": exhaustedInbox.Title,+ "body": util.TextToPtr(exhaustedInbox.Body),+ "read": exhaustedInbox.Read,+ "archived": exhaustedInbox.Archived,+ "created_at": util.TimestampToString(exhaustedInbox.CreatedAt),+ "actor_type": util.TextToPtr(exhaustedInbox.ActorType),+ "actor_id": util.UUIDToPtr(exhaustedInbox.ActorID),+ "details": json.RawMessage(exhaustedInbox.Details),+ "issue_status": target.issue.Status,+ }},+ })+ }+ return created, nil+}++// dispatchDelegatedFailureRecovery routes a recovery comment to the source+// coordinator without relying on generic mention parsing. A pre-claim task+// absorbs it; otherwise a dedicated queued successor is created. The only+// state that blocks both writes is a dispatched task (its claim is already+// built and the pending-task uniqueness slot is still held), so that narrow+// race records the comment as planned-but-undelivered and lets completion+// reconciliation schedule the follow-up. The three-pass loop closes state+// changes around those writes.+func (s *TaskService) dispatchDelegatedFailureRecovery(ctx context.Context, target *delegatedFailureRecoveryTarget, excludeTaskID pgtype.UUID) (delegatedFailureRecoveryDispatchOutcome, error) {+ const maxAttempts = 3+ for attempt := 0; attempt < maxAttempts; attempt++ {+ covered, err := s.Queries.HasTaskCoveringDelegatedFailureComment(ctx, db.HasTaskCoveringDelegatedFailureCommentParams{+ IssueID: target.issue.ID,+ AgentID: target.agent.ID,+ CommentID: target.comment.ID,+ ExcludeTaskID: excludeTaskID,+ })+ if err != nil {+ return delegatedFailureRecoveryCovered, fmt.Errorf("check recovery coverage: %w", err)+ }+ if covered {+ return delegatedFailureRecoveryCovered, nil+ }++ recoveryTasks, err := s.Queries.CountDelegatedFailureRecoveryTasks(ctx, target.failed.ID)+ if err != nil {+ return delegatedFailureRecoveryCovered, fmt.Errorf("count delegated failure recovery tasks: %w", err)+ }+ if recoveryTasks >= delegatedFailureRecoveryMaxTaskAttempts {+ exhausted, err := s.exhaustDelegatedFailureRecovery(ctx, target)+ if err != nil {+ return delegatedFailureRecoveryCovered, err+ }+ if exhausted {+ return delegatedFailureRecoveryExhausted, nil+ }+ return delegatedFailureRecoveryCovered, nil+ }++ if merged, err := s.Queries.MergeDelegatedFailureCommentIntoPendingTask(ctx, db.MergeDelegatedFailureCommentIntoPendingTaskParams{+ CommentID: target.comment.ID,+ TriggerSummary: s.buildCommentTriggerSummary(ctx, target.issue.WorkspaceID, target.comment.ID),+ IssueID: target.issue.ID,+ AgentID: target.agent.ID,+ }); err == nil {+ slog.Info("delegated failure recovery merged into pending coordinator task",+ "failed_task_id", util.UUIDToString(target.failed.ID),+ "coordinator_task_id", util.UUIDToString(merged.ID),+ )+ return delegatedFailureRecoveryReplayed, nil+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return delegatedFailureRecoveryCovered, fmt.Errorf("merge recovery into pending task: %w", err)+ }++ originator, accountable := delegatedFailureRecoveryAttribution(target)+ source := attribution.SourceDelegation+ if !originator.Valid && !accountable.Valid {+ source = attribution.SourceUnattributed+ }+ ruleVersionID := target.failed.RuleVersionID+ if !ruleVersionID.Valid {+ ruleVersionID = target.source.RuleVersionID+ }+ overlay := s.buildRuntimeMCPOverlay(ctx, originator, target.agent)+ task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{+ AgentID: target.agent.ID,+ RuntimeID: target.agent.RuntimeID,+ IssueID: target.issue.ID,+ Priority: priorityToInt(target.issue.Priority),+ TriggerCommentID: target.comment.ID,+ TriggerSummary: s.buildCommentTriggerSummary(ctx, target.issue.WorkspaceID, target.comment.ID),+ IsLeaderTask: pgtype.Bool{Bool: target.source.IsLeaderTask, Valid: target.source.IsLeaderTask},+ SquadID: target.source.SquadID,+ OriginatorUserID: originator,+ AccountableUserID: accountable,+ RuntimeMcpOverlay: overlay.Overlay,+ RuntimeConnectedApps: overlay.ConnectedApps,+ OriginatorSource: pgtype.Text{String: string(source), Valid: true},+ DelegatedFromTaskID: target.failed.ID,+ RuleVersionID: ruleVersionID,+ TriggerEvidenceKind: pgtype.Text{String: string(attribution.EvidenceDelegatedFailure), Valid: true},+ TriggerEvidenceRefID: target.failed.ID,+ HeadSha: headShaText(s.ResolveIssueReviewSHA(ctx, target.issue.ID)),+ })+ if err == nil {+ slog.Info("delegated failure recovery task enqueued",+ "failed_task_id", util.UUIDToString(target.failed.ID),+ "source_task_id", util.UUIDToString(target.source.ID),+ "recovery_task_id", util.UUIDToString(task.ID),+ "coordinator_agent_id", util.UUIDToString(target.agent.ID),+ )+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)+ s.NotifyTaskEnqueued(ctx, task)+ return delegatedFailureRecoveryReplayed, nil+ }+ if !isDuplicatePendingTaskErr(err) {+ return delegatedFailureRecoveryCovered, fmt.Errorf("create recovery task: %w", err)+ }++ // A dispatched task still owns the unique queued/dispatched slot, but+ // its claim payload is immutable. Register the comment as undelivered so+ // its completion reconciliation creates the successor. Running tasks do+ // not own that slot, so they took the durable queued-successor path above.+ if active, err := s.Queries.RegisterPlannedCommentForActiveTask(ctx, db.RegisterPlannedCommentForActiveTaskParams{+ CommentID: target.comment.ID,+ IssueID: target.issue.ID,+ AgentID: target.agent.ID,+ }); err == nil {+ slog.Info("delegated failure recovery registered behind dispatched coordinator task",+ "failed_task_id", util.UUIDToString(target.failed.ID),+ "coordinator_task_id", util.UUIDToString(active.ID),+ )+ return delegatedFailureRecoveryReplayed, nil+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return delegatedFailureRecoveryCovered, fmt.Errorf("register recovery on dispatched task: %w", err)+ }+ }+ return delegatedFailureRecoveryCovered, fmt.Errorf("delegate failure recovery could not acquire coordinator task slot")+}++// recoverDelegatedTaskFailure is the shared post-terminal hook for FailTask and+// HandleFailedTasks. handled reports whether the failure was an eligible+// delegated terminal; the production terminal paths deliberately retain their+// legacy raw-error notice alongside the richer coordinator recovery signal.+func (s *TaskService) recoverDelegatedTaskFailure(ctx context.Context, failed db.AgentTaskQueue) (handled bool, err error) {+ target, _, err := s.ensureDelegatedFailureRecoveryComment(ctx, failed.ID)+ if err != nil || target == nil {+ return false, err+ }+ _, err = s.dispatchDelegatedFailureRecovery(ctx, target, pgtype.UUID{})+ return true, err+}++// RecoverPendingDelegatedFailures replays the durable recovery outbox. The+// platform recovery comment is the obligation; it is complete only while a task+// that carries it can still execute, or after a task records it in+// delivered_comment_ids. This lets a later sweeper repair a process crash or+// transient database error between comment creation and coordinator dispatch+// without producing duplicate runnable tasks.+func (s *TaskService) RecoverPendingDelegatedFailures(ctx context.Context, maxPerTick int32) (DelegatedFailureRecoverySweepResult, error) {+ result := DelegatedFailureRecoverySweepResult{}+ if maxPerTick <= 0 {+ return result, nil+ }+ pending, err := s.Queries.ListPendingDelegatedFailureRecoveries(ctx, maxPerTick)+ if err != nil {+ return result, fmt.Errorf("list pending delegated failure recoveries: %w", err)+ }++ errs := make([]error, 0)+ for _, comment := range pending {+ outcome, recoveryErr := s.dispatchDelegatedFailureRecoveryComment(ctx, comment, pgtype.UUID{})+ if recoveryErr != nil {+ errs = append(errs, fmt.Errorf("dispatch recovery comment %s: %w", util.UUIDToString(comment.ID), recoveryErr))+ continue+ }+ switch outcome {+ case delegatedFailureRecoveryReplayed:+ result.Replayed+++ case delegatedFailureRecoveryExhausted:+ result.Exhausted+++ }+ }+ return result, errors.Join(errs...)+}++// DispatchDelegatedFailureRecoveryComment is used by completion reconciliation+// when a recovery signal arrived after a coordinator task was claimed. The+// completed task is excluded from the coverage check because the comment was+// planned but not delivered to it; routing then merges/enqueues exactly one+// follow-up.+func (s *TaskService) DispatchDelegatedFailureRecoveryComment(ctx context.Context, comment db.Comment, completedTaskID pgtype.UUID) error {+ _, err := s.dispatchDelegatedFailureRecoveryComment(ctx, comment, completedTaskID)+ return err+}++func (s *TaskService) dispatchDelegatedFailureRecoveryComment(ctx context.Context, comment db.Comment, completedTaskID pgtype.UUID) (delegatedFailureRecoveryDispatchOutcome, error) {+ if !IsDelegatedFailureRecoveryComment(comment) {+ return delegatedFailureRecoveryCovered, nil+ }+ failed, err := s.Queries.GetAgentTask(ctx, comment.SourceTaskID)+ if err != nil {+ return delegatedFailureRecoveryCovered, fmt.Errorf("load failed recovery source: %w", err)+ }+ target, err := loadDelegatedFailureRecoveryTarget(ctx, s.Queries, failed)+ if err != nil || target == nil {+ return delegatedFailureRecoveryCovered, err+ }+ if target.issue.ID != comment.IssueID || target.issue.WorkspaceID != comment.WorkspaceID {+ return delegatedFailureRecoveryCovered, fmt.Errorf("delegated failure recovery comment scope mismatch")+ }+ target.comment = comment+ return s.dispatchDelegatedFailureRecovery(ctx, target, completedTaskID)+}+// runInTx executes fn inside a single DB transaction. If TxStarter is nil// (e.g. some tests construct TaskService directly), fn runs against the// regular Queries handle without transactional guarantees.diff --git a/server/migrations/343_comment_delegated_failure_pending_index.down.sql b/server/migrations/343_comment_delegated_failure_pending_index.down.sqlnew file mode 100644index 0000000000..a7f5b94024--- /dev/null+++ b/server/migrations/343_comment_delegated_failure_pending_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_delegated_failure_pending;diff --git a/server/migrations/343_comment_delegated_failure_pending_index.up.sql b/server/migrations/343_comment_delegated_failure_pending_index.up.sqlnew file mode 100644index 0000000000..c240b2e23d--- /dev/null+++ b/server/migrations/343_comment_delegated_failure_pending_index.up.sql@@ -0,0 +1,5 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comment_delegated_failure_pending+ON comment (created_at, id)+WHERE author_type = 'system'+ AND type = 'progress_update'+ AND source_task_id IS NOT NULL;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex dd6dc6cb9a..7575436e2e 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -11,6 +11,101 @@ import ("github.com/jackc/pgx/v5/pgtype")+const acknowledgeExhaustedDelegatedFailureRecovery = `-- name: AcknowledgeExhaustedDelegatedFailureRecovery :one+UPDATE agent_task_queue AS acknowledged+SET delivered_comment_ids = (+ SELECT COALESCE(array_agg(DISTINCT receipt.id), '{}')::uuid[]+ FROM unnest(array_append(acknowledged.delivered_comment_ids, $1::uuid)) AS receipt(id)+)+WHERE acknowledged.id = (+ SELECT attempt.id+ FROM agent_task_queue attempt+ WHERE attempt.trigger_evidence_kind = 'delegated_failure'+ AND attempt.trigger_evidence_ref_id = $2+ ORDER BY attempt.created_at DESC, attempt.id DESC+ LIMIT 1+ FOR UPDATE+)+ AND (+ SELECT count(*)+ FROM agent_task_queue attempt_count+ WHERE attempt_count.trigger_evidence_kind = 'delegated_failure'+ AND attempt_count.trigger_evidence_ref_id = $2+ ) >= $3::int+RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.plugin_execution_manifest_id, acknowledged.branch_name+`++type AcknowledgeExhaustedDelegatedFailureRecoveryParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ FailedTaskID pgtype.UUID `json:"failed_task_id"`+ MaxAttempts int32 `json:"max_attempts"`+}++// Once the bounded automatic attempts are exhausted, record a terminal+// acknowledgement on the newest recovery task. The outbox treats this receipt+// as settled, while the service writes a separate visible system comment that+// tells the user why no further task will be generated.+func (q *Queries) AcknowledgeExhaustedDelegatedFailureRecovery(ctx context.Context, arg AcknowledgeExhaustedDelegatedFailureRecoveryParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, acknowledgeExhaustedDelegatedFailureRecovery, arg.CommentID, arg.FailedTaskID, arg.MaxAttempts)+ 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.PluginExecutionManifestID,+ &i.BranchName,+ )+ return i, err+}+const archiveAgent = `-- name: ArchiveAgent :oneUPDATE agent SET archived_at = now(), archived_by = $2, updated_at = now()WHERE id = $1@@ -207,6 +302,8 @@ WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_dRETURNING 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, plugin_execution_manifest_id, branch_name`+// Automatic cancellation without an explicit persisted failure reason. Unlike+// CancelAgentTaskByUser, this deliberately leaves recovery inputs replayable.func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, cancelAgentTask, id)var i AgentTaskQueue@@ -268,6 +365,128 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTasreturn i, err}+const cancelAgentTaskByUser = `-- name: CancelAgentTaskByUser :one+UPDATE agent_task_queue AS task+SET status = 'cancelled',+ completed_at = now(),+ prepare_lease_expires_at = NULL,+ delivered_comment_ids = CASE+ -- Chat and ordinary issue tasks almost never carry a delegated-failure+ -- recovery signal. Keep their high-frequency user-cancel path to a+ -- no-join update; only validate task lineage after the cheap comment+ -- shape probe finds a possible recovery signal.+ WHEN task.trigger_comment_id IS NULL+ AND COALESCE(cardinality(task.coalesced_comment_ids), 0) = 0+ THEN task.delivered_comment_ids+ WHEN NOT EXISTS (+ SELECT 1+ FROM comment recovery_signal+ WHERE (+ recovery_signal.id = task.trigger_comment_id+ OR recovery_signal.id = ANY(task.coalesced_comment_ids)+ )+ AND recovery_signal.author_type = 'system'+ AND recovery_signal.type = 'progress_update'+ AND recovery_signal.source_task_id IS NOT NULL+ ) THEN task.delivered_comment_ids+ ELSE (+ SELECT COALESCE(array_agg(DISTINCT receipt.id), '{}')::uuid[]+ FROM unnest(array_cat(+ task.delivered_comment_ids,+ ARRAY(+ SELECT recovery.id+ FROM comment recovery+ JOIN agent_task_queue failed ON failed.id = recovery.source_task_id+ JOIN agent_task_queue source ON source.id = failed.delegated_from_task_id+ WHERE (+ recovery.id = task.trigger_comment_id+ OR recovery.id = ANY(task.coalesced_comment_ids)+ )+ AND recovery.author_type = 'system'+ AND recovery.type = 'progress_update'+ AND recovery.source_task_id IS NOT NULL+ AND failed.status = 'failed'+ AND failed.delegated_from_task_id IS NOT NULL+ AND failed.autopilot_run_id IS NULL+ AND failed.trigger_evidence_kind IS DISTINCT FROM 'delegated_failure'+ AND source.autopilot_run_id IS NULL+ AND source.issue_id = task.issue_id+ AND source.agent_id = task.agent_id+ AND recovery.issue_id = source.issue_id+ )+ )) AS receipt(id)+ )+ END+WHERE task.id = $1+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.plugin_execution_manifest_id, task.branch_name+`++// An explicit user cancellation is a terminal acknowledgement for any+// delegated-failure recovery signal planned into this task. Server-initiated+// cancellations keep using CancelAgentTask / CancelAgentTaskWithReason so a+// stale plan, claim failure, or other automatic repair can still be replayed.+func (q *Queries) CancelAgentTaskByUser(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, cancelAgentTaskByUser, 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.PluginExecutionManifestID,+ &i.BranchName,+ )+ return i, err+}+const cancelAgentTaskWithReason = `-- name: CancelAgentTaskWithReason :oneUPDATE agent_task_queueSET status = 'cancelled',@@ -287,12 +506,11 @@ type CancelAgentTaskWithReasonParams struct {// Cancels a task AND records why, for cancellations the user did not ask for.//-// Plain CancelAgentTask leaves error/failure_reason NULL, which is right for a-// user-initiated cancel — the user knows why. A server-initiated one is the-// opposite: without a persisted reason the run surfaces as an unexplained-// "cancelled", and the only trace is a 4xx in a daemon log the user never sees.-// Retrying cannot help either (the task is refused for a durable reason), so-// this is a terminal state that has to carry its own explanation.+// CancelAgentTaskByUser leaves error/failure_reason NULL because the user knows+// why. A server-initiated refusal is the opposite: without a persisted reason+// the run surfaces as an unexplained "cancelled", and the only trace is a 4xx+// in a daemon log the user never sees. Retrying cannot help either (the task is+// refused for a durable reason), so this terminal state carries its explanation.func (q *Queries) CancelAgentTaskWithReason(ctx context.Context, arg CancelAgentTaskWithReasonParams) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, cancelAgentTaskWithReason, arg.Error, arg.FailureReason, arg.ID)var i AgentTaskQueue@@ -1676,6 +1894,23 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPareturn i, err}+const countDelegatedFailureRecoveryTasks = `-- name: CountDelegatedFailureRecoveryTasks :one+SELECT count(*)+FROM agent_task_queue+WHERE trigger_evidence_kind = 'delegated_failure'+ AND trigger_evidence_ref_id = $1+`++// Counts dedicated coordinator wakeups for one failed delegated task. Merged+// recovery signals do not create a new row and therefore do not consume an+// automatic attempt until they need a standalone successor.+func (q *Queries) CountDelegatedFailureRecoveryTasks(ctx context.Context, failedTaskID pgtype.UUID) (int64, error) {+ row := q.db.QueryRow(ctx, countDelegatedFailureRecoveryTasks, failedTaskID)+ var count int64+ err := row.Scan(&count)+ return count, err+}+const countRunningTasks = `-- name: CountRunningTasks :oneSELECT count(*) FROM agent_task_queueWHERE agent_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')@@ -3607,6 +3842,76 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQureturn i, err}+const getAgentTaskForDelegatedFailureUpdate = `-- name: GetAgentTaskForDelegatedFailureUpdate :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, 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, plugin_execution_manifest_id, branch_name FROM agent_task_queue+WHERE id = $1+FOR UPDATE+`++// Serializes the idempotent delegated-failure recovery signal for one failed+// task. FailTask and the stale-task sweepers can converge on the same row; the+// lock ensures they cannot create two recovery comments/tasks for it.+func (q *Queries) GetAgentTaskForDelegatedFailureUpdate(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, getAgentTaskForDelegatedFailureUpdate, 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.PluginExecutionManifestID,+ &i.BranchName,+ )+ return i, err+}+const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :oneSELECT 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, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.plugin_execution_manifest_id, atq.branch_name FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_id@@ -4207,6 +4512,65 @@ func (q *Queries) HasPendingTaskForIssueAndAgentExcludingTriggerComment(ctx contreturn has_pending, err}+const hasRetryTaskForParent = `-- name: HasRetryTaskForParent :one+SELECT count(*) > 0+FROM agent_task_queue+WHERE parent_task_id = $1+ AND status <> 'cancelled'+`++// Defense-in-depth for the recovery path: a delegated failure with any retry+// child is still intermediate and must not wake its coordinator.+func (q *Queries) HasRetryTaskForParent(ctx context.Context, parentTaskID pgtype.UUID) (bool, error) {+ row := q.db.QueryRow(ctx, hasRetryTaskForParent, parentTaskID)+ var column_1 bool+ err := row.Scan(&column_1)+ return column_1, err+}++const hasTaskCoveringDelegatedFailureComment = `-- name: HasTaskCoveringDelegatedFailureComment :one+SELECT count(*) > 0 AS covered+FROM agent_task_queue+WHERE issue_id = $1+ AND agent_id = $2+ AND (+ $3::uuid = ANY(delivered_comment_ids)+ OR (+ id IS DISTINCT FROM $4::uuid+ AND (+ status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')+ )+ AND (trigger_comment_id = $3::uuid OR $3::uuid = ANY(coalesced_comment_ids))+ )+ )+`++type HasTaskCoveringDelegatedFailureCommentParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ CommentID pgtype.UUID `json:"comment_id"`+ ExcludeTaskID pgtype.UUID `json:"exclude_task_id"`+}++// Durable idempotency check for a recovery comment. The completion reconciler+// excludes its own just-completed task when replaying a planned-but-undelivered+// signal. A planned comment is covered only while its task can still execute;+// after a task becomes terminal, delivered_comment_ids is the sole durable+// receipt. This prevents cancelled/failed pre-delivery tasks from swallowing+// the recovery obligation while still avoiding a loop after real delivery.+func (q *Queries) HasTaskCoveringDelegatedFailureComment(ctx context.Context, arg HasTaskCoveringDelegatedFailureCommentParams) (bool, error) {+ row := q.db.QueryRow(ctx, hasTaskCoveringDelegatedFailureComment,+ arg.IssueID,+ arg.AgentID,+ arg.CommentID,+ arg.ExcludeTaskID,+ )+ var covered bool+ err := row.Scan(&covered)+ return covered, err+}+const linkTaskToIssue = `-- name: LinkTaskToIssue :execUPDATE agent_task_queueSET issue_id = $2@@ -4865,6 +5229,102 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListCreturn items, nil}+const listPendingDelegatedFailureRecoveries = `-- name: ListPendingDelegatedFailureRecoveries :many+SELECT recovery.id, recovery.issue_id, recovery.author_type, recovery.author_id, recovery.content, recovery.type, recovery.created_at, recovery.updated_at, recovery.parent_id, recovery.workspace_id, recovery.resolved_at, recovery.resolved_by_type, recovery.resolved_by_id, recovery.source_task_id, recovery.quick_action_id+FROM comment recovery+JOIN agent_task_queue failed ON failed.id = recovery.source_task_id+JOIN agent_task_queue source ON source.id = failed.delegated_from_task_id+JOIN issue source_issue ON source_issue.id = source.issue_id+JOIN agent source_agent ON source_agent.id = source.agent_id+WHERE recovery.author_type = 'system'+ AND recovery.type = 'progress_update'+ AND recovery.source_task_id IS NOT NULL+ AND recovery.issue_id = source_issue.id+ AND recovery.workspace_id = source_issue.workspace_id+ AND failed.status = 'failed'+ AND failed.delegated_from_task_id IS NOT NULL+ AND failed.autopilot_run_id IS NULL+ AND failed.trigger_evidence_kind IS DISTINCT FROM 'delegated_failure'+ AND source.autopilot_run_id IS NULL+ AND source.issue_id IS NOT NULL+ AND source.agent_id <> failed.agent_id+ AND issue_effective_status(source_issue.workspace_id, source_issue.status) NOT IN ('done', 'cancelled', 'backlog')+ AND source_agent.archived_at IS NULL+ AND source_agent.runtime_id IS NOT NULL+ AND source_agent.workspace_id = source_issue.workspace_id+ AND NOT EXISTS (+ SELECT 1+ FROM agent_task_queue retry+ WHERE retry.parent_task_id = failed.id+ AND retry.status <> 'cancelled'+ )+ AND NOT EXISTS (+ SELECT 1+ FROM agent_task_queue covering+ WHERE covering.issue_id = source_issue.id+ AND covering.agent_id = source.agent_id+ AND (+ recovery.id = ANY(covering.delivered_comment_ids)+ OR (+ (+ covering.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ OR (+ covering.status = 'deferred'+ AND covering.context->>'channel_issue_media_pending' = 'true'+ )+ )+ AND (+ covering.trigger_comment_id = recovery.id+ OR recovery.id = ANY(covering.coalesced_comment_ids)+ )+ )+ )+ )+ORDER BY recovery.created_at ASC, recovery.id ASC+LIMIT $1+`++// Durable outbox scan for platform recovery comments that are not yet owned by+// an executable task and have no terminal delivery receipt. Starting from the+// explicit recovery signal avoids retroactively waking unrelated historical+// delegated failures. A bounded runtime sweeper replays these comments after a+// transient dispatch error or process restart.+func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, maxPerTick int32) ([]Comment, error) {+ rows, err := q.db.Query(ctx, listPendingDelegatedFailureRecoveries, maxPerTick)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Comment{}+ for rows.Next() {+ var i Comment+ if err := rows.Scan(+ &i.ID,+ &i.IssueID,+ &i.AuthorType,+ &i.AuthorID,+ &i.Content,+ &i.Type,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ParentID,+ &i.WorkspaceID,+ &i.ResolvedAt,+ &i.ResolvedByType,+ &i.ResolvedByID,+ &i.SourceTaskID,+ &i.QuickActionID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :manySELECT 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, plugin_execution_manifest_id, branch_name FROM agent_task_queueWHERE runtime_id = $1 AND status IN ('queued', 'dispatched')@@ -5904,6 +6364,110 @@ func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeCommreturn i, err}+const mergeDelegatedFailureCommentIntoPendingTask = `-- name: MergeDelegatedFailureCommentIntoPendingTask :one+UPDATE agent_task_queue+SET coalesced_comment_ids = (+ SELECT COALESCE(array_agg(DISTINCT e), '{}')+ FROM unnest(array_append(coalesced_comment_ids, trigger_comment_id)) AS e+ WHERE e IS NOT NULL AND e <> $1::uuid+ ),+ trigger_comment_id = $1::uuid,+ trigger_summary = $2+WHERE id = (+ SELECT t.id FROM agent_task_queue t+ WHERE t.issue_id = $3+ AND t.agent_id = $4+ AND (+ t.status = 'queued'+ OR (t.status = 'deferred' AND t.context->>'channel_issue_media_pending' = 'true')+ )+ AND t.trigger_comment_id IS DISTINCT FROM $1::uuid+ AND NOT ($1::uuid = ANY(t.coalesced_comment_ids))+ ORDER BY t.created_at DESC+ LIMIT 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, 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, plugin_execution_manifest_id, branch_name+`++type MergeDelegatedFailureCommentIntoPendingTaskParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ TriggerSummary pgtype.Text `json:"trigger_summary"`+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+}++// A delegated failure is a platform-owned input, not a new human instruction:+// fold it into the coordinator's pre-claim task without replacing that task's+// attribution snapshot. The recovery comment is the newest input, so it becomes+// the trigger and the prior trigger joins the coalesced plan. This preserves the+// claim/prompt invariant that trigger_comment_id names the newest comment while+// retaining the pending task's original human authority and connected apps.+func (q *Queries) MergeDelegatedFailureCommentIntoPendingTask(ctx context.Context, arg MergeDelegatedFailureCommentIntoPendingTaskParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, mergeDelegatedFailureCommentIntoPendingTask,+ arg.CommentID,+ arg.TriggerSummary,+ arg.IssueID,+ arg.AgentID,+ )+ 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.PluginExecutionManifestID,+ &i.BranchName,+ )+ return i, err+}+const promoteDeferredChannelIssueTask = `-- name: PromoteDeferredChannelIssueTask :oneUPDATE agent_task_queueSET status = 'queued', fire_at = NULLdiff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex afe1454e96..dd3dbaa5b7 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -304,6 +304,94 @@ func (q *Queries) GetCommentInWorkspace(ctx context.Context, arg GetCommentInWorreturn i, err}+const getDelegatedFailureRecoveryComment = `-- name: GetDelegatedFailureRecoveryComment :one+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+WHERE issue_id = $1+ AND workspace_id = $2+ AND author_type = 'system'+ AND type = 'progress_update'+ AND source_task_id = $3+ORDER BY created_at ASC, id ASC+LIMIT 1+`++type GetDelegatedFailureRecoveryCommentParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+}++// The failed task row is locked by the caller before this lookup/insert pair,+// making (source issue, failed task) a durable idempotency key without a new+// hot-table index or schema migration. Platform recovery signals are the only+// system-authored progress updates that carry source_task_id.+func (q *Queries) GetDelegatedFailureRecoveryComment(ctx context.Context, arg GetDelegatedFailureRecoveryCommentParams) (Comment, error) {+ row := q.db.QueryRow(ctx, getDelegatedFailureRecoveryComment, arg.IssueID, arg.WorkspaceID, arg.SourceTaskID)+ var i Comment+ err := row.Scan(+ &i.ID,+ &i.IssueID,+ &i.AuthorType,+ &i.AuthorID,+ &i.Content,+ &i.Type,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ParentID,+ &i.WorkspaceID,+ &i.ResolvedAt,+ &i.ResolvedByType,+ &i.ResolvedByID,+ &i.SourceTaskID,+ &i.QuickActionID,+ )+ return i, err+}++const getDelegatedFailureRecoveryExhaustionComment = `-- name: GetDelegatedFailureRecoveryExhaustionComment :one+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id FROM comment+WHERE issue_id = $1+ AND workspace_id = $2+ AND author_type = 'system'+ AND type = 'system'+ AND source_task_id = $3+ORDER BY created_at ASC, id ASC+LIMIT 1+`++type GetDelegatedFailureRecoveryExhaustionCommentParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ SourceTaskID pgtype.UUID `json:"source_task_id"`+}++// The failed task and newest recovery-attempt row are locked by the caller+// before this lookup/insert pair. Keeping exhaustion as a separate system+// comment preserves the original recovery signal while making the automatic+// stop visible in the issue timeline.+func (q *Queries) GetDelegatedFailureRecoveryExhaustionComment(ctx context.Context, arg GetDelegatedFailureRecoveryExhaustionCommentParams) (Comment, error) {+ row := q.db.QueryRow(ctx, getDelegatedFailureRecoveryExhaustionComment, arg.IssueID, arg.WorkspaceID, arg.SourceTaskID)+ var i Comment+ err := row.Scan(+ &i.ID,+ &i.IssueID,+ &i.AuthorType,+ &i.AuthorID,+ &i.Content,+ &i.Type,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ParentID,+ &i.WorkspaceID,+ &i.ResolvedAt,+ &i.ResolvedByType,+ &i.ResolvedByID,+ &i.SourceTaskID,+ &i.QuickActionID,+ )+ return i, err+}+const getLatestMemberCommentForIssueSince = `-- name: GetLatestMemberCommentForIssueSince :oneSELECT 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, quick_action_id FROM commentWHERE issue_id = $1@@ -844,10 +932,17 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg Listconst listReconcilableCommentsForIssueSince = `-- name: ListReconcilableCommentsForIssueSince :manySELECT 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, quick_action_id FROM commentWHERE issue_id = $1- AND author_type IN ('member', 'agent')AND (- created_at > $2- OR id = ANY($3::uuid[])+ (+ author_type IN ('member', 'agent')+ AND (created_at > $2 OR id = ANY($3::uuid[]))+ )+ OR (+ author_type = 'system'+ AND type = 'progress_update'+ AND source_task_id IS NOT NULL+ AND id = ANY($3::uuid[])+ ))ORDER BY created_at ASC, id ASC`@@ -861,6 +956,11 @@ type ListReconcilableCommentsForIssueSinceParams struct {// 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), plus every id in its planned trigger/coalesced batch.+// The one platform-authored exception is a delegated-failure recovery signal:+// author_type=system, type=progress_update, source_task_id set. Such a signal+// can be registered after a coordinator was claimed and must be replayed when+// that run completes; the handler routes it through the dedicated recovery+// path instead of generic comment/mention routing.// 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, thendiff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 281d70f6b5..b9e4e6f39f 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -641,6 +641,22 @@ RETURNING *;SELECT * FROM agent_task_queueWHERE id = $1;+-- name: GetAgentTaskForDelegatedFailureUpdate :one+-- Serializes the idempotent delegated-failure recovery signal for one failed+-- task. FailTask and the stale-task sweepers can converge on the same row; the+-- lock ensures they cannot create two recovery comments/tasks for it.+SELECT * FROM agent_task_queue+WHERE id = $1+FOR UPDATE;++-- name: HasRetryTaskForParent :one+-- Defense-in-depth for the recovery path: a delegated failure with any retry+-- child is still intermediate and must not wake its coordinator.+SELECT count(*) > 0+FROM agent_task_queue+WHERE parent_task_id = $1+ AND status <> 'cancelled';+-- name: GetAgentTaskInWorkspace :one-- Loads a task only when its owning agent lives in the given workspace.-- agent_id is NOT NULL on every task row (and ON DELETE CASCADE, so the agent@@ -1331,11 +1347,73 @@ WHERE retry.id = victims.idRETURNING retry.*;-- name: CancelAgentTask :one+-- Automatic cancellation without an explicit persisted failure reason. Unlike+-- CancelAgentTaskByUser, this deliberately leaves recovery inputs replayable.UPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULLWHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')RETURNING *;+-- name: CancelAgentTaskByUser :one+-- An explicit user cancellation is a terminal acknowledgement for any+-- delegated-failure recovery signal planned into this task. Server-initiated+-- cancellations keep using CancelAgentTask / CancelAgentTaskWithReason so a+-- stale plan, claim failure, or other automatic repair can still be replayed.+UPDATE agent_task_queue AS task+SET status = 'cancelled',+ completed_at = now(),+ prepare_lease_expires_at = NULL,+ delivered_comment_ids = CASE+ -- Chat and ordinary issue tasks almost never carry a delegated-failure+ -- recovery signal. Keep their high-frequency user-cancel path to a+ -- no-join update; only validate task lineage after the cheap comment+ -- shape probe finds a possible recovery signal.+ WHEN task.trigger_comment_id IS NULL+ AND COALESCE(cardinality(task.coalesced_comment_ids), 0) = 0+ THEN task.delivered_comment_ids+ WHEN NOT EXISTS (+ SELECT 1+ FROM comment recovery_signal+ WHERE (+ recovery_signal.id = task.trigger_comment_id+ OR recovery_signal.id = ANY(task.coalesced_comment_ids)+ )+ AND recovery_signal.author_type = 'system'+ AND recovery_signal.type = 'progress_update'+ AND recovery_signal.source_task_id IS NOT NULL+ ) THEN task.delivered_comment_ids+ ELSE (+ SELECT COALESCE(array_agg(DISTINCT receipt.id), '{}')::uuid[]+ FROM unnest(array_cat(+ task.delivered_comment_ids,+ ARRAY(+ SELECT recovery.id+ FROM comment recovery+ JOIN agent_task_queue failed ON failed.id = recovery.source_task_id+ JOIN agent_task_queue source ON source.id = failed.delegated_from_task_id+ WHERE (+ recovery.id = task.trigger_comment_id+ OR recovery.id = ANY(task.coalesced_comment_ids)+ )+ AND recovery.author_type = 'system'+ AND recovery.type = 'progress_update'+ AND recovery.source_task_id IS NOT NULL+ AND failed.status = 'failed'+ AND failed.delegated_from_task_id IS NOT NULL+ AND failed.autopilot_run_id IS NULL+ AND failed.trigger_evidence_kind IS DISTINCT FROM 'delegated_failure'+ AND source.autopilot_run_id IS NULL+ AND source.issue_id = task.issue_id+ AND source.agent_id = task.agent_id+ AND recovery.issue_id = source.issue_id+ )+ )) AS receipt(id)+ )+ END+WHERE task.id = $1+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+RETURNING task.*;+-- name: SetAgentTaskBranchName :exec-- Records the delivered branch on a CANCELLED task. Needed because the daemon-- finalizes its worktree (committing whatever the agent produced) BEFORE it@@ -1370,12 +1448,11 @@ WHERE id = sqlc.arg('id') AND (error IS NULL OR error = '') AND status = 'cancel-- name: CancelAgentTaskWithReason :one-- Cancels a task AND records why, for cancellations the user did not ask for.----- Plain CancelAgentTask leaves error/failure_reason NULL, which is right for a--- user-initiated cancel — the user knows why. A server-initiated one is the--- opposite: without a persisted reason the run surfaces as an unexplained--- "cancelled", and the only trace is a 4xx in a daemon log the user never sees.--- Retrying cannot help either (the task is refused for a durable reason), so--- this is a terminal state that has to carry its own explanation.+-- CancelAgentTaskByUser leaves error/failure_reason NULL because the user knows+-- why. A server-initiated refusal is the opposite: without a persisted reason+-- the run surfaces as an unexplained "cancelled", and the only trace is a 4xx+-- in a daemon log the user never sees. Retrying cannot help either (the task is+-- refused for a durable reason), so this terminal state carries its explanation.UPDATE agent_task_queueSET status = 'cancelled',completed_at = now(),@@ -1651,6 +1728,154 @@ WHERE id = ()RETURNING id, coalesced_comment_ids;+-- name: MergeDelegatedFailureCommentIntoPendingTask :one+-- A delegated failure is a platform-owned input, not a new human instruction:+-- fold it into the coordinator's pre-claim task without replacing that task's+-- attribution snapshot. The recovery comment is the newest input, so it becomes+-- the trigger and the prior trigger joins the coalesced plan. This preserves the+-- claim/prompt invariant that trigger_comment_id names the newest comment while+-- retaining the pending task's original human authority and connected apps.+UPDATE agent_task_queue+SET coalesced_comment_ids = (+ SELECT COALESCE(array_agg(DISTINCT e), '{}')+ FROM unnest(array_append(coalesced_comment_ids, trigger_comment_id)) AS e+ WHERE e IS NOT NULL AND e <> @comment_id::uuid+ ),+ trigger_comment_id = @comment_id::uuid,+ trigger_summary = sqlc.narg('trigger_summary')+WHERE id = (+ SELECT t.id FROM agent_task_queue t+ WHERE t.issue_id = @issue_id+ AND t.agent_id = @agent_id+ AND (+ t.status = 'queued'+ OR (t.status = 'deferred' AND t.context->>'channel_issue_media_pending' = 'true')+ )+ AND t.trigger_comment_id IS DISTINCT FROM @comment_id::uuid+ AND NOT (@comment_id::uuid = ANY(t.coalesced_comment_ids))+ ORDER BY t.created_at DESC+ LIMIT 1+)+RETURNING *;++-- name: HasTaskCoveringDelegatedFailureComment :one+-- Durable idempotency check for a recovery comment. The completion reconciler+-- excludes its own just-completed task when replaying a planned-but-undelivered+-- signal. A planned comment is covered only while its task can still execute;+-- after a task becomes terminal, delivered_comment_ids is the sole durable+-- receipt. This prevents cancelled/failed pre-delivery tasks from swallowing+-- the recovery obligation while still avoiding a loop after real delivery.+SELECT count(*) > 0 AS covered+FROM agent_task_queue+WHERE issue_id = @issue_id+ AND agent_id = @agent_id+ AND (+ @comment_id::uuid = ANY(delivered_comment_ids)+ OR (+ id IS DISTINCT FROM sqlc.narg('exclude_task_id')::uuid+ AND (+ status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')+ )+ AND (trigger_comment_id = @comment_id::uuid OR @comment_id::uuid = ANY(coalesced_comment_ids))+ )+ );++-- name: CountDelegatedFailureRecoveryTasks :one+-- Counts dedicated coordinator wakeups for one failed delegated task. Merged+-- recovery signals do not create a new row and therefore do not consume an+-- automatic attempt until they need a standalone successor.+SELECT count(*)+FROM agent_task_queue+WHERE trigger_evidence_kind = 'delegated_failure'+ AND trigger_evidence_ref_id = @failed_task_id;++-- name: AcknowledgeExhaustedDelegatedFailureRecovery :one+-- Once the bounded automatic attempts are exhausted, record a terminal+-- acknowledgement on the newest recovery task. The outbox treats this receipt+-- as settled, while the service writes a separate visible system comment that+-- tells the user why no further task will be generated.+UPDATE agent_task_queue AS acknowledged+SET delivered_comment_ids = (+ SELECT COALESCE(array_agg(DISTINCT receipt.id), '{}')::uuid[]+ FROM unnest(array_append(acknowledged.delivered_comment_ids, @comment_id::uuid)) AS receipt(id)+)+WHERE acknowledged.id = (+ SELECT attempt.id+ FROM agent_task_queue attempt+ WHERE attempt.trigger_evidence_kind = 'delegated_failure'+ AND attempt.trigger_evidence_ref_id = @failed_task_id+ ORDER BY attempt.created_at DESC, attempt.id DESC+ LIMIT 1+ FOR UPDATE+)+ AND (+ SELECT count(*)+ FROM agent_task_queue attempt_count+ WHERE attempt_count.trigger_evidence_kind = 'delegated_failure'+ AND attempt_count.trigger_evidence_ref_id = @failed_task_id+ ) >= @max_attempts::int+RETURNING acknowledged.*;++-- name: ListPendingDelegatedFailureRecoveries :many+-- Durable outbox scan for platform recovery comments that are not yet owned by+-- an executable task and have no terminal delivery receipt. Starting from the+-- explicit recovery signal avoids retroactively waking unrelated historical+-- delegated failures. A bounded runtime sweeper replays these comments after a+-- transient dispatch error or process restart.+SELECT recovery.*+FROM comment recovery+JOIN agent_task_queue failed ON failed.id = recovery.source_task_id+JOIN agent_task_queue source ON source.id = failed.delegated_from_task_id+JOIN issue source_issue ON source_issue.id = source.issue_id+JOIN agent source_agent ON source_agent.id = source.agent_id+WHERE recovery.author_type = 'system'+ AND recovery.type = 'progress_update'+ AND recovery.source_task_id IS NOT NULL+ AND recovery.issue_id = source_issue.id+ AND recovery.workspace_id = source_issue.workspace_id+ AND failed.status = 'failed'+ AND failed.delegated_from_task_id IS NOT NULL+ AND failed.autopilot_run_id IS NULL+ AND failed.trigger_evidence_kind IS DISTINCT FROM 'delegated_failure'+ AND source.autopilot_run_id IS NULL+ AND source.issue_id IS NOT NULL+ AND source.agent_id <> failed.agent_id+ AND issue_effective_status(source_issue.workspace_id, source_issue.status) NOT IN ('done', 'cancelled', 'backlog')+ AND source_agent.archived_at IS NULL+ AND source_agent.runtime_id IS NOT NULL+ AND source_agent.workspace_id = source_issue.workspace_id+ AND NOT EXISTS (+ SELECT 1+ FROM agent_task_queue retry+ WHERE retry.parent_task_id = failed.id+ AND retry.status <> 'cancelled'+ )+ AND NOT EXISTS (+ SELECT 1+ FROM agent_task_queue covering+ WHERE covering.issue_id = source_issue.id+ AND covering.agent_id = source.agent_id+ AND (+ recovery.id = ANY(covering.delivered_comment_ids)+ OR (+ (+ covering.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ OR (+ covering.status = 'deferred'+ AND covering.context->>'channel_issue_media_pending' = 'true'+ )+ )+ AND (+ covering.trigger_comment_id = recovery.id+ OR recovery.id = ANY(covering.coalesced_comment_ids)+ )+ )+ )+ )+ORDER BY recovery.created_at ASC, recovery.id ASC+LIMIT @max_per_tick;+-- name: HasActiveTaskForIssueAndAgent :one-- MUL-4195: true when the (issue, agent) pair has any non-terminal task in a-- state whose completion will run completion reconciliation — queued,diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex 058864bdfa..f135bd156e 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -350,6 +350,11 @@ LIMIT 1;-- 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), plus every id in its planned trigger/coalesced batch.+-- The one platform-authored exception is a delegated-failure recovery signal:+-- author_type=system, type=progress_update, source_task_id set. Such a signal+-- can be registered after a coordinator was claimed and must be replayed when+-- that run completes; the handler routes it through the dedicated recovery+-- path instead of generic comment/mention routing.-- 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@@ -376,10 +381,17 @@ LIMIT 1;-- the first.SELECT * FROM commentWHERE issue_id = @issue_id- AND author_type IN ('member', 'agent')AND (- created_at > @since- OR id = ANY(@planned_comment_ids::uuid[])+ (+ author_type IN ('member', 'agent')+ AND (created_at > @since OR id = ANY(@planned_comment_ids::uuid[]))+ )+ OR (+ author_type = 'system'+ AND type = 'progress_update'+ AND source_task_id IS NOT NULL+ AND id = ANY(@planned_comment_ids::uuid[])+ ))ORDER BY created_at ASC, id ASC;@@ -435,6 +447,34 @@ SELECT ti.id, ti.workspace_id, sqlc.arg(author_type), sqlc.arg(author_id), sqlc.FROM touched_issue tiRETURNING *;+-- name: GetDelegatedFailureRecoveryComment :one+-- The failed task row is locked by the caller before this lookup/insert pair,+-- making (source issue, failed task) a durable idempotency key without a new+-- hot-table index or schema migration. Platform recovery signals are the only+-- system-authored progress updates that carry source_task_id.+SELECT * FROM comment+WHERE issue_id = @issue_id+ AND workspace_id = @workspace_id+ AND author_type = 'system'+ AND type = 'progress_update'+ AND source_task_id = @source_task_id+ORDER BY created_at ASC, id ASC+LIMIT 1;++-- name: GetDelegatedFailureRecoveryExhaustionComment :one+-- The failed task and newest recovery-attempt row are locked by the caller+-- before this lookup/insert pair. Keeping exhaustion as a separate system+-- comment preserves the original recovery signal while making the automatic+-- stop visible in the issue timeline.+SELECT * FROM comment+WHERE issue_id = @issue_id+ AND workspace_id = @workspace_id+ AND author_type = 'system'+ AND type = 'system'+ AND source_task_id = @source_task_id+ORDER BY created_at ASC, id ASC+LIMIT 1;+-- name: UpdateComment :oneUPDATE comment SETcontent = $2,