Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7272: fix(comments): preserve deferred worker reply handoffs (#8288)
importcpp1500abe357c2
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex db7f772740..ab54255c12 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1504,6 +1504,11 @@ 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 bool}type commentTriggerComputeOptions struct {@@ -2034,10 +2039,10 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu// - queued — a fresh task was created for it;// - deferred — an active task's completion reconcile will replay it, either// because a planned-id write landed on a claim-receipt task-// (lost-race path, where the comment may PREDATE the task) or+// (worker reply, or lost enqueue race where the comment may predate the task) or// because the comment is newer than that task and therefore// inside reconcile's `created_at > since` window (AlreadyPending-// path, where the task existed before the comment).+// path for member/explicit-mention routes, where the task existed first).//// The deferral is not a one-shot prediction: if a replay is later blocked by a// task that cannot cover the comment, reconcileCommentsOnCompletion hands the@@ -2094,7 +2099,7 @@ func (h *Handler) resolveCommentTriggerEnqueue(ctx context.Context, issue db.Iss}// No same-head QUEUED row to fold into (merge missed). The two paths// resolve differently.- if !lostRace {+ if !lostRace && !trigger.NonLeaderAgentReply {// (b) AlreadyPending path: this comment arrived AFTER its task, so// it is newer than the task and completion reconcile covers it by// timestamp; MUL-4195 leaves the claimed task untouched. Defer to@@ -2105,7 +2110,10 @@ func (h *Handler) resolveCommentTriggerEnqueue(ctx context.Context, issue db.Iss}// enqueueFresh → fall through to the enqueue below.} else {- // (c) Lost INSERT race: the losing comment can PREDATE the winner,+ // (c) A worker reply needs a recorded obligation: unlike explicit+ // mentions, timestamp-only agent replies are not replayed (loop+ // safety). The same registration also covers a lost INSERT race,+ // where the losing comment can PREDATE the winner,// which completion reconcile's `created_at > since` window cannot// see. Register it as a planned (undelivered) input on a same-head// CLAIM-RECEIPT task (dispatched/running/waiting; queued is excluded@@ -2113,7 +2121,7 @@ func (h *Handler) resolveCommentTriggerEnqueue(ctx context.Context, issue db.Iss// into a bounded follow-up (#5914, Elon round 2).registered, err := h.registerPlannedCommentForActiveTask(ctx, issue, trigger.Agent.ID, triggerCommentID, getHeadSha())if err != nil {- slog.Warn("register planned lost-race comment failed",+ slog.Warn("register planned comment failed","issue_id", uuidToString(issue.ID), "agent_id", uuidToString(trigger.Agent.ID), "error", err)return DispatchBlocked, ReasonInternalError}@@ -2398,7 +2406,7 @@ func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issureturn commentMergeSucceeded}-// registerPlannedCommentForActiveTask durably folds a lost-race comment into the+// registerPlannedCommentForActiveTask durably folds an accepted comment into the// same-head active task's planned (coalesced) set when the queued merge could no// longer target it (the winner was already claimed → dispatched/running). It// returns true when a same-head active task absorbed the comment; (false, nil)@@ -2419,7 +2427,7 @@ func (h *Handler) registerPlannedCommentForActiveTask(ctx context.Context, issue}return false, err}- slog.Info("registered lost-race comment as planned follow-up input",+ slog.Info("registered comment as planned follow-up input","task_id", uuidToString(row.ID),"issue_id", uuidToString(issue.ID),"agent_id", uuidToString(agentID),@@ -2621,6 +2629,7 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu// target alongside the assigned leader.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)return []commentAgentTrigger{trigger}, nil}}diff --git a/server/internal/handler/comment_reconcile_test.go b/server/internal/handler/comment_reconcile_test.goindex bbdc910cde..08a3144854 100644--- a/server/internal/handler/comment_reconcile_test.go+++ b/server/internal/handler/comment_reconcile_test.go@@ -378,11 +378,9 @@ func TestCompleteTask_DoesNotReconcilePlainAgentReply(t *testing.T) {// computeCommentAgentTriggers routes a plain worker-agent reply (no mention) to// the squad leader via routeAssignedSquadLeaderFallback (Source = issue// assignee) — that is the create-time leader→worker→leader coordination path.-// Reconcile must NOT replay that fallback: it compensates ONLY explicit-// @agent/@squad mentions (keepExplicitMentionTriggers). So when the squad leader-// completes a task and a worker's plain reply arrived during the run, no-// completion-driven follow-up may be enqueued for the leader. Without the-// explicit-mention filter this test enqueues 1 leader task and fails.+// This reply was never accepted into a run's input plan. Reconcile must NOT+// turn a timestamp-only plain reply into a new conversation. Accepted worker+// handoffs are covered separately by TestWorkerReplyDelivery.func TestCompleteTask_DoesNotReconcilePlainWorkerReplyOnSquadIssue(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")diff --git a/server/internal/handler/comment_worker_handoff_test.go b/server/internal/handler/comment_worker_handoff_test.gonew file mode 100644index 0000000000..ec60baaf4e--- /dev/null+++ b/server/internal/handler/comment_worker_handoff_test.go@@ -0,0 +1,395 @@+package handler++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "slices"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func claimWorkerReplyRun(t *testing.T, runtimeID string) *AgentTaskResponse {+ t.Helper()+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "worker-reply-handoff")+ req = withURLParam(req, "runtimeId", runtimeID)+ req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityCoalescedCommentsV1)+ var response struct {+ Task *AgentTaskResponse `json:"task"`+ }+ testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK).JSON(&response)+ return response.Task+}++func completeWorkerReplyRun(t *testing.T, taskID string) {+ t.Helper()+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/complete", map[string]any{"output": "Processed the inputs delivered to this run"}, testWorkspaceID, "worker-reply-handoff")+ req = withURLParam(req, "taskId", taskID)+ testutil.Call(t, testHandler.CompleteTask, req).Want(http.StatusOK)+}++// A worker progress comment wakes the leader; its final reply must also reach a+// leader run even if the first wake was claimed before the reply arrived.+func TestWorkerReplyDelivery(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ for _, state := range []string{"queued", "dispatched", "running"} {+ for _, explicit := range []bool{false, true} {+ t.Run(fmt.Sprintf("%s/explicit=%t", state, explicit), func(t *testing.T) {+ ctx := context.Background()+ leaderRuntimeID := dbfx.Runtime(t, "Worker handoff leader runtime")+ leaderID := dbfx.Agent(t, "Worker handoff leader", leaderRuntimeID, testutil.Cols{"max_concurrent_tasks": 3})+ workerRuntimeID := dbfx.Runtime(t, "Worker handoff worker runtime")+ workerID := dbfx.Agent(t, "Worker handoff worker", workerRuntimeID)+ squadID := dbfx.Squad(t, "Worker handoff squad", leaderID)+ dbfx.SquadMember(t, squadID, "agent", workerID)+ issueID := dbfx.Issue(t, "Worker results must reach the coordinator", testutil.Cols{+ "status": "in_progress", "assignee_type": "squad", "assignee_id": squadID,+ })+ sourceID := dbfx.Task(t, leaderID, testutil.Cols{+ "runtime_id": leaderRuntimeID, "issue_id": issueID, "status": "completed",+ "is_leader_task": true, "squad_id": squadID,+ "originator_user_id": testUserID, "accountable_user_id": testUserID,+ })+ rootID := dbfx.Comment(t, issueID, fmt.Sprintf("[@Worker](mention://agent/%s) verify the implementation", workerID), testutil.Cols{+ "author_type": "agent", "author_id": leaderID, "source_task_id": sourceID,+ })+ workerTaskID := dbfx.Task(t, workerID, testutil.Cols{+ "runtime_id": workerRuntimeID, "issue_id": issueID, "status": "running",+ "trigger_comment_id": rootID, "squad_id": squadID, "delegated_from_task_id": sourceID,+ "originator_user_id": testUserID, "accountable_user_id": testUserID,+ })+ post := func(content string) CommentResponse {+ req := withURLParam(newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{+ "content": content, "parent_id": rootID,+ }), "id", issueID)+ req.Header.Set("X-Agent-ID", workerID)+ req.Header.Set("X-Task-ID", workerTaskID)+ var response CommentResponse+ testutil.Call(t, testHandler.CreateComment, req).Want(http.StatusCreated).JSON(&response)+ if response.AuthorType != "agent" || response.SourceTaskID == nil || *response.SourceTaskID != workerTaskID {+ t.Fatal("worker reply lost its authenticated source task")+ }+ return response+ }+ progress := post("Verification started; final results will follow in this thread")+ var leaderTaskID string+ dbfx.QueryRow(t, `SELECT id FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`, issueID, leaderID).Scan(&leaderTaskID)+ var first *AgentTaskResponse+ if state != "queued" {+ first = claimWorkerReplyRun(t, leaderRuntimeID)+ if first == nil || first.ID != leaderTaskID || !slices.Contains(first.DeliveredCommentIDs, progress.ID) {+ t.Fatal("first leader run did not receive the worker's progress")+ }+ }+ if state == "running" {+ if _, err := testHandler.TaskService.StartTask(ctx, parseUUID(leaderTaskID)); err != nil {+ t.Fatal(err)+ }+ }+ content := "Verification complete: found a correctness issue; please coordinate the repair"+ if explicit {+ content = fmt.Sprintf("[@Squad](mention://squad/%s) %s", squadID, content)+ }+ details := post("Evidence: the final reply can arrive after the leader claims its inputs")+ result := post(content)+ stored, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(leaderTaskID))+ if err != nil {+ t.Fatal(err)+ }+ if state == "dispatched" && !explicit {+ for _, id := range []string{details.ID, result.ID} {+ if !slices.Contains(stored.CoalescedCommentIds, parseUUID(id)) || slices.Contains(stored.DeliveredCommentIds, parseUUID(id)) {+ t.Fatal("accepted worker reply must be planned without changing the earlier delivery receipt")+ }+ }+ if stored.TriggerCommentID != parseUUID(progress.ID) {+ t.Fatal("registering a worker reply must not replace an already claimed trigger")+ }+ }+ if state == "queued" {+ first = claimWorkerReplyRun(t, leaderRuntimeID)+ if first == nil || first.ID != leaderTaskID || !slices.Contains(first.DeliveredCommentIDs, result.ID) || !slices.Contains(first.DeliveredCommentIDs, details.ID) || first.TriggerCommentContent != content {+ t.Fatal("queued leader must coalesce and receive the worker result")+ }+ } else if slices.Contains(first.DeliveredCommentIDs, result.ID) {+ t.Fatal("an earlier claim cannot have delivered a later comment")+ }+ if state != "running" {+ if _, err := testHandler.TaskService.StartTask(ctx, parseUUID(leaderTaskID)); err != nil {+ t.Fatal(err)+ }+ }+ if other := claimWorkerReplyRun(t, leaderRuntimeID); other != nil {+ t.Fatal("same issue/leader must remain serialized")+ }+ completeWorkerReplyRun(t, leaderTaskID)+ next := claimWorkerReplyRun(t, leaderRuntimeID)+ if state == "queued" {+ if next != nil {+ t.Fatal("already delivered result must not create another leader run")+ }+ return+ }+ if next == nil {+ t.Fatal("worker result persisted but was neither delivered nor followed by another leader run")+ }+ if !next.IsLeaderTask || !slices.Contains(next.DeliveredCommentIDs, result.ID) || !slices.Contains(next.DeliveredCommentIDs, details.ID) || next.TriggerCommentContent != content {+ t.Fatal("follow-up must deliver the result in the squad leader role")+ }+ successor, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(next.ID))+ if err != nil {+ t.Fatal(err)+ }+ if successor.SquadID != parseUUID(squadID) || successor.OriginatorUserID != parseUUID(testUserID) || successor.AccountableUserID != parseUUID(testUserID) || successor.DelegatedFromTaskID != parseUUID(workerTaskID) {+ t.Fatal("worker follow-up lost squad or human delegation provenance")+ }+ if _, err := testHandler.TaskService.StartTask(ctx, parseUUID(next.ID)); err != nil {+ t.Fatal(err)+ }+ completeWorkerReplyRun(t, next.ID)+ if another := claimWorkerReplyRun(t, leaderRuntimeID); another != nil {+ t.Fatal("worker result must not generate an endless leader follow-up loop")+ }+ })+ }+ }+}++// Unplanned replies must be in the completing run's thread and timestamp window:+// otherwise a passing negative case could merely be the SQL scope excluding it.+func TestWorkerReplyReconcileBoundaries(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ for _, mode := range []string{"accepted", "unplanned", "suppressed", "leader_reply", "note", "archived_leader", "reassigned", "registration_failure", "completed_before_registration"} {+ t.Run(mode, func(t *testing.T) {+ ctx := context.Background()+ runtimeID := dbfx.Runtime(t, "Worker replay boundary leader")+ leaderID := dbfx.Agent(t, "Worker replay boundary leader", runtimeID)+ workerRuntimeID := dbfx.Runtime(t, "Worker replay boundary worker")+ workerID := dbfx.Agent(t, "Worker replay boundary worker", workerRuntimeID)+ squadID := dbfx.Squad(t, "Worker replay boundary squad", leaderID)+ dbfx.SquadMember(t, squadID, "agent", workerID)+ issueID := dbfx.Issue(t, "Worker replay boundary", testutil.Cols{+ "status": "in_progress", "assignee_type": "squad", "assignee_id": squadID,+ })+ rootID := dbfx.Comment(t, issueID, "Coordinate this work", testutil.Cols{"created_at": testutil.Raw("now() - interval '6 minutes'")})+ taskID := dbfx.Task(t, leaderID, testutil.Cols{+ "runtime_id": runtimeID, "issue_id": issueID, "status": "queued",+ "trigger_comment_id": rootID, "is_leader_task": true, "squad_id": squadID,+ "originator_user_id": testUserID, "accountable_user_id": testUserID,+ "created_at": testutil.Raw("now() - interval '5 minutes'"),+ })+ workerTaskID := dbfx.Task(t, workerID, testutil.Cols{+ "runtime_id": workerRuntimeID, "issue_id": issueID, "status": "running",+ "trigger_comment_id": rootID, "squad_id": squadID,+ "originator_user_id": testUserID, "accountable_user_id": testUserID,+ })+ first := claimWorkerReplyRun(t, runtimeID)+ if first == nil || first.ID != taskID {+ t.Fatal("leader run was not claimed")+ }+ var replyID string+ if mode == "unplanned" {+ replyID = dbfx.Comment(t, issueID, "An ordinary reply with no accepted dispatch", testutil.Cols{+ "parent_id": rootID, "author_type": "agent", "author_id": workerID, "source_task_id": workerTaskID,+ })+ } else {+ body := map[string]any{"content": "The worker has results", "parent_id": rootID}+ if mode == "note" {+ body["content"] = "/note an informational update"+ }+ if mode == "suppressed" {+ body["suppress_agent_ids"] = []string{leaderID}+ }+ req := withURLParam(newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", body), "id", issueID)+ req.Header.Set("X-Agent-ID", workerID)+ req.Header.Set("X-Task-ID", workerTaskID)+ if mode == "leader_reply" {+ req.Header.Set("X-Agent-ID", leaderID)+ req.Header.Set("X-Task-ID", taskID)+ }+ var response CommentResponse+ h := *testHandler+ registration := &workerReplyRegistrationDB{DBTX: testPool}+ if mode == "registration_failure" {+ registration.err = errors.New("injected worker reply registration failure")+ }+ if mode == "completed_before_registration" {+ registration.before = func() {+ if _, err := testHandler.TaskService.StartTask(ctx, parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ completeWorkerReplyRun(t, taskID)+ }+ }+ if mode == "registration_failure" || mode == "completed_before_registration" {+ h.Queries = db.New(registration)+ }+ testutil.Call(t, h.CreateComment, req).Want(http.StatusCreated).JSON(&response)+ if (mode == "registration_failure" || mode == "completed_before_registration") && registration.calls != 1 {+ t.Fatalf("registration probe called %d times", registration.calls)+ }+ replyID = response.ID+ }+ task, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ comments, err := testHandler.Queries.ListReconcilableCommentsForIssueSince(ctx, db.ListReconcilableCommentsForIssueSinceParams{+ IssueID: task.IssueID, CommentThreadID: task.CommentThreadID, Since: task.CreatedAt,+ PlannedCommentIds: task.CoalescedCommentIds,+ })+ if err != nil {+ t.Fatal(err)+ }+ if !slices.ContainsFunc(comments, func(c db.Comment) bool { return c.ID == parseUUID(replyID) }) {+ t.Fatal("reply must reach the replay filter, not be excluded by the SQL thread/time window")+ }+ wantPlanned := mode == "accepted" || mode == "archived_leader" || mode == "reassigned"+ if slices.Contains(task.CoalescedCommentIds, parseUUID(replyID)) != wantPlanned {+ t.Fatalf("unexpected creation-time obligation for %s", mode)+ }+ if mode == "archived_leader" {+ dbfx.Exec(t, `UPDATE agent SET archived_at = now() WHERE id = $1`, leaderID)+ }+ if mode == "reassigned" {+ dbfx.Exec(t, `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, issueID, workerID)+ }+ if mode != "completed_before_registration" {+ if _, err := testHandler.TaskService.StartTask(ctx, parseUUID(taskID)); err != nil {+ t.Fatal(err)+ }+ completeWorkerReplyRun(t, taskID)+ }+ queued := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND status = 'queued'`, issueID)+ if mode != "accepted" && mode != "completed_before_registration" {+ if queued != 0 {+ t.Fatalf("%s must not create a completion-driven run, got %d", mode, queued)+ }+ return+ }+ if queued != 1 {+ t.Fatalf("accepted reply must create exactly one successor, got %d", queued)+ }+ next := claimWorkerReplyRun(t, runtimeID)+ if next == nil || !slices.Contains(next.DeliveredCommentIDs, replyID) {+ t.Fatal("accepted reply was not delivered")+ }+ if _, err := testHandler.TaskService.StartTask(ctx, parseUUID(next.ID)); err != nil {+ t.Fatal(err)+ }+ completeWorkerReplyRun(t, next.ID)+ if extra := claimWorkerReplyRun(t, runtimeID); extra != nil {+ t.Fatal("delivered worker reply replayed again")+ }+ })+ }+}++// If completion commits while registration waits for the task row lock, the+// caller must see a miss and enqueue fresh, not attach an obligation to a run+// whose completion snapshot can no longer include it.+func TestWorkerReplyRegistrationLosesCompletionRace(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ runtimeID := dbfx.Runtime(t, "Worker registration race")+ agentID := dbfx.Agent(t, "Worker registration race", runtimeID)+ issueID := dbfx.Issue(t, "Worker registration race")+ rootID := dbfx.Comment(t, issueID, "Initial input")+ replyID := dbfx.Comment(t, issueID, "Worker result", testutil.Cols{"parent_id": rootID})+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID, "issue_id": issueID, "status": "running", "trigger_comment_id": rootID,+ })+ tx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer func() {+ if err := tx.Rollback(context.Background()); err != nil && !errors.Is(err, pgx.ErrTxClosed) {+ t.Error(err)+ }+ }()+ if _, err := tx.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, taskID); err != nil {+ t.Fatal(err)+ }+ conn, err := testPool.Acquire(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer conn.Release()+ pid := conn.Conn().PgConn().PID()+ done := make(chan struct{})+ var registrationErr error+ go func() {+ _, registrationErr = db.New(conn).RegisterPlannedCommentForActiveTask(ctx, db.RegisterPlannedCommentForActiveTaskParams{+ IssueID: parseUUID(issueID), AgentID: parseUUID(agentID), CommentID: parseUUID(replyID),+ })+ close(done)+ }()+ // Stop the registration query before returning its connection to the pool,+ // including assertion failures while it is waiting for the task row lock.+ defer func() { cancel(); <-done }()+ for {+ var blocked bool+ if err := testPool.QueryRow(ctx, `SELECT cardinality(pg_blocking_pids($1)) > 0`, pid).Scan(&blocked); err != nil {+ t.Fatal(err)+ }+ if blocked {+ break+ }+ select {+ case <-ctx.Done():+ t.Fatal("registration did not block on the completing row")+ case <-time.After(5 * time.Millisecond):+ }+ }+ if err := tx.Commit(ctx); err != nil {+ t.Fatal(err)+ }+ <-done+ if !errors.Is(registrationErr, pgx.ErrNoRows) {+ t.Fatalf("registration after completion = %v, want no rows", registrationErr)+ }+ task, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ if slices.Contains(task.CoalescedCommentIds, parseUUID(replyID)) {+ t.Fatal("completed run acquired an undeliverable obligation")+ }+}++// Intercept only the new obligation write; all routing, comment persistence,+// completion, and successor enqueue still use their real database paths.+type workerReplyRegistrationDB struct {+ db.DBTX+ before func()+ err error+ calls int+}++func (d *workerReplyRegistrationDB) QueryRow(ctx context.Context, query string, args ...any) pgx.Row {+ if strings.Contains(query, "-- name: RegisterPlannedCommentForActiveTask :one") {+ d.calls+++ if d.before != nil {+ d.before()+ }+ if d.err != nil {+ return errRow{err: d.err}+ }+ }+ return d.DBTX.QueryRow(ctx, query, args...)+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 064b8a5abd..482da80503 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -10,6 +10,7 @@ import ("fmt""log/slog""net/http"+ "slices""sort""strconv""strings"@@ -3982,9 +3983,8 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {// MUL-4195: guarantee at-least-once processing. If a member posted a// deliberate comment while this run was executing (or one was merged into// it after its context was built), schedule a single follow-up so the- // input is never silently dropped. Loop-safe: member-authored only, capped- // by the existing per-(issue, agent) dedup, and terminating because the- // triggering comment always predates the follow-up run's started_at.+ // input is not silently dropped. Agent replays are restricted to explicit+ // mentions and recorded worker inputs; see reconcileCommentsOnCompletion.h.reconcileCommentsOnCompletion(r.Context(), task)// The terminal transaction and completion reconciliation are committed.// Wake the owning runtime now so queued work that was blocked by this@@ -4072,20 +4072,12 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A// a delivered one.//// Scope + loop safety:-// - MEMBER comments qualify as before, with their full routing. AGENT comments-// now also qualify, but ONLY through an explicit @agent/@squad mention-// (keepExplicitMentionTriggers). Every non-mention agent route — the-// assigned-squad-leader fallback, thread-parent / conversation continuation-// — is intentionally excluded, so a plain agent reply / acknowledgement-// earns no follow-up here regardless of issue assignment. That is the-// anti-loop boundary the old member-only filter protected.-// This closes MUL-4304: an explicit agent→agent @mention that landed while-// the target already had a DISPATCHED task is dropped by the create-time-// enqueue path — merge only folds a comment into a QUEUED task, so a-// dispatched target hits the merge-miss + active-task `continue` and is-// deferred here — and was then never replayed because agent comments were-// excluded. (A target with only a RUNNING/queued task does not hit that-// drop: queued merges in, running-only takes the normal fresh-enqueue path.)+// - 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+// implicit agent replies are excluded: completion must not invent a new+// conversation. Current invocation permissions and self-trigger guards+// still apply to every replay.// - Only comments routing to THE AGENT THAT JUST RAN earn a follow-up here;// an `@other-agent` comment is left to that agent's own creation-time// trigger, so a completion never re-wakes an unrelated agent.@@ -4192,17 +4184,12 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.AgExcludeTriggerCommentID: c.ID,OriginatorUserID: originatorUserID,})- // For an AGENT author, compensate ONLY explicit @agent/@squad mentions.- // computeCommentAgentTriggers can also return the assigned-squad-leader- // fallback (Source = issue-assignee) for a plain worker-agent reply on a- // squad-assigned issue; that conversational routing is intentionally NOT- // replayed here. Restricting to the explicit-mention sources keeps the- // invariant unconditional — a plain agent reply / acknowledgement earns- // no follow-up regardless of issue assignment — which is the anti-loop- // boundary the old member-only filter protected (MUL-4304). Member- // comments are unaffected: they keep their full routing.+ // Agent replies discovered only by timestamp must not start a new+ // conversation. Replay explicit mentions, or a worker reply that the+ // creation path already accepted and recorded in this run's input plan.+ // Recomputed routing still checks current permissions and the self guard.if actorType != "member" {- triggers = keepExplicitMentionTriggers(triggers)+ triggers = keepReplayableAgentTriggers(triggers, slices.Contains(plannedCommentIDs, c.ID))}scoped := make([]commentAgentTrigger, 0, 1)for _, trigger := range triggers {@@ -4249,15 +4236,11 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag}}-// keepExplicitMentionTriggers filters a computed trigger set down to the ones-// produced by an EXPLICIT @agent / @squad mention (MUL-4304). It is applied to-// agent-authored comments during completion reconcile so that only a-// deliberately-targeted mention earns a replay — the assigned-squad-leader-// fallback, thread-parent / conversation continuation, and issue-assignee-// routing (all non-mention sources) are intentionally excluded, so a plain-// agent reply or acknowledgement never earns a follow-up here. Member comments-// are never passed through this filter; they keep their full routing.-func keepExplicitMentionTriggers(triggers []commentAgentTrigger) []commentAgentTrigger {+// keepReplayableAgentTriggers preserves explicit mentions (MUL-4304) and+// accepted worker replies recorded in the completing run's plan. A timestamp+// alone never authorizes replay of an implicit agent route. Member comments+// retain their full routing and do not pass through this filter.+func keepReplayableAgentTriggers(triggers []commentAgentTrigger, planned bool) []commentAgentTrigger {if len(triggers) == 0 {return triggers}@@ -4266,6 +4249,10 @@ func keepExplicitMentionTriggers(triggers []commentAgentTrigger) []commentAgentTswitch trigger.Source {case commentTriggerSourceMentionAgent, commentTriggerSourceMentionSquadLeader:filtered = append(filtered, trigger)+ case commentTriggerSourceIssueAssignee:+ if planned && trigger.NonLeaderAgentReply {+ filtered = append(filtered, trigger)+ }}}return filtereddiff --git a/server/internal/service/builtin_skills/multica-platform/references/squads.md b/server/internal/service/builtin_skills/multica-platform/references/squads.mdindex dacf887663..81bec830d7 100644--- a/server/internal/service/builtin_skills/multica-platform/references/squads.md+++ b/server/internal/service/builtin_skills/multica-platform/references/squads.md@@ -195,6 +195,11 @@ it.If an issue is assigned to a squad, a new comment can wake the squad leader. Thisis leader routing, not member fan-out.+A worker's reply also wakes the assigned leader without an explicit mention. If+the leader's current run started before the reply arrived, the reply is+delivered in a follow-up run after that run completes, so the worker does not+need to mention the leader again.+Squad mention format:```mddiff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 373339272d..36e7f998f3 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -7934,6 +7934,7 @@ WHERE id = (ORDER BY t.created_at DESCLIMIT 1)+AND status IN ('dispatched', 'running', 'waiting_local_directory')RETURNING id, coalesced_comment_ids`@@ -7972,6 +7973,9 @@ type RegisterPlannedCommentForActiveTaskRow struct {// could execute under the first member's identity/connected-apps (MUL-4302).// Only claim-receipt statuses (already-built delivered set) are safe planned-id// targets.+// Recheck status on the UPDATE target after a concurrent row-lock wait. The+// subquery can see an active snapshot while completion commits; appending to+// that completed row would be too late for its completion replay to see it.func (q *Queries) RegisterPlannedCommentForActiveTask(ctx context.Context, arg RegisterPlannedCommentForActiveTaskParams) (RegisterPlannedCommentForActiveTaskRow, error) {row := q.db.QueryRow(ctx, registerPlannedCommentForActiveTask,arg.CommentID,diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.goindex f4b3c3a411..83850f69a4 100644--- a/server/pkg/db/generated/comment.sql.go+++ b/server/pkg/db/generated/comment.sql.go@@ -1334,17 +1334,11 @@ type ListReconcilableCommentsForIssueSinceParams struct {// compensated here, because agent-authored comments were excluded. We now also// return 'agent' comments so those explicit mentions can be replayed.//-// This does NOT reopen the anti-loop guarantees the member-only filter was-// protecting. The reconcile pass runs each returned comment through-// computeCommentAgentTriggers under its OWN author_type, and for an agent author-// it then keeps ONLY explicit @agent/@squad mention triggers-// (keepExplicitMentionTriggers) — the assigned-squad-leader fallback and all-// other conversational routing are dropped, so a plain agent reply /-// acknowledgement yields nothing regardless of issue assignment. The reconcile-// pass further keeps only triggers routing to the agent that just completed, so-// an agent comment can never fan out to an unrelated agent. Ordered ASC so-// replaying in order lets later comments coalesce onto the follow-up created by-// the first.+// The handler rechecks current routing and permissions. For agent authors it+// accepts explicit mentions, plus worker-to-assigned-leader replies already+// recorded in this run's planned inputs. Timestamp-only implicit agent replies+// remain excluded. Replays are scoped to the completing agent, never a fan-out.+// Ordered ASC so later comments coalesce onto the follow-up created by the first.func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, arg ListReconcilableCommentsForIssueSinceParams) ([]Comment, error) {rows, err := q.db.Query(ctx, listReconcilableCommentsForIssueSince,arg.IssueID,diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 10f8966011..9a52a9e39c 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -1921,6 +1921,9 @@ RETURNING id, coalesced_comment_ids;-- could execute under the first member's identity/connected-apps (MUL-4302).-- Only claim-receipt statuses (already-built delivered set) are safe planned-id-- targets.+-- Recheck status on the UPDATE target after a concurrent row-lock wait. The+-- subquery can see an active snapshot while completion commits; appending to+-- that completed row would be too late for its completion replay to see it.UPDATE agent_task_queueSET coalesced_comment_ids = (SELECT COALESCE(array_agg(DISTINCT e), '{}')@@ -1940,6 +1943,7 @@ WHERE id = (ORDER BY t.created_at DESCLIMIT 1)+AND status IN ('dispatched', 'running', 'waiting_local_directory')RETURNING id, coalesced_comment_ids;-- name: MergeDelegatedFailureCommentIntoPendingTask :onediff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sqlindex 45d56560b1..e0749ccdac 100644--- a/server/pkg/db/queries/comment.sql+++ b/server/pkg/db/queries/comment.sql@@ -368,17 +368,11 @@ LIMIT 1;-- compensated here, because agent-authored comments were excluded. We now also-- return 'agent' comments so those explicit mentions can be replayed.----- This does NOT reopen the anti-loop guarantees the member-only filter was--- protecting. The reconcile pass runs each returned comment through--- computeCommentAgentTriggers under its OWN author_type, and for an agent author--- it then keeps ONLY explicit @agent/@squad mention triggers--- (keepExplicitMentionTriggers) — the assigned-squad-leader fallback and all--- other conversational routing are dropped, so a plain agent reply /--- acknowledgement yields nothing regardless of issue assignment. The reconcile--- pass further keeps only triggers routing to the agent that just completed, so--- an agent comment can never fan out to an unrelated agent. Ordered ASC so--- replaying in order lets later comments coalesce onto the follow-up created by--- the first.+-- The handler rechecks current routing and permissions. For agent authors it+-- accepts explicit mentions, plus worker-to-assigned-leader replies already+-- recorded in this run's planned inputs. Timestamp-only implicit agent replies+-- remain excluded. Replays are scoped to the completing agent, never a fan-out.+-- Ordered ASC so later comments coalesce onto the follow-up created by the first.SELECT * FROM commentWHERE issue_id = @issue_idAND (id = ANY(@planned_comment_ids::uuid[])