Skip to content

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

Go

feat(server): orphan-task recovery + auto-retry + manual rerun (MUL-1128) (#1476)

LinYushen0b1333fb0093
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 7ca6a18bd7..99b44497c5 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -132,6 +132,13 @@ var issueRunMessagesCmd = &cobra.Command{
RunE: runIssueRunMessages,
}
+var issueRerunCmd = &cobra.Command{
+ Use: "rerun <id>",
+ Short: "Re-enqueue an issue's current agent assignment as a fresh task",
+ Args: exactArgs(1),
+ RunE: runIssueRerun,
+}
+
var issueSearchCmd = &cobra.Command{
Use: "search <query>",
Short: "Search issues by title or description",
@@ -154,6 +161,7 @@ func init() {
issueCmd.AddCommand(issueSubscriberCmd)
issueCmd.AddCommand(issueRunsCmd)
issueCmd.AddCommand(issueRunMessagesCmd)
+ issueCmd.AddCommand(issueRerunCmd)
issueCmd.AddCommand(issueSearchCmd)
issueCommentCmd.AddCommand(issueCommentListCmd)
@@ -216,6 +224,9 @@ func init() {
// issue runs
issueRunsCmd.Flags().String("output", "table", "Output format: table or json")
+ // issue rerun
+ issueRerunCmd.Flags().String("output", "json", "Output format: table or json")
+
// issue run-messages
issueRunMessagesCmd.Flags().String("output", "json", "Output format: table or json")
issueRunMessagesCmd.Flags().Int("since", 0, "Only return messages after this sequence number")
@@ -903,6 +914,28 @@ func runIssueRunMessages(cmd *cobra.Command, args []string) error {
// Search command
// ---------------------------------------------------------------------------
+func runIssueRerun(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ var task map[string]any
+ if err := client.PostJSON(ctx, "/api/issues/"+args[0]+"/rerun", map[string]any{}, &task); err != nil {
+ return fmt.Errorf("rerun issue: %w", err)
+ }
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, task)
+ }
+ fmt.Fprintf(os.Stdout, "Re-enqueued task %s on agent %s\n", strVal(task, "id"), strVal(task, "agent_id"))
+ return nil
+}
+
func runIssueSearch(cmd *cobra.Command, args []string) error {
client, err := newAPIClient(cmd)
if err != nil {
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index bc0403c3cc..8d0f360697 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -85,7 +85,7 @@ func main() {
registerAutopilotListeners(bus, autopilotSvc)
// Start background sweeper to mark stale runtimes as offline.
- go runRuntimeSweeper(sweepCtx, queries, bus)
+ go runRuntimeSweeper(sweepCtx, queries, taskSvc, bus)
go runAutopilotScheduler(autopilotCtx, queries, autopilotSvc)
go runDBStatsLogger(sweepCtx, pool)
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index dc06a1ec3a..d92acc1f62 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -158,6 +158,9 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analytics
r.Get("/tasks/{taskId}/messages", h.ListTaskMessages)
r.Get("/issues/{issueId}/gc-check", h.GetIssueGCCheck)
+
+ r.Post("/runtimes/{runtimeId}/recover-orphans", h.RecoverOrphanedTasks)
+ r.Post("/tasks/{taskId}/session", h.PinTaskSession)
})
// Protected API routes
@@ -245,6 +248,7 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analytics
r.Post("/unsubscribe", h.UnsubscribeFromIssue)
r.Get("/active-task", h.GetActiveTaskForIssue)
r.Post("/tasks/{taskId}/cancel", h.CancelTask)
+ r.Post("/rerun", h.RerunIssue)
r.Get("/task-runs", h.ListTasksByIssue)
r.Get("/usage", h.GetIssueUsage)
r.Post("/reactions", h.AddIssueReaction)
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index e877ad7de2..05ec0f8185 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -7,6 +7,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -34,7 +35,7 @@ const (
// last_seen_at exceeds the stale threshold, and fails orphaned tasks.
// This handles cases where the daemon crashes, is killed without calling
// the deregister endpoint, or leaves tasks in a non-terminal state.
-func runRuntimeSweeper(ctx context.Context, queries *db.Queries, bus *events.Bus) {
+func runRuntimeSweeper(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus) {
ticker := time.NewTicker(sweepInterval)
defer ticker.Stop()
@@ -43,8 +44,8 @@ func runRuntimeSweeper(ctx context.Context, queries *db.Queries, bus *events.Bus
case <-ctx.Done():
return
case <-ticker.C:
- sweepStaleRuntimes(ctx, queries, bus)
- sweepStaleTasks(ctx, queries, bus)
+ sweepStaleRuntimes(ctx, queries, taskSvc, bus)
+ sweepStaleTasks(ctx, queries, taskSvc, bus)
gcRuntimes(ctx, queries, bus)
}
}
@@ -52,7 +53,7 @@ func runRuntimeSweeper(ctx context.Context, queries *db.Queries, bus *events.Bus
// sweepStaleRuntimes marks runtimes offline if they haven't heartbeated,
// then fails any tasks belonging to those offline runtimes.
-func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, bus *events.Bus) {
+func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus) {
staleRows, err := queries.MarkStaleRuntimesOffline(ctx, staleThresholdSeconds)
if err != nil {
slog.Warn("runtime sweeper: failed to mark stale runtimes offline", "error", err)
@@ -77,7 +78,7 @@ func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, bus *events.Bu
slog.Warn("runtime sweeper: failed to clean up stale tasks", "error", err)
} else if len(failedTasks) > 0 {
slog.Info("runtime sweeper: failed orphaned tasks", "count", len(failedTasks))
- broadcastFailedTasks(ctx, queries, bus, failedTasks)
+ taskSvc.HandleFailedTasks(ctx, failedTasks)
}
// Notify frontend clients so they re-fetch runtime list.
@@ -130,7 +131,7 @@ func gcRuntimes(ctx context.Context, queries *db.Queries, bus *events.Bus) {
// - The agent process hangs and the daemon is still heartbeating
// - The daemon failed to report task completion/failure
// - A server restart left tasks in a non-terminal state
-func sweepStaleTasks(ctx context.Context, queries *db.Queries, bus *events.Bus) {
+func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus) {
failedTasks, err := queries.FailStaleTasks(ctx, db.FailStaleTasksParams{
DispatchTimeoutSecs: dispatchTimeoutSeconds,
RunningTimeoutSecs: runningTimeoutSeconds,
@@ -144,87 +145,61 @@ func sweepStaleTasks(ctx context.Context, queries *db.Queries, bus *events.Bus)
}
slog.Info("task sweeper: failed stale tasks", "count", len(failedTasks))
- broadcastFailedTasks(ctx, queries, bus, failedTasks)
+ taskSvc.HandleFailedTasks(ctx, failedTasks)
}
-// failedTask is a common interface for both sweeper result types.
-type failedTask struct {
- ID pgtype.UUID
- AgentID pgtype.UUID
- IssueID pgtype.UUID
-}
-
-// broadcastFailedTasks publishes task:failed events with the correct WorkspaceID
-// and reconciles agent status for all affected agents.
-func broadcastFailedTasks(ctx context.Context, queries *db.Queries, bus *events.Bus, tasks any) {
- var items []failedTask
- switch ts := tasks.(type) {
- case []db.FailStaleTasksRow:
- for _, t := range ts {
- items = append(items, failedTask{ID: t.ID, AgentID: t.AgentID, IssueID: t.IssueID})
- }
- case []db.FailTasksForOfflineRuntimesRow:
- for _, t := range ts {
- items = append(items, failedTask{ID: t.ID, AgentID: t.AgentID, IssueID: t.IssueID})
- }
+// broadcastFailedTasks is preserved as a thin shim for the integration tests
+// in this package. New call sites should use TaskService.HandleFailedTasks
+// directly so the side effects (event broadcast, agent reconcile, issue
+// rollback, auto-retry) are guaranteed in one place.
+func broadcastFailedTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus, tasks []db.AgentTaskQueue) {
+ if taskSvc != nil {
+ taskSvc.HandleFailedTasks(ctx, tasks)
+ return
}
-
- affectedAgents := make(map[string]pgtype.UUID)
+ // Fallback path used by tests that don't construct a TaskService:
+ // publish task:failed events with workspace IDs and reset stuck issues.
processedIssues := make(map[string]bool)
-
- for _, ft := range items {
- // Look up workspace ID from the issue so the event reaches the right WS room.
+ affectedAgents := make(map[string]pgtype.UUID)
+ for _, t := range tasks {
+ failureReason := "agent_error"
+ if t.FailureReason.Valid && t.FailureReason.String != "" {
+ failureReason = t.FailureReason.String
+ }
workspaceID := ""
- if issue, err := queries.GetIssue(ctx, ft.IssueID); err == nil {
- workspaceID = util.UUIDToString(issue.WorkspaceID)
- // If the issue is still in_progress and no other active tasks remain,
- // reset it back to todo so the daemon can pick it up again.
- issueKey := util.UUIDToString(ft.IssueID)
- if issue.Status == "in_progress" && !processedIssues[issueKey] {
- processedIssues[issueKey] = true
- hasActive, checkErr := queries.HasActiveTaskForIssue(ctx, ft.IssueID)
- if checkErr != nil {
- slog.Warn("runtime sweeper: failed to check active tasks for issue",
- "issue_id", issueKey,
- "error", checkErr,
- )
- } else if !hasActive {
- if _, updateErr := queries.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{
- ID: ft.IssueID,
- Status: "todo",
- }); updateErr != nil {
- slog.Warn("runtime sweeper: failed to reset stuck issue to todo",
- "issue_id", issueKey,
- "error", updateErr,
- )
+ if t.IssueID.Valid {
+ if issue, err := queries.GetIssue(ctx, t.IssueID); err == nil {
+ workspaceID = util.UUIDToString(issue.WorkspaceID)
+ issueKey := util.UUIDToString(t.IssueID)
+ if issue.Status == "in_progress" && !processedIssues[issueKey] {
+ processedIssues[issueKey] = true
+ if hasActive, herr := queries.HasActiveTaskForIssue(ctx, t.IssueID); herr == nil && !hasActive {
+ queries.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{ID: t.IssueID, Status: "todo"})
}
}
}
}
-
bus.Publish(events.Event{
Type: protocol.EventTaskFailed,
WorkspaceID: workspaceID,
ActorType: "system",
Payload: map[string]any{
- "task_id": util.UUIDToString(ft.ID),
- "agent_id": util.UUIDToString(ft.AgentID),
- "issue_id": util.UUIDToString(ft.IssueID),
- "status": "failed",
+ "task_id": util.UUIDToString(t.ID),
+ "agent_id": util.UUIDToString(t.AgentID),
+ "issue_id": util.UUIDToString(t.IssueID),
+ "status": "failed",
+ "failure_reason": failureReason,
},
})
-
- agentKey := util.UUIDToString(ft.AgentID)
- affectedAgents[agentKey] = ft.AgentID
+ affectedAgents[util.UUIDToString(t.AgentID)] = t.AgentID
}
-
- // Reconcile status for each affected agent.
for _, agentID := range affectedAgents {
reconcileAgentStatus(ctx, queries, bus, agentID)
}
}
// reconcileAgentStatus checks running task count and updates agent status.
+// Used only by the test-fallback path of broadcastFailedTasks above.
func reconcileAgentStatus(ctx context.Context, queries *db.Queries, bus *events.Bus, agentID pgtype.UUID) {
running, err := queries.CountRunningTasks(ctx, agentID)
if err != nil {
diff --git a/server/cmd/server/runtime_sweeper_test.go b/server/cmd/server/runtime_sweeper_test.go
index 5d9e7991aa..f8f4c7c8ef 100644
--- a/server/cmd/server/runtime_sweeper_test.go
+++ b/server/cmd/server/runtime_sweeper_test.go
@@ -127,7 +127,7 @@ func TestSweepStaleTasksBroadcastsWithWorkspaceID(t *testing.T) {
}
// Call broadcastFailedTasks — this is what we're testing
- broadcastFailedTasks(context.Background(), queries, bus, failedTasks)
+ broadcastFailedTasks(context.Background(), queries, nil, bus, failedTasks)
// Verify the event was published with WorkspaceID (the core of the bug fix)
mu.Lock()
@@ -195,7 +195,7 @@ func TestSweepStaleTasksReconcileAgentStatus(t *testing.T) {
t.Fatal("expected at least 1 stale task")
}
- broadcastFailedTasks(context.Background(), queries, bus, failedTasks)
+ broadcastFailedTasks(context.Background(), queries, nil, bus, failedTasks)
// Verify agent status is now "idle" in DB
var agentStatus string
@@ -256,7 +256,7 @@ func TestSweepDispatchedStaleTask(t *testing.T) {
t.Fatal("expected at least 1 stale dispatched task")
}
- broadcastFailedTasks(context.Background(), queries, bus, failedTasks)
+ broadcastFailedTasks(context.Background(), queries, nil, bus, failedTasks)
// Verify DB: task should be failed
var status string
@@ -378,7 +378,7 @@ func TestSweepResetsInProgressIssueToTodo(t *testing.T) {
}
// This is what we're testing: issue must be reset from in_progress → todo.
- broadcastFailedTasks(ctx, queries, bus, failedTasks)
+ broadcastFailedTasks(ctx, queries, nil, bus, failedTasks)
var issueStatus string
err = testPool.QueryRow(ctx, `SELECT status FROM issue WHERE id = $1`, issueID).Scan(&issueStatus)
@@ -449,7 +449,7 @@ func TestSweepDoesNotResetIssueAlreadyInReview(t *testing.T) {
t.Fatalf("FailStaleTasks failed: %v", err)
}
- broadcastFailedTasks(ctx, queries, bus, failedTasks)
+ broadcastFailedTasks(ctx, queries, nil, bus, failedTasks)
// Issue should remain in_review — the sweeper must not clobber agent progress.
var issueStatus string
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index a06d97127a..aae32b0dea 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -122,7 +122,7 @@ func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []Tas
}, nil)
}
-func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir string) error {
+func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir, failureReason string) error {
body := map[string]any{"error": errMsg}
if sessionID != "" {
body["session_id"] = sessionID
@@ -130,9 +130,35 @@ func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDi
if workDir != "" {
body["work_dir"] = workDir
}
+ if failureReason != "" {
+ body["failure_reason"] = failureReason
+ }
return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/fail", taskID), body, nil)
}
+// PinTaskSession persists the agent's session_id and work_dir on the task
+// row mid-flight so a daemon crash doesn't lose the resume pointer.
+func (c *Client) PinTaskSession(ctx context.Context, taskID, sessionID, workDir string) error {
+ if sessionID == "" && workDir == "" {
+ return nil
+ }
+ body := map[string]any{}
+ if sessionID != "" {
+ body["session_id"] = sessionID
+ }
+ if workDir != "" {
+ body["work_dir"] = workDir
+ }
+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/session", taskID), body, nil)
+}
+
+// RecoverOrphans tells the server to fail any dispatched/running tasks the
+// previous daemon process for this runtime left behind. The server will
+// auto-retry eligible tasks.
+func (c *Client) RecoverOrphans(ctx context.Context, runtimeID string) error {
+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/runtimes/%s/recover-orphans", runtimeID), map[string]any{}, nil)
+}
+
// GetTaskStatus returns the current status of a task. Used by the daemon to
// detect if a task was cancelled while it was executing.
func (c *Client) GetTaskStatus(ctx context.Context, taskID string) (string, error) {
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 19fe86d00d..600c368b83 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -443,6 +443,16 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context) error {
go d.syncWorkspaceRepos(id, resp.Repos)
}
+ // Tell the server about any tasks the previous daemon process was
+ // running on these runtimes. Without this, an issue can stay stuck
+ // at in_progress until the slow heartbeat sweeper or the in-flight
+ // task timeout (2.5h) kicks in.
+ for _, rid := range runtimeIDs {
+ if err := d.client.RecoverOrphans(ctx, rid); err != nil {
+ d.logger.Warn("recover-orphans failed", "runtime_id", rid, "error", err)
+ }
+ }
+
d.logger.Info("watching workspace", "workspace_id", id, "name", name, "runtimes", len(resp.Runtimes), "repos", len(resp.Repos))
registered++
}
@@ -849,7 +859,7 @@ func (d *Daemon) handleTask(ctx context.Context, task Task) {
if err := d.client.StartTask(ctx, task.ID); err != nil {
taskLog.Error("start task failed", "error", err)
- if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("start task failed: %s", err.Error()), "", ""); failErr != nil {
+ if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("start task failed: %s", err.Error()), "", "", "agent_error"); failErr != nil {
taskLog.Error("fail task after start error", "error", failErr)
}
return
@@ -896,7 +906,7 @@ func (d *Daemon) handleTask(ctx context.Context, task Task) {
taskLog.Error("task failed", "error", err)
// runTask returned without a TaskResult, so we don't have a SessionID
// to forward — best we can do is record the failure.
- if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", ""); failErr != nil {
+ if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", "agent_error"); failErr != nil {
taskLog.Error("fail task callback failed", "error", failErr)
}
return
@@ -925,14 +935,14 @@ func (d *Daemon) handleTask(ctx context.Context, task Task) {
// have built a real session before getting stuck (rate-limit, tool
// error, etc.) and we want the next chat turn to resume there
// rather than start over and "forget" the conversation.
- if err := d.client.FailTask(ctx, task.ID, result.Comment, result.SessionID, result.WorkDir); err != nil {
+ if err := d.client.FailTask(ctx, task.ID, result.Comment, result.SessionID, result.WorkDir, "agent_error"); err != nil {
taskLog.Error("report blocked task failed", "error", err)
}
default:
taskLog.Info("task completed", "status", result.Status)
if err := d.client.CompleteTask(ctx, task.ID, result.Comment, result.BranchName, result.SessionID, result.WorkDir); err != nil {
taskLog.Error("complete task failed, falling back to fail", "error", err)
- if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("complete task failed: %s", err.Error()), result.SessionID, result.WorkDir); failErr != nil {
+ if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("complete task failed: %s", err.Error()), result.SessionID, result.WorkDir, "agent_error"); failErr != nil {
taskLog.Error("fail task fallback also failed", "error", failErr)
}
}
@@ -1298,6 +1308,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
}
}()
+ var sessionPinned atomic.Bool
for {
select {
case msg, ok := <-session.Messages:
@@ -1305,6 +1316,22 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro
goto drainDone
}
switch msg.Type {
+ case agent.MessageStatus:
+ // Persist the session/work_dir as soon as the backend
+ // reveals them. Without this, a daemon crash mid-run
+ // loses the resume pointer and the auto-retry fires
+ // without context.
+ if msg.SessionID != "" && !sessionPinned.Swap(true) {
+ sid := msg.SessionID
+ wd := opts.Cwd
+ go func() {
+ pinCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := d.client.PinTaskSession(pinCtx, taskID, sid, wd); err != nil {
+ taskLog.Debug("pin session failed", "error", err)
+ }
+ }()
+ }
case agent.MessageToolUse:
n := toolCount.Add(1)
taskLog.Info(fmt.Sprintf("tool #%d: %s", n, msg.Tool))
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index cc9c526d4d..d14f29171a 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -125,6 +125,10 @@ type AgentTaskResponse struct {
CompletedAt *string `json:"completed_at"`
Result any `json:"result"`
Error *string `json:"error"`
+ FailureReason string `json:"failure_reason,omitempty"` // see TaskService.MaybeRetryFailedTask
+ Attempt int32 `json:"attempt"`
+ MaxAttempts int32 `json:"max_attempts"`
+ ParentTaskID *string `json:"parent_task_id,omitempty"`
Agent *TaskAgentData `json:"agent,omitempty"`
Repos []RepoData `json:"repos,omitempty"`
CreatedAt string `json:"created_at"`
@@ -154,6 +158,10 @@ func taskToResponse(t db.AgentTaskQueue) AgentTaskResponse {
if t.Result != nil {
json.Unmarshal(t.Result, &result)
}
+ failureReason := ""
+ if t.FailureReason.Valid {
+ failureReason = t.FailureReason.String
+ }
return AgentTaskResponse{
ID: uuidToString(t.ID),
AgentID: uuidToString(t.AgentID),
@@ -166,6 +174,10 @@ func taskToResponse(t db.AgentTaskQueue) AgentTaskResponse {
CompletedAt: timestampToPtr(t.CompletedAt),
Result: result,
Error: textToPtr(t.Error),
+ FailureReason: failureReason,
+ Attempt: t.Attempt,
+ MaxAttempts: t.MaxAttempts,
+ ParentTaskID: uuidToPtr(t.ParentTaskID),
CreatedAt: timestampToString(t.CreatedAt),
TriggerCommentID: uuidToPtr(t.TriggerCommentID),
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 166eb6b505..7de03b5163 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -969,9 +969,10 @@ func (h *Handler) GetTaskStatus(w http.ResponseWriter, r *http.Request) {
// FailTask marks a running task as failed.
type TaskFailRequest struct {
- Error string `json:"error"`
- SessionID string `json:"session_id,omitempty"`
- WorkDir string `json:"work_dir,omitempty"`
+ Error string `json:"error"`
+ SessionID string `json:"session_id,omitempty"`
+ WorkDir string `json:"work_dir,omitempty"`
+ FailureReason string `json:"failure_reason,omitempty"`
}
func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
@@ -988,14 +989,14 @@ func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {
return
}
- task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir)
+ task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir, req.FailureReason)
if err != nil {
slog.Warn("fail task failed", "task_id", taskID, "error", err)
writeError(w, http.StatusBadRequest, err.Error())
return
}
- slog.Info("task failed", "task_id", taskID, "agent_id", uuidToString(task.AgentID), "task_error", req.Error)
+ slog.Info("task failed", "task_id", taskID, "agent_id", uuidToString(task.AgentID), "task_error", req.Error, "failure_reason", req.FailureReason)
writeJSON(w, http.StatusOK, taskToResponse(*task))
}
diff --git a/server/internal/handler/task_lifecycle.go b/server/internal/handler/task_lifecycle.go
new file mode 100644
index 0000000000..73a120fc30
--- /dev/null
+++ b/server/internal/handler/task_lifecycle.go
@@ -0,0 +1,115 @@
+package handler
+
+import (
+ "encoding/json"
+ "log/slog"
+ "net/http"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// RecoverOrphanedTasks is called by the daemon at startup for each runtime
+// it owns. It atomically fails any dispatched/running tasks the server still
+// believes belong to that runtime — those are the tasks the previous daemon
+// process was running when it died — and triggers MaybeRetryFailedTask for
+// each so the user sees a fresh attempt instead of a permanently stuck row.
+//
+// This is the targeted fix for "issue stuck at in_progress when daemon
+// restarts mid-task": the runtime heartbeat sweeper takes up to 75s + the
+// in-process task timeout (2.5h) to notice such tasks; the daemon itself
+// knows the moment it comes back up, so we let it report orphan recovery.
+func (h *Handler) RecoverOrphanedTasks(w http.ResponseWriter, r *http.Request) {
+ runtimeID := chi.URLParam(r, "runtimeId")
+ if _, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID); !ok {
+ return
+ }
+
+ rows, err := h.Queries.RecoverOrphanedTasksForRuntime(r.Context(), parseUUID(runtimeID))
+ if err != nil {
+ slog.Warn("recover-orphans failed", "runtime_id", runtimeID, "error", err)
+ writeError(w, http.StatusInternalServerError, "recover orphans failed")
+ return
+ }
+
+ // Funnel through the shared post-failure pipeline so we get the same
+ // task:failed events, agent reconcile, issue rollback, and auto-retry
+ // behaviour as the runtime sweeper. This was previously a fast-path
+ // that bypassed those side effects, leaving the UI stale when no retry
+ // was created (max_attempts exhausted, autopilot, non-retryable reason).
+ retried := h.TaskService.HandleFailedTasks(r.Context(), rows)
+
+ if len(rows) > 0 {
+ slog.Info("recover-orphans completed",
+ "runtime_id", runtimeID,
+ "orphaned", len(rows),
+ "retried", retried,
+ )
+ }
+
+ writeJSON(w, http.StatusOK, map[string]any{
+ "orphaned": len(rows),
+ "retried": retried,
+ })
+}
+
+// PinTaskSession lets the daemon persist the agent's session_id and
+// work_dir as soon as they're known — typically right after the agent
+// emits its first system message — so a crash mid-run doesn't lose the
+// resume pointer needed to continue the conversation on the next attempt.
+type PinTaskSessionRequest struct {
+ SessionID string `json:"session_id,omitempty"`
+ WorkDir string `json:"work_dir,omitempty"`
+}
+
+func (h *Handler) PinTaskSession(w http.ResponseWriter, r *http.Request) {
+ taskID := chi.URLParam(r, "taskId")
+ if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {
+ return
+ }
+
+ var req PinTaskSessionRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if req.SessionID == "" && req.WorkDir == "" {
+ writeError(w, http.StatusBadRequest, "session_id or work_dir required")
+ return
+ }
+
+ params := db.UpdateAgentTaskSessionParams{ID: parseUUID(taskID)}
+ if req.SessionID != "" {
+ params.SessionID = pgtype.Text{String: req.SessionID, Valid: true}
+ }
+ if req.WorkDir != "" {
+ params.WorkDir = pgtype.Text{String: req.WorkDir, Valid: true}
+ }
+ if err := h.Queries.UpdateAgentTaskSession(r.Context(), params); err != nil {
+ slog.Warn("pin-session failed", "task_id", taskID, "error", err)
+ writeError(w, http.StatusInternalServerError, "pin session failed")
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// RerunIssue manually re-enqueues the issue's current agent assignment as a
+// fresh task. Useful when an issue is stuck or the user wants to retry a
+// failed run. The new task carries the most recent session_id/work_dir so
+// the agent can resume where it left off when the backend supports it.
+func (h *Handler) RerunIssue(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ issue, ok := h.loadIssueForUser(w, r, id)
+ if !ok {
+ return
+ }
+
+ task, err := h.TaskService.RerunIssue(r.Context(), issue.ID, pgtype.UUID{})
+ if err != nil {
+ slog.Warn("issue rerun failed", "issue_id", id, "error", err)
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusAccepted, taskToResponse(*task))
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 170aef90a9..d175bb686a 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -470,14 +470,18 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
// tool error), the daemon should pass them so we can preserve the resume
// pointer on both the task row and the chat_session — otherwise the next
// chat turn would silently start a brand-new session and lose memory.
-func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir string) (*db.AgentTaskQueue, error) {
+//
+// failureReason is a coarse classifier consumed by the auto-retry path.
+// Pass "" when unknown (treated as 'agent_error').
+func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, failureReason string) (*db.AgentTaskQueue, error) {
var task db.AgentTaskQueue
if err := s.runInTx(ctx, func(qtx *db.Queries) error {
t, err := qtx.FailAgentTask(ctx, db.FailAgentTaskParams{
- ID: taskID,
- Error: pgtype.Text{String: errMsg, Valid: true},
- SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
- WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
+ ID: taskID,
+ Error: pgtype.Text{String: errMsg, Valid: true},
+ FailureReason: pgtype.Text{String: failureReason, Valid: failureReason != ""},
+ SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
+ WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
})
if err != nil {
return err
@@ -521,9 +525,18 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
return nil, fmt.Errorf("fail task: %w", err)
}
- slog.Warn("task failed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID), "error", errMsg)
+ slog.Warn("task failed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID), "error", errMsg, "failure_reason", failureReason)
- if errMsg != "" && task.IssueID.Valid {
+ // Auto-retry eligible failures (orphan, timeout, runtime_offline,
+ // runtime_recovery). The helper itself enforces attempt < max_attempts
+ // and only triggers for issue/chat tasks.
+ retried, _ := s.MaybeRetryFailedTask(ctx, task)
+
+ // 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.
+ if errMsg != "" && task.IssueID.Valid && retried == nil {
s.createAgentComment(ctx, task.IssueID, task.AgentID, redact.Text(errMsg), "system", task.TriggerCommentID)
}
// Reconcile agent status
@@ -535,6 +548,213 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
return &task, nil
}
+// retryableReasons enumerates failure reasons that the auto-retry path is
+// allowed to act on. Agent-side errors (compile failures, model rejections,
+// etc.) are intentionally excluded — those are real problems that the user
+// should see, not infrastructure flakiness.
+var retryableReasons = map[string]bool{
+ "runtime_offline": true,
+ "runtime_recovery": true,
+ "timeout": true,
+}
+
+// MaybeRetryFailedTask spawns a fresh queued attempt for a recently-failed
+// task when the failure was infrastructure-shaped (daemon crash, runtime
+// went offline, dispatch/run timeout) and the task hasn't exhausted its
+// max_attempts budget. The child task inherits agent/runtime/issue/chat
+// links and the parent's session_id/work_dir so the agent can resume the
+// conversation when the backend supports it. Returns the new task, or nil
+// when no retry was created.
+//
+// Autopilot tasks are NOT auto-retried here; the autopilot scheduler owns
+// its own re-run cadence and we don't want to double-fire it.
+func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentTaskQueue) (*db.AgentTaskQueue, error) {
+ if parent.Status != "failed" {
+ return nil, nil
+ }
+ reason := ""
+ if parent.FailureReason.Valid {
+ reason = parent.FailureReason.String
+ }
+ if !retryableReasons[reason] {
+ return nil, nil
+ }
+ if parent.Attempt >= parent.MaxAttempts {
+ slog.Info("task auto-retry skipped: budget exhausted",
+ "task_id", util.UUIDToString(parent.ID),
+ "attempt", parent.Attempt,
+ "max_attempts", parent.MaxAttempts,
+ )
+ return nil, nil
+ }
+ if parent.AutopilotRunID.Valid {
+ // Autopilot has its own retry semantics; do not double-trigger.
+ return nil, nil
+ }
+ if !parent.IssueID.Valid && !parent.ChatSessionID.Valid {
+ return nil, nil
+ }
+
+ child, err := s.Queries.CreateRetryTask(ctx, parent.ID)
+ if err != nil {
+ slog.Warn("task auto-retry failed",
+ "parent_task_id", util.UUIDToString(parent.ID),
+ "reason", reason,
+ "error", err,
+ )
+ return nil, err
+ }
+ slog.Info("task auto-retry enqueued",
+ "parent_task_id", util.UUIDToString(parent.ID),
+ "child_task_id", util.UUIDToString(child.ID),
+ "reason", reason,
+ "attempt", child.Attempt,
+ "max_attempts", child.MaxAttempts,
+ )
+ s.broadcastTaskEvent(ctx, protocol.EventTaskDispatch, child)
+ return &child, nil
+}
+
+// RerunIssue creates a fresh queued task for the agent currently assigned
+// to the issue. Used by the manual rerun endpoint. Carries the most recent
+// session_id/work_dir on the issue (across any status) so the new run
+// resumes from where the prior one left off when the backend supports it.
+//
+// Only tasks belonging to the issue's current assignee are cancelled.
+// Tasks owned by other agents on the same issue (e.g. a parallel
+// @-mention agent) are left alone — rerun must not collateral-cancel
+// them.
+func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, triggerCommentID pgtype.UUID) (*db.AgentTaskQueue, error) {
+ issue, err := s.Queries.GetIssue(ctx, issueID)
+ if err != nil {
+ return nil, fmt.Errorf("load issue: %w", err)
+ }
+ if !issue.AssigneeID.Valid || issue.AssigneeType.String != "agent" {
+ return nil, fmt.Errorf("issue is not assigned to an agent")
+ }
+ // Cancel only the assignee's active/queued tasks on this issue. This
+ // covers both the unique-index conflict (queued/dispatched) and a
+ // stuck running task without touching other agents on the issue.
+ cancelled, err := s.Queries.CancelAgentTasksByIssueAndAgent(ctx, db.CancelAgentTasksByIssueAndAgentParams{
+ IssueID: issueID,
+ AgentID: issue.AssigneeID,
+ })
+ if err != nil {
+ slog.Warn("rerun: cancel prior tasks failed",
+ "issue_id", util.UUIDToString(issueID),
+ "agent_id", util.UUIDToString(issue.AssigneeID),
+ "error", err,
+ )
+ }
+ for _, t := range cancelled {
+ s.ReconcileAgentStatus(ctx, t.AgentID)
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
+ }
+
+ task, err := s.EnqueueTaskForIssue(ctx, issue, triggerCommentID)
+ if err != nil {
+ return nil, err
+ }
+ slog.Info("issue rerun enqueued",
+ "task_id", util.UUIDToString(task.ID),
+ "issue_id", util.UUIDToString(issueID),
+ "agent_id", util.UUIDToString(issue.AssigneeID),
+ "cancelled_prior", len(cancelled),
+ )
+ return &task, nil
+}
+
+// HandleFailedTasks runs the post-failure side effects for a batch of
+// freshly-failed tasks: optional auto-retry, task:failed event broadcast,
+// agent status reconciliation, and (when an issue has no remaining active
+// task and isn't being retried) resetting the issue back to todo so the
+// daemon can pick it up again.
+//
+// All callers that surface a task as failed — sweepers, FailTask,
+// recover-orphans — funnel through here so the same UI-consistency
+// guarantees apply on every code path.
+func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTaskQueue) int {
+ if len(tasks) == 0 {
+ return 0
+ }
+
+ affectedAgents := make(map[string]pgtype.UUID)
+ processedIssues := make(map[string]bool)
+ retriedIssues := make(map[string]bool)
+ retried := 0
+
+ for _, t := range tasks {
+ // Auto-retry first so the issue stays in_progress rather than
+ // flapping todo → in_progress within a tick.
+ if child, _ := s.MaybeRetryFailedTask(ctx, t); child != nil {
+ retried++
+ if t.IssueID.Valid {
+ retriedIssues[util.UUIDToString(t.IssueID)] = true
+ }
+ }
+
+ failureReason := "agent_error"
+ if t.FailureReason.Valid && t.FailureReason.String != "" {
+ failureReason = t.FailureReason.String
+ }
+
+ workspaceID := ""
+ if t.IssueID.Valid {
+ if issue, err := s.Queries.GetIssue(ctx, t.IssueID); err == nil {
+ workspaceID = util.UUIDToString(issue.WorkspaceID)
+ // Reset stuck in_progress issues only when no other active
+ // task exists for the issue and no retry was just enqueued.
+ issueKey := util.UUIDToString(t.IssueID)
+ if issue.Status == "in_progress" && !processedIssues[issueKey] && !retriedIssues[issueKey] {
+ processedIssues[issueKey] = true
+ hasActive, checkErr := s.Queries.HasActiveTaskForIssue(ctx, t.IssueID)
+ if checkErr != nil {
+ slog.Warn("handle failed tasks: active check failed",
+ "issue_id", issueKey,
+ "error", checkErr,
+ )
+ } else if !hasActive {
+ if _, updateErr := s.Queries.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{
+ ID: t.IssueID,
+ Status: "todo",
+ }); updateErr != nil {
+ slog.Warn("handle failed tasks: reset stuck issue failed",
+ "issue_id", issueKey,
+ "error", updateErr,
+ )
+ }
+ }
+ }
+ }
+ }
+ if workspaceID == "" {
+ workspaceID = s.ResolveTaskWorkspaceID(ctx, t)
+ }
+
+ if workspaceID != "" {
+ s.Bus.Publish(events.Event{
+ Type: protocol.EventTaskFailed,
+ WorkspaceID: workspaceID,
+ ActorType: "system",
+ Payload: map[string]any{
+ "task_id": util.UUIDToString(t.ID),
+ "agent_id": util.UUIDToString(t.AgentID),
+ "issue_id": util.UUIDToString(t.IssueID),
+ "status": "failed",
+ "failure_reason": failureReason,
+ },
+ })
+ }
+
+ affectedAgents[util.UUIDToString(t.AgentID)] = t.AgentID
+ }
+
+ for _, agentID := range affectedAgents {
+ s.ReconcileAgentStatus(ctx, agentID)
+ }
+ return retried
+}
+
// 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/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index 495518a3a2..dd9dd56b9a 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -150,7 +150,7 @@ func TestFailTask_AlreadyFinalized(t *testing.T) {
Bus: events.New(),
}
- got, err := svc.FailTask(context.Background(), taskID, "agent crashed", "", "")
+ got, err := svc.FailTask(context.Background(), taskID, "agent crashed", "", "", "")
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
diff --git a/server/migrations/055_task_lease_and_retry.down.sql b/server/migrations/055_task_lease_and_retry.down.sql
new file mode 100644
index 0000000000..72f3eee886
--- /dev/null
+++ b/server/migrations/055_task_lease_and_retry.down.sql
@@ -0,0 +1,8 @@
+DROP INDEX IF EXISTS idx_agent_task_queue_parent;
+
+ALTER TABLE agent_task_queue
+ DROP COLUMN IF EXISTS attempt,
+ DROP COLUMN IF EXISTS max_attempts,
+ DROP COLUMN IF EXISTS parent_task_id,
+ DROP COLUMN IF EXISTS failure_reason,
+ DROP COLUMN IF EXISTS last_heartbeat_at;
diff --git a/server/migrations/055_task_lease_and_retry.up.sql b/server/migrations/055_task_lease_and_retry.up.sql
new file mode 100644
index 0000000000..730f2118d5
--- /dev/null
+++ b/server/migrations/055_task_lease_and_retry.up.sql
@@ -0,0 +1,26 @@
+-- Adds task-level retry/lease bookkeeping so the runtime sweeper and the
+-- daemon startup recovery path can distinguish "fresh attempt" from
+-- "auto-rerun after orphan", and so resume context survives a daemon
+-- restart mid-execution.
+--
+-- Columns:
+-- attempt -- 1 for the first run, incremented per auto-retry/manual rerun
+-- max_attempts -- ceiling honored by the auto-retry path; 1 disables retry
+-- parent_task_id -- back-pointer to the task that this one re-attempts
+-- failure_reason -- coarse classifier set when status flips to failed:
+-- 'agent_error', 'timeout', 'runtime_offline',
+-- 'runtime_recovery', 'manual'. The auto-retry path
+-- uses this to decide whether to spawn a child task.
+-- last_heartbeat_at -- mid-task heartbeat timestamp; the runtime heartbeat
+-- already drives runtime liveness, but per-task
+-- timestamps let us tell stale tasks apart from
+-- long-running ones in future enhancements.
+
+ALTER TABLE agent_task_queue
+ ADD COLUMN attempt INT NOT NULL DEFAULT 1,
+ ADD COLUMN max_attempts INT NOT NULL DEFAULT 2,
+ ADD COLUMN parent_task_id UUID REFERENCES agent_task_queue(id) ON DELETE SET NULL,
+ ADD COLUMN failure_reason TEXT,
+ ADD COLUMN last_heartbeat_at TIMESTAMPTZ;
+
+CREATE INDEX idx_agent_task_queue_parent ON agent_task_queue(parent_task_id);
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index 255061d792..f6f2dce835 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -56,14 +56,15 @@ const (
// Message is a unified event emitted by an agent during execution.
type Message struct {
- Type MessageType
- Content string // text content (Text, Error, Log)
- Tool string // tool name (ToolUse, ToolResult)
- CallID string // tool call ID (ToolUse, ToolResult)
- Input map[string]any // tool input (ToolUse)
- Output string // tool output (ToolResult)
- Status string // agent status string (Status)
- Level string // log level (Log)
+ Type MessageType
+ Content string // text content (Text, Error, Log)
+ Tool string // tool name (ToolUse, ToolResult)
+ CallID string // tool call ID (ToolUse, ToolResult)
+ Input map[string]any // tool input (ToolUse)
+ Output string // tool output (ToolResult)
+ Status string // agent status string (Status)
+ Level string // log level (Log)
+ SessionID string // backend session id (Status), for early resume-pointer pinning
}
// TokenUsage tracks token consumption for a single model.
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index 8dba21581a..a436949c26 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -149,7 +149,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
if msg.SessionID != "" {
sessionID = msg.SessionID
}
- trySend(msgCh, Message{Type: MessageStatus, Status: "running"})
+ trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sessionID})
case "result":
closeStdin()
sessionID = msg.SessionID
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index b7f21ff974..fe4df78d76 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -628,7 +628,7 @@ func (c *codexClient) handleEvent(msg map[string]any) {
case "task_started":
c.turnStarted = true
if c.onMessage != nil {
- c.onMessage(Message{Type: MessageStatus, Status: "running"})
+ c.onMessage(Message{Type: MessageStatus, Status: "running", SessionID: c.threadID})
}
case "agent_message":
text, _ := msg["message"].(string)
@@ -709,7 +709,7 @@ func (c *codexClient) handleRawNotification(method string, params map[string]any
c.turnID = turnID
}
if c.onMessage != nil {
- c.onMessage(Message{Type: MessageStatus, Status: "running"})
+ c.onMessage(Message{Type: MessageStatus, Status: "running", SessionID: c.threadID})
}
case "turn/completed":
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index d7654c7582..ad85dc9c0c 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -55,7 +55,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id
+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, last_heartbeat_at
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -80,6 +80,11 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
)
return i, err
}
@@ -106,6 +111,66 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
return err
}
+const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgent :many
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now()
+WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running')
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at
+`
+
+type CancelAgentTasksByIssueAndAgentParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+// Cancels active tasks for a single (issue, agent) pair without touching
+// tasks belonging to other agents on the same issue. Used by the manual
+// rerun flow so re-running the assignee doesn't collateral-cancel a
+// still-running @-mention agent on the same issue.
+func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg CancelAgentTasksByIssueAndAgentParams) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, cancelAgentTasksByIssueAndAgent, arg.IssueID, arg.AgentID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const claimAgentTask = `-- name: ClaimAgentTask :one
UPDATE agent_task_queue
SET status = 'dispatched', dispatched_at = now()
@@ -125,7 +190,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id
+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, last_heartbeat_at
`
// Claims the next queued task for an agent, enforcing per-(issue, agent) serialization:
@@ -155,6 +220,11 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (Agen
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
)
return i, err
}
@@ -198,7 +268,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :one
UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4
WHERE id = $1 AND status = 'running'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id
+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, last_heartbeat_at
`
type CompleteAgentTaskParams struct {
@@ -235,6 +305,11 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
)
return i, err
}
@@ -326,7 +401,7 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent
const createAgentTask = `-- name: CreateAgentTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id)
VALUES ($1, $2, $3, 'queued', $4, $5)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id
+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, last_heartbeat_at
`
type CreateAgentTaskParams struct {
@@ -365,6 +440,63 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
+ )
+ return i, err
+}
+
+const createRetryTask = `-- name: CreateRetryTask :one
+INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
+ status, priority, trigger_comment_id, context,
+ session_id, work_dir,
+ attempt, max_attempts, parent_task_id
+)
+SELECT
+ p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
+ 'queued', p.priority, p.trigger_comment_id, p.context,
+ p.session_id, p.work_dir,
+ p.attempt + 1, p.max_attempts, p.id
+FROM agent_task_queue p
+WHERE p.id = $1
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at
+`
+
+// Clones a parent task into a fresh queued attempt. Carries forward the
+// agent's resume context (session_id/work_dir) so the child can continue
+// the conversation when the backend supports it. attempt is incremented;
+// max_attempts and trigger_comment_id are inherited.
+func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, createRetryTask, 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.LastHeartbeatAt,
)
return i, err
}
@@ -374,17 +506,19 @@ UPDATE agent_task_queue
SET status = 'failed',
completed_at = now(),
error = $2,
- session_id = COALESCE($3, session_id),
- work_dir = COALESCE($4, work_dir)
+ failure_reason = COALESCE($3, 'agent_error'),
+ session_id = COALESCE($4, session_id),
+ work_dir = COALESCE($5, work_dir)
WHERE id = $1 AND status IN ('dispatched', 'running')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id
+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, last_heartbeat_at
`
type FailAgentTaskParams struct {
- ID pgtype.UUID `json:"id"`
- Error pgtype.Text `json:"error"`
- SessionID pgtype.Text `json:"session_id"`
- WorkDir pgtype.Text `json:"work_dir"`
+ ID pgtype.UUID `json:"id"`
+ Error pgtype.Text `json:"error"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
}
// Marks a task as failed. session_id and work_dir are merged via COALESCE so
@@ -393,10 +527,14 @@ type FailAgentTaskParams struct {
// pointer is preserved on the task row. The next chat task can then fall
// back to GetLastChatTaskSession and continue the conversation instead of
// silently starting over.
+//
+// failure_reason is a coarse classifier consumed by the auto-retry path;
+// 'agent_error' is the safe default when the daemon doesn't supply one.
func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, failAgentTask,
arg.ID,
arg.Error,
+ arg.FailureReason,
arg.SessionID,
arg.WorkDir,
)
@@ -420,16 +558,22 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
)
return i, err
}
const failStaleTasks = `-- name: FailStaleTasks :many
UPDATE agent_task_queue
-SET status = 'failed', completed_at = now(), error = 'task timed out'
+SET status = 'failed', completed_at = now(), error = 'task timed out',
+ failure_reason = 'timeout'
WHERE (status = 'dispatched' AND dispatched_at < now() - make_interval(secs => $1::double precision))
OR (status = 'running' AND started_at < now() - make_interval(secs => $2::double precision))
-RETURNING id, agent_id, issue_id
+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, last_heartbeat_at
`
type FailStaleTasksParams struct {
@@ -437,25 +581,43 @@ type FailStaleTasksParams struct {
RunningTimeoutSecs float64 `json:"running_timeout_secs"`
}
-type FailStaleTasksRow struct {
- ID pgtype.UUID `json:"id"`
- AgentID pgtype.UUID `json:"agent_id"`
- IssueID pgtype.UUID `json:"issue_id"`
-}
-
// Fails tasks stuck in dispatched/running beyond the given thresholds.
// Handles cases where the daemon is alive but the task is orphaned
// (e.g. agent process hung, daemon failed to report completion).
-func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams) ([]FailStaleTasksRow, error) {
+func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams) ([]AgentTaskQueue, error) {
rows, err := q.db.Query(ctx, failStaleTasks, arg.DispatchTimeoutSecs, arg.RunningTimeoutSecs)
if err != nil {
return nil, err
}
defer rows.Close()
- items := []FailStaleTasksRow{}
+ items := []AgentTaskQueue{}
for rows.Next() {
- var i FailStaleTasksRow
- if err := rows.Scan(&i.ID, &i.AgentID, &i.IssueID); err != nil {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
+ ); err != nil {
return nil, err
}
items = append(items, i)
@@ -540,7 +702,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at FROM agent_task_queue
WHERE id = $1
`
@@ -566,14 +728,21 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
)
return i, err
}
const getLastTaskSession = `-- name: GetLastTaskSession :one
SELECT session_id, work_dir FROM agent_task_queue
-WHERE agent_id = $1 AND issue_id = $2 AND status = 'completed' AND session_id IS NOT NULL
-ORDER BY completed_at DESC
+WHERE agent_id = $1 AND issue_id = $2
+ AND status IN ('completed', 'failed')
+ AND session_id IS NOT NULL
+ORDER BY COALESCE(completed_at, started_at, dispatched_at, created_at) DESC
LIMIT 1
`
@@ -587,8 +756,14 @@ type GetLastTaskSessionRow struct {
WorkDir pgtype.Text `json:"work_dir"`
}
-// Returns the session_id and work_dir from the most recent completed task
-// for a given (agent_id, issue_id) pair, used for session resumption.
+// Returns the session_id and work_dir from the most recent task for a given
+// (agent_id, issue_id) pair, used for session resumption. We accept both
+// 'completed' and 'failed' tasks: a failed task may have established a real
+// agent session before crashing (orphaned by a daemon restart, runtime offline,
+// or sweeper timeout), and the daemon pins the resume pointer mid-flight via
+// UpdateAgentTaskSession. Without this, an auto-retry / manual rerun of a
+// mid-run failure would silently start a fresh conversation and lose the
+// in-flight context — exactly what MUL-1128's B branch is meant to fix.
func (q *Queries) GetLastTaskSession(ctx context.Context, arg GetLastTaskSessionParams) (GetLastTaskSessionRow, error) {
row := q.db.QueryRow(ctx, getLastTaskSession, arg.AgentID, arg.IssueID)
var i GetLastTaskSessionRow
@@ -645,7 +820,7 @@ func (q *Queries) HasPendingTaskForIssueAndAgent(ctx context.Context, arg HasPen
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('dispatched', 'running')
ORDER BY created_at DESC
`
@@ -678,6 +853,11 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
); err != nil {
return nil, err
}
@@ -690,7 +870,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -723,6 +903,11 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
); err != nil {
return nil, err
}
@@ -831,7 +1016,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -864,6 +1049,11 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
); err != nil {
return nil, err
}
@@ -876,7 +1066,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -909,6 +1099,69 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const recoverOrphanedTasksForRuntime = `-- name: RecoverOrphanedTasksForRuntime :many
+UPDATE agent_task_queue
+SET status = 'failed',
+ completed_at = now(),
+ error = 'daemon restarted while task was in flight',
+ failure_reason = 'runtime_recovery'
+WHERE runtime_id = $1 AND status IN ('dispatched', 'running')
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, last_heartbeat_at
+`
+
+// Called by the daemon at startup. Atomically fails any dispatched/running
+// task that the prior incarnation of this runtime owned but did not
+// finalize. Returns the failed rows so callers can hand them to the
+// auto-retry path.
+func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, recoverOrphanedTasksForRuntime, runtimeID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
); err != nil {
return nil, err
}
@@ -959,7 +1212,7 @@ const startAgentTask = `-- name: StartAgentTask :one
UPDATE agent_task_queue
SET status = 'running', started_at = now()
WHERE id = $1 AND status = 'dispatched'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id
+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, last_heartbeat_at
`
func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -984,6 +1237,11 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
)
return i, err
}
@@ -1111,3 +1369,25 @@ func (q *Queries) UpdateAgentStatus(ctx context.Context, arg UpdateAgentStatusPa
)
return i, err
}
+
+const updateAgentTaskSession = `-- name: UpdateAgentTaskSession :exec
+UPDATE agent_task_queue
+SET session_id = COALESCE($2, session_id),
+ work_dir = COALESCE($3, work_dir),
+ last_heartbeat_at = now()
+WHERE id = $1 AND status IN ('dispatched', 'running')
+`
+
+type UpdateAgentTaskSessionParams struct {
+ ID pgtype.UUID `json:"id"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+}
+
+// Pins the resume pointer mid-flight so a daemon crash leaves a usable
+// session_id/work_dir on the task row. No-op if the task is no longer
+// in dispatched/running.
+func (q *Queries) UpdateAgentTaskSession(ctx context.Context, arg UpdateAgentTaskSessionParams) error {
+ _, err := q.db.Exec(ctx, updateAgentTaskSession, arg.ID, arg.SessionID, arg.WorkDir)
+ return err
+}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index bcf025f873..a1e159692f 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -210,7 +210,7 @@ const createAutopilotTask = `-- name: CreateAutopilotTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id)
VALUES ($1, $2, NULL, 'queued', $3, $4)
-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
+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, last_heartbeat_at
`
type CreateAutopilotTaskParams struct {
@@ -250,6 +250,11 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 283b911f46..9f3275413b 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -93,7 +93,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
const createChatTask = `-- name: CreateChatTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id)
VALUES ($1, $2, NULL, 'queued', $3, $4)
-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
+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, last_heartbeat_at
`
type CreateChatTaskParams struct {
@@ -130,6 +130,11 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.TriggerCommentID,
&i.ChatSessionID,
&i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index cc04858cd3..a749c967ad 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -85,6 +85,11 @@ type AgentTaskQueue struct {
TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
ChatSessionID pgtype.UUID `json:"chat_session_id"`
AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ Attempt int32 `json:"attempt"`
+ MaxAttempts int32 `json:"max_attempts"`
+ ParentTaskID pgtype.UUID `json:"parent_task_id"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ LastHeartbeatAt pgtype.Timestamptz `json:"last_heartbeat_at"`
}
type Attachment struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 813153f2aa..a08d8ff272 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -78,32 +78,51 @@ func (q *Queries) DeleteStaleOfflineRuntimes(ctx context.Context, staleSeconds f
const failTasksForOfflineRuntimes = `-- name: FailTasksForOfflineRuntimes :many
UPDATE agent_task_queue
-SET status = 'failed', completed_at = now(), error = 'runtime went offline'
+SET status = 'failed', completed_at = now(), error = 'runtime went offline',
+ failure_reason = 'runtime_offline'
WHERE status IN ('dispatched', 'running')
AND runtime_id IN (
SELECT id FROM agent_runtime WHERE status = 'offline'
)
-RETURNING id, agent_id, issue_id
+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, last_heartbeat_at
`
-type FailTasksForOfflineRuntimesRow struct {
- ID pgtype.UUID `json:"id"`
- AgentID pgtype.UUID `json:"agent_id"`
- IssueID pgtype.UUID `json:"issue_id"`
-}
-
// Marks dispatched/running tasks as failed when their runtime is offline.
// This cleans up orphaned tasks after a daemon crash or network partition.
-func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]FailTasksForOfflineRuntimesRow, error) {
+func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQueue, error) {
rows, err := q.db.Query(ctx, failTasksForOfflineRuntimes)
if err != nil {
return nil, err
}
defer rows.Close()
- items := []FailTasksForOfflineRuntimesRow{}
+ items := []AgentTaskQueue{}
for rows.Next() {
- var i FailTasksForOfflineRuntimesRow
- if err := rows.Scan(&i.ID, &i.AgentID, &i.IssueID); err != nil {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.LastHeartbeatAt,
+ ); err != nil {
return nil, err
}
items = append(items, i)
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index f364ba9d49..9e98003b0f 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -69,11 +69,41 @@ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority,
VALUES ($1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id))
RETURNING *;
+-- name: CreateRetryTask :one
+-- Clones a parent task into a fresh queued attempt. Carries forward the
+-- agent's resume context (session_id/work_dir) so the child can continue
+-- the conversation when the backend supports it. attempt is incremented;
+-- max_attempts and trigger_comment_id are inherited.
+INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
+ status, priority, trigger_comment_id, context,
+ session_id, work_dir,
+ attempt, max_attempts, parent_task_id
+)
+SELECT
+ p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
+ 'queued', p.priority, p.trigger_comment_id, p.context,
+ p.session_id, p.work_dir,
+ p.attempt + 1, p.max_attempts, p.id
+FROM agent_task_queue p
+WHERE p.id = $1
+RETURNING *;
+
-- name: CancelAgentTasksByIssue :exec
UPDATE agent_task_queue
SET status = 'cancelled'
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running');
+-- name: CancelAgentTasksByIssueAndAgent :many
+-- Cancels active tasks for a single (issue, agent) pair without touching
+-- tasks belonging to other agents on the same issue. Used by the manual
+-- rerun flow so re-running the assignee doesn't collateral-cancel a
+-- still-running @-mention agent on the same issue.
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now()
+WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running')
+RETURNING *;
+
-- name: CancelAgentTasksByAgent :exec
UPDATE agent_task_queue
SET status = 'cancelled'
@@ -122,11 +152,19 @@ WHERE id = $1 AND status = 'running'
RETURNING *;
-- name: GetLastTaskSession :one
--- Returns the session_id and work_dir from the most recent completed task
--- for a given (agent_id, issue_id) pair, used for session resumption.
+-- Returns the session_id and work_dir from the most recent task for a given
+-- (agent_id, issue_id) pair, used for session resumption. We accept both
+-- 'completed' and 'failed' tasks: a failed task may have established a real
+-- agent session before crashing (orphaned by a daemon restart, runtime offline,
+-- or sweeper timeout), and the daemon pins the resume pointer mid-flight via
+-- UpdateAgentTaskSession. Without this, an auto-retry / manual rerun of a
+-- mid-run failure would silently start a fresh conversation and lose the
+-- in-flight context — exactly what MUL-1128's B branch is meant to fix.
SELECT session_id, work_dir FROM agent_task_queue
-WHERE agent_id = $1 AND issue_id = $2 AND status = 'completed' AND session_id IS NOT NULL
-ORDER BY completed_at DESC
+WHERE agent_id = $1 AND issue_id = $2
+ AND status IN ('completed', 'failed')
+ AND session_id IS NOT NULL
+ORDER BY COALESCE(completed_at, started_at, dispatched_at, created_at) DESC
LIMIT 1;
-- name: FailAgentTask :one
@@ -136,24 +174,52 @@ LIMIT 1;
-- pointer is preserved on the task row. The next chat task can then fall
-- back to GetLastChatTaskSession and continue the conversation instead of
-- silently starting over.
+--
+-- failure_reason is a coarse classifier consumed by the auto-retry path;
+-- 'agent_error' is the safe default when the daemon doesn't supply one.
UPDATE agent_task_queue
SET status = 'failed',
completed_at = now(),
error = $2,
+ failure_reason = COALESCE(sqlc.narg('failure_reason'), 'agent_error'),
session_id = COALESCE(sqlc.narg('session_id'), session_id),
work_dir = COALESCE(sqlc.narg('work_dir'), work_dir)
WHERE id = $1 AND status IN ('dispatched', 'running')
RETURNING *;
+-- name: UpdateAgentTaskSession :exec
+-- Pins the resume pointer mid-flight so a daemon crash leaves a usable
+-- session_id/work_dir on the task row. No-op if the task is no longer
+-- in dispatched/running.
+UPDATE agent_task_queue
+SET session_id = COALESCE(sqlc.narg('session_id'), session_id),
+ work_dir = COALESCE(sqlc.narg('work_dir'), work_dir),
+ last_heartbeat_at = now()
+WHERE id = $1 AND status IN ('dispatched', 'running');
+
+-- name: RecoverOrphanedTasksForRuntime :many
+-- Called by the daemon at startup. Atomically fails any dispatched/running
+-- task that the prior incarnation of this runtime owned but did not
+-- finalize. Returns the failed rows so callers can hand them to the
+-- auto-retry path.
+UPDATE agent_task_queue
+SET status = 'failed',
+ completed_at = now(),
+ error = 'daemon restarted while task was in flight',
+ failure_reason = 'runtime_recovery'
+WHERE runtime_id = $1 AND status IN ('dispatched', 'running')
+RETURNING *;
+
-- name: FailStaleTasks :many
-- Fails tasks stuck in dispatched/running beyond the given thresholds.
-- Handles cases where the daemon is alive but the task is orphaned
-- (e.g. agent process hung, daemon failed to report completion).
UPDATE agent_task_queue
-SET status = 'failed', completed_at = now(), error = 'task timed out'
+SET status = 'failed', completed_at = now(), error = 'task timed out',
+ failure_reason = 'timeout'
WHERE (status = 'dispatched' AND dispatched_at < now() - make_interval(secs => @dispatch_timeout_secs::double precision))
OR (status = 'running' AND started_at < now() - make_interval(secs => @running_timeout_secs::double precision))
-RETURNING id, agent_id, issue_id;
+RETURNING *;
-- name: CancelAgentTask :one
UPDATE agent_task_queue
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index adc1f01960..40ab65dc93 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -61,12 +61,13 @@ RETURNING id, workspace_id;
-- Marks dispatched/running tasks as failed when their runtime is offline.
-- This cleans up orphaned tasks after a daemon crash or network partition.
UPDATE agent_task_queue
-SET status = 'failed', completed_at = now(), error = 'runtime went offline'
+SET status = 'failed', completed_at = now(), error = 'runtime went offline',
+ failure_reason = 'runtime_offline'
WHERE status IN ('dispatched', 'running')
AND runtime_id IN (
SELECT id FROM agent_runtime WHERE status = 'offline'
)
-RETURNING id, agent_id, issue_id;
+RETURNING *;
-- name: ListAgentRuntimesByOwner :many
SELECT * FROM agent_runtime