Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6490 fix(server): keep the A2A originator chain across cross-issue agent comments (#7381)
Bohan Jiang3adc0061a967
diff --git a/server/internal/handler/agent_access.go b/server/internal/handler/agent_access.goindex de18f45443..76358079e4 100644--- a/server/internal/handler/agent_access.go+++ b/server/internal/handler/agent_access.go@@ -2,6 +2,7 @@ package handlerimport ("context"+ "log/slog""net/http""github.com/jackc/pgx/v5/pgtype"@@ -46,6 +47,30 @@ import (// agent/system principals, but member/team targets fail closed without a// matching human.func (h *Handler) canInvokeAgent(ctx context.Context, agent db.Agent, actorType, actorID, originatorUserID, workspaceID string) bool {+ allowed := h.invokeAgentDecision(ctx, agent, actorType, actorID, originatorUserID, workspaceID)+ if !allowed && actorType != "member" && originatorUserID == "" {+ // MUL-6490: the wire reason stays the deliberately generic+ // invocation_not_allowed (dispatch/reason.go — it must not reveal whether a+ // target exists), which leaves the one denial a workspace CAN fix looking+ // identical to a plain permission error. Name the root cause here, where+ // only operators read it: the chain reached this gate with no human at its+ // top, so member-scoped allow-lists could not match anyone. Without this+ // line the reported failure mode (a broken originator chain N hops back)+ // was only diagnosable by querying agent_task_queue directly.+ slog.WarnContext(ctx, "agent invoke denied: delegation chain carries no human originator",+ "agent_id", uuidToString(agent.ID),+ "agent_permission_mode", agent.PermissionMode,+ "actor_type", actorType,+ "actor_id", actorID,+ "workspace_id", workspaceID,+ )+ }+ return allowed+}++// invokeAgentDecision is canInvokeAgent's pure verdict, split out so the gate has+// exactly one place to observe a denial from.+func (h *Handler) invokeAgentDecision(ctx context.Context, agent db.Agent, actorType, actorID, originatorUserID, workspaceID string) bool {effectiveUser := actorIDif actorType != "member" {// agent / system: never trust the immediate principal, only the@@ -217,9 +242,12 @@ func (h *Handler) invokeOriginatorFromRequest(r *http.Request, actorType, actorI// 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.+// comment here, and since MUL-6490 that cross-issue lineage IS persisted on+// source_task_id (so the human originator chain survives the hop), so it could+// otherwise borrow a stranger autopilot creator's invoke rights just by mentioning+// on that autopilot's issue. The task.issue_id check below is what keeps that shut:+// this function is the sole owner of the same-issue requirement, which is why the+// stamp itself no longer carries it.// `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:@@ -299,15 +327,21 @@ func (h *Handler) autopilotDelegationAuthorityFromComment(ctx context.Context, ireturn 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 {+// commentSourceTaskID returns the agent's currently-executing task (from the+// server-trusted X-Task-ID header), else an invalid UUID. This is the exact+// lineage CreateComment stamps onto source_task_id, so an edit re-stamps what a+// fresh authoring of the same content would have stamped and the two resolvers+// can never disagree (MUL-6490).+//+// The task is NOT required to be running on the edited comment's issue: the+// stamp records "which run wrote this", and a run may legitimately write on+// another issue. Authority rules that additionally require same-issue work keep+// that check themselves — autopilotDelegationAuthority verifies+// task.issue_id == issue.id before granting the autopilot creator's invoke+// rights, so a cross-issue lineage still fails closed there (MUL-4857).+func (h *Handler) commentSourceTaskID(r *http.Request) pgtype.UUID {task, ok := h.taskFromRequestHeader(r)- if !ok || !task.IssueID.Valid || uuidToString(task.IssueID) != uuidToString(issue.ID) {+ if !ok {return pgtype.UUID{}}return task.IDdiff --git a/server/internal/handler/autopilot_mention_authority_test.go b/server/internal/handler/autopilot_mention_authority_test.goindex aa124bf403..a573de2fae 100644--- a/server/internal/handler/autopilot_mention_authority_test.go+++ b/server/internal/handler/autopilot_mention_authority_test.go@@ -6,6 +6,7 @@ import ("net/http/httptest""testing"+ "github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -458,8 +459,11 @@ func TestReconcileCommentsOnCompletion_AutopilotDelegationRestoresAuthority(t *t// 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).+// cross-issue edit re-stamps source_task_id to the EDITING task and still fails+// closed, so it can never borrow the old autopilot run's authority (preview and+// save now agree). Since MUL-6490 the lineage itself is always persisted — the+// same-issue requirement lives in autopilotDelegationAuthority, which is what+// rejects the cross-issue editing task here.func TestUpdateComment_AutopilotAuthorityReStampedToEditingTask(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")@@ -502,7 +506,7 @@ func TestUpdateComment_AutopilotAuthorityReStampedToEditingTask(t *testing.T) {}})- t.Run("cross-issue edit re-stamps source task to NULL and fails closed", func(t *testing.T) {+ t.Run("cross-issue edit re-stamps source task to the editing task 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)@@ -514,12 +518,16 @@ func TestUpdateComment_AutopilotAuthorityReStampedToEditingTask(t *testing.T) {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 {+ // MUL-6490: the lineage now records the EDITING run (that is what "which+ // run wrote this" means, and it is how a human originator survives a+ // cross-issue hop). The old authoring task must NOT survive the edit —+ // that is the value the autopilot authority would have accepted.+ var sourceTaskID pgtype.UUID+ if err := testPool.QueryRow(ctx, `SELECT source_task_id FROM comment WHERE id = $1`, commentID).Scan(&sourceTaskID); 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")+ if uuidToString(sourceTaskID) != crossTaskID {+ t.Fatalf("source_task_id = %q, want the editing task %q", uuidToString(sourceTaskID), crossTaskID)}})}diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex e185fe108b..607665a0fb 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1783,69 +1783,84 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {// Determine author identity: agent (via X-Agent-ID header) or member.authorType, authorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))- // Defense against resumed-session drift: when an agent posts from inside a- // comment-triggered task AND the comment is being posted on that same- // issue, the parent_id must exactly match the task's trigger comment.- // Resumed Claude sessions otherwise carry forward a previous turn's- // --parent UUID and silently misplace the reply.- //- // The task.IssueID scope is important: the CLI stamps X-Task-ID on every- // request, so an agent legitimately commenting on a different issue must- // not be blocked by its current task's trigger. Assignment-triggered- // tasks (no TriggerCommentID) are also unaffected.// sourceTaskID captures the agent's currently-executing task when it posts// via the CLI (X-Task-ID header). Stamping it on the comment row keeps the// originator inheritance chain (resolveOriginatorFromTriggerComment →// comment.source_task_id → parent task's originator_user_id) intact across- // the leader→worker mention hop. Without this stamp, a private squad- // leader's worker-agent whose completion wakes the leader via- // routeAssignedSquadLeaderFallback can't pass canInvokeAgent — the- // worker's task originator is unattributed, effectiveUser resolves to "",- // and the private-agent gate denies the wake (MUL-4015).+ // an agent→agent hop. Without this stamp, a private squad leader's+ // worker-agent whose completion wakes the leader via+ // routeAssignedSquadLeaderFallback can't pass canInvokeAgent — the worker's+ // task originator is unattributed, effectiveUser resolves to "", and the+ // private-agent gate denies the wake (MUL-4015).+ //+ // The header is NOT client-chosen: the task token forces X-Task-ID and+ // X-Agent-ID from its own row, and resolveActor rejects the JWT path unless+ // the named task belongs to the named agent. So the stamp always records the+ // authoring agent's own run.+ //+ // It is deliberately NOT scoped to that run's own issue (MUL-6490 / GH+ // #7328). A run that legitimately comments on ANOTHER issue — the ordinary+ // "agent creates issue Y, then coordinates there" flow — used to persist a+ // NULL lineage, so the run that comment woke resolved as unattributed and+ // every @mention / assign / sub-issue inside it hit invocation_not_allowed,+ // even though the SAME delegation had just succeeded on the originating+ // issue. Propagating the chain is monotonic: it can only carry the human+ // this run ALREADY acts for, and every hop still re-runs canInvokeAgent+ // against that same human, so the admissible set stays a subset of what that+ // human could trigger directly. What must never happen is SUBSTITUTING a+ // human — an owner fallback, or adopting the target issue's own originator —+ // because that borrows a different person's authority; those stay rejected.+ //+ // Consumers that genuinely need "the authoring run is working on THIS issue"+ // keep that check next to their own rule instead: the reply-parent /+ // no_action guards below, and autopilotDelegationAuthority's lineage+ // verification (MUL-4857).var sourceTaskID pgtype.UUIDif authorType == "agent" {- if taskIDHeader := r.Header.Get("X-Task-ID"); taskIDHeader != "" {- taskUUID, parseErr := util.ParseUUID(taskIDHeader)- if parseErr == nil {- task, err := h.Queries.GetAgentTask(r.Context(), taskUUID)- if err == nil && task.IssueID.Valid && uuidToString(task.IssueID) == uuidToString(issue.ID) {- if task.TriggerCommentID.Valid {- if !taskCoversReplyParent(task, parentID) {- // Keep this error actionable for agents (MUL-4417 / GH #5266).- // The two rejections need different copy. A resumed- // session carrying a previous turn's --parent forward- // (GH #6264) did NOT ask for a top-level comment, and- // telling it that it did sends it looking for a- // new-thread opt-in instead of simply correcting the- // parent it already passed.- fix := "set parent_id (--parent) to " + uuidToString(task.TriggerCommentID) + " or a coalesced comment id"- msg := "comment-triggered tasks cannot create top-level comments; " + fix- if parentID.Valid {- msg = "parent_id " + uuidToString(parentID) + " is not a comment this task may reply under; " + fix- }- writeError(w, http.StatusConflict, msg)- return+ if task, ok := h.taskFromRequestHeader(r); ok {+ // Defense against resumed-session drift: when an agent posts from+ // inside a comment-triggered task AND the comment is being posted on+ // that same issue, the parent_id must exactly match the task's+ // trigger comment. Resumed Claude sessions otherwise carry forward a+ // previous turn's --parent UUID and silently misplace the reply.+ //+ // The task.IssueID scope is important: the CLI stamps X-Task-ID on+ // every request, so an agent legitimately commenting on a different+ // issue must not be blocked by its current task's trigger.+ // Assignment-triggered tasks (no TriggerCommentID) are also+ // unaffected.+ if task.IssueID.Valid && uuidToString(task.IssueID) == uuidToString(issue.ID) {+ if task.TriggerCommentID.Valid {+ if !taskCoversReplyParent(task, parentID) {+ // Keep this error actionable for agents (MUL-4417 / GH #5266).+ // The two rejections need different copy. A resumed+ // session carrying a previous turn's --parent forward+ // (GH #6264) did NOT ask for a top-level comment, and+ // telling it that it did sends it looking for a+ // new-thread opt-in instead of simply correcting the+ // parent it already passed.+ fix := "set parent_id (--parent) to " + uuidToString(task.TriggerCommentID) + " or a coalesced comment id"+ msg := "comment-triggered tasks cannot create top-level comments; " + fix+ if parentID.Valid {+ msg = "parent_id " + uuidToString(parentID) + " is not a comment this task may reply under; " + fix}- }- noAction, checkErr := service.HasSquadLeaderNoActionEvaluationForTask(r.Context(), h.Queries, task)- if checkErr != nil {- slog.Warn("checking squad leader no_action evaluation failed", append(logger.RequestAttrs(r),- "error", checkErr,- "task_id", taskIDHeader,- "issue_id", issueID,- )...)- } else if noAction {- writeError(w, http.StatusConflict, "squad leader recorded no_action; comments are not allowed for this task")+ writeError(w, http.StatusConflict, msg)return}- // Only stamp source_task_id for a task belonging to THIS- // issue. An agent legitimately commenting on a DIFFERENT- // issue than its current task must not stamp that task's- // id here — the resulting chain would then attribute the- // out-of-band comment to an unrelated task's originator.- sourceTaskID = taskUUID+ }+ noAction, checkErr := service.HasSquadLeaderNoActionEvaluationForTask(r.Context(), h.Queries, task)+ if checkErr != nil {+ slog.Warn("checking squad leader no_action evaluation failed", append(logger.RequestAttrs(r),+ "error", checkErr,+ "task_id", uuidToString(task.ID),+ "issue_id", issueID,+ )...)+ } else if noAction {+ writeError(w, http.StatusConflict, "squad leader recorded no_action; comments are not allowed for this task")+ return}}+ sourceTaskID = task.ID}}@@ -3302,17 +3317,17 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {}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).+ // edit. Only the AGENT author re-editing its OWN comment carries the lineage+ // forward (commentSourceTaskID re-stamps the current editing task) — 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)+ sourceTaskID = h.commentSourceTaskID(r)} else {sourceTaskID = pgtype.UUID{}}@@ -3432,9 +3447,10 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {// 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.+ // request, and to what the completion-reconcile will restore. A non-author+ // edit left it NULL, and a cross-issue editing task is rejected inside+ // autopilotDelegationAuthority, so neither can borrow 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)}diff --git a/server/internal/handler/cross_issue_originator_test.go b/server/internal/handler/cross_issue_originator_test.gonew file mode 100644index 0000000000..77207c74df--- /dev/null+++ b/server/internal/handler/cross_issue_originator_test.go@@ -0,0 +1,420 @@+package handler++import (+ "net/http"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// MUL-6490 / GH #7328 — the authorization chain must survive a cross-issue hop.+//+// The invariant under test (MUL-3963): a run always acts "on behalf of" exactly+// one human U, and every A2A delegation is judged by whether U is on the target's+// allow-list — never by the agent principal doing the asking. The chain's carrier+// is comment.source_task_id: an agent's comment records the run that wrote it, and+// the run that comment wakes inherits that run's originator.+//+// The bug: CreateComment only stamped source_task_id when the authoring run's task+// was on the SAME issue as the comment. An agent coordinating on an issue it just+// created wrote a NULL lineage, so the woken run resolved to unattributed and+// every @mention / assign / sub-issue inside it hit invocation_not_allowed — while+// the identical delegation on the originating issue succeeded.+//+// The fix propagates the chain unconditionally, which is monotonic: a run can only+// carry the human it ALREADY acts for, and each hop re-runs canInvokeAgent against+// that same human. What must stay impossible is SUBSTITUTING a human — falling+// back to the coordinator's owner, or adopting the target issue's originator —+// because that borrows a different person's authority. Both directions are pinned+// below, and the three entry points a woken run delegates through are driven+// through their real handlers: the risk this fix carries is precisely that one+// entry point resolves the chain differently from another.++// crossIssueChain is the {coordinator, two issues, one running task} shape every+// case here starts from. IssueX is where the coordinator's run lives; IssueY is+// the issue it coordinates on.+type crossIssueChain struct {+ CoordinatorID string+ IssueX string+ IssueY string+ TaskA string // the coordinator's running task, on IssueX+}++// newCrossIssueChain seeds a coordinator agent owned by ownerUserID with a running+// task on IssueX whose originator is originatorUserID (pass nil for an+// unattributed run, e.g. a schedule/webhook autopilot dispatch).+func newCrossIssueChain(t *testing.T, ownerUserID string, originatorUserID any) crossIssueChain {+ t.Helper()+ coordinator := seedAllowListedAgent(t, "MUL-6490 coordinator", ownerUserID, "private")+ issueX := seedChainIssue(t, "MUL-6490 originating issue", coordinator)+ return crossIssueChain{+ CoordinatorID: coordinator,+ IssueX: issueX,+ IssueY: seedChainIssue(t, "MUL-6490 coordinated issue", coordinator),+ TaskA: dbfx.Task(t, coordinator, testutil.Cols{+ "runtime_id": handlerTestRuntimeID(t),+ "issue_id": issueX,+ "status": "running",+ "originator_user_id": originatorUserID,+ "accountable_user_id": originatorUserID,+ }),+ }+}++// seedChainIssue inserts an agent-created issue and registers teardown for the+// rows the HANDLERS will add to it. dbfx removes only what it inserted itself, and+// these tests exist to make real handlers write comments and enqueue tasks.+//+// The number comes from the workspace counter rather than dbfx's MAX(number)+1+// default: CreateIssue allocates from that counter, so a fixture issue that+// bypasses it collides with the sub-issue the test asks the real handler to make.+func seedChainIssue(t *testing.T, title, creatorAgentID string) string {+ t.Helper()+ issueID := dbfx.Issue(t, title, testutil.Cols{+ "creator_type": "agent",+ "creator_id": creatorAgentID,+ "number": nextWorkspaceIssueNumber(t),+ })+ dbfx.Cleanup(t, `DELETE FROM comment WHERE issue_id = $1`, issueID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)+ return issueID+}++// seedAllowListedAgent creates an agent with the given permission mode. Any+// memberTargets make it public_to and allow-list exactly those users — the+// minimum-privilege configuration the report ran ("only Bohan may invoke this").+// The grants are removed explicitly because the project forbids DB cascades, so+// they would outlive the agent row dbfx deletes.+func seedAllowListedAgent(t *testing.T, name, ownerUserID, mode string, memberTargets ...string) string {+ t.Helper()+ agentID := dbfx.Agent(t, name, handlerTestRuntimeID(t), testutil.Cols{+ "permission_mode": mode,+ "owner_id": ownerUserID,+ "max_concurrent_tasks": 5,+ "instructions": "",+ "custom_env": testutil.Raw("'{}'::jsonb"),+ "custom_args": testutil.Raw("'[]'::jsonb"),+ "mcp_config": testutil.Raw("'[]'::jsonb"),+ })+ for _, target := range memberTargets {+ dbfx.InsertNoID(t, "agent_invocation_target", testutil.Cols{+ "agent_id": agentID,+ "target_type": "member",+ "target_id": target,+ }, "agent_id = $1 AND target_type = 'member' AND target_id = $2", agentID, target)+ }+ return agentID+}++// ---- entry points ---------------------------------------------------------+//+// The three ways a run delegates. Each goes through the real handler, because the+// failure this fix repairs is entry-point wiring: the gate and the enqueue used to+// resolve the chain from different places, and only the wired path shows that.++// agentComments posts a comment as the agent, speaking from taskID — the only way+// an agent's lineage reaches the comment row. A comment-triggered run must reply+// under its own trigger, so replyUnder carries that parent; it is empty for a run+// with no trigger comment to answer.+func agentComments(t *testing.T, agentID, taskID, issueID, content, replyUnder string) *testutil.Response {+ t.Helper()+ body := map[string]any{"content": content}+ if replyUnder != "" {+ body["parent_id"] = replyUnder+ }+ return testutil.Call(t, testHandler.CreateComment, testutil.WithURLParams(+ asRun(newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", body), agentID, taskID),+ "id", issueID,+ ))+}++// agentAssigns points an existing issue at targetAgentID through UpdateIssue.+func agentAssigns(t *testing.T, agentID, taskID, issueID, targetAgentID string) *testutil.Response {+ t.Helper()+ return testutil.Call(t, testHandler.UpdateIssue, testutil.WithURLParams(+ asRun(newRequest(http.MethodPatch, "/api/issues/"+issueID, map[string]any{+ "assignee_type": "agent",+ "assignee_id": targetAgentID,+ }), agentID, taskID),+ "id", issueID,+ ))+}++// agentCreatesSubIssue creates a `todo` sub-issue assigned to targetAgentID, which+// dispatches that agent immediately — the third way the report saw the chain fail.+// The title is unique per target so the active-duplicate guard never masks the+// authorization outcome this asserts.+func agentCreatesSubIssue(t *testing.T, agentID, taskID, parentIssueID, targetAgentID string) *testutil.Response {+ t.Helper()+ resp := testutil.Call(t, testHandler.CreateIssue, asRun(+ newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "MUL-6490 delegated sub-issue for " + targetAgentID,+ "status": "todo",+ "priority": "medium",+ "assignee_type": "agent",+ "assignee_id": targetAgentID,+ "parent_issue_id": parentIssueID,+ }), agentID, taskID))+ if resp.Code == http.StatusCreated {+ var created struct {+ ID string `json:"id"`+ }+ resp.JSON(&created)+ dbfx.Cleanup(t, `DELETE FROM issue WHERE id = $1`, created.ID)+ dbfx.Cleanup(t, `DELETE FROM comment WHERE issue_id = $1`, created.ID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, created.ID)+ }+ return resp+}++// asRun makes a request speak as the agent from inside one of its runs. The+// member headers newRequest sets stay put on purpose: X-User-ID remains a+// workspace member while the ACTOR is the agent, which is exactly the+// confused-deputy shape the gate must judge by the chain's human, not the caller's+// session.+func asRun(req *http.Request, agentID, taskID string) *http.Request {+ return testutil.WithHeaders(req, "X-Agent-ID", agentID, "X-Task-ID", taskID)+}++// ---- reads ----------------------------------------------------------------++// queuedTaskFor returns the queued task for (issue, agent) and its originator.+// ok is false when the delegation was refused and nothing was enqueued.+func queuedTaskFor(t *testing.T, issueID, agentID string) (taskID string, originator pgtype.UUID, ok bool) {+ t.Helper()+ const where = `FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`+ if dbfx.Count(t, `SELECT count(*) `+where, issueID, agentID) == 0 {+ return "", pgtype.UUID{}, false+ }+ dbfx.QueryRow(t, `SELECT id, originator_user_id `+where, issueID, agentID).Scan(&taskID, &originator)+ return taskID, originator, true+}++func commentSourceTaskOf(t *testing.T, commentID string) pgtype.UUID {+ t.Helper()+ var sourceTaskID pgtype.UUID+ dbfx.QueryRow(t, `SELECT source_task_id FROM comment WHERE id = $1`, commentID).Scan(&sourceTaskID)+ return sourceTaskID+}++func lastCommentOn(t *testing.T, issueID string) string {+ t.Helper()+ var commentID string+ dbfx.QueryRow(t,+ `SELECT id FROM comment WHERE issue_id = $1 ORDER BY created_at DESC, id DESC LIMIT 1`,+ issueID).Scan(&commentID)+ return commentID+}++// triggerCommentOf returns the comment a task was woken by, which is the only+// parent its replies may use (taskCoversReplyParent).+func triggerCommentOf(t *testing.T, taskID string) string {+ t.Helper()+ var triggerCommentID pgtype.UUID+ dbfx.QueryRow(t, `SELECT trigger_comment_id FROM agent_task_queue WHERE id = $1`, taskID).Scan(&triggerCommentID)+ return uuidToString(triggerCommentID)+}++func runTo(t *testing.T, taskID string) {+ t.Helper()+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'running' WHERE id = $1`, taskID)+}++func mention(agentID string) string {+ return "[@Worker](mention://agent/" + agentID + ") please take this"+}++// TestCrossIssueDelegation_OriginatorChainSurvivesTheHop is the reported bug, end+// to end over HTTP: the delegation that works on the coordinator's own issue must+// keep working when the coordinator delegates on another issue, and the woken run+// must carry the SAME human — that inherited originator is what every later+// mention / assign / sub-issue in it is judged by.+func TestCrossIssueDelegation_OriginatorChainSurvivesTheHop(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ // bohan owns the coordinator and is the only member on the worker's allow-list.+ bohan := testUserID+ worker := seedAllowListedAgent(t, "MUL-6490 worker", bohan, "public_to", bohan)++ for _, tc := range []struct {+ name string+ cross bool+ }{+ {"same issue (already worked)", false},+ {"cross issue (the regression)", true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ chain := newCrossIssueChain(t, bohan, bohan)+ target := chain.IssueX+ if tc.cross {+ target = chain.IssueY+ }++ agentComments(t, chain.CoordinatorID, chain.TaskA, target, mention(worker), "").+ Want(http.StatusCreated)++ // The comment must record the run that wrote it. This is the carrier;+ // a NULL here is the break the report saw.+ if got := commentSourceTaskOf(t, lastCommentOn(t, target)); uuidToString(got) != chain.TaskA {+ t.Fatalf("comment.source_task_id = %q, want the authoring run %q", uuidToString(got), chain.TaskA)+ }++ taskID, originator, ok := queuedTaskFor(t, target, worker)+ if !ok {+ t.Fatal("the allow-listed worker was not enqueued: the delegation was refused")+ }+ if uuidToString(originator) != bohan {+ t.Fatalf("woken run originator = %q (valid=%v), want %q — the chain lost its human across the hop",+ uuidToString(originator), originator.Valid, bohan)+ }++ // A third hop proves the chain keeps travelling rather than surviving+ // exactly one boundary. Entry-point coverage is in the sibling test.+ t.Run("the chain continues past the woken run", func(t *testing.T) {+ runTo(t, taskID)+ second := seedAllowListedAgent(t, "MUL-6490 second worker", bohan, "public_to", bohan)++ agentComments(t, worker, taskID, target, mention(second), triggerCommentOf(t, taskID)).+ Want(http.StatusCreated)+ if _, _, ok := queuedTaskFor(t, target, second); !ok {+ t.Fatal("@mention from inside the woken run was refused (invocation_not_allowed)")+ }+ })+ })+ }+}++// TestCrossIssueDelegation_EveryEntryPointJudgesTheSameHuman is the matrix that+// matters for this fix: {mention, assign, sub-issue} × {bohan's chain, alice's+// chain, no chain}, all from inside a run woken across an issue boundary.+//+// Two things are pinned at once. The chain must be CARRIED — all three entry+// points recover for the human who started it. And it must never be REPLACED:+// alice triggers a coordinator that BOHAN owns, so the owner-inheritance fallback+// the report proposed would silently upgrade alice's flow to bohan's authority.+// Every entry point resolves the acting human through its own wiring, so a fix+// that repairs one and not the others is a real outcome this catches.+func TestCrossIssueDelegation_EveryEntryPointJudgesTheSameHuman(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ bohan := testUserID+ _, _, alice := privateAgentTestFixture(t)++ // firstHop admits both members, so every case reaches the second hop and the+ // difference isolates to whose authority the chain carries. secondHop admits+ // ONLY bohan — it is the agent an owner fallback would wrongly unlock.+ firstHop := seedAllowListedAgent(t, "MUL-6490 shared worker", bohan, "public_to", bohan, alice)+ secondHop := seedAllowListedAgent(t, "MUL-6490 bohan-only worker", bohan, "public_to", bohan)++ for _, tc := range []struct {+ name string+ chainOf any+ admit bool+ }{+ {"bohan's chain reaches a bohan-only agent", bohan, true},+ {"alice's chain does not become bohan's", alice, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ // The coordinator is owned by BOHAN in every case: only the human at+ // the top of the chain may vary the outcome.+ chain := newCrossIssueChain(t, bohan, tc.chainOf)+ agentComments(t, chain.CoordinatorID, chain.TaskA, chain.IssueY, mention(firstHop), "").+ Want(http.StatusCreated)++ firstTaskID, originator, ok := queuedTaskFor(t, chain.IssueY, firstHop)+ if !ok {+ t.Fatal("first hop was refused although both members are allow-listed")+ }+ if uuidToString(originator) != tc.chainOf {+ t.Fatalf("first hop originator = %q, want %q", uuidToString(originator), tc.chainOf)+ }+ runTo(t, firstTaskID)++ t.Run("mention", func(t *testing.T) {+ agentComments(t, firstHop, firstTaskID, chain.IssueY, mention(secondHop),+ triggerCommentOf(t, firstTaskID)).Want(http.StatusCreated)+ // A blocked mention is reported in trigger_outcomes, not as an+ // error status, so the enqueue is what says yes or no.+ if _, _, got := queuedTaskFor(t, chain.IssueY, secondHop); got != tc.admit {+ t.Fatalf("mention admitted = %v, want %v", got, tc.admit)+ }+ })++ t.Run("assign", func(t *testing.T) {+ want := http.StatusForbidden+ if tc.admit {+ want = http.StatusOK+ }+ resp := agentAssigns(t, firstHop, firstTaskID, chain.IssueY, secondHop).Want(want)+ if !tc.admit {+ assertDenialReason(t, resp, "you do not have permission to assign work to this agent")+ }+ })++ t.Run("sub-issue", func(t *testing.T) {+ want := http.StatusForbidden+ if tc.admit {+ want = http.StatusCreated+ }+ resp := agentCreatesSubIssue(t, firstHop, firstTaskID, chain.IssueY, secondHop).Want(want)+ if !tc.admit {+ assertDenialReason(t, resp, "you do not have permission to assign work to this agent")+ }+ })+ })+ }++ // A chain with no human at its top grants nothing anywhere, which is the+ // fail-closed side of the same rule: propagation carries a human, it never+ // invents one. The first hop already stops here, so there is no second hop to+ // drive — a member-scoped allow-list has nobody to match.+ t.Run("an unattributed chain grants nothing", func(t *testing.T) {+ chain := newCrossIssueChain(t, bohan, nil)+ agentComments(t, chain.CoordinatorID, chain.TaskA, chain.IssueY, mention(firstHop), "").+ Want(http.StatusCreated)+ if _, _, ok := queuedTaskFor(t, chain.IssueY, firstHop); ok {+ t.Fatal("an unattributed chain must not satisfy a member-scoped allow-list")+ }+ agentAssigns(t, chain.CoordinatorID, chain.TaskA, chain.IssueY, firstHop).Want(http.StatusForbidden)+ agentCreatesSubIssue(t, chain.CoordinatorID, chain.TaskA, chain.IssueY, firstHop).Want(http.StatusForbidden)+ })+}++// TestCrossIssueDelegation_GateAndStampAgreeOnTheHuman closes the split-brain the+// bug created: the invoke gate resolved the human from the request's X-Task-ID+// (cross-issue OK) while the enqueued run resolved it from the stored comment+// (cross-issue NULL). The gate said yes and the run started with no authority, so+// the failure only surfaced one hop later. Both resolvers must answer identically+// for the same action.+func TestCrossIssueDelegation_GateAndStampAgreeOnTheHuman(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ bohan := testUserID+ worker := seedAllowListedAgent(t, "MUL-6490 agreement worker", bohan, "public_to", bohan)+ chain := newCrossIssueChain(t, bohan, bohan)++ agentComments(t, chain.CoordinatorID, chain.TaskA, chain.IssueY, mention(worker), "").+ Want(http.StatusCreated)+ commentID := lastCommentOn(t, chain.IssueY)++ // What the gate saw at admission time, from the request header.+ fromGate := testHandler.invokeOriginatorFromRequest(+ asRun(newRequest(http.MethodPost, "/api/issues/"+chain.IssueY+"/comments", nil), chain.CoordinatorID, chain.TaskA),+ "agent", chain.CoordinatorID)++ // What the enqueue path sees afterwards, from the persisted comment.+ fromStamp := uuidToString(testHandler.TaskService.ResolveOriginatorFromTriggerComment(+ t.Context(), parseUUID(testWorkspaceID), parseUUID(commentID)))++ if fromGate != fromStamp {+ t.Fatalf("gate resolved %q but the stored chain resolves %q — a run would start with authority the gate never granted",+ fromGate, fromStamp)+ }+ if fromGate != bohan {+ t.Fatalf("both resolvers agree on %q, want %q", fromGate, bohan)+ }+}diff --git a/server/internal/service/builtin_skills/multica-mentioning/SKILL.md b/server/internal/service/builtin_skills/multica-mentioning/SKILL.mdindex af634c7ea2..ec370dbea2 100644--- a/server/internal/service/builtin_skills/multica-mentioning/SKILL.md+++ b/server/internal/service/builtin_skills/multica-mentioning/SKILL.md@@ -167,6 +167,17 @@ read. Read that array after posting — it is the only place any of this shows uis the squad assignment/promote path, not this one; the child-done wake isungated — see the multica-squads skill.)+A chain that crosses issues keeps its human (MUL-6490). The A2A gate judges the+human at the top of your chain, and that human travels on the comment you write:+the comment records the run that authored it, so the run it wakes inherits your+originator. This holds when you comment on a DIFFERENT issue than the one you are+running on — the ordinary "create issue Y, then coordinate there" flow — so a+delegation that works on your own issue keeps working on the issue you just+created. It does not go the other way: nothing ever substitutes a different human+(your agent's owner, or the target issue's originator), so if your chain has no+human at its top, member-scoped allow-lists stay closed no matter which issue you+move to.+One nuance for automation (MUL-4857): when an UNATTRIBUTED autopilot run (aschedule/webhook dispatch has no human originator, so the A2A gate has no humanto key on) delegates by `@mention` while working on the issue that autopilotdiff --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.mdindex cdcf45a08b..ab51f2fe14 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@@ -108,7 +108,8 @@ that never parsed at all (a name where a UUID belongs) is a true silent no-op.| `canEnqueueSquadLeader` (loads leader, delegates to `canInvokeAgent`) — squad assignment/promote path, NOT the mention path | n/a (reference) | `server/internal/handler/agent_access.go` (search `func (h *Handler) canEnqueueSquadLeader`) || 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) | feeds the invoke gate | 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) | feeds the invoke gate | `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) | fails closed | `server/internal/handler/comment.go` (search `commentSourceTaskIDForIssue` and the `isAuthor` branch in `UpdateComment`) |+| authority lineage is persisted per-action: only an agent editing its OWN comment re-stamps `source_task_id` to the current editing task (like create, cross-issue included); any other editor — including a workspace owner/admin editing an agent's comment (manage rights, not invoke rights) — CLEARS it, so an admin edit makes every authority/originator read fail closed, including the deferred completion-reconcile — preview, save, and reconcile agree (MUL-4857) | fails closed | `server/internal/handler/comment.go` (search `commentSourceTaskID` and the `isAuthor` branch in `UpdateComment`) |+| an agent's comment records the run that WROTE it on `source_task_id`, whichever issue it lands on, so the human originator chain survives an agent coordinating on another issue; the same-issue requirement lives only in the consumers that need it (`autopilotDelegationAuthority`, the reply-parent guard), never in the stamp (MUL-6490) | chain preserved, gate unchanged | `server/internal/handler/comment.go` (search `sourceTaskID captures the agent's currently-executing task`) |## @all broadcast and assignee-trigger suppression