Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(issues): let verified autopilot runs assign private agents (#7572)
Multica Eve7b8c7839913f
diff --git a/server/internal/handler/agent_access.go b/server/internal/handler/agent_access.goindex 13bf98d520..bce9f095b2 100644--- a/server/internal/handler/agent_access.go+++ b/server/internal/handler/agent_access.go@@ -6,6 +6,7 @@ import ("net/http""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/attribution""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -224,16 +225,277 @@ func (h *Handler) invokeOriginatorFromRequest(r *http.Request, actorType, actorIreturn ""}+// assignAuthorityScope tells the invoke gate WHAT an assignment is being made+// against, so an unattributed autopilot run can only borrow authority for work+// it is verifiably doing itself (MUL-6691).+//+// Exactly which shape the caller vouched for decides what may be borrowed, so+// the kinds are distinct rather than a single "some issue" pointer. The zero+// value grants nothing — a caller that supplies no scope keeps the pre-MUL-4857+// behavior of "real originator or deny", which is what the member-only entry+// points want.+type assignAuthorityScope struct {+ // Issue is the already-loaded issue the assignment binds to: the PARENT for+ // scopeKindChildOf, the issue ITSELF for scopeKindExistingIssue. Its+ // workspace must match the request's, and the speaking run must be+ // verifiably attached to it (issueBoundToAutopilotTask) before any authority+ // is borrowed.+ Issue *db.Issue++ Kind assignScopeKind+}++// assignScopeKind distinguishes the assignment shapes, because they do NOT admit+// the same fallbacks: only child creation — the surface MUL-4857 already shipped+// — may fall back to the coarse autopilot-creator authority.+type assignScopeKind int++const (+ // scopeKindNone: no autopilot authority may be borrowed at all.+ scopeKindNone assignScopeKind = iota+ // scopeKindChildOf: creating a child under Issue.+ scopeKindChildOf+ // scopeKindExistingIssue: assigning Issue itself.+ scopeKindExistingIssue+ // scopeKindNewTopLevelIssue: creating a parentless issue, which does not+ // exist yet, so the binding is the speaking task's own autopilot run.+ scopeKindNewTopLevelIssue+)++// scopeChildOf binds the assignment to the parent a child is being created+// under. A nil parent yields the empty scope, which grants nothing.+func scopeChildOf(parent *db.Issue) assignAuthorityScope {+ if parent == nil {+ return assignAuthorityScope{}+ }+ return assignAuthorityScope{Issue: parent, Kind: scopeKindChildOf}+}++// scopeExistingIssue binds the assignment to the issue being updated.+func scopeExistingIssue(issue *db.Issue) assignAuthorityScope {+ if issue == nil {+ return assignAuthorityScope{}+ }+ return assignAuthorityScope{Issue: issue, Kind: scopeKindExistingIssue}+}++// scopeNewTopLevelIssue marks a create with no parent, where the issue being+// assigned does not exist yet.+func scopeNewTopLevelIssue() assignAuthorityScope {+ return assignAuthorityScope{Kind: scopeKindNewTopLevelIssue}+}++// scopeNoDelegation disables the autopilot fallback entirely — for entry points+// that only ever run as a member and must not gain an agent-borrowed path.+func scopeNoDelegation() assignAuthorityScope {+ return assignAuthorityScope{}+}+// effectiveInvocationAuthorityFromRequest returns the human principal used by// canInvokeAgent without changing attribution. A real top-of-chain originator-// always wins. Only an unattributed agent request may fall back to the creator-// of a lineage-verified autopilot issue supplied by the caller.-func (h *Handler) effectiveInvocationAuthorityFromRequest(r *http.Request, delegationIssue *db.Issue, actorType, actorID string) string {+// always wins. Only an unattributed AGENT request may fall back to an autopilot+// authority, and only within the scope the caller vouched for.+func (h *Handler) effectiveInvocationAuthorityFromRequest(r *http.Request, scope assignAuthorityScope, actorType, actorID, workspaceID string) string {originatorUserID := h.invokeOriginatorFromRequest(r, actorType, actorID)- if originatorUserID != "" || delegationIssue == nil {+ if originatorUserID != "" {return originatorUserID}- return h.autopilotDelegationAuthorityFromRequest(r, *delegationIssue, actorType, actorID)+ return h.autopilotAssignAuthorityFromRequest(r, scope, actorType, actorID, workspaceID)+}++// autopilotAssignAuthorityFromRequest resolves the borrowed authority for an+// assignment made by an unattributed agent run, in precedence order:+//+// 1. the speaking task's OWN accountable human (autopilotTaskAssignAuthority) —+// precise, already recorded on the task row, and available for both+// autopilot execution modes;+// 2. the autopilot's member creator (autopilotDelegationAuthority, MUL-4857) —+// the coarser pre-existing rule, kept ONLY where it already shipped: child+// creation under an `origin_type=autopilot` issue, so a leader task that+// predates attribution stamping does not lose the path it has today.+//+// (2) is deliberately NOT available to the newly-wired surfaces. It performs no+// liveness or attribution check of its own, so extending it to the assign verb+// would have let a completed task, an `owner_fallback` task, or a task with no+// attribution at all assign private agents whenever the autopilot's creator+// happened to have rights — a strictly wider grant than this fix needs. The+// request path additionally requires the speaking task to still be `running`;+// the comment-replay resolvers keep their own semantics and are untouched.+func (h *Handler) autopilotAssignAuthorityFromRequest(r *http.Request, scope assignAuthorityScope, actorType, actorID, workspaceID string) string {+ if actorType != "agent" || scope.Kind == scopeKindNone {+ return ""+ }+ task, ok := h.taskFromRequestHeader(r)+ if !ok {+ return ""+ }+ // A finished run never lends authority over HTTP, on either branch below.+ if task.Status != "running" {+ return ""+ }+ if user := h.autopilotTaskAssignAuthority(r.Context(), scope, actorType, actorID, workspaceID, task); user != "" {+ return user+ }+ if scope.Kind != scopeKindChildOf || scope.Issue == nil {+ return ""+ }+ return h.autopilotDelegationAuthority(r.Context(), *scope.Issue, actorType, actorID, task)+}++// autopilotTaskAssignAuthority resolves the effective invoking human for an+// assignment performed by an unattributed autopilot run, keyed on the run's OWN+// accountable human rather than on the autopilot's creator (MUL-6691).+//+// WHY the accountable user and not autopilot.created_by_id: since MUL-4302 the+// accountable human for a schedule/webhook run is the trigger_owner — whoever+// last shaped the firing trigger — which need NOT be the autopilot's original+// creator. Keying authorization on the creator while the audit trail names the+// trigger owner would let the audit record one human and the private-agent /+// OAuth access come from another. The task row already carries the resolved+// value, so this reads it instead of re-deriving a different one.+//+// SECURITY. The gate is unchanged; only the human handed to it is. Every one of+// these must hold, and anything missing, mismatched, or unreadable returns ""+// and leaves canInvokeAgent fail-closed:+//+// - the actor is an agent and IS the speaking task's agent;+// - the task is still `running` — a finished run cannot keep lending rights;+// - the task carries NO originator (a real one is preferred by the caller and+// must never be silently replaced by this coarser value);+// - originator_source is `trigger_owner` or `rule_owner`. This IS the+// autopilot-lineage proof: only the autopilot enqueue paths stamp those two+// labels. `owner_fallback` is deliberately excluded — that value is the+// AGENT OWNER, and borrowing it would let any unattributed autopilot run+// invoke its own owner's private agents, which is precisely the owner+// white-list bypass canInvokeAgent exists to prevent. `delegation` is+// excluded too, so authority does not propagate to descendant runs;+// - the assignment is bound to work this run verifiably owns —+// issueBoundToAutopilotTask for an existing issue (which for a run_only-created+// issue re-proves the run_only lineage, so a create_issue task cannot escape+// its same-issue bound via a fresh top-level issue), or the task's own+// verified autopilot run when creating a parentless issue;+// - the issue (when there is one) is in the request's workspace;+// - the accountable human is STILL a member of that workspace.+//+// The returned id is used for AUTHORIZATION only: the new issue and any task it+// enqueues are attributed separately and stay unattributed, so the audit+// semantics of "no human directly started this" are preserved.+func (h *Handler) autopilotTaskAssignAuthority(ctx context.Context, scope assignAuthorityScope, actorType, actorID, workspaceID string, task db.AgentTaskQueue) string {+ if actorType != "agent" {+ return ""+ }+ if !task.AgentID.Valid || uuidToString(task.AgentID) != actorID {+ return ""+ }+ if task.Status != "running" {+ return ""+ }+ if task.OriginatorUserID.Valid || !task.AccountableUserID.Valid {+ return ""+ }+ if !task.OriginatorSource.Valid {+ return ""+ }+ switch attribution.Source(task.OriginatorSource.String) {+ case attribution.SourceTriggerOwner, attribution.SourceRuleOwner:+ default:+ return ""+ }++ switch scope.Kind {+ case scopeKindChildOf, scopeKindExistingIssue:+ if scope.Issue == nil {+ return ""+ }+ if uuidToString(scope.Issue.WorkspaceID) != workspaceID {+ return ""+ }+ if !h.issueBoundToAutopilotTask(ctx, *scope.Issue, task, workspaceID) {+ return ""+ }+ case scopeKindNewTopLevelIssue:+ if !h.taskRunsAutopilotInWorkspace(ctx, task, workspaceID) {+ return ""+ }+ default:+ return ""+ }++ accountable := uuidToString(task.AccountableUserID)+ if accountable == "" {+ return ""+ }+ if _, err := h.getWorkspaceMember(ctx, accountable, workspaceID); err != nil {+ return ""+ }+ return accountable+}++// issueBoundToAutopilotTask reports whether `task` verifiably owns the work on+// `issue`, which is what keeps a borrowed autopilot authority from becoming a+// workspace-wide capability (the confused-deputy bound MUL-4857 established).+// Two shapes, one per autopilot execution mode:+//+// - create_issue: the autopilot created the issue (origin_type=autopilot) and+// the speaking task is the run working ON it (task.issue_id == issue.id) —+// the exact MUL-4857 binding.+// - run_only: no autopilot issue exists, so the binding is authorship. The+// issue was created by THIS task, which CreateIssue records as+// origin_type=agent_create + origin_id=<creating task id> (MUL-4305), AND the+// task must independently prove run_only lineage (its own autopilot run, in+// this workspace). Without that second half a create_issue-mode task could+// escape its `task.issue_id == issue.id` bound simply by creating a fresh+// top-level issue — which stamps its own task id — and then assigning that.+// Using the task id rather than the autopilot id also stops two concurrent+// runs of the same autopilot from borrowing on each other's issues, and needs+// no migration or backfill.+//+// A run_only leader therefore reaches only the issues it created (and, through+// the child scope, their children) — never a pre-existing or foreign issue. A+// create_issue leader reaches only the autopilot's own issue.+func (h *Handler) issueBoundToAutopilotTask(ctx context.Context, issue db.Issue, task db.AgentTaskQueue, workspaceID string) bool {+ if !issue.OriginType.Valid || !issue.OriginID.Valid || !issue.ID.Valid {+ return false+ }+ switch issue.OriginType.String {+ case "autopilot":+ return task.IssueID.Valid && uuidToString(task.IssueID) == uuidToString(issue.ID)+ case "agent_create":+ if !task.ID.Valid || uuidToString(issue.OriginID) != uuidToString(task.ID) {+ return false+ }+ return h.taskRunsAutopilotInWorkspace(ctx, task, workspaceID)+ }+ return false+}++// taskRunsAutopilotInWorkspace verifies run_only lineage: the task must belong to+// an autopilot RUN whose autopilot lives in the request's workspace. Used both+// when there is no issue to bind to yet and when binding to a run_only-created+// issue. A create_issue-mode leader task carries no autopilot_run_id (it is+// enqueued through the ordinary issue-assignment path), so it never qualifies+// here and must go through the `origin_type=autopilot` binding instead.+func (h *Handler) taskRunsAutopilotInWorkspace(ctx context.Context, task db.AgentTaskQueue, workspaceID string) bool {+ if !task.AutopilotRunID.Valid {+ return false+ }+ wsUUID, err := util.ParseUUID(workspaceID)+ if err != nil {+ return false+ }+ run, err := h.Queries.GetAutopilotRun(ctx, task.AutopilotRunID)+ if err != nil || !run.AutopilotID.Valid {+ return false+ }+ // Workspace-scoped read: an autopilot run from another tenant resolves to+ // no autopilot here, so a foreign run id cannot lend authority (MUL-4252).+ if _, err := h.Queries.GetAutopilotInWorkspace(ctx, db.GetAutopilotInWorkspaceParams{+ ID: run.AutopilotID,+ WorkspaceID: wsUUID,+ }); err != nil {+ return false+ }+ return true}// autopilotDelegationAuthority resolves the effective invoking human for the A2Adiff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex c785b14d88..bf781e47af 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -2645,7 +2645,7 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {r.Context(), r, workspaceID,pgtype.Text{String: "agent", Valid: true},agentUUID,- nil,+ scopeNoDelegation(),); status != 0 {writeError(w, status, msg)return@@ -2960,7 +2960,17 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {}}- if status, msg := h.validateAssigneePair(r.Context(), r, workspaceID, assigneeType, assigneeID, parentIssue); status != 0 {+ // An agent/squad assignee on a PARENTLESS create has no issue to bind an+ // autopilot authority to, so the scope names the create itself: only a+ // verified, still-running run_only autopilot task may borrow there+ // (MUL-6691 — the reported flow, where the leader creates DRA-109/DRA-110+ // from scratch rather than under an autopilot-created issue).+ assignScope := scopeChildOf(parentIssue)+ if req.ParentIssueID == nil {+ assignScope = scopeNewTopLevelIssue()+ }++ if status, msg := h.validateAssigneePair(r.Context(), r, workspaceID, assigneeType, assigneeID, assignScope); status != 0 {writeError(w, status, msg)return}@@ -3598,10 +3608,16 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {// Validate the resulting (assignee_type, assignee_id) pair when the caller// touches either field. Existing data on the issue is left alone if the// caller is not changing it.+ //+ // The scope is THIS issue: an unattributed autopilot run that verifiably owns+ // the work on it may point it at a private agent, exactly as it may when+ // creating a child under it. Before MUL-6691 this passed nil, so the reported+ // flow — create DRA-109 unassigned, then assign it — was refused even though+ // the identical lineage was accepted on the create path._, touchedType := rawFields["assignee_type"]_, touchedID := rawFields["assignee_id"]if touchedType || touchedID {- if status, msg := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID, nil); status != 0 {+ if status, msg := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID, scopeExistingIssue(&prevIssue)); status != 0 {writeError(w, status, msg)return}@@ -3755,15 +3771,16 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {// That means owner-only for a private agent, with NO workspace-admin bypass// and NO unconditional agent-to-agent bypass — an agent caller (X-Agent-ID) is// judged by the top-of-chain human originator like everywhere else.-// delegationIssue is non-nil only for child creation. It lets an unattributed-// autopilot task borrow the parent autopilot creator's invoke rights after the-// request task has been verified against that exact parent; it never changes-// the new issue or task attribution.+// scope names the work the assignment belongs to. An unattributed autopilot+// run may borrow an autopilot authority only within it — the parent issue for+// child creation, the issue itself for an update, or the run's own verified+// autopilot when creating a parentless issue (MUL-4857, MUL-6691). It never+// changes the new issue's or task's attribution.//// Returns (statusCode, errorMessage). statusCode == 0 means the pair is valid;// callers should treat any non-zero status as a rejection and surface it back// to the client.-func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, workspaceID string, assigneeType pgtype.Text, assigneeID pgtype.UUID, delegationIssue *db.Issue) (int, string) {+func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, workspaceID string, assigneeType pgtype.Text, assigneeID pgtype.UUID, scope assignAuthorityScope) (int, string) {// Both unset → unassigned issue, valid.if !assigneeType.Valid && !assigneeID.Valid {return 0, ""@@ -3797,7 +3814,7 @@ func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, worreturn http.StatusBadRequest, "cannot assign to archived agent"}actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)- effectiveInvoker := h.effectiveInvocationAuthorityFromRequest(r, delegationIssue, actorType, actorID)+ effectiveInvoker := h.effectiveInvocationAuthorityFromRequest(r, scope, actorType, actorID, workspaceID)if !h.canInvokeAgent(ctx, agent, actorType, actorID, effectiveInvoker, workspaceID) {// Names the missing permission, not the target's configuration: the// old "private agent" wording both disclosed the agent's permission@@ -3826,7 +3843,7 @@ func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, worreturn http.StatusBadRequest, "squad leader is archived; cannot assign to this squad"}actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)- effectiveInvoker := h.effectiveInvocationAuthorityFromRequest(r, delegationIssue, actorType, actorID)+ effectiveInvoker := h.effectiveInvocationAuthorityFromRequest(r, scope, actorType, actorID, workspaceID)if !h.canInvokeAgent(ctx, leader, actorType, actorID, effectiveInvoker, workspaceID) {// Same wording rule as the agent branch above; "this squad"// avoids disclosing the leader agent's permission mode.@@ -4336,10 +4353,17 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {// Validate the resulting assignee pair when this batch update touches// either assignee field. Skip the issue silently on failure.+ //+ // Scoped PER ISSUE (prevIssue is this iteration's row), so one bound+ // issue in the batch can never lend its authority to the others: an+ // unbound entry simply fails the check and is skipped. This IS a real+ // agent-reachable authorization point — a task token authenticates as its+ // bound workspace member, so requireUserID above is satisfied and+ // resolveActor still classifies the caller as an agent (MUL-6691)._, batchTouchedType := rawUpdates["assignee_type"]_, batchTouchedID := rawUpdates["assignee_id"]if batchTouchedType || batchTouchedID {- if status, _ := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID, nil); status != 0 {+ if status, _ := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID, scopeExistingIssue(&prevIssue)); status != 0 {continue}}diff --git a/server/internal/handler/issue_autopilot_run_only_assignment_test.go b/server/internal/handler/issue_autopilot_run_only_assignment_test.gonew file mode 100644index 0000000000..e531718aef--- /dev/null+++ b/server/internal/handler/issue_autopilot_run_only_assignment_test.go@@ -0,0 +1,598 @@+package handler++import (+ "fmt"+ "net/http"+ "sync/atomic"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+)++// runOnlyFixtureSeq keeps leader agent names unique: the agent table has a+// per-workspace name constraint and one test builds two fixtures.+var runOnlyFixtureSeq atomic.Int64++// MUL-6691 / GH #7563. A schedule/webhook autopilot run carries no top-of-chain+// human originator by design (MUL-4302), so canInvokeAgent fails closed for a+// private agent. MUL-4857 restored the autopilot's authority for ONE action —+// creating a child under the autopilot's own issue — which left the reported+// flow broken in two places:+//+// - a run_only leader has no autopilot issue at all, so its top-level+// `issue create` had nothing to borrow against;+// - assigning an ALREADY-created issue went through UpdateIssue, which passed+// no scope whatsoever, so even the create_issue lineage MUL-4857 accepts was+// refused there. That is the exact reported symptom: DRA-109/DRA-110 got+// created and then could not be pointed at anyone.+//+// These tests pin the repaired positive paths and, more importantly, the bounds:+// the borrowed authority comes from the task's OWN accountable human, only while+// the task runs, only for work the task verifiably owns, and never from+// owner_fallback (which is the agent owner, i.e. the white-list itself).++// runOnlyAutopilotFixture is the run_only shape: a member-created autopilot with+// a live run, and a dispatched leader task that carries autopilot attribution+// (accountable set, originator NULL) and NO issue — the state the reported Squad+// scan runs in.+type runOnlyAutopilotFixture struct {+ LeaderAgentID string+ LeaderTaskID string+ AutopilotID string+ RunID string+ RuntimeID string+}++// newRunOnlyAutopilotFixture wires the fixture with accountableUserID as the+// task's accountable human (the trigger_owner MUL-4302 resolves) and+// targetAgentID as the autopilot's assignee.+func newRunOnlyAutopilotFixture(t *testing.T, targetAgentID, accountableUserID string, over ...testutil.Cols) runOnlyAutopilotFixture {+ t.Helper()++ runtimeID := handlerTestRuntimeID(t)+ leaderID := dbfx.Agent(t, fmt.Sprintf("mul6691-run-only-leader-%d", runOnlyFixtureSeq.Add(1)), runtimeID, testutil.Cols{+ "permission_mode": "public_to",+ "visibility": "workspace",+ })+ autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "title": "MUL-6691 run_only",+ "assignee_id": targetAgentID,+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": accountableUserID,+ })+ runID := dbfx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": autopilotID,+ "status": "running",+ "source": "schedule",+ })++ taskCols := testutil.Cols{+ "runtime_id": runtimeID,+ "status": "running",+ "autopilot_run_id": runID,+ "accountable_user_id": accountableUserID,+ "originator_source": "trigger_owner",+ }+ for _, o := range over {+ for k, v := range o {+ taskCols[k] = v+ }+ }+ taskID := dbfx.Task(t, leaderID, taskCols)++ return runOnlyAutopilotFixture{+ LeaderAgentID: leaderID,+ LeaderTaskID: taskID,+ AutopilotID: autopilotID,+ RunID: runID,+ RuntimeID: runtimeID,+ }+}++// topLevelIssueRequest is a parentless `issue create` with an assignee, spoken by+// an agent run — the request a run_only leader makes when it turns scan results+// into work.+func topLevelIssueRequest(t *testing.T, assigneeType, assigneeID, status, actorAgentID, taskID string) *http.Request {+ t.Helper()+ r := newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "MUL-6691 top-level " + t.Name(),+ "status": status,+ "priority": "low",+ "assignee_type": assigneeType,+ "assignee_id": assigneeID,+ "allow_duplicate": true,+ })+ if actorAgentID != "" {+ r.Header.Set("X-Agent-ID", actorAgentID)+ }+ if taskID != "" {+ r.Header.Set("X-Task-ID", taskID)+ }+ return r+}++// createUnassignedIssueAsRun has the run create a parentless issue with no+// assignee (always allowed) and returns its id. This is the DRA-109 state the+// report got stuck in.+func createUnassignedIssueAsRun(t *testing.T, actorAgentID, taskID string) string {+ t.Helper()+ r := newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "MUL-6691 unassigned " + t.Name(),+ "status": "todo",+ "priority": "low",+ "allow_duplicate": true,+ })+ r.Header.Set("X-Agent-ID", actorAgentID)+ r.Header.Set("X-Task-ID", taskID)++ var created IssueResponse+ testutil.Call(t, testHandler.CreateIssue, r).Want(http.StatusCreated).JSON(&created)+ cleanupAutopilotChildIssue(t, created.ID)+ return created.ID+}++// stampAutopilotAttribution gives a task the attribution a production autopilot+// enqueue writes (MUL-4302): an accountable human, no originator, and the source+// label that proves autopilot lineage. The raw fixtures insert bare task rows.+func stampAutopilotAttribution(t *testing.T, taskID, accountableUserID, source string) {+ t.Helper()+ dbfx.Exec(t, `+ UPDATE agent_task_queue+ SET accountable_user_id = $1, originator_source = $2+ WHERE id = $3+ `, accountableUserID, source, taskID)+}++// tasksFor returns (task count, non-null originator count) for an (issue, agent)+// pair, so a test can assert both "was it dispatched" and "did the borrowed+// authority leak into attribution".+func tasksFor(t *testing.T, issueID, agentID string) (int, int) {+ t.Helper()+ var total, withOriginator int+ dbfx.QueryRow(t, `+ SELECT count(*), count(originator_user_id) FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2+ `, issueID, agentID).Scan(&total, &withOriginator)+ return total, withOriginator+}++func TestCreateIssue_RunOnlyAutopilotLeaderAssignsPrivateWorker(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ t.Run("top-level create dispatches the private worker once, unattributed", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)++ var created IssueResponse+ testutil.Call(t, testHandler.CreateIssue,+ topLevelIssueRequest(t, "agent", workerID, "todo", fx.LeaderAgentID, fx.LeaderTaskID),+ ).Want(http.StatusCreated).JSON(&created)+ cleanupAutopilotChildIssue(t, created.ID)++ total, withOriginator := tasksFor(t, created.ID, workerID)+ if total != 1 {+ t.Fatalf("run_only top-level create must enqueue the private worker exactly once, got %d tasks", total)+ }+ if withOriginator != 0 {+ t.Fatal("borrowed authority is authorization-only; the worker task must stay unattributed")+ }+ })++ t.Run("top-level create accepts a private-leader squad", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ squadID := dbfx.Squad(t, "MUL-6691 Private Leader Squad", workerID)++ var created IssueResponse+ testutil.Call(t, testHandler.CreateIssue,+ topLevelIssueRequest(t, "squad", squadID, "todo", fx.LeaderAgentID, fx.LeaderTaskID),+ ).Want(http.StatusCreated).JSON(&created)+ cleanupAutopilotChildIssue(t, created.ID)++ total, withOriginator := tasksFor(t, created.ID, workerID)+ if total != 1 || withOriginator != 0 {+ t.Fatalf("squad assignment must dispatch its private leader once and unattributed, got %d tasks (%d attributed)", total, withOriginator)+ }+ })++ t.Run("sub-issue under an issue the run created is admitted", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ parentID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)++ var created IssueResponse+ testutil.Call(t, testHandler.CreateIssue,+ autopilotChildIssueRequest(t, "agent", workerID, parentID, "todo", fx.LeaderAgentID, fx.LeaderTaskID),+ ).Want(http.StatusCreated).JSON(&created)+ cleanupAutopilotChildIssue(t, created.ID)+ })++ t.Run("denials", func(t *testing.T) {+ cases := []struct {+ name string+ // setup returns the actor agent id and task id used for the request.+ setup func(t *testing.T, workerID, ownerID, plainMemberID string) (string, string)+ }{+ {+ // A finished run must not keep lending its authority.+ name: "task is no longer running",+ setup: func(t *testing.T, workerID, ownerID, _ string) (string, string) {+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID, testutil.Cols{"status": "completed"})+ return fx.LeaderAgentID, fx.LeaderTaskID+ },+ },+ {+ // owner_fallback names the AGENT OWNER, so honouring it would let+ // any unattributed run invoke its own owner's private agents.+ name: "originator_source is owner_fallback",+ setup: func(t *testing.T, workerID, ownerID, _ string) (string, string) {+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID, testutil.Cols{"originator_source": "owner_fallback"})+ return fx.LeaderAgentID, fx.LeaderTaskID+ },+ },+ {+ // delegation is a DESCENDANT run; authority must not propagate.+ name: "originator_source is delegation",+ setup: func(t *testing.T, workerID, ownerID, _ string) (string, string) {+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID, testutil.Cols{"originator_source": "delegation"})+ return fx.LeaderAgentID, fx.LeaderTaskID+ },+ },+ {+ name: "attribution stamp is missing",+ setup: func(t *testing.T, workerID, ownerID, _ string) (string, string) {+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID, testutil.Cols{+ "originator_source": nil,+ "accountable_user_id": nil,+ })+ return fx.LeaderAgentID, fx.LeaderTaskID+ },+ },+ {+ // The accountable human simply has no rights on the target.+ name: "accountable user cannot invoke the target",+ setup: func(t *testing.T, workerID, _, plainMemberID string) (string, string) {+ fx := newRunOnlyAutopilotFixture(t, workerID, plainMemberID)+ return fx.LeaderAgentID, fx.LeaderTaskID+ },+ },+ {+ // Accountable is the agent owner but no longer (or never) a member+ // of this workspace.+ name: "accountable user is not a workspace member",+ setup: func(t *testing.T, workerID, ownerID, _ string) (string, string) {+ // Email keyed to this test's agent id so the row is unique;+ // the owner_id is restored on cleanup (registered AFTER the+ // user, so it runs BEFORE the user delete) to keep the FK+ // from stranding the row.+ outsiderID := dbfx.User(t, "MUL-6691 Outsider",+ fmt.Sprintf("mul6691-outsider-%[email protected]", workerID))+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1 WHERE id = $2`, outsiderID, workerID)+ t.Cleanup(func() {+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1 WHERE id = $2`, ownerID, workerID)+ })+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID, testutil.Cols{"accountable_user_id": outsiderID})+ return fx.LeaderAgentID, fx.LeaderTaskID+ },+ },+ {+ // Lineage is fine but the speaking actor is not the task's agent.+ name: "actor is not the task agent",+ setup: func(t *testing.T, workerID, ownerID, _ string) (string, string) {+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ return workerID, fx.LeaderTaskID+ },+ },+ {+ // No autopilot run behind the task at all.+ name: "task belongs to no autopilot run",+ setup: func(t *testing.T, workerID, ownerID, _ string) (string, string) {+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID, testutil.Cols{"autopilot_run_id": nil})+ return fx.LeaderAgentID, fx.LeaderTaskID+ },+ },+ {+ // The run's autopilot lives in another workspace.+ name: "autopilot run belongs to another workspace",+ setup: func(t *testing.T, workerID, ownerID, _ string) (string, string) {+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ foreignWorkspaceID := dbfx.Workspace(t, "MUL-6691 Foreign", "mul6691-foreign-"+workerID[:8])+ dbfx.Exec(t, `UPDATE autopilot SET workspace_id = $1 WHERE id = $2`, foreignWorkspaceID, fx.AutopilotID)+ return fx.LeaderAgentID, fx.LeaderTaskID+ },+ },+ {+ // A real originator always wins, even when it has fewer rights+ // than the accountable human would have lent.+ name: "real originator without rights is not replaced",+ setup: func(t *testing.T, workerID, ownerID, plainMemberID string) (string, string) {+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID, testutil.Cols{+ "originator_user_id": plainMemberID,+ "accountable_user_id": plainMemberID,+ "originator_source": "direct_human",+ })+ return fx.LeaderAgentID, fx.LeaderTaskID+ },+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ workerID, ownerID, plainMemberID := privateAgentTestFixture(t)+ actorAgentID, taskID := tc.setup(t, workerID, ownerID, plainMemberID)++ testutil.Call(t, testHandler.CreateIssue,+ topLevelIssueRequest(t, "agent", workerID, "todo", actorAgentID, taskID),+ ).Want(http.StatusForbidden)++ if count := dbfx.Count(t,+ `SELECT count(*) FROM issue WHERE workspace_id = $1 AND title = $2`,+ testWorkspaceID, "MUL-6691 top-level "+t.Name()); count != 0 {+ t.Fatalf("refused create left %d issue rows behind", count)+ }+ })+ }+ })+}++func TestUpdateIssue_AutopilotLeaderAssignsPrivateWorker(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ // The reported symptom, end to end: create unassigned, then assign.+ t.Run("run_only run assigns an issue it created", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ issueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)++ agentAssigns(t, fx.LeaderAgentID, fx.LeaderTaskID, issueID, workerID).Want(http.StatusOK)++ total, withOriginator := tasksFor(t, issueID, workerID)+ if total != 1 {+ t.Fatalf("assignment must dispatch the private worker exactly once, got %d tasks", total)+ }+ if withOriginator != 0 {+ t.Fatal("borrowed authority is authorization-only; the worker task must stay unattributed")+ }+ })++ t.Run("run_only run assigns a private-leader squad on an issue it created", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ squadID := dbfx.Squad(t, "MUL-6691 Update Squad", workerID)+ issueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)++ testutil.Call(t, testHandler.UpdateIssue, testutil.WithURLParams(+ asRun(newRequest(http.MethodPatch, "/api/issues/"+issueID, map[string]any{+ "assignee_type": "squad",+ "assignee_id": squadID,+ }), fx.LeaderAgentID, fx.LeaderTaskID),+ "id", issueID,+ )).Want(http.StatusOK)+ })++ // create_issue mode: the same lineage MUL-4857 already accepts for child+ // creation now also works for the assignment verb — but ONLY through the+ // precise accountable-human rule, never through the coarse creator fallback.+ t.Run("create_issue leader with an attribution stamp assigns via its accountable human", func(t *testing.T) {+ workerID, ownerID, plainMemberID := privateAgentTestFixture(t)+ fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")+ // Production stamps this task trigger_owner/accountable (MUL-4302); the+ // fixture does not, so set it explicitly to exercise that branch. Point+ // the autopilot's creator at someone with no rights so ONLY the+ // accountable human can carry the assignment.+ dbfx.Exec(t, `UPDATE autopilot SET created_by_id = $1 WHERE id = $2`, plainMemberID, fx.AutopilotID)+ stampAutopilotAttribution(t, fx.LeaderTaskID, ownerID, "trigger_owner")++ agentAssigns(t, fx.LeaderAgentID, fx.LeaderTaskID, uuidToString(fx.Issue.ID), workerID).Want(http.StatusOK)+ })++ // Review must-fix 2: autopilotDelegationAuthority performs no liveness or+ // attribution check of its own, so it stays confined to the child-creation+ // surface where it already shipped. On the assign verb, a task that fails the+ // strict rule must NOT be rescued by the autopilot's creator having rights.+ t.Run("creator fallback does not reach the assign verb", func(t *testing.T) {+ cases := []struct {+ name string+ accountable string // "" leaves accountable_user_id NULL+ originatorSource any // nil leaves originator_source NULL+ taskStatus string+ }{+ // The autopilot creator (ownerID) owns the target throughout, so any+ // 200 here would mean the fallback carried the request.+ {name: "no attribution stamp at all", originatorSource: nil, taskStatus: "running"},+ {name: "owner_fallback", accountable: "owner", originatorSource: "owner_fallback", taskStatus: "running"},+ {name: "delegation", accountable: "owner", originatorSource: "delegation", taskStatus: "running"},+ {name: "task no longer running", accountable: "owner", originatorSource: "trigger_owner", taskStatus: "completed"},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")+ accountable := any(nil)+ if tc.accountable == "owner" {+ accountable = ownerID+ }+ dbfx.Exec(t, `+ UPDATE agent_task_queue+ SET accountable_user_id = $1, originator_source = $2, status = $3+ WHERE id = $4+ `, accountable, tc.originatorSource, tc.taskStatus, fx.LeaderTaskID)++ agentAssigns(t, fx.LeaderAgentID, fx.LeaderTaskID, uuidToString(fx.Issue.ID), workerID).+ Want(http.StatusForbidden)+ })+ }+ })++ // The request path requires a live run on BOTH branches, including the+ // legacy child-creation fallback.+ t.Run("creator fallback still requires a running task on child creation", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed' WHERE id = $1`, fx.LeaderTaskID)++ testutil.Call(t, testHandler.CreateIssue,+ autopilotChildIssueRequest(t, "agent", workerID, uuidToString(fx.Issue.ID), "backlog", fx.LeaderAgentID, fx.LeaderTaskID),+ ).Want(http.StatusForbidden)+ })++ // Review must-fix 1: a create_issue-mode task must not escape its+ // `task.issue_id == issue.id` bound by creating a fresh top-level issue —+ // which stamps origin_id with its own task id — and assigning that instead.+ t.Run("create_issue leader cannot launder authority through a new top-level issue", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")+ stampAutopilotAttribution(t, fx.LeaderTaskID, ownerID, "trigger_owner")++ // Creating the unassigned issue is allowed (no assignee, no gate).+ launderedID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)++ // Assigning it is not: the issue is agent_create-bound to this task, but+ // the task has no run_only lineage to prove.+ agentAssigns(t, fx.LeaderAgentID, fx.LeaderTaskID, launderedID, workerID).Want(http.StatusForbidden)++ // Nor is creating a private-assignee child under it.+ testutil.Call(t, testHandler.CreateIssue,+ autopilotChildIssueRequest(t, "agent", workerID, launderedID, "todo", fx.LeaderAgentID, fx.LeaderTaskID),+ ).Want(http.StatusForbidden)++ if total, _ := tasksFor(t, launderedID, workerID); total != 0 {+ t.Fatalf("laundered assignment enqueued %d tasks", total)+ }+ })++ t.Run("run_only run cannot assign an issue it did not create", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ foreignIssueID := seedBareIssue(t, fx.LeaderAgentID)++ agentAssigns(t, fx.LeaderAgentID, fx.LeaderTaskID, foreignIssueID, workerID).Want(http.StatusForbidden)++ if total, _ := tasksFor(t, foreignIssueID, workerID); total != 0 {+ t.Fatalf("refused assignment enqueued %d tasks", total)+ }+ })++ t.Run("run_only run cannot assign an issue created by a sibling run", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ owning := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ issueID := createUnassignedIssueAsRun(t, owning.LeaderAgentID, owning.LeaderTaskID)++ // A second, equally well-formed run of its own autopilot. Binding on the+ // creating TASK (not the autopilot) is what keeps it out.+ sibling := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ agentAssigns(t, sibling.LeaderAgentID, sibling.LeaderTaskID, issueID, workerID).Want(http.StatusForbidden)+ })++ t.Run("plain member is still refused", func(t *testing.T) {+ workerID, _, plainMemberID := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, plainMemberID)+ issueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)++ testutil.Call(t, testHandler.UpdateIssue, testutil.WithURLParams(+ newRequestAs(plainMemberID, http.MethodPatch, "/api/issues/"+issueID, map[string]any{+ "assignee_type": "agent",+ "assignee_id": workerID,+ }),+ "id", issueID,+ )).Want(http.StatusForbidden)+ })+}++// batchAssignAsRun points every issue in issueIDs at targetAgentID through+// BatchUpdateIssues, speaking as an agent run.+//+// The header trio mirrors a real task token: the auth middleware writes+// X-User-ID (the token's bound member), X-Agent-ID and X-Task-ID together, so+// this endpoint's requireUserID is satisfied while resolveActor still classifies+// the caller as an agent. headerUserID is deliberately a member with NO rights on+// the target, so any success proves the authority came from the run's accountable+// human rather than from the header user.+func batchAssignAsRun(t *testing.T, headerUserID, agentID, taskID, targetAgentID string, issueIDs ...string) *testutil.Response {+ t.Helper()+ req := newRequestAs(headerUserID, http.MethodPost, "/api/issues/batch?workspace_id="+testWorkspaceID, map[string]any{+ "issue_ids": issueIDs,+ "updates": map[string]any{+ "assignee_type": "agent",+ "assignee_id": targetAgentID,+ },+ })+ req.Header.Set("X-Agent-ID", agentID)+ req.Header.Set("X-Task-ID", taskID)+ return testutil.Call(t, testHandler.BatchUpdateIssues, req)+}++// assigneeOf returns an issue's assignee agent id, or "" when unassigned.+func assigneeOf(t *testing.T, issueID string) string {+ t.Helper()+ var assignee *string+ dbfx.QueryRow(t, `SELECT assignee_id::text FROM issue WHERE id = $1`, issueID).Scan(&assignee)+ if assignee == nil {+ return ""+ }+ return *assignee+}++// Review must-fix 3: BatchUpdateIssues is a real agent-reachable authorization+// point, not just defence in depth, so the per-issue scope needs its own+// coverage — both that it works and that it cannot be widened.+func TestBatchUpdateIssues_AutopilotAuthorityIsPerIssue(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ t.Run("bound issue is updated and a foreign issue in the same batch is not", func(t *testing.T) {+ workerID, ownerID, plainMemberID := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ ownIssueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)+ foreignIssueID := seedBareIssue(t, fx.LeaderAgentID)++ batchAssignAsRun(t, plainMemberID, fx.LeaderAgentID, fx.LeaderTaskID, workerID, ownIssueID, foreignIssueID).+ Want(http.StatusOK)++ if got := assigneeOf(t, ownIssueID); got != workerID {+ t.Fatalf("bound issue assignee = %q, want %q", got, workerID)+ }+ if got := assigneeOf(t, foreignIssueID); got != "" {+ t.Fatalf("foreign issue in the same batch was assigned to %q; per-issue scoping leaked", got)+ }+ if total, _ := tasksFor(t, foreignIssueID, workerID); total != 0 {+ t.Fatalf("foreign issue enqueued %d tasks", total)+ }+ })++ t.Run("refuses the create_issue laundering path", func(t *testing.T) {+ workerID, ownerID, plainMemberID := privateAgentTestFixture(t)+ fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")+ stampAutopilotAttribution(t, fx.LeaderTaskID, ownerID, "trigger_owner")+ launderedID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)++ batchAssignAsRun(t, plainMemberID, fx.LeaderAgentID, fx.LeaderTaskID, workerID, launderedID).+ Want(http.StatusOK)++ if got := assigneeOf(t, launderedID); got != "" {+ t.Fatalf("laundered issue was assigned to %q; the run_only lineage check did not apply", got)+ }+ })++ t.Run("refuses a task that is no longer running", func(t *testing.T) {+ workerID, ownerID, plainMemberID := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ ownIssueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed' WHERE id = $1`, fx.LeaderTaskID)++ batchAssignAsRun(t, plainMemberID, fx.LeaderAgentID, fx.LeaderTaskID, workerID, ownIssueID).+ Want(http.StatusOK)++ if got := assigneeOf(t, ownIssueID); got != "" {+ t.Fatalf("completed task assigned the issue to %q", got)+ }+ })+}diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.goindex 4aaa415978..0b91f0618d 100644--- a/server/internal/handler/source_context.go+++ b/server/internal/handler/source_context.go@@ -641,7 +641,7 @@ func (h *Handler) createManualCommentSubIssue(w http.ResponseWriter, r *http.Req}assigneeID = parsed}- if code, message := h.validateAssigneePair(r.Context(), r, util.UUIDToString(workspaceID), assigneeType, assigneeID, nil); code != 0 {+ if code, message := h.validateAssigneePair(r.Context(), r, util.UUIDToString(workspaceID), assigneeType, assigneeID, scopeNoDelegation()); code != 0 {writeError(w, code, message)return errSourceContextResponseWritten}@@ -754,7 +754,7 @@ func (h *Handler) prepareAgentCommentSubIssue(w http.ResponseWriter, r *http.Req}agentID = parsed}- if status, message := h.validateAssigneePair(r.Context(), r, util.UUIDToString(workspaceID), pgtype.Text{String: "agent", Valid: true}, agentID, nil); status != 0 {+ if status, message := h.validateAssigneePair(r.Context(), r, util.UUIDToString(workspaceID), pgtype.Text{String: "agent", Valid: true}, agentID, scopeNoDelegation()); status != 0 {writeError(w, status, message)return nil, errSourceContextResponseWritten}