Skip to content

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

Go

fix(comment): restore autopilot @mention delegation authority (MUL-4857) (#5512)

Bohan Jiang69744241e860
diff --git a/server/internal/handler/agent_access.go b/server/internal/handler/agent_access.go
index 53968c122e..fd1706834e 100644
--- a/server/internal/handler/agent_access.go
+++ b/server/internal/handler/agent_access.go
@@ -199,6 +199,139 @@ func (h *Handler) invokeOriginatorFromRequest(r *http.Request, actorType, actorI
return ""
}
+// autopilotDelegationAuthority resolves the effective invoking human for the A2A
+// invoke gate (canInvokeAgent) when a trigger comment is authored by an
+// UNATTRIBUTED autopilot dispatch delegating mid-chain on the very issue that
+// autopilot created (MUL-4857).
+//
+// A schedule/webhook autopilot run carries no top-of-chain human originator by
+// design (MUL-4302). Without one, canInvokeAgent fails closed for the DEFAULT
+// private agent (and member-scoped public_to agents), so a mid-run @mention
+// delegation silently enqueues nothing — even though the SAME autopilot's first
+// dispatch was admitted via the autopilot creator (autopilotAdmitInvoke ->
+// canCreatorInvokeAgent). This restores exactly that first-dispatch authority for
+// the mid-run delegation path: the gate still runs, now keyed on the autopilot
+// creator, so NO unrestricted agent-to-agent bypass is reopened.
+//
+// SECURITY (confused-deputy defense, review MUL-4857): the creator's authority is
+// granted ONLY when the SPEAKING run is verified to be doing work on THIS very
+// autopilot-created issue. Binding to issue provenance + an empty originator alone
+// is NOT enough — an agent running a task on some OTHER issue can legitimately
+// comment here (comment.go CreateComment only stamps source_task_id when the
+// authoring task's issue matches), so it could otherwise borrow a stranger
+// autopilot creator's invoke rights just by mentioning on that autopilot's issue.
+// `task` MUST therefore come from a server-trusted source — the X-Task-ID header
+// on create/preview, or the stored comment.source_task_id on reconcile/edit —
+// never a client-supplied field, and authority is granted only when ALL hold:
+// - the comment author is an agent and IS the task's agent;
+// - the issue is autopilot-origin (origin_type=autopilot, origin_id set);
+// - the speaking task is running on THIS issue (task.issue_id == issue.id).
+//
+// That last check is the load-bearing one: every unattributed agent task whose
+// issue_id is this autopilot issue is part of the work this autopilot set in
+// motion (the dispatched leader task, or a descendant it @mentioned into being),
+// while a foreign run's task carries a different issue_id and is rejected. Note we
+// do NOT key on autopilot_run_id: in create_issue mode (the reported scenario) the
+// leader task is enqueued through the ordinary issue-assignment path and carries
+// no autopilot_run_id — the run links back via its own issue_id, not the task's.
+//
+// Any mismatch, missing lineage, or lookup error returns "" and the gate stays
+// fail-closed. Only a MEMBER-created autopilot yields a user id; an agent-created
+// autopilot has no human to key the gate on, and the existing agent-actor
+// workspace-target exception in canInvokeAgent already covers the one case
+// (public_to workspace) it should. The returned id is used for AUTHORIZATION only
+// — the enqueued task's originator/attribution is computed separately and stays
+// unattributed.
+func (h *Handler) autopilotDelegationAuthority(ctx context.Context, issue db.Issue, authorType, authorID string, task db.AgentTaskQueue) string {
+ if authorType != "agent" {
+ return ""
+ }
+ if !issue.OriginType.Valid || issue.OriginType.String != "autopilot" || !issue.OriginID.Valid {
+ return ""
+ }
+ // The speaking run must be authored by THIS agent and doing work on THIS
+ // autopilot issue — not a foreign run that merely commented here.
+ if !task.AgentID.Valid || uuidToString(task.AgentID) != authorID {
+ return ""
+ }
+ if !task.IssueID.Valid || uuidToString(task.IssueID) != uuidToString(issue.ID) {
+ return ""
+ }
+ ap, err := h.Queries.GetAutopilotInWorkspace(ctx, db.GetAutopilotInWorkspaceParams{
+ ID: issue.OriginID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil || ap.CreatedByType != "member" || !ap.CreatedByID.Valid {
+ return ""
+ }
+ return uuidToString(ap.CreatedByID)
+}
+
+// autopilotDelegationAuthorityFromRequest resolves the MUL-4857 delegation
+// authority for a comment being created or previewed over HTTP. The speaking task
+// is taken from the server-trusted X-Task-ID header (the CLI stamps it on every
+// agent request); autopilotDelegationAuthority then verifies its lineage. Returns
+// "" for member actors or when no valid task is named, keeping the gate closed.
+func (h *Handler) autopilotDelegationAuthorityFromRequest(r *http.Request, issue db.Issue, actorType, actorID string) string {
+ if actorType != "agent" {
+ return ""
+ }
+ task, ok := h.taskFromRequestHeader(r)
+ if !ok {
+ return ""
+ }
+ return h.autopilotDelegationAuthority(r.Context(), issue, actorType, actorID, task)
+}
+
+// autopilotDelegationAuthorityFromComment resolves the MUL-4857 delegation
+// authority when reconciling an already-persisted comment (retrigger after
+// cancel). The speaking task is taken from the stored comment.source_task_id — the
+// same server-trusted lineage CreateComment stamped for the authoring run — and
+// its lineage is verified by autopilotDelegationAuthority.
+func (h *Handler) autopilotDelegationAuthorityFromComment(ctx context.Context, issue db.Issue, comment db.Comment) string {
+ if comment.AuthorType != "agent" || !comment.SourceTaskID.Valid {
+ return ""
+ }
+ task, err := h.Queries.GetAgentTask(ctx, comment.SourceTaskID)
+ if err != nil {
+ return ""
+ }
+ return h.autopilotDelegationAuthority(ctx, issue, comment.AuthorType, uuidToString(comment.AuthorID), task)
+}
+
+// commentSourceTaskIDForIssue returns the agent's currently-executing task (from
+// the X-Task-ID header) when it is running on the given issue, else an invalid
+// UUID. This is the exact issue-scoped lineage CreateComment stamps onto
+// source_task_id; a cross-issue (or missing) task yields invalid so the persisted
+// lineage — and every authority/originator resolution that reads it — fails closed
+// (MUL-4857).
+func (h *Handler) commentSourceTaskIDForIssue(r *http.Request, issue db.Issue) pgtype.UUID {
+ task, ok := h.taskFromRequestHeader(r)
+ if !ok || !task.IssueID.Valid || uuidToString(task.IssueID) != uuidToString(issue.ID) {
+ return pgtype.UUID{}
+ }
+ return task.ID
+}
+
+// taskFromRequestHeader resolves the agent's currently-executing task from the
+// X-Task-ID header (set by the CLI on every request). Returns ok=false when the
+// header is absent, malformed, or names no existing task.
+func (h *Handler) taskFromRequestHeader(r *http.Request) (db.AgentTaskQueue, bool) {
+ taskIDHeader := r.Header.Get("X-Task-ID")
+ if taskIDHeader == "" {
+ return db.AgentTaskQueue{}, false
+ }
+ taskUUID, err := util.ParseUUID(taskIDHeader)
+ if err != nil {
+ return db.AgentTaskQueue{}, false
+ }
+ task, err := h.Queries.GetAgentTask(r.Context(), taskUUID)
+ if err != nil {
+ return db.AgentTaskQueue{}, false
+ }
+ return task, true
+}
+
// accessibleAgentIDs returns the set of agent IDs in the workspace the actor
// is allowed to see, for use by workspace-wide aggregation endpoints
// (run counts, activity histograms, task snapshots) that need to filter out
diff --git a/server/internal/handler/autopilot_mention_authority_test.go b/server/internal/handler/autopilot_mention_authority_test.go
new file mode 100644
index 0000000000..aa124bf403
--- /dev/null
+++ b/server/internal/handler/autopilot_mention_authority_test.go
@@ -0,0 +1,691 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// autopilotDelegationFixture builds the MUL-4857 create_issue scenario: a
+// member-created autopilot creates an issue, and its dispatched leader agent runs
+// a task ON that issue and authors an @mention delegation comment whose
+// source_task_id points back at that leader task. The authoring run is
+// UNATTRIBUTED (originator NULL) exactly as a schedule/webhook autopilot run is.
+//
+// This is the shape the authority fallback must recognise — but ONLY through the
+// verified lineage of the speaking task (author == task agent, task.issue_id ==
+// this issue), never from the issue's autopilot provenance alone. The fields are
+// exposed so negative cases can rewrite the comment's source_task_id to a foreign
+// task and prove the fallback then fails closed.
+type autopilotDelegationFixture struct {
+ Issue db.Issue
+ LeaderAgentID string // the autopilot-dispatched agent authoring the comment
+ LeaderTaskID string // its running task on this issue (comment.source_task_id)
+ Comment db.Comment
+ AutopilotID string
+ RuntimeID string
+}
+
+func newAutopilotDelegationFixture(t *testing.T, targetAgentID, autopilotCreatorUserID, originType string) autopilotDelegationFixture {
+ t.Helper()
+ ctx := context.Background()
+
+ runtimeID := handlerTestRuntimeID(t)
+
+ // The seeded workspace agent stands in for the autopilot-dispatched leader
+ // that authors the delegation comment (distinct from the mentioned target).
+ var leaderID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id FROM agent WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1
+ `, testWorkspaceID).Scan(&leaderID); err != nil {
+ t.Fatalf("load seeded agent: %v", err)
+ }
+
+ // A member-created autopilot; assignee is the target agent (any valid agent
+ // satisfies the assignee reference).
+ var autopilotID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO autopilot (workspace_id, title, assignee_id, execution_mode, created_by_type, created_by_id)
+ VALUES ($1, 'MUL-4857 delegation', $2, 'create_issue', 'member', $3) RETURNING id
+ `, testWorkspaceID, targetAgentID, autopilotCreatorUserID).Scan(&autopilotID); err != nil {
+ t.Fatalf("create autopilot: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
+
+ // Next per-workspace issue number (default 0 would trip uq_issue_workspace_number).
+ var number int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(issue_counter, (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)) + 1
+ WHERE id = $1 RETURNING issue_counter
+ `, testWorkspaceID).Scan(&number); err != nil {
+ t.Fatalf("next issue number: %v", err)
+ }
+
+ // The issue mirrors an autopilot-created issue (creator is the dispatched
+ // leader agent; provenance is origin_type=autopilot + origin_id). When
+ // originType is not "autopilot" the issue carries no origin, so no creator
+ // can be recovered even from a perfectly-lineaged task.
+ var originTypeArg, originIDArg any
+ if originType == "autopilot" {
+ originTypeArg = "autopilot"
+ originIDArg = autopilotID
+ }
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, creator_type, creator_id, title, assignee_type, assignee_id, number, origin_type, origin_id)
+ VALUES ($1, 'agent', $2, 'MUL-4857 delegation issue', 'agent', $2, $3, $4, $5)
+ RETURNING id
+ `, testWorkspaceID, leaderID, number, originTypeArg, originIDArg).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ // The leader's dispatch task, running ON this issue. In create_issue mode the
+ // leader task is enqueued through the ordinary issue-assignment path, so it
+ // carries NO autopilot_run_id — the lineage that matters is agent + issue.
+ // Unattributed (originator NULL) like a schedule/webhook autopilot run.
+ var leaderTaskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)
+ VALUES ($1, $2, $3, 'running', 0) RETURNING id
+ `, leaderID, runtimeID, issueID).Scan(&leaderTaskID); err != nil {
+ t.Fatalf("create leader task: %v", err)
+ }
+
+ // The delegation comment: authored by the leader agent, mentioning the target,
+ // with source_task_id pointing back at the leader's running task (the lineage
+ // the reconcile/edit path reads).
+ var commentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, source_task_id)
+ VALUES ($1, $2, 'agent', $3, $4, $5) RETURNING id
+ `, testWorkspaceID, issueID, leaderID, "[@Worker](mention://agent/"+targetAgentID+") please take this", leaderTaskID).Scan(&commentID); err != nil {
+ t.Fatalf("create comment: %v", err)
+ }
+
+ issue, err := testHandler.Queries.GetIssue(ctx, util.MustParseUUID(issueID))
+ if err != nil {
+ t.Fatalf("load issue: %v", err)
+ }
+ comment, err := testHandler.Queries.GetComment(ctx, util.MustParseUUID(commentID))
+ if err != nil {
+ t.Fatalf("load comment: %v", err)
+ }
+ return autopilotDelegationFixture{
+ Issue: issue,
+ LeaderAgentID: leaderID,
+ LeaderTaskID: leaderTaskID,
+ Comment: comment,
+ AutopilotID: autopilotID,
+ RuntimeID: runtimeID,
+ }
+}
+
+// setCommentSourceTask rewrites the fixture comment's source_task_id and reloads
+// the row, so a test can point the lineage at a foreign task (or clear it).
+func setCommentSourceTask(t *testing.T, fx *autopilotDelegationFixture, sourceTaskID any) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE comment SET source_task_id = $1 WHERE id = $2`, sourceTaskID, uuidToString(fx.Comment.ID)); err != nil {
+ t.Fatalf("rewrite comment source_task_id: %v", err)
+ }
+ c, err := testHandler.Queries.GetComment(context.Background(), fx.Comment.ID)
+ if err != nil {
+ t.Fatalf("reload comment: %v", err)
+ }
+ fx.Comment = c
+}
+
+// seedTaskOnIssue inserts a running task for the given agent on the given issue
+// and returns its id, for building foreign-lineage negative cases.
+func seedTaskOnIssue(t *testing.T, agentID, issueID, runtimeID string) string {
+ t.Helper()
+ var taskID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)
+ VALUES ($1, $2, $3, 'running', 0) RETURNING id
+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {
+ t.Fatalf("seed task on issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+ return taskID
+}
+
+// TestAutopilotDelegationAuthority_LineageBinding is the MUL-4857 fix, guarded by
+// the review's confused-deputy finding: an unattributed autopilot run may borrow
+// its autopilot creator's invoke rights to delegate mid-chain, but ONLY when the
+// speaking task's lineage is verified against THIS issue — never from the issue's
+// autopilot provenance plus an empty originator alone.
+func TestAutopilotDelegationAuthority_LineageBinding(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ // agentID: private (default) agent owned by ownerID. plainMemberID: unrelated.
+ agentID, ownerID, plainMemberID := privateAgentTestFixture(t)
+
+ // authorityFor resolves the delegation authority the reconcile/edit path uses,
+ // straight from the persisted comment's source_task_id lineage.
+ authorityFor := func(fx autopilotDelegationFixture) string {
+ return testHandler.autopilotDelegationAuthorityFromComment(ctx, fx.Issue, fx.Comment)
+ }
+ // mentionTriggersTarget wires that resolved authority into the trigger compute
+ // exactly as the live paths do, and reports whether the private target fires.
+ mentionTriggersTarget := func(fx autopilotDelegationFixture) bool {
+ triggers, _ := testHandler.computeCommentAgentTriggers(
+ ctx, fx.Issue, fx.Comment.Content, nil, "agent", fx.LeaderAgentID,
+ commentTriggerComputeOptions{
+ ExcludeTriggerCommentID: fx.Comment.ID,
+ AutopilotDelegationAuthorityUserID: authorityFor(fx),
+ },
+ )
+ for _, tr := range triggers {
+ if uuidToString(tr.Agent.ID) == agentID {
+ return true
+ }
+ }
+ return false
+ }
+
+ t.Run("verified lineage + creator owns target -> triggers", func(t *testing.T) {
+ fx := newAutopilotDelegationFixture(t, agentID, ownerID, "autopilot")
+ if got := authorityFor(fx); got != ownerID {
+ t.Fatalf("delegation authority = %q, want autopilot creator %q", got, ownerID)
+ }
+ if !mentionTriggersTarget(fx) {
+ t.Fatal("expected the private agent to be triggered via the lineage-verified autopilot-creator authority")
+ }
+ })
+
+ t.Run("creator cannot invoke target -> still denied", func(t *testing.T) {
+ // Lineage is perfect but the creator (plainMemberID) is neither the target's
+ // owner nor on any allow-list: the authority resolves but the gate denies.
+ fx := newAutopilotDelegationFixture(t, agentID, plainMemberID, "autopilot")
+ if got := authorityFor(fx); got != plainMemberID {
+ t.Fatalf("delegation authority = %q, want %q", got, plainMemberID)
+ }
+ if mentionTriggersTarget(fx) {
+ t.Fatal("autopilot creator without invoke rights must not reach a private agent")
+ }
+ })
+
+ t.Run("non-autopilot issue -> no authority", func(t *testing.T) {
+ fx := newAutopilotDelegationFixture(t, agentID, ownerID, "")
+ if got := authorityFor(fx); got != "" {
+ t.Fatalf("non-autopilot issue must resolve no authority, got %q", got)
+ }
+ if mentionTriggersTarget(fx) {
+ t.Fatal("a non-autopilot unattributed run must not invoke a private agent")
+ }
+ })
+
+ t.Run("missing source task -> no authority", func(t *testing.T) {
+ // The previous fix's blind spot: an unattributed comment with no verifiable
+ // lineage (source_task_id NULL) must NOT inherit the creator's authority.
+ fx := newAutopilotDelegationFixture(t, agentID, ownerID, "autopilot")
+ setCommentSourceTask(t, &fx, nil)
+ if got := authorityFor(fx); got != "" {
+ t.Fatalf("comment without source_task_id must resolve no authority, got %q", got)
+ }
+ if mentionTriggersTarget(fx) {
+ t.Fatal("a comment with no verifiable task lineage must not borrow creator authority")
+ }
+ })
+
+ t.Run("source task on a different issue -> no authority", func(t *testing.T) {
+ // Confused-deputy: a run working on ANOTHER issue comments here. Its task's
+ // issue_id != this issue, so it cannot borrow this autopilot's authority even
+ // though its agent authored the comment.
+ fx := newAutopilotDelegationFixture(t, agentID, ownerID, "autopilot")
+ other := newAutopilotDelegationFixture(t, agentID, ownerID, "autopilot")
+ foreignTask := seedTaskOnIssue(t, fx.LeaderAgentID, uuidToString(other.Issue.ID), fx.RuntimeID)
+ setCommentSourceTask(t, &fx, foreignTask)
+ if got := authorityFor(fx); got != "" {
+ t.Fatalf("cross-issue source task must resolve no authority, got %q", got)
+ }
+ if mentionTriggersTarget(fx) {
+ t.Fatal("a task from a different issue must not borrow this autopilot's creator authority")
+ }
+ })
+
+ t.Run("author is not the source task's agent -> no authority", func(t *testing.T) {
+ // The comment author is the leader, but its source task belongs to a
+ // different agent (the target). Author/agent mismatch fails closed.
+ fx := newAutopilotDelegationFixture(t, agentID, ownerID, "autopilot")
+ mismatchTask := seedTaskOnIssue(t, agentID, uuidToString(fx.Issue.ID), fx.RuntimeID)
+ setCommentSourceTask(t, &fx, mismatchTask)
+ if got := authorityFor(fx); got != "" {
+ t.Fatalf("author != task agent must resolve no authority, got %q", got)
+ }
+ if mentionTriggersTarget(fx) {
+ t.Fatal("a source task owned by a different agent must not confer authority on the comment author")
+ }
+ })
+}
+
+// TestCreateComment_AutopilotLeaderMentionEnqueuesPrivateWorker is the MUL-4857
+// end-to-end: the autopilot-dispatched leader posts an @mention delegation on the
+// autopilot-created issue through the real HTTP CreateComment surface (X-Agent-ID
+// + X-Task-ID), and the mentioned DEFAULT-private worker is actually enqueued —
+// keyed on the autopilot creator's invoke rights, resolved from the request's
+// trusted X-Task-ID lineage. This exercises handler -> comment persistence ->
+// trigger -> enqueue, not just the compute function.
+func TestCreateComment_AutopilotLeaderMentionEnqueuesPrivateWorker(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ // Private worker owned by ownerID; the autopilot is created by that same owner
+ // so the creator legitimately owns the worker.
+ workerID, ownerID, _ := privateAgentTestFixture(t)
+ fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")
+ issueID := uuidToString(fx.Issue.ID)
+
+ // The leader posts the mention comment in its agent identity. resolveActor
+ // trusts the header pair because fx.LeaderTaskID belongs to the leader agent.
+ w := httptest.NewRecorder()
+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{
+ "content": "[@Worker](mention://agent/" + workerID + ") please handle",
+ })
+ r.Header.Set("X-Agent-ID", fx.LeaderAgentID)
+ r.Header.Set("X-Task-ID", fx.LeaderTaskID)
+ r = withURLParam(r, "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("leader mention CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var workerTasks int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, workerID).Scan(&workerTasks); err != nil {
+ t.Fatalf("count worker tasks: %v", err)
+ }
+ if workerTasks != 1 {
+ t.Fatalf("expected the private worker to be enqueued once via autopilot-creator authority, got %d queued tasks", workerTasks)
+ }
+
+ // The enqueued run must stay UNATTRIBUTED: the creator authority is used for
+ // the gate only, never written onto the delegated task's originator (MUL-4302).
+ var workerOriginatorValid bool
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT originator_user_id IS NOT NULL FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, workerID).Scan(&workerOriginatorValid); err != nil {
+ t.Fatalf("read worker originator: %v", err)
+ }
+ if workerOriginatorValid {
+ t.Fatal("the delegated worker task must remain unattributed; the creator authority is authorization-only")
+ }
+}
+
+// nextWorkspaceIssueNumber advances and returns the test workspace's issue
+// counter so a directly-inserted issue does not collide on uq_issue_workspace_number.
+func nextWorkspaceIssueNumber(t *testing.T) int {
+ t.Helper()
+ var number int
+ if err := testPool.QueryRow(context.Background(), `
+ UPDATE workspace
+ SET issue_counter = GREATEST(issue_counter, (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)) + 1
+ WHERE id = $1 RETURNING issue_counter
+ `, testWorkspaceID).Scan(&number); err != nil {
+ t.Fatalf("next issue number: %v", err)
+ }
+ return number
+}
+
+// seedBareIssue inserts a plain (non-autopilot) issue authored by the given agent
+// and returns its id, for building a cross-issue editing context.
+func seedBareIssue(t *testing.T, creatorAgentID string) string {
+ t.Helper()
+ var issueID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO issue (workspace_id, creator_type, creator_id, title, number)
+ VALUES ($1, 'agent', $2, 'MUL-4857 unrelated issue', $3) RETURNING id
+ `, testWorkspaceID, creatorAgentID, nextWorkspaceIssueNumber(t)).Scan(&issueID); err != nil {
+ t.Fatalf("seed bare issue: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+ return issueID
+}
+
+// seedCompletedTaskOnIssueBefore inserts a completed task for the agent on the
+// issue with a created_at safely before any comment made during the test, so the
+// completion-reconcile pass (ListReconcilableCommentsForIssueSince) picks those
+// comments up.
+func seedCompletedTaskOnIssueBefore(t *testing.T, agentID, issueID, runtimeID string) string {
+ t.Helper()
+ var taskID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, created_at)
+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 hour') RETURNING id
+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {
+ t.Fatalf("seed completed task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+ return taskID
+}
+
+// seedLeaderPlainComment inserts a plain (no-mention) agent comment stamped with
+// the given source_task_id, so a test can later edit it to add a mention.
+func seedLeaderPlainComment(t *testing.T, issueID, leaderID, sourceTaskID string) string {
+ t.Helper()
+ var commentID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, source_task_id)
+ VALUES ($1, $2, 'agent', $3, 'starting on this', $4) RETURNING id
+ `, testWorkspaceID, issueID, leaderID, sourceTaskID).Scan(&commentID); err != nil {
+ t.Fatalf("seed plain comment: %v", err)
+ }
+ return commentID
+}
+
+// TestReconcileCommentsOnCompletion_AutopilotDelegationRestoresAuthority is the
+// MUL-4857 must-fix #1 (review round 2): when the mentioned target was BUSY at
+// delegation time, the delegation is deferred to the target's completion
+// reconcile. That replay must restore the SAME autopilot-creator authority from
+// the comment's source_task_id — otherwise the unattributed autopilot chain's
+// follow-up is gate-denied again and the delegation is silently lost.
+func TestReconcileCommentsOnCompletion_AutopilotDelegationRestoresAuthority(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ workerID, ownerID, plainMemberID := privateAgentTestFixture(t)
+
+ // followUps drives the reconcile: an autopilot delegation comment mentions the
+ // busy private worker, the worker's task then completes, and we count the
+ // follow-up tasks the completion reconcile enqueues for it.
+ followUps := func(t *testing.T, creatorUserID string) (string, int) {
+ fx := newAutopilotDelegationFixture(t, workerID, creatorUserID, "autopilot")
+ issueID := uuidToString(fx.Issue.ID)
+ workerTaskID := seedCompletedTaskOnIssueBefore(t, workerID, issueID, fx.RuntimeID)
+ workerTask, err := testHandler.Queries.GetAgentTask(ctx, util.MustParseUUID(workerTaskID))
+ if err != nil {
+ t.Fatalf("load worker task: %v", err)
+ }
+ testHandler.reconcileCommentsOnCompletion(ctx, &workerTask)
+ var queued int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, workerID).Scan(&queued); err != nil {
+ t.Fatalf("count follow-ups: %v", err)
+ }
+ return issueID, queued
+ }
+
+ t.Run("creator owns busy target -> one unattributed follow-up", func(t *testing.T) {
+ issueID, queued := followUps(t, ownerID)
+ if queued != 1 {
+ t.Fatalf("expected exactly 1 reconcile follow-up for the freed worker, got %d", queued)
+ }
+ var originatorValid bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT originator_user_id IS NOT NULL FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, workerID).Scan(&originatorValid); err != nil {
+ t.Fatalf("read follow-up originator: %v", err)
+ }
+ if originatorValid {
+ t.Fatal("the reconcile follow-up must stay unattributed; creator authority is authorization-only")
+ }
+ })
+
+ t.Run("creator without rights -> no follow-up", func(t *testing.T) {
+ if _, queued := followUps(t, plainMemberID); queued != 0 {
+ t.Fatalf("a creator without invoke rights must not spawn a reconcile follow-up, got %d", queued)
+ }
+ })
+}
+
+// TestUpdateComment_AutopilotAuthorityReStampedToEditingTask is the MUL-4857
+// must-fix #2 (review round 2): an edit is a NEW action, so it must judge (and
+// persist) authority by the CURRENT editing task, not the comment's original
+// authoring task. A same-issue edit keeps the autopilot-creator authority; a
+// cross-issue edit re-stamps source_task_id to NULL and fails closed, so it can
+// never borrow the old autopilot run's authority (preview and save now agree).
+func TestUpdateComment_AutopilotAuthorityReStampedToEditingTask(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ workerID, ownerID, _ := privateAgentTestFixture(t)
+
+ editAddingMention := func(t *testing.T, editTaskID, commentID, issueID string, fx autopilotDelegationFixture) {
+ w := httptest.NewRecorder()
+ r := newRequest(http.MethodPut, "/api/comments/"+commentID, map[string]any{
+ "content": "[@Worker](mention://agent/" + workerID + ") please take this",
+ })
+ r.Header.Set("X-Agent-ID", fx.LeaderAgentID)
+ r.Header.Set("X-Task-ID", editTaskID)
+ r = withURLParam(r, "commentId", commentID)
+ testHandler.UpdateComment(w, r)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateComment: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ }
+ countQueued := func(t *testing.T, issueID string) int {
+ var n int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, workerID).Scan(&n); err != nil {
+ t.Fatalf("count queued: %v", err)
+ }
+ return n
+ }
+
+ t.Run("same-issue edit keeps creator authority and triggers", func(t *testing.T) {
+ fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")
+ issueID := uuidToString(fx.Issue.ID)
+ commentID := seedLeaderPlainComment(t, issueID, fx.LeaderAgentID, fx.LeaderTaskID)
+ // Edit from the leader's own task on THIS autopilot issue.
+ editAddingMention(t, fx.LeaderTaskID, commentID, issueID, fx)
+ if got := countQueued(t, issueID); got != 1 {
+ t.Fatalf("same-issue edit should enqueue the private worker once, got %d", got)
+ }
+ })
+
+ t.Run("cross-issue edit re-stamps source task to NULL and fails closed", func(t *testing.T) {
+ fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")
+ issueID := uuidToString(fx.Issue.ID)
+ commentID := seedLeaderPlainComment(t, issueID, fx.LeaderAgentID, fx.LeaderTaskID)
+ // The leader now runs an UNATTRIBUTED task on an unrelated issue and edits
+ // its old autopilot comment from there.
+ otherIssueID := seedBareIssue(t, fx.LeaderAgentID)
+ crossTaskID := seedTaskOnIssue(t, fx.LeaderAgentID, otherIssueID, fx.RuntimeID)
+ editAddingMention(t, crossTaskID, commentID, issueID, fx)
+ if got := countQueued(t, issueID); got != 0 {
+ t.Fatalf("cross-issue edit must not borrow the old autopilot authority; got %d queued", got)
+ }
+ var sourceTaskValid bool
+ if err := testPool.QueryRow(ctx, `SELECT source_task_id IS NOT NULL FROM comment WHERE id = $1`, commentID).Scan(&sourceTaskValid); err != nil {
+ t.Fatalf("read comment source_task_id: %v", err)
+ }
+ if sourceTaskValid {
+ t.Fatal("a cross-issue edit must clear source_task_id so preview, save, and reconcile all fail closed")
+ }
+ })
+}
+
+// TestCreateComment_AutopilotWorkerResultWakesSquadLeader locks the review's
+// accepted behavior: effectiveInvoker() lets the autopilot-creator authority reach
+// the plain (non-@mention) assigned-squad-leader fallback too, so a worker's
+// result comment on the autopilot issue can still wake the private squad leader
+// and close the leader -> worker -> leader loop under the autopilot chain.
+func TestCreateComment_AutopilotWorkerResultWakesSquadLeader(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := handlerTestRuntimeID(t)
+
+ // Private squad leader owned by the autopilot creator; the worker is a distinct
+ // seeded agent so the leader self-trigger guard does not apply.
+ leaderID, ownerID, _ := privateAgentTestFixture(t)
+ var workerID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id FROM agent WHERE workspace_id = $1 AND id <> $2 ORDER BY created_at ASC LIMIT 1
+ `, testWorkspaceID, leaderID).Scan(&workerID); err != nil {
+ t.Fatalf("load worker agent: %v", err)
+ }
+
+ var autopilotID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO autopilot (workspace_id, title, assignee_id, execution_mode, created_by_type, created_by_id)
+ VALUES ($1, 'MUL-4857 squad', $2, 'create_issue', 'member', $3) RETURNING id
+ `, testWorkspaceID, leaderID, ownerID).Scan(&autopilotID); err != nil {
+ t.Fatalf("create autopilot: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
+
+ var squadID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)
+ VALUES ($1, 'MUL-4857 Squad', '', $2, $3) RETURNING id
+ `, testWorkspaceID, leaderID, ownerID).Scan(&squadID); err != nil {
+ t.Fatalf("create squad: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID) })
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, creator_type, creator_id, title, assignee_type, assignee_id, number, origin_type, origin_id)
+ VALUES ($1, 'agent', $2, 'MUL-4857 squad issue', 'squad', $3, $4, 'autopilot', $5) RETURNING id
+ `, testWorkspaceID, leaderID, squadID, nextWorkspaceIssueNumber(t), autopilotID).Scan(&issueID); err != nil {
+ t.Fatalf("create squad issue: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ // The worker is running an unattributed task on this autopilot issue.
+ workerTaskID := seedTaskOnIssue(t, workerID, issueID, runtimeID)
+
+ // The worker posts a PLAIN result comment (no @mention) via HTTP.
+ w := httptest.NewRecorder()
+ r := newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{
+ "content": "done — pushed the change",
+ })
+ r.Header.Set("X-Agent-ID", workerID)
+ r.Header.Set("X-Task-ID", workerTaskID)
+ r = withURLParam(r, "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("worker result CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var leaderTasks int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued' AND is_leader_task = TRUE
+ `, issueID, leaderID).Scan(&leaderTasks); err != nil {
+ t.Fatalf("count leader tasks: %v", err)
+ }
+ if leaderTasks != 1 {
+ t.Fatalf("expected the private squad leader to be woken once via autopilot-creator authority, got %d", leaderTasks)
+ }
+}
+
+// TestUpdateComment_AdminEditOfAgentCommentClearsStaleLineage is the MUL-4857
+// must-fix (review round 3): a workspace admin may EDIT another author's comment,
+// but that manage right is NOT an invoke right over the author's private agents
+// (canInvokeAgent is deny-by-default for private agents — no admin bypass). When an
+// admin edits an autopilot Agent's comment to add a private @mention while the
+// target is busy, the immediate save is blocked on the admin's own member identity,
+// AND the persisted source_task_id MUST be cleared. Otherwise the deferred
+// completion-reconcile — which routes the comment under its ORIGINAL agent author on
+// the unattributed autopilot chain — would read the stale lineage and resurrect the
+// autopilot creator's authority once the target frees up.
+func TestUpdateComment_AdminEditOfAgentCommentClearsStaleLineage(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ workerID, ownerID, _ := privateAgentTestFixture(t)
+
+ // The autopilot is created by ownerID, who owns the private worker — so the
+ // ORIGINAL agent lineage genuinely carries invoke authority. That is precisely
+ // the authority an admin edit must not be able to borrow.
+ fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")
+ issueID := uuidToString(fx.Issue.ID)
+ // Neutralise the fixture's own (valid) mention comment so the ONLY comment whose
+ // reconcile fate is under test is the admin-edited one below.
+ setCommentSourceTask(t, &fx, nil)
+
+ // A plain (no-mention) leader comment stamped with the leader's real task
+ // lineage — the comment the admin edits to inject the mention.
+ commentID := seedLeaderPlainComment(t, issueID, fx.LeaderAgentID, fx.LeaderTaskID)
+
+ // A workspace admin who is NEITHER the worker owner nor the comment author.
+ adminID := createPermissionTestAdmin(t, "[email protected]")
+
+ countQueued := func() int {
+ var n int
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, workerID).Scan(&n); err != nil {
+ t.Fatalf("count queued: %v", err)
+ }
+ return n
+ }
+
+ // The admin edits the leader's comment to add the private @Worker mention.
+ w := httptest.NewRecorder()
+ r := newRequestAs(adminID, http.MethodPut, "/api/comments/"+commentID, map[string]any{
+ "content": "[@Worker](mention://agent/" + workerID + ") please take this",
+ })
+ r = withURLParam(r, "commentId", commentID)
+ testHandler.UpdateComment(w, r)
+ if w.Code != http.StatusOK {
+ t.Fatalf("admin UpdateComment: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Immediate save is judged on the admin's member identity, which holds no invoke
+ // right over the private worker — nothing is enqueued.
+ if got := countQueued(); got != 0 {
+ t.Fatalf("admin edit must be blocked immediately (no invoke right over a private agent); got %d queued", got)
+ }
+
+ // The stale autopilot lineage MUST be cleared so the deferred reconcile fails closed.
+ var sourceTaskValid bool
+ if err := testPool.QueryRow(ctx, `SELECT source_task_id IS NOT NULL FROM comment WHERE id = $1`, commentID).Scan(&sourceTaskValid); err != nil {
+ t.Fatalf("read comment source_task_id: %v", err)
+ }
+ if sourceTaskValid {
+ t.Fatal("an admin edit of an agent comment must clear source_task_id so the deferred reconcile cannot borrow the original autopilot creator authority")
+ }
+
+ // The busy worker now completes: the completion reconcile routes the comment
+ // under its original agent author (unattributed autopilot chain). With the
+ // lineage cleared it must NOT resurrect the creator authority or enqueue a
+ // follow-up. (Without the fix this reconcile would enqueue exactly one.)
+ workerTaskID := seedCompletedTaskOnIssueBefore(t, workerID, issueID, fx.RuntimeID)
+ workerTask, err := testHandler.Queries.GetAgentTask(ctx, util.MustParseUUID(workerTaskID))
+ if err != nil {
+ t.Fatalf("load worker task: %v", err)
+ }
+ testHandler.reconcileCommentsOnCompletion(ctx, &workerTask)
+ if got := countQueued(); got != 0 {
+ t.Fatalf("completion reconcile must not borrow the stale autopilot authority after an admin edit; got %d queued", got)
+ }
+}
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 5103460b77..01c3057dd2 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -1073,6 +1073,31 @@ type commentTriggerComputeOptions struct {
// by the originator, not the immediate agent principal. Members are their
// own originator so this may be empty for member-authored triggers.
OriginatorUserID string
+
+ // AutopilotDelegationAuthorityUserID is the lineage-verified autopilot creator
+ // whose invoke rights an UNATTRIBUTED autopilot dispatch borrows for the A2A
+ // gate when it delegates mid-chain on the issue that autopilot created
+ // (MUL-4857). It is resolved SEPARATELY from OriginatorUserID, at the trusted
+ // request/comment boundary, from the server-trusted speaking task (see
+ // autopilotDelegationAuthority); it is empty whenever that lineage cannot be
+ // verified, which keeps the gate fail-closed. effectiveInvoker consults it ONLY
+ // when OriginatorUserID is empty. Authorization input only — attribution/audit
+ // read OriginatorUserID, never this, so the enqueued run stays unattributed.
+ AutopilotDelegationAuthorityUserID string
+}
+
+// effectiveInvoker is the human principal the A2A invoke gate (canInvokeAgent)
+// keys on for this comment: the resolved top-of-chain human originator, or — only
+// when the run carried no human originator — the lineage-verified autopilot
+// delegation authority (MUL-4857). OriginatorUserID is left untouched so
+// attribution stays accurate; the authority is a gate-only fallback. For member
+// actors both are the member (or the fallback is unset), and canInvokeAgent
+// ignores this value for members anyway.
+func (o commentTriggerComputeOptions) effectiveInvoker() string {
+ if o.OriginatorUserID != "" {
+ return o.OriginatorUserID
+ }
+ return o.AutopilotDelegationAuthorityUserID
}
func commentAgentTriggerReason(trigger commentAgentTrigger) string {
@@ -1178,6 +1203,7 @@ 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)
+ opts.AutopilotDelegationAuthorityUserID = h.autopilotDelegationAuthorityFromRequest(r, issue, actorType, actorID)
triggers, targets := h.computeCommentAgentTriggers(r.Context(), issue, content, parentComment, actorType, actorID, opts)
resp := CommentTriggerPreviewResponse{
Agents: make([]CommentTriggerAgentResponse, 0, len(triggers)),
@@ -1399,10 +1425,15 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
}
originatorUserID := h.invokeOriginatorFromRequest(r, authorType, authorID)
+ // MUL-4857: resolve the autopilot delegation authority from the SAME
+ // server-trusted X-Task-ID header the originator resolution uses, so an
+ // unattributed autopilot dispatch delegating mid-chain is keyed on its
+ // autopilot creator only when the speaking task's lineage checks out.
+ delegationAuthority := h.autopilotDelegationAuthorityFromRequest(r, issue, authorType, authorID)
// The comment is already saved; a blocked mention must not fail the whole
// request. Surface the per-target outcomes so the client can show partial
// success instead of a silent no-op (MUL-4525 §2).
- resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, originatorUserID, suppressAgentIDs)
+ resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, originatorUserID, delegationAuthority, suppressAgentIDs)
writeJSON(w, http.StatusCreated, resp)
}
@@ -1430,13 +1461,14 @@ func isNoteComment(content string) bool {
// (MUL-4525 §2): blocked mentions from resolution plus queued / coalesced /
// deferred / blocked from enqueue. UI-suppressed triggers (the user unchecked
// them) are removed before enqueue and produce no outcome.
-func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID, originatorUserID string, suppressAgentIDs []pgtype.UUID) []CommentTriggerOutcome {
+func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID, originatorUserID, delegationAuthorityUserID string, suppressAgentIDs []pgtype.UUID) []CommentTriggerOutcome {
if isNoteComment(comment.Content) {
return nil
}
triggers, targets := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
- ExcludeTriggerCommentID: comment.ID,
- OriginatorUserID: originatorUserID,
+ ExcludeTriggerCommentID: comment.ID,
+ OriginatorUserID: originatorUserID,
+ AutopilotDelegationAuthorityUserID: delegationAuthorityUserID,
})
triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)
enqueued := h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
@@ -1867,6 +1899,14 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu
return nil, nil
}
+ // Autopilot delegation authority (MUL-4857) is applied by the gate via
+ // opts.effectiveInvoker(): when a run carried no human originator, the gate
+ // falls back to opts.AutopilotDelegationAuthorityUserID, which the caller has
+ // already resolved from a server-trusted, lineage-verified speaking task (see
+ // autopilotDelegationAuthority). Nothing is re-derived from issue provenance
+ // here, so an unrelated unattributed run cannot borrow a stranger autopilot
+ // creator's authority by commenting on that autopilot's issue.
+
mentions := util.ParseMentions(content)
if util.HasMentionAll(mentions) {
return nil, nil
@@ -1967,7 +2007,7 @@ func (h *Handler) routeReplyToParentAuthor(ctx context.Context, issue db.Issue,
if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
return commentAgentTrigger{}, false
}
- if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, uuidToString(issue.WorkspaceID)) {
+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.effectiveInvoker(), uuidToString(issue.WorkspaceID)) {
return commentAgentTrigger{}, false
}
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, parent.AuthorID, opts)
@@ -2141,7 +2181,7 @@ func (h *Handler) routeAssignedSquadLeaderFallback(ctx context.Context, issue db
if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
return commentAgentTrigger{}, false
}
- if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, uuidToString(issue.WorkspaceID)) {
+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.effectiveInvoker(), uuidToString(issue.WorkspaceID)) {
return commentAgentTrigger{}, false
}
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, squad.LeaderID, opts)
@@ -2280,7 +2320,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
}
// Private-leader gate first (enumeration-safe: a caller who cannot
// invoke the leader never learns its archived/runtime state).
- if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, wsID) {
+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.effectiveInvoker(), wsID) {
blockTarget("squad", m.ID, ReasonInvocationNotAllowed)
continue
}
@@ -2322,7 +2362,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
continue
}
// Private-agent gate first, before any archived/runtime state is read.
- if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, wsID) {
+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.effectiveInvoker(), wsID) {
blockTarget("agent", m.ID, ReasonInvocationNotAllowed)
continue
}
@@ -2420,6 +2460,11 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
// NOTE: See CreateComment — Markdown is sanitized at render/edit time, not here.
oldContent := existing.Content
+ // Preserve the existing authority lineage by default — this path is taken only
+ // for an UNCHANGED edit (no re-trigger). When the content changes below, the
+ // lineage is re-derived from the EDIT action itself (MUL-4857), never carried
+ // over from the comment's original authoring run.
+ sourceTaskID := existing.SourceTaskID
var triggerIssue *db.Issue
var cancelled []db.AgentTaskQueue
if oldContent != req.Content {
@@ -2430,6 +2475,21 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
return
}
triggerIssue = &issue
+ // A content edit is a NEW action, so its delegation lineage must key on THIS
+ // edit. Only the AGENT author re-editing its OWN comment carries issue-scoped
+ // lineage forward (commentSourceTaskIDForIssue re-stamps the current editing
+ // task, and clears it on a cross-issue edit) — so preview, save, and the
+ // deferred completion-reconcile all resolve the authority from this one
+ // action. Any OTHER editor — a workspace owner/admin editing an AGENT's
+ // comment, or a member editing their own — CLEARS the lineage so the deferred
+ // reconcile fails closed instead of resurrecting the original autopilot run's
+ // creator authority. An admin holds manage rights over the comment, not
+ // invoke rights over the author's private agents (Elon must-fix, round 3).
+ if actorType == "agent" && isAuthor {
+ sourceTaskID = h.commentSourceTaskIDForIssue(r, issue)
+ } else {
+ sourceTaskID = pgtype.UUID{}
+ }
cancelled, err = h.TaskService.CancelTasksByTriggerComment(r.Context(), existing.ID)
if err != nil {
slog.Warn("cancel tasks for edited comment failed", "comment_id", uuidToString(existing.ID), "error", err)
@@ -2439,8 +2499,9 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
}
comment, err := h.Queries.UpdateComment(r.Context(), db.UpdateCommentParams{
- ID: commentUUID,
- Content: req.Content,
+ ID: commentUUID,
+ Content: req.Content,
+ SourceTaskID: sourceTaskID,
})
if err != nil {
slog.Warn("update comment failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
@@ -2466,7 +2527,15 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
}
h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, existing.ID)
- return h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), suppressAgentIDs)
+ // MUL-4857: source_task_id was just re-derived from THIS edit above (the agent
+ // author re-stamps its current task; every other editor clears it), so
+ // resolving from the comment keys the delegation authority on the current
+ // editing action — identical to what the edit preview computed from the same
+ // request, and to what the completion-reconcile will restore. A cross-issue
+ // or non-author edit left it NULL, so this fails closed rather than borrowing
+ // the old authoring run's authority.
+ delegationAuthority := h.autopilotDelegationAuthorityFromComment(r.Context(), issue, comment)
+ return h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), delegationAuthority, suppressAgentIDs)
}
// Replace the comment attachment set when a modern client sends
@@ -2650,12 +2719,17 @@ func (h *Handler) retriggerCancelledTaskSurvivors(ctx context.Context, issue db.
actorType := comment.AuthorType
actorID := uuidToString(comment.AuthorID)
originatorUserID := actorID
+ var delegationAuthority string
if actorType != "member" {
originatorUserID = uuidToString(h.TaskService.ResolveOriginatorFromTriggerComment(ctx, issue.WorkspaceID, comment.ID))
+ // MUL-4857: reconcile works from persisted comments, so the autopilot
+ // delegation authority is resolved from the stored comment.source_task_id.
+ delegationAuthority = h.autopilotDelegationAuthorityFromComment(ctx, issue, comment)
}
triggers, _ := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
- ExcludeTriggerCommentID: comment.ID,
- OriginatorUserID: originatorUserID,
+ ExcludeTriggerCommentID: comment.ID,
+ OriginatorUserID: originatorUserID,
+ AutopilotDelegationAuthorityUserID: delegationAuthority,
})
targets := targetsByComment[uuidToString(comment.ID)]
scoped := make([]commentAgentTrigger, 0, len(targets))
diff --git a/server/internal/handler/comment_reconcile_test.go b/server/internal/handler/comment_reconcile_test.go
index f2dfa444c6..efc89b668b 100644
--- a/server/internal/handler/comment_reconcile_test.go
+++ b/server/internal/handler/comment_reconcile_test.go
@@ -348,7 +348,7 @@ func TestCompleteTask_ReconcilesAgentAuthoredMentionToCompletedAgent(t *testing.
if err != nil {
t.Fatalf("setup: load mention comment: %v", err)
}
- testHandler.triggerTasksForComment(ctx, issue, mentionComment, nil, "agent", agentA, "", nil)
+ testHandler.triggerTasksForComment(ctx, issue, mentionComment, nil, "agent", agentA, "", "", nil)
// Drop happened: the mention found no queued task to merge into and an
// active (dispatched) task exists, so NO fresh queued follow-up was created.
@@ -583,14 +583,14 @@ func TestConsecutiveCommentsDifferentOriginatorsFullEnqueuePath(t *testing.T) {
// A's comment → creates the queued task (originator A).
cA := insertMemberComment(testUserID, "first, from A")
- testHandler.triggerTasksForComment(ctx, issue, cA, nil, "member", testUserID, testUserID, nil)
+ testHandler.triggerTasksForComment(ctx, issue, cA, nil, "member", testUserID, testUserID, "", nil)
if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {
t.Fatalf("after A's comment expected exactly 1 queued task, got %d", n)
}
// B's comment (different originator) before start → must fold in, NOT drop.
cB := insertMemberComment(userB, "second, from B — different user")
- testHandler.triggerTasksForComment(ctx, issue, cB, nil, "member", userB, userB, nil)
+ testHandler.triggerTasksForComment(ctx, issue, cB, nil, "member", userB, userB, "", nil)
// Still exactly one task (bounded concurrency, no unique-index collision).
if n := pendingTaskCountForAgentIssue(t, issueID, agentID); n != 1 {
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index dea82f6ce1..cc8772087c 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2986,12 +2986,21 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
actorType := c.AuthorType
actorID := uuidToString(c.AuthorID)
originatorUserID := actorID
+ var delegationAuthority string
if actorType != "member" {
originatorUserID = uuidToString(h.TaskService.ResolveOriginatorFromTriggerComment(ctx, issue.WorkspaceID, c.ID))
+ // MUL-4857: this is the deferred replay of an already-accepted delegation
+ // (e.g. the mentioned target was busy at create time). Restore the SAME
+ // verified authorization context from the comment's stored source_task_id,
+ // so an unattributed autopilot delegation's follow-up still fires once the
+ // busy target frees up. The source_task_id is re-stamped on edit, so this
+ // tracks the current content's authoring action, not a stale one.
+ delegationAuthority = h.autopilotDelegationAuthorityFromComment(ctx, issue, c)
}
triggers, _ := h.computeCommentAgentTriggers(ctx, issue, c.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
- ExcludeTriggerCommentID: c.ID,
- OriginatorUserID: originatorUserID,
+ ExcludeTriggerCommentID: c.ID,
+ OriginatorUserID: originatorUserID,
+ AutopilotDelegationAuthorityUserID: delegationAuthority,
})
// For an AGENT author, compensate ONLY explicit @agent/@squad mentions.
// computeCommentAgentTriggers can also return the assigned-squad-leader
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 13849c9d69..6dbf29d281 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -2894,7 +2894,7 @@ func (h *Handler) assigneeFallbackAgent(ctx context.Context, issue db.Issue, act
if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
return db.Agent{}, false, false
}
- if !h.canInvokeAgent(ctx, agent, actorType, actorID, opts.OriginatorUserID, uuidToString(issue.WorkspaceID)) {
+ if !h.canInvokeAgent(ctx, agent, actorType, actorID, opts.effectiveInvoker(), uuidToString(issue.WorkspaceID)) {
return db.Agent{}, false, false
}
// Coalescing queue: pending is still a valid route target, but callers
diff --git a/server/internal/handler/trigger_test.go b/server/internal/handler/trigger_test.go
index 61295747d5..c066606cad 100644
--- a/server/internal/handler/trigger_test.go
+++ b/server/internal/handler/trigger_test.go
@@ -113,5 +113,5 @@ func TestTriggerTasksForComment_NoteShortCircuits(t *testing.T) {
}
// Must not panic — the guard short-circuits before any DB access.
- h.triggerTasksForComment(context.Background(), issue, comment, nil, "member", memberID, memberID, nil)
+ h.triggerTasksForComment(context.Background(), issue, comment, nil, "member", memberID, memberID, "", nil)
}
diff --git a/server/internal/service/builtin_skills/multica-mentioning/SKILL.md b/server/internal/service/builtin_skills/multica-mentioning/SKILL.md
index aa28b0eab6..201f3dae52 100644
--- a/server/internal/service/builtin_skills/multica-mentioning/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-mentioning/SKILL.md
@@ -127,6 +127,30 @@ These are all silent no-ops — no error, no run:
`canEnqueueSquadLeader` wrapper is the squad assignment/promote path, not this
one; the child-done wake is ungated — see the multica-squads skill).
+One nuance for automation (MUL-4857): when an UNATTRIBUTED autopilot run (a
+schedule/webhook dispatch has no human originator, so the A2A gate has no human
+to key on) delegates by `@mention` while working on the issue that autopilot
+created, the invoke gate falls back to the **autopilot creator** as the effective
+invoking user — the same principal that admitted the first dispatch. So a mid-run
+`@agent` / `@squad` delegation fires exactly when the autopilot creator could
+invoke that target (owner / `public_to` match), and stays skipped otherwise. It
+is authorization only — the enqueued run's originator/attribution is unchanged.
+This fallback is bound to verified task lineage: it applies only when the
+delegating run's own task is the one working on that autopilot issue (author ==
+task agent, `task.issue_id` == this issue), so a run doing work elsewhere can
+never borrow another autopilot creator's authority by commenting on its issue.
+The same authority carries the plain assigned-squad-leader wake (a worker's
+result comment on the autopilot issue can still wake the leader), and it survives
+a busy target: if the mentioned agent is already running, the delegation is
+replayed at that run's completion under the same authority, so it is never lost.
+An edit is treated as a fresh action — it re-derives the comment's lineage from
+the editing action. Only the agent author editing its OWN comment re-stamps the
+lineage to the editing task; any other editor — including a workspace owner/admin
+editing an agent's comment — CLEARS it. So editing an old autopilot comment from
+an unrelated issue, or an admin editing an agent's comment (manage rights, not
+invoke rights), fails closed at the deferred completion-reconcile instead of
+reusing the original run's authority.
+
## Incorrect → Correct
Incorrect: `@alice please review`
diff --git a/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md b/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md
index d9b9b7ca2d..ef1064e8ba 100644
--- a/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md
+++ b/server/internal/service/builtin_skills/multica-mentioning/references/mentioning-source-map.md
@@ -88,6 +88,9 @@ a pointer.
| already-pending dedup (squad leader) → shared pending-task helper → `continue` | `server/internal/handler/comment.go:1429-1433` |
| `canAccessPrivateAgent` definition | `server/internal/handler/agent_access.go` (search `func (h *Handler) canAccessPrivateAgent`) |
| `canEnqueueSquadLeader` (loads leader, delegates to `canInvokeAgent`) | `server/internal/handler/agent_access.go:261-267` |
+| autopilot-delegation invoke authority: an unattributed autopilot run delegating on the issue it created falls back to the autopilot creator as the effective invoking user for the gate, bound to verified speaking-task lineage (author == task agent, `task.issue_id` == this issue) so no cross-issue borrow (MUL-4857) | gate application via `opts.effectiveInvoker()` in `server/internal/handler/comment.go` (search `func (o commentTriggerComputeOptions) effectiveInvoker`); lineage-verifying helper in `server/internal/handler/agent_access.go` (search `func (h *Handler) autopilotDelegationAuthority`); resolved from the trusted X-Task-ID / `comment.source_task_id` via `autopilotDelegationAuthorityFromRequest` / `autopilotDelegationAuthorityFromComment` |
+| autopilot-delegation authority on the DEFERRED path: a delegation to a busy target replays at the target's completion reconcile, which restores the same authority from `comment.source_task_id` (MUL-4857) | `server/internal/handler/daemon.go` (search `reconcileCommentsOnCompletion`, the `autopilotDelegationAuthorityFromComment` call) |
+| authority lineage is persisted per-action: only an agent editing its OWN comment re-stamps `source_task_id` to the current editing task (issue-scoped, like create); any other editor — including a workspace owner/admin editing an agent's comment (manage rights, not invoke rights) — CLEARS it, so a cross-issue edit or an admin edit makes every authority/originator read fail closed, including the deferred completion-reconcile — preview, save, and reconcile agree (MUL-4857) | `server/internal/handler/comment.go` (search `commentSourceTaskIDForIssue` and the `isAuthor` branch in `UpdateComment`) |
## @all broadcast and assignee-trigger suppression
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index a831d734f1..2d7f601a3c 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -1282,18 +1282,20 @@ func (q *Queries) UnresolveComment(ctx context.Context, id pgtype.UUID) (Comment
const updateComment = `-- name: UpdateComment :one
UPDATE comment SET
content = $2,
+ source_task_id = $3,
updated_at = now()
WHERE id = $1
RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id
`
type UpdateCommentParams struct {
- ID pgtype.UUID `json:"id"`
- Content string `json:"content"`
+ ID pgtype.UUID `json:"id"`
+ Content string `json:"content"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
}
func (q *Queries) UpdateComment(ctx context.Context, arg UpdateCommentParams) (Comment, error) {
- row := q.db.QueryRow(ctx, updateComment, arg.ID, arg.Content)
+ row := q.db.QueryRow(ctx, updateComment, arg.ID, arg.Content, arg.SourceTaskID)
var i Comment
err := row.Scan(
&i.ID,
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index 80a75652a7..5c045d9378 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -400,6 +400,7 @@ RETURNING *;
-- name: UpdateComment :one
UPDATE comment SET
content = $2,
+ source_task_id = sqlc.narg(source_task_id),
updated_at = now()
WHERE id = $1
RETURNING *;