Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8696: allow squad handoffs from the agent picker (#10137)
Bohan Jiang83964c5cec4d
diff --git a/packages/views/workflows/handoff-confirm-dialog.test.tsx b/packages/views/workflows/handoff-confirm-dialog.test.tsxindex 6d75f64da9..efcd40608f 100644--- a/packages/views/workflows/handoff-confirm-dialog.test.tsx+++ b/packages/views/workflows/handoff-confirm-dialog.test.tsx@@ -88,10 +88,10 @@ describe("WorkflowHandoffConfirmDialog (MUL-7420)", () => {expect(onConfirm).toHaveBeenCalledWith({ stopPreviousRuns: false });});- it("words a run that has not started as queued and cancels it", async () => {+ it.each(["queued", "deferred"])("words a %s run as waiting and cancels it", async (status) => {previewWorkflowHandoff.mockResolvedValue({...handoff,- previous_runs: [{ task_id: "t1", agent_id: "forge", status: "queued", started_at: new Date().toISOString() }],+ previous_runs: [{ task_id: "t1", agent_id: "forge", status, started_at: new Date().toISOString() }],});const { onConfirm } = renderDialog();diff --git a/packages/views/workflows/handoff-form.test.tsx b/packages/views/workflows/handoff-form.test.tsxindex 37b3d28687..43b97d2965 100644--- a/packages/views/workflows/handoff-form.test.tsx+++ b/packages/views/workflows/handoff-form.test.tsx@@ -4,7 +4,7 @@ import { cleanup, fireEvent, screen } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, describe, expect, it, vi } from "vitest";import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";-import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";+import { agentListOptions, memberListOptions, squadListOptions } from "@multica/core/workspace/queries";import { projectListOptions } from "@multica/core/projects/queries";import type { IssueWorkflow, IssueWorkflowStep } from "@multica/core/types";import { renderWithI18n } from "../test/i18n";@@ -35,6 +35,10 @@ function renderFields(step: IssueWorkflowStep, onPatch = vi.fn()) {const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });qc.setQueryData(agentListOptions("ws-1").queryKey, [{ id: "agent-1", name: "Builder", archived_at: null }] as never);qc.setQueryData(memberListOptions("ws-1").queryKey, [{ user_id: "user-1", name: "Ada" }] as never);+ qc.setQueryData(squadListOptions("ws-1").queryKey, [+ { id: "squad-1", name: "Review team", archived_at: null },+ { id: "squad-old", name: "Retired team", archived_at: "2026-01-01" },+ ] as never);renderWithI18n(<QueryClientProvider client={qc}><HandoffFields step={step} workflow={WORKFLOW} canEdit onPatch={onPatch} />@@ -46,7 +50,7 @@ function renderFields(step: IssueWorkflowStep, onPatch = vi.fn()) {afterEach(cleanup);describe("HandoffFields", () => {- it("offers no handoff, an agent or a member — never a squad", () => {+ it("keeps squads within the agent handoff option", () => {const onPatch = renderFields({ status_key: "in_progress", handler: { type: "none" }, instructions: "" });const radios = screen.getAllByRole("radio");@@ -61,10 +65,12 @@ describe("HandoffFields", () => {expect(onPatch).toHaveBeenCalledWith({ handler: { type: "agent" } });});- it("lists only agents for an agent handoff", async () => {+ it("lists agents and squads for an agent handoff", async () => {const onPatch = renderFields({ status_key: "in_progress", handler: { type: "agent" }, instructions: "" });fireEvent.click(screen.getByRole("button", { name: "Choose an agent" }));+ expect(await screen.findByText("Review team")).toBeTruthy();+ expect(screen.queryByText("Retired team")).toBeNull();fireEvent.click(await screen.findByText("Builder"));expect(screen.queryByText("Ada")).toBeNull();expect(screen.queryByText("Project lead")).toBeNull();@@ -72,6 +78,25 @@ describe("HandoffFields", () => {expect(onPatch).toHaveBeenCalledWith({ handler: { type: "agent", id: "agent-1" } });});+ it("searches and selects a squad from the agent picker", async () => {+ const onPatch = renderFields({ status_key: "in_progress", handler: { type: "agent" }, instructions: "" });+ fireEvent.click(screen.getByRole("button", { name: "Choose an agent" }));+ await screen.findByText("Review team");+ fireEvent.change(screen.getByPlaceholderText("Search agents"), { target: { value: "review" } });+ expect(screen.queryByText("Builder")).toBeNull();+ fireEvent.click(screen.getByText("Review team"));+ expect(onPatch).toHaveBeenCalledWith({ handler: { type: "squad", id: "squad-1" } });+ });++ it("reopens a saved squad with the agent controls and stage instructions", () => {+ renderFields({ status_key: "in_review", handler: { type: "squad", id: "squad-1" }, instructions: "Check accessibility." });+ expect(screen.getByRole("radio", { name: /Hand to an agent/ }).getAttribute("aria-checked")).toBe("true");+ expect(screen.getByRole("button", { name: "Choose an agent" }).textContent).toBe("Review team");+ expect(screen.getByRole("textbox").getAttribute("readonly")).toBeNull();+ expect(screen.getByDisplayValue("Check accessibility.")).toBeTruthy();+ expect(screen.getAllByRole("combobox")).toHaveLength(2);+ });+it("lists the project lead and members for a member handoff, without instructions", async () => {const onPatch = renderFields({ status_key: "in_review", handler: { type: "member" }, instructions: "" });@@ -79,6 +104,7 @@ describe("HandoffFields", () => {fireEvent.click(screen.getByRole("button", { name: "Choose a member" }));expect(await screen.findByText("Project lead")).toBeTruthy();expect(screen.queryByText("Builder")).toBeNull();+ expect(screen.queryByText("Review team")).toBeNull();fireEvent.click(screen.getByText("Ada"));expect(onPatch).toHaveBeenCalledWith({ handler: { type: "member", id: "user-1" } });@@ -115,6 +141,7 @@ describe("WorkflowHandoffForm", () => {const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });qc.setQueryData(agentListOptions("ws-1").queryKey, [{ id: "agent-1", name: "Builder", archived_at: null }] as never);qc.setQueryData(memberListOptions("ws-1").queryKey, [] as never);+ qc.setQueryData(squadListOptions("ws-1").queryKey, [{ id: "squad-1", name: "Review team", archived_at: null }] as never);qc.setQueryData(projectListOptions("ws-1").queryKey, { projects: PROJECTS } as never);renderWithI18n(<QueryClientProvider client={qc}>@@ -172,4 +199,21 @@ describe("WorkflowHandoffForm", () => {await vi.waitFor(() => expect(mutateAsync).toHaveBeenCalled());expect(mutateAsync.mock.calls[0]![0].copyForProjectId).toBeUndefined();});++ it("saves a squad without dropping its instructions or next and back statuses", async () => {+ const wf = workflow(["p-pay"]);+ wf.steps = wf.steps.map((step) => step.status_key === "in_progress" ? {+ ...step, handler: { type: "agent", id: "agent-1" }, instructions: "Review the PR.",+ next_status_key: "done", back_status_key: "todo",+ } : step);+ renderForm(wf);+ fireEvent.click(screen.getByRole("button", { name: "Choose an agent" }));+ fireEvent.click(await screen.findByText("Review team"));+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ await vi.waitFor(() => expect(mutateAsync).toHaveBeenCalled());+ expect(mutateAsync.mock.calls[0]![0]).toMatchObject({+ handler: { type: "squad", id: "squad-1" }, instructions: "Review the PR.",+ next_status_key: "done", back_status_key: "todo",+ });+ });});diff --git a/packages/views/workflows/handoff-form.tsx b/packages/views/workflows/handoff-form.tsxindex 336540dbf6..a931f3f02f 100644--- a/packages/views/workflows/handoff-form.tsx+++ b/packages/views/workflows/handoff-form.tsx@@ -8,7 +8,7 @@ import { useWorkspaceId } from "@multica/core/hooks";import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";import { useSetWorkflowHandoff, workflowNextStatus } from "@multica/core/issue-workflows";import { projectListOptions } from "@multica/core/projects/queries";-import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";+import { agentListOptions, memberListOptions, squadListOptions } from "@multica/core/workspace/queries";import type { IssueWorkflow, IssueWorkflowStep, Project } from "@multica/core/types";import { Button } from "@multica/ui/components/ui/button";import {@@ -39,19 +39,19 @@ const NOT_SET = "__not_set__";type HandoffMode = "none" | "agent" | "member";function modeOf(handler: IssueWorkflowStep["handler"]): HandoffMode {- if (handler.type === "agent") return "agent";+ if (handler.type === "agent" || handler.type === "squad") return "agent";if (handler.type === "member" || handler.type === "project_lead") return "member";return "none";}/*** The parts of a handoff that are saved. Instructions and next/back statuses- * only reach an agent's brief, so they are kept for agent handoffs alone.+ * reach an agent's or squad leader's brief.*/export function savedHandoff<T extends Pick<IssueWorkflowStep, "handler" | "instructions" | "next_status_key" | "back_status_key">>(step: T,): T {- if (step.handler.type === "agent") return step;+ if (step.handler.type === "agent" || step.handler.type === "squad") return step;return { ...step, instructions: "", next_status_key: undefined, back_status_key: undefined };}@@ -135,7 +135,7 @@ export function WorkflowHandoffForm({useEffect(() => setDraft(saved), [saved]);const handler = draft.handler;- const needsTarget = (handler.type === "agent" || handler.type === "member") && !handler.id;+ const needsTarget = (handler.type === "agent" || handler.type === "squad" || handler.type === "member") && !handler.id;const dirty = !sameStep(savedHandoff(draft), savedHandoff(saved));const askScope = canEdit && canCopyForProject && dirty && !!project && !workflow.is_default && sharing.others.length > 0;useEffect(() => {@@ -394,8 +394,7 @@ export function HandoffFields({}/**- * The agent, or the member (project lead included), a column hands the issue- * to. Squads are left out on purpose — they route work themselves. (MUL-7420)+ * The agent, squad or member (project lead included) a column hands the issue to.*/function HandlerPicker({kind,@@ -411,12 +410,14 @@ function HandlerPicker({const { t } = useT("issues");const wsId = useWorkspaceId();const { data: agents = [] } = useQuery(agentListOptions(wsId));+ const { data: squads = [] } = useQuery({ ...squadListOptions(wsId), enabled: kind === "agent" });const { data: members = [] } = useQuery(memberListOptions(wsId));const [open, setOpen] = useState(false);const [query, setQuery] = useState("");const q = query.trim().toLowerCase();const matches = (name: string) => !q || name.toLowerCase().includes(q);const agentRows = kind === "agent" ? agents.filter((a) => !a.archived_at && matches(a.name)) : [];+ const squadRows = kind === "agent" ? squads.filter((s) => !s.archived_at && matches(s.name)) : [];const memberRows = kind === "member" ? members.filter((m) => matches(m.name)) : [];const leadLabel = t(($) => $.workflows.handler.project_lead);const pick = (handler: IssueWorkflowStep["handler"]) => {@@ -428,7 +429,11 @@ function HandlerPicker({value.type === "project_lead"? leadLabel: value.id- ? (value.type === "agent" ? agents.find((a) => a.id === value.id)?.name : members.find((m) => m.user_id === value.id)?.name) ?? ""+ ? (value.type === "agent"+ ? agents.find((a) => a.id === value.id)?.name+ : value.type === "squad"+ ? squads.find((s) => s.id === value.id)?.name+ : members.find((m) => m.user_id === value.id)?.name) ?? "": "";const placeholder = kind === "agent" ? t(($) => $.workflows.handoff.pick_agent) : t(($) => $.workflows.handoff.pick_member);@@ -451,7 +456,7 @@ function HandlerPicker({}trigger={<>- {(value.type === "agent" || value.type === "member") && value.id && (+ {(value.type === "agent" || value.type === "squad" || value.type === "member") && value.id && (<ActorAvatar actorType={value.type} actorId={value.id} size="xs" profileLink={false} />)}<span className={cn("min-w-0 flex-1 truncate", !current && "text-muted-foreground")}>{current || placeholder}</span>@@ -470,6 +475,20 @@ function HandlerPicker({<span className="truncate">{agent.name}</span></PickerItem>))}+ {squadRows.length > 0 && (+ <PickerSection label={t(($) => $.pickers.assignee.squads_group)}>+ {squadRows.map((squad) => (+ <PickerItem+ key={squad.id}+ selected={is("squad", squad.id)}+ onClick={() => pick({ type: "squad", id: squad.id })}+ >+ <ActorAvatar actorType="squad" actorId={squad.id} size="xs" profileLink={false} />+ <span className="truncate">{squad.name}</span>+ </PickerItem>+ ))}+ </PickerSection>+ )}{memberRows.length > 0 && (<PickerSection label={t(($) => $.workflows.handoff.members)}>{memberRows.map((member) => (@@ -484,7 +503,7 @@ function HandlerPicker({))}</PickerSection>)}- {agentRows.length === 0 && memberRows.length === 0 && (q || kind === "agent") && <PickerEmpty />}+ {agentRows.length === 0 && squadRows.length === 0 && memberRows.length === 0 && (q || kind === "agent") && <PickerEmpty />}</PropertyPicker>);}diff --git a/packages/views/workflows/workflow-editor-page.tsx b/packages/views/workflows/workflow-editor-page.tsxindex c1803da630..64b8fe9751 100644--- a/packages/views/workflows/workflow-editor-page.tsx+++ b/packages/views/workflows/workflow-editor-page.tsx@@ -765,7 +765,7 @@ function StepCard({<span className="shrink-0">{t(($) => $.workflows.editor.card_hand_to)}</span>{actor && <ActorAvatar actorType={actor.type} actorId={actor.id} size="xs" profileLink={false} />}<span className="min-w-0 truncate text-foreground">{actor ? getActorName(actor.type, actor.id) : who}</span>- {handoff?.handler.type === "agent" && nextLabel && (+ {(handoff?.handler.type === "agent" || handoff?.handler.type === "squad") && nextLabel && (<span className="shrink-0 truncate">· {t(($) => $.workflows.editor.card_then, { status: nextLabel })}</span>)}</>diff --git a/server/internal/handler/issue_trigger.go b/server/internal/handler/issue_trigger.goindex 19bd3a119a..e3cb44885f 100644--- a/server/internal/handler/issue_trigger.go+++ b/server/internal/handler/issue_trigger.go@@ -90,7 +90,7 @@ func (h *Handler) dispatchIssueRun(ctx context.Context, issue db.Issue, trigger// member actor is threaded; otherwise attribution falls back to the chain._, _ = h.TaskService.EnqueueTaskForIssueWithHandoff(ctx, issue, handoffNote, memberActorUserID(actorType, actorID))case "squad":- h.enqueueSquadLeaderTask(ctx, issue, pgtype.UUID{}, actorType, actorID, handoffNote)+ h.enqueueSquadLeaderTask(ctx, issue, actorType, actorID, handoffNote, trigger.WorkflowHandoff)}}diff --git a/server/internal/handler/issue_workflow_entry.go b/server/internal/handler/issue_workflow_entry.goindex 3446b683e0..87c599e78a 100644--- a/server/internal/handler/issue_workflow_entry.go+++ b/server/internal/handler/issue_workflow_entry.go@@ -326,10 +326,10 @@ func (h *Handler) stopPreviousAssigneeRuns(ctx context.Context, prev, issue db.I}}-// assigneeActiveRuns lists the active runs of an issue's assignee on it: the-// agent's own runs, or every run made on a squad's behalf. Members run-// nothing.-func (h *Handler) assigneeActiveRuns(ctx context.Context, issue db.Issue) []db.AgentTaskQueue {+// assigneeActiveRuns lists the unfinished runs of an issue's assignee on it,+// including deferred work: the agent's own runs, or every run made on a+// squad's behalf. Members run nothing.+func (h *Handler) assigneeActiveRuns(ctx context.Context, issue db.Issue) []db.ListAssigneeRunsForHandoffRow {if !issue.AssigneeID.Valid {return nil}@@ -337,19 +337,14 @@ func (h *Handler) assigneeActiveRuns(ctx context.Context, issue db.Issue) []db.Aif assigneeType != "agent" && assigneeType != "squad" {return nil}- tasks, err := h.Queries.ListActiveTasksByIssue(ctx, issue.ID)+ tasks, err := h.Queries.ListAssigneeRunsForHandoff(ctx, db.ListAssigneeRunsForHandoffParams{+ IssueID: issue.ID, AssigneeType: assigneeType, AssigneeID: issue.AssigneeID,+ })if err != nil {slog.Warn("workflow: list active tasks failed", "issue_id", uuidToString(issue.ID), "error", err)return nil}- var out []db.AgentTaskQueue- for _, task := range tasks {- if (assigneeType == "agent" && task.AgentID == issue.AssigneeID) ||- (assigneeType == "squad" && task.SquadID == issue.AssigneeID) {- out = append(out, task)- }- }- return out+ return tasks}// claimProjectWorkflow renders the issue's project workflow for a task claim,diff --git a/server/internal/handler/issue_workflow_squad_test.go b/server/internal/handler/issue_workflow_squad_test.gonew file mode 100644index 0000000000..6d81b2b242--- /dev/null+++ b/server/internal/handler/issue_workflow_squad_test.go@@ -0,0 +1,270 @@+package handler++import (+ "errors"+ "fmt"+ "net/http"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestWorkflowHandoffCancelsDeferredSquadStages(t *testing.T) {+ seedTestCatalog(t)+ for _, queued := range []bool{true, false} {+ for _, stop := range []bool{true, false} {+ t.Run(fmt.Sprintf("queued=%v/stop=%v", queued, stop), func(t *testing.T) {+ fx := newSquadBriefingClaimFixture(t, t.Context(), "Cancel waiting squad stages")+ wf := createTestWorkflow(t, "Cancel waiting flow "+workflowTestSuffix(), "in_progress", "in_review")+ projectID := createWorkflowTestProject(t, "Cancel waiting project")+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": wf.ID}).Want(http.StatusOK)+ for _, status := range []string{"in_progress", "in_review"} {+ setWorkflowHandoff(t, wf.ID, status, map[string]any{"handler": map[string]any{"type": "squad", "id": fx.SquadID}}).Want(http.StatusOK)+ }+ setWorkflowHandoff(t, wf.ID, "todo", map[string]any{"handler": map[string]any{"type": "member", "id": testUserID}}).Want(http.StatusOK)+ dbfx.Exec(t, `UPDATE issue SET project_id=$2,status='backlog' WHERE id=$1`, fx.IssueID, projectID)+ updateIssueForTest(t, fx.IssueID, map[string]any{"status": "in_progress"}).Want(http.StatusOK)+ updateIssueForTest(t, fx.IssueID, map[string]any{"status": "in_review"}).Want(http.StatusOK)+ if !queued {+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='completed',completed_at=now() WHERE issue_id=$1 AND workflow_step='in_progress'`, fx.IssueID)+ }+ before, err := testHandler.Queries.ListTasksByIssue(t.Context(), parseUUID(fx.IssueID))+ if err != nil || len(before) != 2 {+ t.Fatalf("handoff fixture tasks = %+v, %v", before, err)+ }+ var deferred bool+ for _, task := range before {+ deferred = deferred || task.Status == "deferred"+ }+ if !deferred {+ t.Fatal("fixture did not retain a deferred stage handoff")+ }+ var preview WorkflowHandoffPreviewResponse+ req := withURLParam(newRequest(http.MethodGet, "/api/issues/"+fx.IssueID+"/workflow-handoff?status=todo", nil), "id", fx.IssueID)+ testutil.Call(t, testHandler.PreviewWorkflowHandoff, req).Want(http.StatusOK).JSON(&preview)+ wantRuns := 1+ if queued {+ wantRuns+++ }+ if len(preview.PreviousRuns) != wantRuns {+ t.Errorf("preview lists %d runs, want %d including deferred stages", len(preview.PreviousRuns), wantRuns)+ }+ updateIssueForTest(t, fx.IssueID, map[string]any{"status": "todo", "stop_previous_assignee_runs": stop}).Want(http.StatusOK)+ for _, previous := range before {+ after, err := testHandler.Queries.GetAgentTask(t.Context(), previous.ID)+ if err != nil {+ t.Fatal(err)+ }+ wantStatus := previous.Status+ if stop && previous.Status != "completed" {+ wantStatus = "cancelled"+ if after.CancelledByType.String != "member" || after.CancelledByID != parseUUID(testUserID) {+ t.Errorf("stage %s lost cancellation attribution", previous.WorkflowStep.String)+ }+ }+ if after.Status != wantStatus {+ t.Errorf("stage %s: status = %s, want %s", previous.WorkflowStep.String, after.Status, wantStatus)+ }+ }+ claimed, _, _, _ := claimAgentInstructionsForTest(t, fx.RuntimeID)+ if stop && claimed != "" {+ t.Errorf("explicitly stopped squad task was claimed: %s", claimed)+ } else if !stop && claimed == "" {+ t.Error("opting out of stopping must preserve runnable squad work")+ }+ })+ }+ }+}++func TestWorkflowSquadHandoffReplayDoesNotDuplicate(t *testing.T) {+ seedTestCatalog(t)+ fx := newSquadBriefingClaimFixture(t, t.Context(), "Idempotent squad handoff")+ projectID := createWorkflowTestProject(t, "Idempotent squad project")+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": createTestWorkflow(t, "Idempotent flow "+workflowTestSuffix(), "in_progress").ID}).Want(http.StatusOK)+ setColumnHandoff(t, projectID, "in_progress", map[string]any{"handler": map[string]any{"type": "squad", "id": fx.SquadID}}).Want(http.StatusOK)+ dbfx.Exec(t, `UPDATE issue SET project_id=$2,status='todo' WHERE id=$1`, fx.IssueID, projectID)+ updateIssueForTest(t, fx.IssueID, map[string]any{"status": "in_progress"}).Want(http.StatusOK)+ issue, err := testHandler.Queries.GetIssue(t.Context(), parseUUID(fx.IssueID))+ if err != nil {+ t.Fatal(err)+ }+ var wg sync.WaitGroup+ errs := make(chan error, 8)+ for range 8 {+ wg.Go(func() {+ _, err := testHandler.TaskService.EnqueueTaskForWorkflowSquadLeader(t.Context(), issue, parseUUID(fx.AgentID), parseUUID(fx.SquadID), "", parseUUID(testUserID))+ errs <- err+ })+ }+ wg.Wait()+ close(errs)+ for err := range errs {+ if !errors.Is(err, service.ErrDuplicatePendingTask) {+ t.Fatalf("same handoff replay = %v, want coalesced", err)+ }+ }+ tasks, err := testHandler.Queries.ListTasksByIssue(t.Context(), issue.ID)+ if err != nil || len(tasks) != 1 {+ t.Fatalf("handoff replay created duplicate tasks: %+v, %v", tasks, err)+ }+ // A run may advance its binding itself; the original handoff identity+ // still refers to the source status write, not the mutable run binding.+ dbfx.Exec(t, `UPDATE agent_task_queue SET workflow_step='todo' WHERE id=$1`, tasks[0].ID)+ if _, err := testHandler.TaskService.EnqueueTaskForWorkflowSquadLeader(t.Context(), issue, parseUUID(fx.AgentID), parseUUID(fx.SquadID), "", parseUUID(testUserID)); !errors.Is(err, service.ErrDuplicatePendingTask) {+ t.Fatalf("advanced handoff replay = %v, want coalesced", err)+ }++ // Re-entering a stage is new work even if an earlier visit is still pending.+ updateIssueForTest(t, fx.IssueID, map[string]any{"status": "todo"}).Want(http.StatusOK)+ updateIssueForTest(t, fx.IssueID, map[string]any{"status": "in_progress"}).Want(http.StatusOK)+ tasks, err = testHandler.Queries.ListTasksByIssue(t.Context(), issue.ID)+ if err != nil || len(tasks) != 2 {+ t.Fatalf("a new visit to the same stage was coalesced: %+v, %v", tasks, err)+ }+}++func TestWorkflowSquadHandoffPreservesPendingStages(t *testing.T) {+ seedTestCatalog(t)+ for _, sharedLeader := range []bool{false, true} {+ for _, oldStatus := range []string{"queued", "dispatched", "running"} {+ t.Run(fmt.Sprintf("sharedLeader=%v/old=%s", sharedLeader, oldStatus), func(t *testing.T) {+ fx := newSquadBriefingClaimFixture(t, t.Context(), "Pending stage handoff")+ nextSquad := fx.SquadID+ if sharedLeader {+ nextSquad = dbfx.Squad(t, "Next stage squad", fx.AgentID)+ }+ wf := createTestWorkflow(t, "Pending squad flow "+workflowTestSuffix(), "in_progress", "in_review")+ projectID := createWorkflowTestProject(t, "Pending squad project")+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": wf.ID}).Want(http.StatusOK)+ for status, squad := range map[string]string{"in_progress": fx.SquadID, "in_review": nextSquad} {+ setWorkflowHandoff(t, wf.ID, status, map[string]any{+ "handler": map[string]any{"type": "squad", "id": squad}, "instructions": "Handle only " + status,+ }).Want(http.StatusOK)+ }+ dbfx.Exec(t, `UPDATE issue SET project_id=$2,status='todo' WHERE id=$1`, fx.IssueID, projectID)+ updateIssueForTest(t, fx.IssueID, map[string]any{"status": "in_progress"}).Want(http.StatusOK)+ old, err := testHandler.Queries.ListTasksByIssue(t.Context(), parseUUID(fx.IssueID))+ if err != nil || len(old) != 1 {+ t.Fatalf("first handoff tasks = %+v, %v", old, err)+ }+ dbfx.Exec(t, `UPDATE agent_task_queue SET status=$2 WHERE id=$1`, old[0].ID, oldStatus)++ // Enter the next stage while the old run still occupies the queue.+ updateIssueForTest(t, fx.IssueID, map[string]any{"status": "in_review"}).Want(http.StatusOK)+ tasks, err := testHandler.Queries.ListTasksByIssue(t.Context(), parseUUID(fx.IssueID))+ if err != nil || len(tasks) != 2 {+ t.Fatalf("second handoff tasks = %+v, %v; want both stages persisted", tasks, err)+ }+ var nextID string+ for _, task := range tasks {+ if task.ID == old[0].ID {+ if task.Status != oldStatus || task.WorkflowStep.String != "in_progress" || task.SquadID != parseUUID(fx.SquadID) {+ t.Fatalf("handoff changed the existing run: %+v", task)+ }+ continue+ }+ if task.WorkflowStep.String != "in_review" || task.SquadID != parseUUID(nextSquad) || !task.IsLeaderTask {+ t.Fatalf("new stage lost its execution context: %+v", task)+ }+ nextID = uuidToString(task.ID)+ }++ // Releasing the old run must make the new stage claimable without+ // another status update, mention or manually enqueued task.+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='completed',completed_at=now() WHERE id=$1`, old[0].ID)+ claim := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+fx.RuntimeID+"/tasks/claim", nil), "runtimeId", fx.RuntimeID)+ claim.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityWorkflowStatusRulesV1)+ var resp struct {+ Task *AgentTaskResponse `json:"task"`+ }+ testutil.Call(t, testHandler.ClaimTaskByRuntime, claim).Want(http.StatusOK).JSON(&resp)+ if resp.Task == nil || resp.Task.ID != nextID || !resp.Task.IsLeaderTask || resp.Task.ProjectWorkflow == nil || resp.Task.Agent == nil {+ t.Fatalf("new stage was not delivered: %+v", resp.Task)+ }+ if !strings.Contains(resp.Task.ProjectWorkflow.Brief, "Handle only in_review") || strings.Contains(resp.Task.ProjectWorkflow.Brief, "This run remains bound") || !strings.Contains(resp.Task.Agent.Instructions, "Own the parent issue status — through its project workflow") {+ t.Fatalf("new stage received stale or guest instructions: %+v", resp.Task)+ }+ })+ }+ }+}++func TestWorkflowHandoffToSquadStartsLeaderAtEachStep(t *testing.T) {+ seedTestCatalog(t)+ fx := newSquadBriefingClaimFixture(t, t.Context(), "Workflow squad handoff")+ wf := createTestWorkflow(t, "Squad flow "+workflowTestSuffix(), "in_progress", "in_review")+ projectID := createWorkflowTestProject(t, "Squad handoff project")+ setProjectWorkflow(t, projectID, map[string]any{"workflow_id": wf.ID}).Want(http.StatusOK)+ dbfx.Exec(t, `UPDATE issue SET project_id=$2,status='todo' WHERE id=$1`, fx.IssueID, projectID)++ for _, status := range []string{"in_progress", "in_review"} {+ instruction := "Coordinate only the " + status + " step."+ setWorkflowHandoff(t, wf.ID, status, map[string]any{+ "handler": map[string]any{"type": "squad", "id": fx.SquadID}, "instructions": instruction,+ "next_status_key": "done", "back_status_key": "todo",+ }).Want(http.StatusOK)++ var preview WorkflowHandoffPreviewResponse+ req := withURLParam(newRequest(http.MethodGet, "/api/issues/"+fx.IssueID+"/workflow-handoff?status="+status, nil), "id", fx.IssueID)+ testutil.Call(t, testHandler.PreviewWorkflowHandoff, req).Want(http.StatusOK).JSON(&preview)+ if !preview.Handoff || preview.HandlerType != "squad" || preview.HandlerID != fx.SquadID || !strings.Contains(preview.Brief, instruction) {+ t.Fatalf("squad handoff preview = %+v", preview)+ }++ updateIssueForTest(t, fx.IssueID, map[string]any{"status": status}).Want(http.StatusOK)+ _, assigneeType, assigneeID := issueStatusAndAssignee(t, fx.IssueID)+ if assigneeType != "squad" || assigneeID != fx.SquadID {+ t.Fatalf("handoff assignee = %s/%s, want squad/%s", assigneeType, assigneeID, fx.SquadID)+ }+ tasks, err := testHandler.Queries.ListActiveTasksByIssue(t.Context(), parseUUID(fx.IssueID))+ if err != nil || len(tasks) != 1 {+ t.Fatalf("active tasks = %+v, %v; want one leader run", tasks, err)+ }+ task := tasks[0]+ if task.AgentID != parseUUID(fx.AgentID) || task.SquadID != parseUUID(fx.SquadID) || !task.IsLeaderTask || task.WorkflowStep.String != status {+ t.Fatalf("handoff lost leader role or workflow binding: %+v", task)+ }+ claim := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+fx.RuntimeID+"/tasks/claim", nil), "runtimeId", fx.RuntimeID)+ claim.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityWorkflowStatusRulesV1)+ var resp struct {+ Task *AgentTaskResponse `json:"task"`+ }+ testutil.Call(t, testHandler.ClaimTaskByRuntime, claim).Want(http.StatusOK).JSON(&resp)+ if resp.Task == nil || resp.Task.ID != uuidToString(task.ID) || !resp.Task.IsLeaderTask || resp.Task.Agent == nil || resp.Task.ProjectWorkflow == nil {+ t.Fatalf("missing leader workflow claim: %+v", resp.Task)+ }+ if !strings.Contains(resp.Task.Agent.Instructions, "## Squad Roster") || !strings.Contains(resp.Task.Agent.Instructions, "current step's goal") || !strings.Contains(resp.Task.ProjectWorkflow.Brief, instruction) {+ t.Fatalf("claim lost squad coordination or step instructions: %+v", resp.Task)+ }+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='completed',completed_at=now() WHERE id=$1`, task.ID)+ }+}++func TestWorkflowSquadHandoffKeepsAssignmentGates(t *testing.T) {+ seedTestCatalog(t)+ wf := createTestWorkflow(t, "Squad permissions "+workflowTestSuffix(), "in_progress")+ leaderID := seededReadyAgentID(t)+ otherWS := dbfx.Workspace(t, "Other squad workspace", "squad-handoff-"+workflowTestSuffix())+ privateLeaderID, _, _ := privateAgentTestFixture(t)+ cases := []struct {+ name, squadID string+ status int+ }{+ {"another workspace", dbfx.Squad(t, "Foreign squad", leaderID, testutil.Cols{"workspace_id": otherWS}), http.StatusBadRequest},+ {"archived squad", dbfx.Squad(t, "Archived squad", leaderID, testutil.Cols{"archived_at": time.Now()}), http.StatusBadRequest},+ {"private leader", dbfx.Squad(t, "Private leader squad", privateLeaderID), http.StatusForbidden},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ setWorkflowHandoff(t, wf.ID, "in_progress", map[string]any{+ "handler": map[string]any{"type": "squad", "id": tc.squadID},+ }).Want(tc.status)+ })+ }+}diff --git a/server/internal/handler/issue_workflow_test.go b/server/internal/handler/issue_workflow_test.goindex 128705618a..3c75a303f4 100644--- a/server/internal/handler/issue_workflow_test.go+++ b/server/internal/handler/issue_workflow_test.go@@ -1229,16 +1229,15 @@ func TestAgentStatusChangeOnDefaultIgnoresStep(t *testing.T) {agentUpdateIssue(t, issueID, agentID, taskID, map[string]any{"status": "in_review"}).Want(http.StatusOK)}-// Squads can't be handed to, but a handoff away from an issue a squad owns-// offers to stop — and stops — the runs made on-// the squad's behalf, recording who stopped them.+// A handoff away from an issue a squad owns offers to stop — and stops — the+// runs made on the squad's behalf, recording who stopped them.func TestHandoffStopsPreviousSquadRuns(t *testing.T) {seedTestCatalog(t)agentID := seededReadyAgentID(t)squadID := dbfx.Squad(t, "Workflow review squad "+workflowTestSuffix(), agentID)projectID := createWorkflowTestProject(t, "Workflow squad stop project")setColumnHandoff(t, projectID, "in_progress", map[string]any{"handler": map[string]any{"type": "member", "id": testUserID}}).Want(http.StatusOK)- setColumnHandoff(t, projectID, "in_review", map[string]any{"handler": map[string]any{"type": "squad", "id": squadID}}).Want(http.StatusBadRequest)+ setColumnHandoff(t, projectID, "in_review", map[string]any{"handler": map[string]any{"type": "squad", "id": squadID}}).Want(http.StatusOK)issueID := dbfx.Issue(t, "squad reviewing", testutil.Cols{"project_id": projectID, "status": "in_review", "assignee_type": "squad", "assignee_id": squadID,})@@ -1247,6 +1246,10 @@ func TestHandoffStopsPreviousSquadRuns(t *testing.T) {running := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "squad_id": squadID, "runtime_id": runtimeID, "status": "running", "started_at": time.Now(),})+ otherSquad := dbfx.Squad(t, "Another squad sharing the leader "+workflowTestSuffix(), agentID)+ unrelated := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID, "squad_id": otherSquad, "runtime_id": runtimeID, "status": "deferred", "fire_at": time.Now(),+ })var preview WorkflowHandoffPreviewResponsereq := withURLParam(newRequest("GET", "/api/issues/"+issueID+"/workflow-handoff?status=in_progress", nil), "id", issueID)@@ -1264,6 +1267,10 @@ func TestHandoffStopsPreviousSquadRuns(t *testing.T) {if status != "cancelled" || stoppedBy == nil || *stoppedBy != memberName {t.Fatalf("squad run = %s stopped by %v, want cancelled by %s", status, stoppedBy, memberName)}+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, unrelated).Scan(&status)+ if status != "deferred" {+ t.Fatalf("handoff cancelled another squad's waiting run: %s", status)+ }}// Remapping an issue into a done status on a workflow switch ends its wakeups,diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.goindex aa2f21acf6..59534ac4d4 100644--- a/server/internal/handler/squad.go+++ b/server/internal/handler/squad.go@@ -1186,7 +1186,7 @@ func commentMentionsAnyone(content string) bool {// paths go through computeCommentAgentTriggers so preview and create share the// same trigger set.// It returns true only when a leader task was actually enqueued.-func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, authorType, authorID, handoffNote string) bool {+func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, authorType, authorID, handoffNote string, workflowHandoff bool) bool {squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: issue.AssigneeID,WorkspaceID: issue.WorkspaceID,@@ -1215,23 +1215,27 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, trreturn false}- hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{- IssueID: issue.ID,- AgentID: squad.LeaderID,- // Key dedup on the reviewed head (TEN-356).- HeadSha: h.TaskService.ResolveIssueReviewSHAParam(ctx, issue.ID),- })- if err != nil || hasPending {- return false+ if !workflowHandoff {+ hasPending, err := h.Queries.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{+ IssueID: issue.ID,+ AgentID: squad.LeaderID,+ // Key dedup on the reviewed head (TEN-356).+ HeadSha: h.TaskService.ResolveIssueReviewSHAParam(ctx, issue.ID),+ })+ if err != nil || hasPending {+ return false+ }}- // triggerCommentID is always empty on the assign/promote path; legacy- // handoff text rides its dedicated task column instead.- _ = triggerCommentID// The member who performed the assign/promote is the accountable human for the// leader run (MUL-4302 §4) — the same principal the gate above judged. An agent// author is not a human, so only a member actor is threaded.- if _, err := h.TaskService.EnqueueTaskForSquadLeaderWithHandoff(ctx, issue, squad.LeaderID, squad.ID, handoffNote, memberActorUserID(authorType, authorID)); err != nil {+ if workflowHandoff {+ _, err = h.TaskService.EnqueueTaskForWorkflowSquadLeader(ctx, issue, squad.LeaderID, squad.ID, handoffNote, memberActorUserID(authorType, authorID))+ } else {+ _, err = h.TaskService.EnqueueTaskForSquadLeaderWithHandoff(ctx, issue, squad.LeaderID, squad.ID, handoffNote, memberActorUserID(authorType, authorID))+ }+ if err != nil {slog.Warn("enqueue squad leader task failed","issue_id", uuidToString(issue.ID),"squad_id", uuidToString(squad.ID),diff --git a/server/internal/handler/squad_briefing.go b/server/internal/handler/squad_briefing.goindex 7cf93c8427..1aaf9806bf 100644--- a/server/internal/handler/squad_briefing.go+++ b/server/internal/handler/squad_briefing.go@@ -160,10 +160,13 @@ const squadParentStatusStepMoved = `6. **Leave the parent issue's status unchangconst squadParentStatusOwnedInWorkflow = `6. **Own the parent issue status — through its project workflow.** This issueis assigned to your squad and follows its project workflow, so its statusis yours to move (unless Agent Identity forbids status changes), using only- the commands in ` + "`" + `[Project workflow]` + "`" + `. The parent stays at its+ the commands in ` + "`" + `[Project workflow]` + "`" + `. Delegate only the current+ step's work and pass its instructions and constraints to members in your+ delegation comment; their observer brief does not include step instructions.+ The parent stays at itscurrent step while members work — a successful dispatch is not completion.On later turns, do not move it for routine progress updates. When you- confirm the overall goal is met, run that block's Step done command — this+ confirm the current step's goal is met, run that block's Step done command — thisresponsibility is itself the standing instruction that authorizes thatchange, so do it even when no comment asked you to.`diff --git a/server/internal/handler/squad_workflow_status_contract_test.go b/server/internal/handler/squad_workflow_status_contract_test.goindex b6c8f93cac..7004647679 100644--- a/server/internal/handler/squad_workflow_status_contract_test.go+++ b/server/internal/handler/squad_workflow_status_contract_test.go@@ -67,6 +67,9 @@ func TestOwningLeaderInWorkflowMovesOnlyByWorkflowCommands(t *testing.T) {for _, want := range []string{// The ownership grant and its standing wrap-up authorization survive."Own the parent issue status — through its project workflow.",+ "Delegate only the current step's work",+ "pass its instructions and constraints to members",+ "confirm the current step's goal is met","run that block's Step done command","do it even when no comment asked you to",// Dispatch is not delivery, in workflow terms, in both halves.diff --git a/server/internal/issueworkflow/issueworkflow.go b/server/internal/issueworkflow/issueworkflow.goindex 2f55de0fd3..8fe6249617 100644--- a/server/internal/issueworkflow/issueworkflow.go+++ b/server/internal/issueworkflow/issueworkflow.go@@ -508,14 +508,12 @@ func ValidateHandoff(s Step, def Definition) error {}switch s.Handler.Type {case HandlerNone, HandlerProjectLead:- case HandlerAgent, HandlerMember:+ case HandlerAgent, HandlerSquad, HandlerMember:if s.Handler.ID == "" {return invalid("choose a %s to hand off to", s.Handler.Type)}- case HandlerSquad, HandlerCreator:- // A squad routes work itself, so a handoff to one would compete with- // its own assignment. (MUL-7420)- return invalid("hand off to an agent, a member or the project lead")+ case HandlerCreator:+ return invalid("hand off to an agent, a squad, a member or the project lead")default:return invalid("unknown handler type %q", s.Handler.Type)}diff --git a/server/internal/issueworkflow/issueworkflow_test.go b/server/internal/issueworkflow/issueworkflow_test.goindex c463ae5033..3013ac1968 100644--- a/server/internal/issueworkflow/issueworkflow_test.go+++ b/server/internal/issueworkflow/issueworkflow_test.go@@ -79,7 +79,7 @@ func TestValidateRejectsBrokenWorkflows(t *testing.T) {"duplicate status": {name: "x", middle: []string{"implement", "implement"}, want: "more than once"},}broken := stepsFor([]string{"implement"})- broken[0].Handler = Handler{Type: HandlerSquad, ID: testAgentID}+ broken[0].Handler = Handler{Type: HandlerCreator}name, desc, steps := Normalize("x", "", broken)if err := Validate(name, desc, steps, false, testCatalog()); err == nil || !strings.Contains(err.Error(), "hand off to an agent") {t.Fatalf("Validate must check handoffs, got %v", err)@@ -111,6 +111,7 @@ func TestValidateHandoff(t *testing.T) {}{"not a column": {step: Step{StatusKey: "nope", Handler: Handler{Type: HandlerProjectLead}}, want: "not part"},"needs an id": {step: Step{StatusKey: "implement", Handler: Handler{Type: HandlerAgent}}, want: "choose a agent"},+ "squad needs an id": {step: Step{StatusKey: "implement", Handler: Handler{Type: HandlerSquad}}, want: "choose a squad"},"unknown handler": {step: Step{StatusKey: "implement", Handler: Handler{Type: "robot"}}, want: "unknown handler"},"backlog parks": {step: Step{StatusKey: "backlog", Handler: Handler{Type: HandlerProjectLead}}, want: "cannot be handed off"},"done finishes": {step: Step{StatusKey: "done", Handler: Handler{Type: HandlerProjectLead}}, want: "cannot be handed off"},@@ -128,6 +129,9 @@ func TestValidateHandoff(t *testing.T) {if err := ValidateHandoff(NormalizeHandoff(Step{StatusKey: "todo", Handler: Handler{Type: HandlerProjectLead}}), def); err != nil {t.Fatalf("todo may hand off: %v", err)}+ if err := ValidateHandoff(Step{StatusKey: "implement", Handler: Handler{Type: HandlerSquad, ID: testAgentID}}, def); err != nil {+ t.Fatalf("squad may receive a handoff: %v", err)+ }}func TestNormalizeHandoffDropsStaleHandlerData(t *testing.T) {diff --git a/server/internal/service/issue_trigger.go b/server/internal/service/issue_trigger.goindex 902748b464..048fac1de1 100644--- a/server/internal/service/issue_trigger.go+++ b/server/internal/service/issue_trigger.go@@ -66,10 +66,11 @@ type IssueTriggerInput struct {// paths. AgentID is the agent that will actually run — the assignee for an// agent issue, the squad leader for a squad issue.type IssueRunTrigger struct {- IssueID pgtype.UUID- AgentID pgtype.UUID- AssigneeType string- Source RunEnqueueSource+ IssueID pgtype.UUID+ AgentID pgtype.UUID+ AssigneeType string+ Source RunEnqueueSource+ WorkflowHandoff bool}func allowAllAgents(db.Agent) bool { return true }@@ -201,10 +202,11 @@ func (s *IssueService) WillEnqueueRun(ctx context.Context, in IssueTriggerInput,return IssueRunTrigger{}, false}return IssueRunTrigger{- IssueID: issue.ID,- AgentID: squad.LeaderID,- AssigneeType: "squad",- Source: source,+ IssueID: issue.ID,+ AgentID: squad.LeaderID,+ AssigneeType: "squad",+ Source: source,+ WorkflowHandoff: in.EnteredHandoffStep,}, true}return IssueRunTrigger{}, falsediff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 34c2cff1a4..766364e271 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1458,10 +1458,10 @@ func (s *TaskService) EnqueueTaskForSquadLeaderWithHandoff(ctx context.Context,}func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin) (db.AgentTaskQueue, error) {- return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, nil, isLeader, squadID, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID, origin, false)+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, nil, isLeader, squadID, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID, origin, false, false)}-func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin, freshRerun bool) (db.AgentTaskQueue, error) {+func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin, freshRerun, workflowHandoff bool) (db.AgentTaskQueue, error) {if err := guardIssueNotInTriage(ctx, s.Queries, issue.ID, origin); err != nil {return db.AgentTaskQueue{}, err}@@ -1494,7 +1494,7 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issoriginatorUserID := attr.UserIDruntimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)- task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{+ params := db.CreateAgentTaskParams{ID: dbid.NewV7(),AgentID: agentID,RuntimeID: agent.RuntimeID,@@ -1521,14 +1521,20 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, iss// Stamp the reviewed head so dedup can distinguish this run's target// from a later request against a new HEAD (TEN-356).HeadSha: headShaText(s.ResolveIssueReviewSHA(ctx, issue.ID)),- })+ }+ var task db.AgentTaskQueue+ if workflowHandoff {+ task, err = s.createWorkflowSquadHandoffTask(ctx, issue, params)+ } else {+ task, err = s.Queries.CreateAgentTask(ctx, params)+ }if err != nil {// A concurrent enqueue for the same (issue, agent) won the race and the// unique index rejected this insert. That is benign — a sibling run// already covers this target — so log it at debug and return a typed// sentinel the caller maps to a coalesced outcome / 409 rather than a// 500 that leaks the raw constraint name (#5914).- if isDuplicatePendingTaskErr(err) {+ if errors.Is(err, ErrDuplicatePendingTask) || isDuplicatePendingTaskErr(err) {slog.Debug("mention task enqueue coalesced: pending task already exists", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))return db.AgentTaskQueue{}, ErrDuplicatePendingTask}@@ -1538,6 +1544,18 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issslog.Info("mention task enqueued", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "is_leader_task", isLeader)s.RecordHumanDelegation(ctx, attr)+ if workflowHandoff {+ // Publish the durable waiting task before promotion can publish queued+ // or the daemon can claim it. Existing promotion handles occupied slots.+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)+ s.notifyTaskAvailable(task)+ if err := s.PromoteDueDeferredTasksForRuntime(ctx, task.RuntimeID); err != nil {+ // The handoff is already durable; the daemon's next claim retries+ // promotion, including after a server restart.+ slog.Warn("promote workflow squad handoff failed", "task_id", util.UUIDToString(task.ID), "error", err)+ }+ return task, nil+ }// See EnqueueTaskForIssue for ordering rationale.s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)s.NotifyTaskEnqueued(ctx, task)@@ -6186,7 +6204,7 @@ func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agenutil.UUIDToString(issue.AssigneeID) == util.UUIDToString(agentID) {return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, coalescedCommentIDs, true, "", actorUserID, rerunOfTaskID, pgtype.Timestamptz{}, origin, fresh)}- return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "", actorUserID, rerunOfTaskID, origin, fresh)+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "", actorUserID, rerunOfTaskID, origin, fresh, false)}// The bulk terminal writes below are the sweeper, archive and daemon-recoverydiff --git a/server/internal/service/workflow_squad_handoff.go b/server/internal/service/workflow_squad_handoff.gonew file mode 100644index 0000000000..f72fc5c752--- /dev/null+++ b/server/internal/service/workflow_squad_handoff.go@@ -0,0 +1,48 @@+package service++import (+ "context"+ "errors"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// EnqueueTaskForWorkflowSquadLeader preserves each stage handoff even when an+// older stage or another squad already holds the leader's pending-task slot.+func (s *TaskService) EnqueueTaskForWorkflowSquadLeader(ctx context.Context, issue db.Issue, leaderID, squadID pgtype.UUID, handoffNote string, actorUserID pgtype.UUID) (db.AgentTaskQueue, error) {+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, leaderID, pgtype.UUID{}, nil, true, squadID, false, handoffNote, actorUserID, pgtype.UUID{}, OriginDerived, false, true)+}++func (s *TaskService) createWorkflowSquadHandoffTask(ctx context.Context, issue db.Issue, params db.CreateAgentTaskParams) (db.AgentTaskQueue, error) {+ if s.TxStarter == nil {+ return db.AgentTaskQueue{}, errors.New("workflow squad handoff requires a transaction")+ }+ // Deferred rows can coexist with an occupied queued/dispatched slot. The+ // existing promoter releases them when that slot frees; never rewrite the+ // binding, role, comments or attribution of a task already offered to a daemon.+ params.FireAt = pgtype.Timestamptz{Time: time.Now(), Valid: true}+ params.WorkflowStep = pgtype.Text{String: issue.Status, Valid: true}+ params.WorkflowHandoffRevision = pgtype.Int8{Int64: issue.Revision, Valid: true}+ var task db.AgentTaskQueue+ err := s.runInTx(ctx, func(q *db.Queries) error {+ if err := q.LockWorkflowSquadHandoff(ctx, issue.ID); err != nil {+ return err+ }+ _, err := q.GetWorkflowSquadHandoffTask(ctx, db.GetWorkflowSquadHandoffTaskParams{+ IssueID: issue.ID, AgentID: params.AgentID, SquadID: params.SquadID,+ IssueRevision: issue.Revision,+ })+ if err == nil {+ return ErrDuplicatePendingTask+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return err+ }+ task, err = q.CreateAgentTask(ctx, params)+ return err+ })+ return task, err+}diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex e3492b85b1..439cf05a8f 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -2269,27 +2269,31 @@ INSERT INTO agent_task_queue (coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,- workflow_step, id+ workflow_step, fire_at, id)SELECT- $1, $2, $3, 'queued', $4, $5,- COALESCE($6::uuid[], '{}'),- $7,- COALESCE($8::boolean, FALSE),+ $1, $2, $3,+ CASE WHEN $5::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,+ $4, $6,+ COALESCE($7::uuid[], '{}'),+ $8,COALESCE($9::boolean, FALSE),- $10,+ COALESCE($10::boolean, FALSE),$11,+ $12,NULLIF(CASE- WHEN COALESCE($12::text, '') <> ''- THEN jsonb_build_object('head_sha', $12::text)+ WHEN COALESCE($13::text, '') <> ''+ THEN jsonb_build_object('head_sha', $13::text)ELSE '{}'::jsonbEND || CASE- WHEN COALESCE($13::boolean, FALSE)+ WHEN COALESCE($14::boolean, FALSE)THEN '{"fresh_rerun":true}'::jsonbELSE '{}'::jsonb+ END || CASE+ WHEN $15::bigint IS NOT NULL+ THEN jsonb_build_object('workflow_handoff_revision', $15::bigint)+ ELSE '{}'::jsonbEND, '{}'::jsonb),- $14,- $15,$16,$17,$18,@@ -2298,38 +2302,44 @@ SELECT$21,$22,$23,+ $24,+ $25,-- The issue's status as this task is queued: the workflow step it works on (MUL-7420).- (SELECT i.status FROM issue i WHERE i.id = $3),- COALESCE($24::uuid, gen_random_uuid())+ COALESCE($26::text, (SELECT i.status FROM issue i WHERE i.id = $3)),+ $5,+ COALESCE($27::uuid, gen_random_uuid())WHERE lock_task_owner_rows($1, $3, $2)RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step`type CreateAgentTaskParams struct {- AgentID pgtype.UUID `json:"agent_id"`- RuntimeID pgtype.UUID `json:"runtime_id"`- IssueID pgtype.UUID `json:"issue_id"`- Priority int32 `json:"priority"`- TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`- CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`- TriggerSummary pgtype.Text `json:"trigger_summary"`- ForceFreshSession pgtype.Bool `json:"force_fresh_session"`- IsLeaderTask pgtype.Bool `json:"is_leader_task"`- HandoffNote pgtype.Text `json:"handoff_note"`- SquadID pgtype.UUID `json:"squad_id"`- HeadSha pgtype.Text `json:"head_sha"`- FreshRerun pgtype.Bool `json:"fresh_rerun"`- OriginatorUserID pgtype.UUID `json:"originator_user_id"`- AccountableUserID pgtype.UUID `json:"accountable_user_id"`- RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`- OriginatorSource pgtype.Text `json:"originator_source"`- DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`- RuleVersionID pgtype.UUID `json:"rule_version_id"`- RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`- TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`- TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`- ID pgtype.UUID `json:"id"`+ AgentID pgtype.UUID `json:"agent_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ Priority int32 `json:"priority"`+ FireAt pgtype.Timestamptz `json:"fire_at"`+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`+ TriggerSummary pgtype.Text `json:"trigger_summary"`+ ForceFreshSession pgtype.Bool `json:"force_fresh_session"`+ IsLeaderTask pgtype.Bool `json:"is_leader_task"`+ HandoffNote pgtype.Text `json:"handoff_note"`+ SquadID pgtype.UUID `json:"squad_id"`+ HeadSha pgtype.Text `json:"head_sha"`+ FreshRerun pgtype.Bool `json:"fresh_rerun"`+ WorkflowHandoffRevision pgtype.Int8 `json:"workflow_handoff_revision"`+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`+ OriginatorSource pgtype.Text `json:"originator_source"`+ DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`+ RuleVersionID pgtype.UUID `json:"rule_version_id"`+ RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`+ WorkflowStep pgtype.Text `json:"workflow_step"`+ ID pgtype.UUID `json:"id"`}// Fenced against workspace teardown: lock_task_owner_rows (migration 284)@@ -2351,12 +2361,16 @@ type CreateAgentTaskParams struct {// COALESCE keeps the column's gen_random_uuid() default reachable, so a caller// that passes no id still inserts — it just gets a random v4, exactly as before.// The same pattern is used by every INSERT listed in pkg/dbid's write table.+// Workflow handoffs pass their original step and source revision explicitly.+// A fire_at value admits a durable deferred task outside the pending slot;+// existing callers omit it and continue to insert queued tasks.func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, createAgentTask,arg.AgentID,arg.RuntimeID,arg.IssueID,arg.Priority,+ arg.FireAt,arg.TriggerCommentID,arg.CoalescedCommentIds,arg.TriggerSummary,@@ -2366,6 +2380,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParamsarg.SquadID,arg.HeadSha,arg.FreshRerun,+ arg.WorkflowHandoffRevision,arg.OriginatorUserID,arg.AccountableUserID,arg.RuntimeMcpOverlay,@@ -2376,6 +2391,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParamsarg.RerunOfTaskID,arg.TriggerEvidenceKind,arg.TriggerEvidenceRefID,+ arg.WorkflowStep,arg.ID,)var i AgentTaskQueuediff --git a/server/pkg/db/generated/workflow_handoff.sql.go b/server/pkg/db/generated/workflow_handoff.sql.gonew file mode 100644index 0000000000..956950a7cb--- /dev/null+++ b/server/pkg/db/generated/workflow_handoff.sql.go@@ -0,0 +1,109 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: workflow_handoff.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const getWorkflowSquadHandoffTask = `-- name: GetWorkflowSquadHandoffTask :one+SELECT id FROM agent_task_queue+WHERE issue_id = $1+ AND agent_id = $2+ AND squad_id = $3+ AND is_leader_task+ AND context->>'workflow_handoff_revision' = $4::bigint::text+ORDER BY created_at DESC, id DESC+LIMIT 1+`++type GetWorkflowSquadHandoffTaskParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ SquadID pgtype.UUID `json:"squad_id"`+ IssueRevision int64 `json:"issue_revision"`+}++// A replay of the same status write is already covered, including after claim+// or completion. A later visit to the same stage has a different issue revision.+func (q *Queries) GetWorkflowSquadHandoffTask(ctx context.Context, arg GetWorkflowSquadHandoffTaskParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, getWorkflowSquadHandoffTask,+ arg.IssueID,+ arg.AgentID,+ arg.SquadID,+ arg.IssueRevision,+ )+ var id pgtype.UUID+ err := row.Scan(&id)+ return id, err+}++const listAssigneeRunsForHandoff = `-- name: ListAssigneeRunsForHandoff :many+SELECT id, agent_id, status, started_at, created_at+FROM agent_task_queue+WHERE issue_id = $1+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND (+ ($2::text = 'agent' AND agent_id = $3)+ OR ($2::text = 'squad' AND squad_id = $3)+ )+ORDER BY created_at DESC, id DESC+`++type ListAssigneeRunsForHandoffParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ AssigneeType string `json:"assignee_type"`+ AssigneeID pgtype.UUID `json:"assignee_id"`+}++type ListAssigneeRunsForHandoffRow struct {+ ID pgtype.UUID `json:"id"`+ AgentID pgtype.UUID `json:"agent_id"`+ Status string `json:"status"`+ StartedAt pgtype.Timestamptz `json:"started_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++// Preview and explicit stop must cover every unfinished run of the previous+// assignee, including stage handoffs still waiting for a pending queue slot.+func (q *Queries) ListAssigneeRunsForHandoff(ctx context.Context, arg ListAssigneeRunsForHandoffParams) ([]ListAssigneeRunsForHandoffRow, error) {+ rows, err := q.db.Query(ctx, listAssigneeRunsForHandoff, arg.IssueID, arg.AssigneeType, arg.AssigneeID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListAssigneeRunsForHandoffRow{}+ for rows.Next() {+ var i ListAssigneeRunsForHandoffRow+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.Status,+ &i.StartedAt,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const lockWorkflowSquadHandoff = `-- name: LockWorkflowSquadHandoff :exec+SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':workflow_squad_handoff', 0))+`++// Serialize admission for one issue without taking its owner-row locks out of+// the order lock_task_owner_rows uses to fence workspace teardown.+func (q *Queries) LockWorkflowSquadHandoff(ctx context.Context, issueID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, lockWorkflowSquadHandoff, issueID)+ return err+}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex b0d499307f..890ca16395 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -336,15 +336,20 @@ LIMIT @page_limit;-- COALESCE keeps the column's gen_random_uuid() default reachable, so a caller-- that passes no id still inserts — it just gets a random v4, exactly as before.-- The same pattern is used by every INSERT listed in pkg/dbid's write table.+-- Workflow handoffs pass their original step and source revision explicitly.+-- A fire_at value admits a durable deferred task outside the pending slot;+-- existing callers omit it and continue to insert queued tasks.INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,- workflow_step, id+ workflow_step, fire_at, id)SELECT- $1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),+ $1, $2, $3,+ CASE WHEN sqlc.narg(fire_at)::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,+ $4, sqlc.narg(trigger_comment_id),COALESCE(sqlc.narg(coalesced_comment_ids)::uuid[], '{}'),sqlc.narg(trigger_summary),COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),@@ -359,6 +364,10 @@ SELECTWHEN COALESCE(sqlc.narg('fresh_rerun')::boolean, FALSE)THEN '{"fresh_rerun":true}'::jsonbELSE '{}'::jsonb+ END || CASE+ WHEN sqlc.narg(workflow_handoff_revision)::bigint IS NOT NULL+ THEN jsonb_build_object('workflow_handoff_revision', sqlc.narg(workflow_handoff_revision)::bigint)+ ELSE '{}'::jsonbEND, '{}'::jsonb),sqlc.narg(originator_user_id),sqlc.narg(accountable_user_id),@@ -371,7 +380,8 @@ SELECTsqlc.narg(trigger_evidence_kind),sqlc.narg(trigger_evidence_ref_id),-- The issue's status as this task is queued: the workflow step it works on (MUL-7420).- (SELECT i.status FROM issue i WHERE i.id = $3),+ COALESCE(sqlc.narg(workflow_step)::text, (SELECT i.status FROM issue i WHERE i.id = $3)),+ sqlc.narg(fire_at),COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())WHERE lock_task_owner_rows($1, $3, $2)RETURNING *;diff --git a/server/pkg/db/queries/workflow_handoff.sql b/server/pkg/db/queries/workflow_handoff.sqlnew file mode 100644index 0000000000..12a67b35b5--- /dev/null+++ b/server/pkg/db/queries/workflow_handoff.sql@@ -0,0 +1,29 @@+-- name: LockWorkflowSquadHandoff :exec+-- Serialize admission for one issue without taking its owner-row locks out of+-- the order lock_task_owner_rows uses to fence workspace teardown.+SELECT pg_advisory_xact_lock(hashtextextended(sqlc.arg('issue_id')::uuid::text || ':workflow_squad_handoff', 0));++-- name: GetWorkflowSquadHandoffTask :one+-- A replay of the same status write is already covered, including after claim+-- or completion. A later visit to the same stage has a different issue revision.+SELECT id FROM agent_task_queue+WHERE issue_id = @issue_id+ AND agent_id = @agent_id+ AND squad_id = @squad_id+ AND is_leader_task+ AND context->>'workflow_handoff_revision' = sqlc.arg('issue_revision')::bigint::text+ORDER BY created_at DESC, id DESC+LIMIT 1;++-- name: ListAssigneeRunsForHandoff :many+-- Preview and explicit stop must cover every unfinished run of the previous+-- assignee, including stage handoffs still waiting for a pending queue slot.+SELECT id, agent_id, status, started_at, created_at+FROM agent_task_queue+WHERE issue_id = @issue_id+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ AND (+ (sqlc.arg('assignee_type')::text = 'agent' AND agent_id = @assignee_id)+ OR (sqlc.arg('assignee_type')::text = 'squad' AND squad_id = @assignee_id)+ )+ORDER BY created_at DESC, id DESC;