Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7288: fix(server): wake guest squad leaders on worker replies (#8314)
bojackliaf62622e50e5
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 4c2c8070bd..4bf0fe6ff3 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1519,16 +1519,19 @@ type commentAgentTrigger struct {Source commentAgentTriggerSourceSquad *db.SquadAlreadyPending bool- // NonLeaderAgentReply marks an agent comment, not authored by the leader,- // that the assigned-squad-leader fallback routes to that leader. The author- // need not be a squad member. Completion may replay it only if creation- // recorded it as a planned input.+ // NonLeaderAgentReply marks an agent comment routed back to a squad leader+ // from worker context. The worker need not be a squad member. Completion may+ // replay it only if creation recorded it as a planned input.NonLeaderAgentReply bool}type commentTriggerComputeOptions struct {ThreadCommentID pgtype.UUIDExcludeTriggerCommentID pgtype.UUID+ // AuthoringTaskID is the server-trusted task that wrote an agent comment.+ // It lets a worker result continue the exact guest squad-leader delegation+ // without guessing from squad membership or the issue assignee.+ AuthoringTaskID pgtype.UUID// OriginatorUserID is the top-of-chain human user id for this trigger// (MUL-3963). Only consulted for AGENT actors — canInvokeAgent judges A2A// by the originator, not the immediate agent principal. Members are their@@ -1639,6 +1642,9 @@ func (h *Handler) PreviewCommentTriggers(w http.ResponseWriter, r *http.Request)actorType, actorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))opts.OriginatorUserID = h.invokeOriginatorFromRequest(r, actorType, actorID)+ if actorType == "agent" {+ opts.AuthoringTaskID = h.commentSourceTaskID(r)+ }triggers, targets := h.computeCommentAgentTriggers(r.Context(), issue, content, parentComment, actorType, actorID, opts)resp := CommentTriggerPreviewResponse{Agents: make([]CommentTriggerAgentResponse, 0, len(triggers)),@@ -2000,6 +2006,7 @@ func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, co}triggers, targets := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{ExcludeTriggerCommentID: comment.ID,+ AuthoringTaskID: comment.SourceTaskID,OriginatorUserID: originatorUserID,})triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)@@ -2694,14 +2701,17 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issuif actorType != "member" {// Agent-authored comments do not participate in the member-driven// conversation routing (parent-author / thread-root continuation) or- // the member assignee fallback. They retain one narrow path restored- // after MUL-3794 (MUL-3879): a worker-agent result comment on a- // squad-assigned issue can still wake the assigned squad leader, so- // the leader→worker→leader coordination loop stays closed. The leader- // self-trigger guard lives in- // routeAssignedSquadLeaderFallback. Explicit @agent / @squad mentions- // are already handled above, so this never double-enqueues a mentioned- // target alongside the assigned leader.+ // the member assignee fallback. Worker-result comments retain the+ // leader→worker→leader loop: the assigned squad is resolved from the+ // issue (MUL-3879), while a guest squad is resolved from the exact+ // covered leader delegation (GH-8301). Explicit @agent / @squad mentions+ // are already handled above, so neither fallback double-enqueues a+ // mentioned target.+ if actorType == "agent" {+ if triggers, handled := h.routeGuestSquadLeaderFallback(ctx, issue, parentComment, actorID, opts); handled {+ return triggers, nil+ }+ }if issue.AssigneeType.Valid && issue.AssigneeType.String == "squad" {if trigger, ok := h.routeAssignedSquadLeaderFallback(ctx, issue, actorType, actorID, opts); ok {trigger.NonLeaderAgentReply = actorType == "agent" && actorID != uuidToString(trigger.Agent.ID)@@ -2836,6 +2846,53 @@ func (h *Handler) squadLeaderRoleOfAuthoringTask(ctx context.Context, issue db.Ireturn &squad, true}+// routeGuestSquadLeaderFallback closes the leader→worker→leader loop when the+// squad was @mentioned as a guest instead of assigned to the issue. The+// authoring worker task must cover the replied-to delegation comment; that+// comment's own task then proves the exact squad and current leader role. Once+// that historical leader role is identified, a now-invalid squad or leader+// fails closed instead of falling through to an unrelated assigned squad.+func (h *Handler) routeGuestSquadLeaderFallback(ctx context.Context, issue db.Issue, parent *db.Comment, authorID string, opts commentTriggerComputeOptions) ([]commentAgentTrigger, bool) {+ if parent == nil || !parent.ID.Valid {+ return nil, false+ }+ // A tombstone preserves only the reply tree, not the guest delegation's+ // routing authority (#8323). The issue's assignment remains an independent+ // source of authority for the assigned-squad fallback.+ if parent.DeletedAt.Valid {+ return nil, false+ }+ if !opts.AuthoringTaskID.Valid {+ return nil, false+ }+ workerTask, err := h.Queries.GetAgentTask(ctx, opts.AuthoringTaskID)+ if err != nil || workerTask.IsLeaderTask || !workerTask.AgentID.Valid ||+ uuidToString(workerTask.AgentID) != authorID || !workerTask.IssueID.Valid ||+ uuidToString(workerTask.IssueID) != uuidToString(issue.ID) || !taskCoversReplyParent(workerTask, parent.ID) {+ return nil, false+ }+ if !parent.SourceTaskID.Valid {+ return nil, false+ }+ leaderTask, err := h.Queries.GetAgentTask(ctx, parent.SourceTaskID)+ if err != nil || !leaderTask.IsLeaderTask || !leaderTask.SquadID.Valid ||+ !leaderTask.AgentID.Valid || leaderTask.AgentID != parent.AuthorID {+ return nil, false+ }+ // Preserve the established assigned-squad path when this delegation came+ // from that same squad. This fallback is only for a distinct guest squad.+ if issue.AssigneeType.Valid && issue.AssigneeType.String == "squad" &&+ issue.AssigneeID.Valid && issue.AssigneeID == leaderTask.SquadID {+ return nil, false+ }+ trigger, ok := h.routeReplyToParentAuthor(ctx, issue, parent, "agent", authorID, opts)+ if !ok || trigger.Squad == nil {+ return nil, true+ }+ trigger.NonLeaderAgentReply = true+ return []commentAgentTrigger{trigger}, true+}+type conversationRoutedAgentInfo struct {SquadID pgtype.UUID}@@ -3923,6 +3980,7 @@ func (h *Handler) retriggerCancelledTaskSurvivors(ctx context.Context, issue db.}triggers, _ := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{ExcludeTriggerCommentID: comment.ID,+ AuthoringTaskID: comment.SourceTaskID,OriginatorUserID: originatorUserID,})targets := targetsByComment[uuidToString(comment.ID)]diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 8e657e1e10..7f06b43cce 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -4384,8 +4384,8 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A//// Scope + loop safety:// - MEMBER comments keep their full routing. AGENT comments qualify through-// explicit mentions, or the worker-to-assigned-leader route when the input-// was already accepted and recorded in this run's plan. Timestamp-only+// explicit mentions, or a worker-to-leader route when the input was already+// accepted and recorded in this run's plan. Timestamp-only// implicit agent replies are excluded: completion must not invent a new// conversation. Current invocation permissions and self-trigger guards// still apply to every replay.@@ -4493,6 +4493,7 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag}triggers, _ := h.computeCommentAgentTriggers(ctx, issue, c.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{ExcludeTriggerCommentID: c.ID,+ AuthoringTaskID: c.SourceTaskID,OriginatorUserID: originatorUserID,})// Agent replies discovered only by timestamp must not start a new@@ -4560,7 +4561,7 @@ func keepReplayableAgentTriggers(triggers []commentAgentTrigger, planned bool) [switch trigger.Source {case commentTriggerSourceMentionAgent, commentTriggerSourceMentionSquadLeader:filtered = append(filtered, trigger)- case commentTriggerSourceIssueAssignee:+ case commentTriggerSourceIssueAssignee, commentTriggerSourceThreadParent:if planned && trigger.NonLeaderAgentReply {filtered = append(filtered, trigger)}diff --git a/server/internal/handler/squad_worker_comment_wakes_leader_test.go b/server/internal/handler/squad_worker_comment_wakes_leader_test.goindex eb61765c7b..2b96986972 100644--- a/server/internal/handler/squad_worker_comment_wakes_leader_test.go+++ b/server/internal/handler/squad_worker_comment_wakes_leader_test.go@@ -6,9 +6,154 @@ import ("net/http/httptest""testing"+ "github.com/google/uuid""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil")+func TestGuestSquadWorkerReplayRequiresPlannedInput_GH8301(t *testing.T) {+ trigger := commentAgentTrigger{Source: commentTriggerSourceThreadParent, NonLeaderAgentReply: true}+ if got := keepReplayableAgentTriggers([]commentAgentTrigger{trigger}, false); len(got) != 0 {+ t.Fatal("timestamp-only guest worker reply must not replay")+ }+ if got := keepReplayableAgentTriggers([]commentAgentTrigger{trigger}, true); len(got) != 1 {+ t.Fatal("planned guest worker reply must replay")+ }+}++func TestGuestSquadWorkerRouteOnMemberAssignedIssue_GH8301(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ fx := newSquadCommentTriggerFixture(t)+ issueID := uuidToString(fx.Issue.ID)+ dbfx.Exec(t, `UPDATE issue SET assignee_type = 'member', assignee_id = $2 WHERE id = $1`, issueID, testUserID)+ fx.Issue.AssigneeType = pgtype.Text{String: "member", Valid: true}+ fx.Issue.AssigneeID = parseUUID(testUserID)++ leaderTaskID := dbfx.Task(t, fx.LeaderID, testutil.Cols{+ "runtime_id": testRuntimeID, "issue_id": issueID, "status": "completed",+ "is_leader_task": true, "squad_id": fx.SquadID,+ "originator_user_id": testUserID, "accountable_user_id": testUserID,+ })+ delegationID := dbfx.Comment(t, issueID, "delegate to guest worker", testutil.Cols{+ "author_type": "agent", "author_id": fx.LeaderID, "source_task_id": leaderTaskID,+ })+ workerTaskID := dbfx.Task(t, fx.OtherID, testutil.Cols{+ "runtime_id": testRuntimeID, "issue_id": issueID, "status": "running",+ "trigger_comment_id": delegationID, "squad_id": fx.SquadID,+ "delegated_from_task_id": leaderTaskID,+ "originator_user_id": testUserID, "accountable_user_id": testUserID,+ })+ parent, err := testHandler.Queries.GetComment(ctx, parseUUID(delegationID))+ if err != nil {+ t.Fatal(err)+ }+ triggers, _ := testHandler.computeCommentAgentTriggers(ctx, fx.Issue, "done", &parent, "agent", fx.OtherID, commentTriggerComputeOptions{+ AuthoringTaskID: parseUUID(workerTaskID), OriginatorUserID: testUserID,+ })+ if len(triggers) != 1 || triggers[0].Source != commentTriggerSourceThreadParent || triggers[0].Squad == nil {+ t.Fatalf("guest worker route = %+v, want one squad leader thread-parent trigger", triggers)+ }+ if got := keepReplayableAgentTriggers(triggers, true); len(got) != 1 {+ t.Fatal("planned guest worker reply must replay")+ }+}++func TestCreateComment_GuestSquadWorkerRouting_GH8301(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ cases := []struct {+ mode string+ name string+ wantAssigned, wantGuest int+ }{+ {mode: "live", name: "live guest delegation", wantGuest: 1},+ {mode: "leader_changed", name: "changed guest leader fails closed"},+ {mode: "permission_denied", name: "guest permission denied fails closed"},+ {mode: "deleted", name: "deleted guest delegation uses assigned squad", wantAssigned: 1},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ mode := tc.mode+ var outsiderID string+ if mode == "permission_denied" {+ outsiderID = dbfx.User(t, "GH-8301 outsider", "gh-8301-outsider-"+uuid.NewString()+"@multica.test")+ }+ assignedLeaderID := dbfx.Agent(t, "GH-8301 assigned leader "+mode, testRuntimeID)+ guestLeaderID := dbfx.Agent(t, "GH-8301 exact guest leader "+mode, testRuntimeID)+ replacementID := dbfx.Agent(t, "GH-8301 replacement leader "+mode, testRuntimeID)+ workerID := dbfx.Agent(t, "GH-8301 exact guest worker "+mode, testRuntimeID)+ assignedSquadID := dbfx.Squad(t, "GH-8301 assigned squad "+mode, assignedLeaderID)+ guestSquadID := dbfx.Squad(t, "GH-8301 exact guest squad "+mode, guestLeaderID)+ issueID := dbfx.Issue(t, "guest route beats assigned fallback "+mode, testutil.Cols{+ "assignee_type": "squad",+ "assignee_id": assignedSquadID,+ })+ guestLeaderTaskID := dbfx.Task(t, guestLeaderID, testutil.Cols{+ "runtime_id": testRuntimeID,+ "issue_id": issueID,+ "status": "completed",+ "is_leader_task": true,+ "squad_id": guestSquadID,+ "originator_user_id": testUserID,+ "accountable_user_id": testUserID,+ })+ delegationID := dbfx.Comment(t, issueID, "delegate to guest worker", testutil.Cols{+ "author_type": "agent",+ "author_id": guestLeaderID,+ "source_task_id": guestLeaderTaskID,+ })+ workerTaskID := dbfx.Task(t, workerID, testutil.Cols{+ "runtime_id": testRuntimeID,+ "issue_id": issueID,+ "status": "running",+ "trigger_comment_id": delegationID,+ "squad_id": guestSquadID,+ "delegated_from_task_id": guestLeaderTaskID,+ "originator_user_id": testUserID,+ "accountable_user_id": testUserID,+ })+ dbfx.Cleanup(t, `DELETE FROM comment WHERE issue_id = $1`, issueID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)++ switch mode {+ case "leader_changed":+ dbfx.Exec(t, `UPDATE squad SET leader_id = $2 WHERE id = $1`, guestSquadID, replacementID)+ case "permission_denied":+ dbfx.Exec(t, `UPDATE agent SET owner_id = $2 WHERE id = $1`, guestLeaderID, outsiderID)+ case "deleted":+ dbfx.Comment(t, issueID, "keep delegation reply tree", testutil.Cols{"parent_id": delegationID})+ deleted, err := testHandler.deleteComment(context.Background(), parseUUID(delegationID), parseUUID(testWorkspaceID))+ if err != nil {+ t.Fatal(err)+ }+ if deleted.Tombstone == nil {+ t.Fatal("delegation with replies was removed instead of tombstoned")+ }+ }++ r := newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{+ "content": "guest work complete",+ "parent_id": delegationID,+ })+ r.Header.Set("X-Agent-ID", workerID)+ r.Header.Set("X-Task-ID", workerTaskID)+ r = withURLParam(r, "id", issueID)+ testutil.Call(t, testHandler.CreateComment, r).Want(http.StatusCreated)++ if got := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued' AND is_leader_task = TRUE AND squad_id = $3`, issueID, assignedLeaderID, assignedSquadID); got != tc.wantAssigned {+ t.Fatalf("assigned squad leader received %d task(s), want %d", got, tc.wantAssigned)+ }+ if got := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued' AND is_leader_task = TRUE AND squad_id = $3`, issueID, guestLeaderID, guestSquadID); got != tc.wantGuest {+ t.Fatalf("exact guest squad leader received %d task(s), want %d", got, tc.wantGuest)+ }+ })+ }+}+// TestCreateComment_WorkerAgentCommentWakesSquadLeader_MUL4015 pins the// full CreateComment behavior for the scenario reported in MUL-4015://