Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6951 fix(autopilot): carry the trigger creator's authorization on scheduled runs (#7918)
Bohan Jiang765321f05392
diff --git a/server/cmd/server/autopilot_dispatch_for_plan_test.go b/server/cmd/server/autopilot_dispatch_for_plan_test.goindex 131088495c..4da90fa89c 100644--- a/server/cmd/server/autopilot_dispatch_for_plan_test.go+++ b/server/cmd/server/autopilot_dispatch_for_plan_test.go@@ -69,6 +69,10 @@ func TestDispatchAutopilotForPlanIsIdempotent(t *testing.T) {Enabled: true,CronExpression: pgtype.Text{String: "*/5 * * * *", Valid: true},Timezone: pgtype.Text{String: "UTC", Valid: true},+ // MUL-6951: the trigger's creator is the human its runs act as, and+ // dispatch fails closed without one.+ CreatedByType: pgtype.Text{String: "member", Valid: true},+ CreatedByID: ap.CreatedByID,})if err != nil {t.Fatalf("CreateAutopilotTrigger: %v", err)@@ -186,7 +190,8 @@ func TestDispatchAutopilotSuppressesRecentDuplicateIssue(t *testing.T) {_, _ = testPool.Exec(bg, `DELETE FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title)})- first, err := autopilotSvc.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ dupTrigger := seedAutopilotScheduleTrigger(t, queries, ap)+ first, err := autopilotSvc.DispatchAutopilot(ctx, ap, dupTrigger, "manual", nil)if err != nil {t.Fatalf("first DispatchAutopilot: %v", err)}@@ -194,7 +199,7 @@ func TestDispatchAutopilotSuppressesRecentDuplicateIssue(t *testing.T) {t.Fatalf("first dispatch = %+v, want issue_created with issue_id", first)}- second, err := autopilotSvc.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ second, err := autopilotSvc.DispatchAutopilot(ctx, ap, dupTrigger, "manual", nil)if err != nil {t.Fatalf("second DispatchAutopilot: %v", err)}@@ -316,6 +321,9 @@ func TestDispatchAutopilotForPlanRecoversPartialRun(t *testing.T) {Enabled: true,CronExpression: pgtype.Text{String: "*/5 * * * *", Valid: true},Timezone: pgtype.Text{String: "UTC", Valid: true},+ // MUL-6951: see the sibling fixture above.+ CreatedByType: pgtype.Text{String: "member", Valid: true},+ CreatedByID: ap.CreatedByID,})if err != nil {t.Fatalf("CreateAutopilotTrigger: %v", err)diff --git a/server/cmd/server/autopilot_listeners_test.go b/server/cmd/server/autopilot_listeners_test.goindex c93ee88367..f902ea4efe 100644--- a/server/cmd/server/autopilot_listeners_test.go+++ b/server/cmd/server/autopilot_listeners_test.go@@ -11,6 +11,27 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated")+// seedAutopilotScheduleTrigger gives an autopilot a schedule trigger recording its+// creator. Since MUL-6951 an automatic dispatch resolves the human it acts as from+// this row — and admits the assignee agent as that human — so a dispatch with no+// trigger has no principal and fails closed.+func seedAutopilotScheduleTrigger(t *testing.T, queries *db.Queries, ap db.Autopilot) pgtype.UUID {+ t.Helper()+ trig, err := queries.CreateAutopilotTrigger(context.Background(), db.CreateAutopilotTriggerParams{+ AutopilotID: ap.ID,+ Kind: "schedule",+ Enabled: true,+ CronExpression: pgtype.Text{String: "*/5 * * * *", Valid: true},+ Timezone: pgtype.Text{String: "UTC", Valid: true},+ CreatedByType: pgtype.Text{String: "member", Valid: ap.CreatedByType == "member"},+ CreatedByID: ap.CreatedByID,+ })+ if err != nil {+ t.Fatalf("seed schedule trigger: %v", err)+ }+ return trig.ID+}+func TestAutopilotRunOnlyTaskTerminalEventsUpdateRun(t *testing.T) {ctx := context.Background()queries := db.New(testPool)@@ -79,7 +100,7 @@ func TestAutopilotRunOnlyTaskTerminalEventsUpdateRun(t *testing.T) {}})- run, err := autopilotSvc.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ run, err := autopilotSvc.DispatchAutopilot(ctx, ap, seedAutopilotScheduleTrigger(t, queries, ap), "manual", nil)if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}@@ -172,7 +193,7 @@ func dispatchCreateIssueAutopilot(t *testing.T, title string) linkedIssueAutopil_, _ = testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, ap.ID)})- run, err := autopilotSvc.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "schedule", nil)+ run, err := autopilotSvc.DispatchAutopilot(ctx, ap, seedAutopilotScheduleTrigger(t, queries, ap), "schedule", nil)if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}@@ -369,7 +390,7 @@ func TestAutopilotDispatchSkipsWhenRuntimeOffline(t *testing.T) {_, _ = testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, ap.ID)})- run, err := autopilotSvc.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "schedule", nil)+ run, err := autopilotSvc.DispatchAutopilot(ctx, ap, seedAutopilotScheduleTrigger(t, queries, ap), "schedule", nil)if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}@@ -458,7 +479,7 @@ func TestAutopilotCreateIssueDispatchCreatesIssueWhenRuntimeOffline(t *testing.T_, _ = testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, ap.ID)})- run, err := autopilotSvc.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "schedule", nil)+ run, err := autopilotSvc.DispatchAutopilot(ctx, ap, seedAutopilotScheduleTrigger(t, queries, ap), "schedule", nil)if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}@@ -570,7 +591,7 @@ func TestManualTriggerDoesNotErrorOnPostAdmissionSkip(t *testing.T) {_, _ = testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, ap.ID)})- run, err := autopilotSvc.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ run, err := autopilotSvc.DispatchAutopilot(ctx, ap, seedAutopilotScheduleTrigger(t, queries, ap), "manual", nil)if err != nil {t.Fatalf("manual DispatchAutopilot returned error (would 500 the handler): %v", err)}diff --git a/server/cmd/server/autopilot_schedule_job_test.go b/server/cmd/server/autopilot_schedule_job_test.goindex 2f9d012e13..e6712cbf7b 100644--- a/server/cmd/server/autopilot_schedule_job_test.go+++ b/server/cmd/server/autopilot_schedule_job_test.go@@ -58,6 +58,10 @@ func setupAutopilotScheduleJob(t *testing.T, cron string) (db.AutopilotTrigger,Enabled: true,CronExpression: pgtype.Text{String: cron, Valid: true},Timezone: pgtype.Text{String: "UTC", Valid: true},+ // MUL-6951: the scheduler dispatches as this human; without it the run+ // has no principal and fails closed.+ CreatedByType: pgtype.Text{String: "member", Valid: true},+ CreatedByID: ap.CreatedByID,})if err != nil {t.Fatalf("CreateAutopilotTrigger: %v", err)@@ -640,6 +644,10 @@ func seedColdStartTrigger(t *testing.T, cron string) (db.AutopilotTrigger, *db.QEnabled: true,CronExpression: pgtype.Text{String: cron, Valid: true},Timezone: pgtype.Text{String: "UTC", Valid: true},+ // MUL-6951: the scheduler dispatches as this human; without it the run+ // has no principal and fails closed.+ CreatedByType: pgtype.Text{String: "member", Valid: true},+ CreatedByID: ap.CreatedByID,})if err != nil {t.Fatalf("CreateAutopilotTrigger: %v", err)diff --git a/server/internal/attribution/attribution.go b/server/internal/attribution/attribution.goindex 3da1b2592b..20374efe40 100644--- a/server/internal/attribution/attribution.go+++ b/server/internal/attribution/attribution.go@@ -12,12 +12,21 @@// into the Classify* functions so the rules remain side-effect-free and fully// unit-testable without a database.//-// Hard invariant (MUL-4302 §1.3): attribution is "on behalf of", never blame-// and never authorization. Nothing in this package is consulted for permission-// decisions — it labels provenance for visibility, audit, and cost only. In-// particular the accountable-human value stamped here mirrors the existing-// originator_user_id, which is computed by the caller; this package never-// widens or narrows who that human is.+// Hard invariant (MUL-4302 §1.3): the accountable human is "on behalf of", never+// blame. The SOURCE label is provenance only — no permission decision reads it.+//+// The originator (Result.UserID) IS the authorization value, and since MUL-6951+// this package decides it for autopilot runs: TriggerOwner names the human an+// armed autopilot acts as, which canInvokeAgent then honors. That grant is exactly+// that human's own rights — the gate is unchanged, only the principal handed to it+// — but it does mean a change to TriggerOwner is an AUTHORIZATION change, not a+// labelling one. Every other constructor here only mirrors a human the caller+// computed.+//+// It does NOT decide Composio access: since MUL-3963 the connected-apps overlay is+// built from the AGENT OWNER's connections and allow-list and ignores the+// originator entirely (integrations/composio/dispatch.go). Naming the originator+// here therefore hands out no third-party credentials.package attributionimport "github.com/jackc/pgx/v5/pgtype"@@ -43,17 +52,19 @@ const (// comment.source_task_id (a special case of delegation, MUL-4302 §3.3).SourceCommentSource Source = "comment_source"// SourceTriggerOwner — an autopilot schedule/webhook trigger enqueued the run;- // the accountable human is the member who CREATED that specific trigger (set up- // the schedule / registered the webhook). Preferred over rule_owner: a run is- // accountable to whoever armed the trigger that fired it, not to whoever last- // published the rule (MUL-4302; Bohan's refinement). originator stays NULL — an- // autonomous fire carries no human authorization — so this is the same authz-safe- // audit-only divergence as rule_owner.+ // the human is the member who CREATED that specific trigger (set up the schedule+ // / registered the webhook). Preferred over rule_owner: a run belongs to whoever+ // armed the trigger that fired it, not to whoever last published the rule+ // (MUL-4302; Bohan's refinement). Since MUL-6951 that human is the ORIGINATOR as+ // well as the accountable — arming a trigger authorizes the run the same way+ // clicking "run now" does — so this label marks HOW the human was resolved, not a+ // weaker grant. The label is what still distinguishes an autonomous fire from a+ // manual one in the audit trail.SourceTriggerOwner Source = "trigger_owner"- // SourceRuleOwner — an autopilot trigger enqueued the run but its creator is not- // recoverable (a trigger created before per-trigger creators were recorded); the- // accountable human degrades to the publisher of the rule's active version- // (MUL-4302 §3.4). Precise, but coarser than trigger_owner.+ // SourceRuleOwner — an autopilot trigger enqueued the run but records no+ // provable creator (a trigger predating per-trigger creators); the ACCOUNTABLE+ // human degrades to the publisher of the rule's active version (MUL-4302 §3.4),+ // while authorization carries none. Precise for audit, deliberately powerless.SourceRuleOwner Source = "rule_owner"// SourceOwnerFallback — nothing above resolved a human, so attribution// degrades to the agent owner. This is DEGRADED, not compliance-grade, and@@ -136,14 +147,17 @@ const (// Result is the attribution stamped onto a queued run.//// - UserID is the AUTHORIZATION human the caller writes into-// originator_user_id. It is the value canInvokeAgent and the Composio overlay-// read; it is legitimately invalid (NULL) when no human authorized the run.+// originator_user_id. It is the value canInvokeAgent reads; it is legitimately+// invalid (NULL) when no human authorized the run. It does NOT select Composio+// connections — those follow the agent owner (MUL-3963).// - AccountableUserID is the AUDIT human written into accountable_user_id. The// one-way invariant (enforced by finalizeAttribution): when UserID is valid,// AccountableUserID equals it. When UserID is NULL (no human authorized the-// run), the two may diverge — rule_owner names the rule publisher and-// owner_fallback names the agent owner as the accountable human while-// authorization correctly carries none.+// run), the two may diverge — owner_fallback names the agent owner, and+// rule_owner the rule publisher, as the accountable human while authorization+// correctly carries none. trigger_owner is NOT such a case since MUL-6951: an+// armed autopilot carries its trigger creator's authorization, so both columns+// hold that human.//// The remaining fields are audit metadata written into the Phase 1 provenance// columns. Construct a Result through ClassifyComment / ClassifyDirect /@@ -354,15 +368,24 @@ func Unattributed(evidenceKind EvidenceKind, evidenceRefID pgtype.UUID) Result {return finalizeAttribution(Result{Source: SourceUnattributed, EvidenceKind: evidenceKind, EvidenceRefID: evidenceRefID})}-// RuleOwner builds attribution for an autopilot-triggered run (MUL-4302 §3.4).-// No human authorized it, so UserID (originator, the authorization value) stays-// NULL and canInvokeAgent / the Composio overlay keep seeing "no human"; the-// AUDIT-accountable human is publisherUserID — the member who published the active-// rule version — which is THE divergence the two-column split exists for-// (accountable set, originator NULL). ruleVersionID records which snapshot-// resolved it; evidence points the caller supplies (autopilot_run for run_only,-// the issue for create_issue). A missing publisher (system-published rule, or no-// version resolved yet) degrades to unattributed so we never fabricate a human.+// RuleOwner builds attribution for an autopilot-triggered run whose firing+// trigger records no provable creator (MUL-4302 §3.4) — the coarser fallback+// behind TriggerOwner. publisherUserID, the member who published the active rule+// version, becomes the AUDIT-accountable human only; UserID (the originator, the+// authorization value) stays NULL.+//+// This asymmetry with TriggerOwner is deliberate (MUL-6951, Elon review). The rule+// publisher never armed anything — it is a guess at "who probably owns this rule",+// recovered from a version snapshot. Promoting it to the authorization principal+// would hand a legacy trigger somebody's invoke rights without that person having+// authorized a single run. A run that lands here therefore carries no originator+// and the invoke gate fails closed, which is the intended outcome for a trigger+// too old to name its creator.+//+// ruleVersionID records which snapshot resolved it; evidence points the caller+// supplies (autopilot_run for run_only, the issue for create_issue). A missing+// publisher (system-published rule, or no version resolved yet) degrades to+// unattributed so we never fabricate a human.func RuleOwner(publisherUserID, ruleVersionID pgtype.UUID, evidenceKind EvidenceKind, evidenceRefID pgtype.UUID) Result {r := Result{RuleVersionID: ruleVersionID,@@ -379,12 +402,29 @@ func RuleOwner(publisherUserID, ruleVersionID pgtype.UUID, evidenceKind Evidence}// TriggerOwner builds attribution for an autopilot schedule/webhook run keyed to-// the human who created the firing trigger (MUL-4302; Bohan's refinement). Like-// RuleOwner, no human authorized the run, so UserID (originator) stays NULL and-// only the audit-accountable side is set — to creatorUserID, the trigger's member-// creator. Evidence is caller-supplied (autopilot_run for run_only, the issue for-// create_issue). An invalid creator degrades to unattributed so callers that lost-// the creator fall back to rule_owner rather than fabricating a human.+// the firing trigger's CREATOR (MUL-4302; MUL-6951). It sets UserID — the ORIGINATOR — so the run carries+// that human's authorization context, exactly as a manual "run now" by the same+// person would (MUL-6951; Bohan's call). finalizeAttribution mirrors it onto the+// accountable side, satisfying the originator == accountable invariant migration+// 190/197 enforces. Evidence is caller-supplied (autopilot_run for run_only, the+// issue for create_issue). An invalid creator degrades to unattributed so callers+// that lost the creator fall back to rule_owner rather than fabricating a human.+//+// WHY the originator and not accountable-only (MUL-6951): arming a trigger IS the+// authorization — the same act as clicking "run now", just deferred. Withholding+// the originator did not remove that authority, it only made every capability the+// automation legitimately needed arrive as a separately-bounded borrow path+// (MUL-4857, then MUL-6691, then #7902), each with a hand-written scope no+// operator could see. Carrying the human here grants exactly that human's own+// rights — canInvokeAgent still runs unchanged, so this is not an escalation —+// and lets those borrow paths be deleted.+//+// The caller (service.ResolveAutopilotTriggerPrincipal) resolves that human from+// the trigger's IMMUTABLE created_by, never published_by: published_by transfers+// on a substantive edit, so using it would let a collaborator editing a cron+// expression silently move whose rights the automation runs with. The same+// resolver feeds dispatch admission, so one run can never be admitted as one human+// and executed as another.func TriggerOwner(creatorUserID pgtype.UUID, evidenceKind EvidenceKind, evidenceRefID pgtype.UUID) Result {r := Result{EvidenceKind: evidenceKind,@@ -392,7 +432,7 @@ func TriggerOwner(creatorUserID pgtype.UUID, evidenceKind EvidenceKind, evidence}if creatorUserID.Valid {r.Source = SourceTriggerOwner- r.AccountableUserID = creatorUserID+ r.UserID = creatorUserID} else {r.Source = SourceUnattributed}diff --git a/server/internal/attribution/attribution_test.go b/server/internal/attribution/attribution_test.goindex 155c43c232..d56c0fb764 100644--- a/server/internal/attribution/attribution_test.go+++ b/server/internal/attribution/attribution_test.go@@ -312,10 +312,16 @@ func TestClassifyDirect_AgentCreateInheritsOriginAsDelegation(t *testing.T) {// TestAccountableMirrorsOriginatorInvariant is the MUL-4302 §11 acceptance check// at the classification layer: EVERY result the resolver produces must satisfy the// ONE-WAY invariant `originator (UserID) IS NOT NULL ⟹ accountable == originator`.-// When UserID is NULL the two MAY diverge (rule_owner / owner_fallback name an-// accountable human while authorization carries none), so the invariant only-// constrains the valid-originator direction. finalizeAttribution centralizes this;-// the test guards against a future Classify path forgetting to route through it.+// When UserID is NULL the two MAY diverge (owner_fallback names an accountable+// human while authorization carries none), so the invariant only constrains the+// valid-originator direction. finalizeAttribution centralizes this; the test+// guards against a future Classify path forgetting to route through it.+//+// Since MUL-6951 trigger_owner is NOT in that divergent set — an armed autopilot+// carries its trigger creator's authorization — so it is excluded from the+// allow-list below and the check proves it populates the originator. rule_owner+// stays divergent on purpose: it is a guess at who owns a rule, and must never+// become an authorization identity (Elon review).func TestAccountableMirrorsOriginatorInvariant(t *testing.T) {results := []Result{ClassifyComment(CommentFacts{CommentID: comment, AuthorType: "member", AuthorID: human}, SourceCommentSource),@@ -331,6 +337,8 @@ func TestAccountableMirrorsOriginatorInvariant(t *testing.T) {Unattributed(EvidenceAutopilotRun, srcTask),RuleOwner(human, ruleVer, EvidenceAutopilotRun, srcTask), // divergent: accountable set, originator NULLRuleOwner(pgtype.UUID{}, ruleVer, EvidenceAutopilotRun, srcTask), // no publisher → unattributed+ TriggerOwner(human, EvidenceAutopilotRun, srcTask), // originator = trigger owner (MUL-6951)+ TriggerOwner(pgtype.UUID{}, EvidenceAutopilotRun, srcTask), // no owner → unattributed}for i, r := range results {// One-way invariant: a valid originator must equal accountable.@@ -341,9 +349,9 @@ func TestAccountableMirrorsOriginatorInvariant(t *testing.T) {// accountable with a NULL originator is allowed (divergence), but the// reverse — originator set from accountable — must never happen implicitly.if r.AccountableUserID.Valid && !r.UserID.Valid &&- r.Source != SourceRuleOwner && r.Source != SourceTriggerOwner && r.Source != SourceOwnerFallback &&+ r.Source != SourceOwnerFallback && r.Source != SourceRuleOwner &&r.Source != SourceDelegation && r.Source != SourceCommentSource {- t.Errorf("result[%d]: accountable set with NULL originator only allowed for delegation/comment_source/trigger_owner/rule_owner/owner_fallback, got source=%q", i, r.Source)+ t.Errorf("result[%d]: accountable set with NULL originator only allowed for delegation/comment_source/rule_owner/owner_fallback, got source=%q", i, r.Source)}}}@@ -367,8 +375,9 @@ func TestDirectHumanRun(t *testing.T) {}func TestRuleOwner(t *testing.T) {- // The divergence case: an autopilot run has NO authorizing human (originator- // NULL) but IS accountable to the rule publisher.+ // The divergent case, and deliberately so (MUL-6951, Elon review): the rule+ // publisher never armed anything, so it is accountable for audit but carries no+ // authorization. A run that lands here fails the invoke gate closed.got := RuleOwner(human, ruleVer, EvidenceAutopilotRun, issue)if got.Source != SourceRuleOwner {t.Fatalf("source = %q, want rule_owner", got.Source)@@ -397,9 +406,9 @@ func TestRuleOwner(t *testing.T) {}func TestTriggerOwner(t *testing.T) {- // The divergence case (MUL-4302; Bohan): an autopilot schedule/webhook run has- // NO authorizing human (originator NULL) but IS accountable to the member who- // created the firing trigger.+ // MUL-4302 (Bohan) resolves the trigger's human; MUL-6951 makes the trigger+ // CREATOR the run's ORIGINATOR, so a scheduled fire carries the same+ // authorization their manual "run now" would.got := TriggerOwner(human, EvidenceAutopilotRun, issue)if got.Source != SourceTriggerOwner {t.Fatalf("source = %q, want trigger_owner", got.Source)@@ -407,8 +416,8 @@ func TestTriggerOwner(t *testing.T) {if !got.Source.Precise() {t.Errorf("trigger_owner must be a precise source")}- if got.UserID.Valid {- t.Errorf("trigger_owner must NOT set originator (authorization stays NULL), got %v", got.UserID)+ if got.UserID != human {+ t.Errorf("originator should be the trigger creator, got %v", got.UserID)}if got.AccountableUserID != human {t.Errorf("accountable should be the trigger creator, got %v", got.AccountableUserID)diff --git a/server/internal/handler/agent_access.go b/server/internal/handler/agent_access.goindex bce9f095b2..62470b5ace 100644--- a/server/internal/handler/agent_access.go+++ b/server/internal/handler/agent_access.go@@ -6,7 +6,6 @@ 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")@@ -209,6 +208,17 @@ func memberAllowedToViewAgent(agent db.Agent, targets []db.AgentInvocationTarget// (set by the CLI on every request), matching// TaskService.resolveOriginatorFromTriggerComment. Returns "" when no human// can be attributed — canInvokeAgent then fails closed for member/team targets.+//+// A TERMINAL task lends nothing (MUL-6951, Elon review). A run represents its+// human only while it is live: once the task is completed / failed / cancelled,+// the work that human authorized is over. Task-token revocation at the terminal+// transition is the primary guard, but it is best-effort and explicitly non-fatal+// on failure (TaskService, MUL-2600) with a 24h token expiry behind it, so a+// revocation that fails would otherwise leave a window in which a finished run+// keeps spending a member's invoke rights. This check closes that window at the+// authorization boundary rather than the auth boundary, so a terminal task can+// still complete ordinary API work (posting its final comment) without being able+// to start new work as its human.func (h *Handler) invokeOriginatorFromRequest(r *http.Request, actorType, actorID string) string {if actorType == "member" {return actorID@@ -217,6 +227,9 @@ func (h *Handler) invokeOriginatorFromRequest(r *http.Request, actorType, actorIif taskIDHeader := r.Header.Get("X-Task-ID"); taskIDHeader != "" {if taskUUID, err := util.ParseUUID(taskIDHeader); err == nil {if task, err := h.Queries.GetAgentTask(r.Context(), taskUUID); err == nil {+ if isTerminalTaskStatus(task.Status) {+ return ""+ }return uuidToString(task.OriginatorUserID)}}@@ -225,382 +238,19 @@ 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 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 != "" {- return originatorUserID- }- 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)+// isTerminalTaskStatus reports whether a task has finished, in any of the three+// ways it can. Mirrors the agent_task_queue status CHECK constraint; a status the+// constraint does not know is treated as NOT terminal so an added in-flight state+// keeps working (an added terminal state would need adding here, which the invoke+// gate's fail-closed default makes visible rather than silent).+func isTerminalTaskStatus(status string) bool {+ switch status {+ case "completed", "failed", "cancelled":+ return true}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 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, 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:-// - 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)-}-// 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@@ -609,10 +259,9 @@ func (h *Handler) autopilotDelegationAuthorityFromComment(ctx context.Context, i//// 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).+// another issue. That is safe for the invoke gate because the gate keys on the+// task's own originator (MUL-6951) — a human who already holds those rights —+// rather than on a same-issue binding standing in for one.func (h *Handler) commentSourceTaskID(r *http.Request) pgtype.UUID {task, ok := h.taskFromRequestHeader(r)if !ok {diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex 2ffd5c7d32..0549157b49 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -1049,18 +1049,21 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {}// A substantive change (target / enabled-state / execution mode) republishes the- // rule: append a new version with THIS member as publisher, so a later run- // attributes to whoever last changed what the rule does — not the original- // creator. Cosmetic edits (title / description / template) write no version and- // leave accountability with the previous publisher (MUL-4302 §3.4).+ // rule: append a new version with THIS member as publisher, recording who last+ // changed what the rule does. Cosmetic edits (title / description / template)+ // write no version (MUL-4302 §3.4). Since MUL-6951 the rule publisher is an+ // AUDIT value only — it is the coarse fallback a run degrades to when its+ // trigger records no creator, and such a run carries no authorization.if autopilotRuleSubstantiveChange(prev, autopilot) {if err := h.recordAutopilotRuleVersion(r.Context(), qtx, autopilot, "member", parseUUID(userID)); err != nil {writeError(w, http.StatusInternalServerError, "failed to update autopilot")return}- // An autopilot-level substantive edit governs every trigger, so responsibility- // for each firing trigger transfers to this editor (source=trigger_owner). A- // trigger-scoped edit re-stamps only its own row (see UpdateAutopilotTrigger).+ // An autopilot-level substantive edit governs every trigger, so CONFIG+ // responsibility for each one transfers to this editor. A trigger-scoped edit+ // re-stamps only its own row (see UpdateAutopilotTrigger). Since MUL-6951 this+ // moves published_by alone: the runs each trigger fires keep acting as, and+ // stay accountable to, that trigger's immutable created_by.if err := qtx.SetAutopilotTriggerPublishersByAutopilot(r.Context(), db.SetAutopilotTriggerPublishersByAutopilotParams{AutopilotID: autopilot.ID,PublishedByType: pgtype.Text{String: "member", Valid: true},@@ -1496,11 +1499,17 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)NextRunAt: nextRunAt,Label: ptrToText(req.Label),WebhookToken: webhookToken,- // Seed the responsible publisher = creator; a later substantive edit re-stamps- // it to the editor so runs attribute to whoever last shaped this trigger- // (source=trigger_owner, MUL-4302).+ // published_by records who is currently responsible for this trigger's+ // CONFIG: seeded to the creator, re-stamped to whoever later substantively+ // edits it (MUL-4302). Since MUL-6951 it no longer decides anything about a+ // run — neither authorization nor the task's accountable human — so an edit+ // moves this column alone.PublishedByType: pgtype.Text{String: "member", Valid: publisherID.Valid},PublishedByID: publisherID,+ // created_by is the AUTHORIZATION principal and is immutable: the run acts+ // as this member forever, so no edit may move it (MUL-6951).+ CreatedByType: pgtype.Text{String: "member", Valid: publisherID.Valid},+ CreatedByID: publisherID,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to create trigger")@@ -1563,10 +1572,15 @@ func (h *Handler) createWebhookTriggerWithMintedToken(WebhookToken: pgtype.Text{String: token, Valid: true},Provider: pgtype.Text{String: provider, Valid: provider != ""},EventFilters: eventFilters,- // Seed the responsible publisher = creator; re-stamped to the editor on a- // later substantive edit (source=trigger_owner, MUL-4302).+ // published_by records CONFIG responsibility only: seeded to the creator,+ // re-stamped to a later substantive editor (MUL-4302). It has no bearing+ // on the runs this trigger fires (MUL-6951).PublishedByType: pgtype.Text{String: "member", Valid: publisherID.Valid},PublishedByID: publisherID,+ // Immutable authorization principal — see the schedule path above+ // (MUL-6951).+ CreatedByType: pgtype.Text{String: "member", Valid: publisherID.Valid},+ CreatedByID: publisherID,})if err != nil {tx.Rollback(ctx)@@ -2176,7 +2190,9 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {// A manual "run now" is a direct human action, so the run is attributed// direct_human to the triggering member (MUL-4302 §4). Resolve the actor the// same way assign/promote does; only a member actor is a human — an agent- // triggering via A2A yields an invalid actor and falls back to rule_owner.+ // triggering via A2A yields an invalid actor, which then follows the automation+ // path: the firing trigger's creator, or nobody when this entry point supplies+ // no trigger, in which case the run carries no authorization (MUL-6951).userID, ok := requireUserID(w, r)if !ok {returndiff --git a/server/internal/handler/autopilot_mention_authority_test.go b/server/internal/handler/autopilot_mention_authority_test.goindex a573de2fae..8528c86982 100644--- a/server/internal/handler/autopilot_mention_authority_test.go+++ b/server/internal/handler/autopilot_mention_authority_test.go@@ -11,17 +11,17 @@ import (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.+// autopilotDelegationFixture builds the 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.//-// 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.+// Since MUL-6951 that leader task carries a real ORIGINATOR — the human+// responsible for the firing trigger — exactly as a live schedule/webhook run+// does. So the invoke gate judges these comments by that human's own rights, with+// no autopilot-specific borrow path involved. The fields stay exposed so tests can+// rewrite the comment's source_task_id, or strip the originator, and prove the+// gate then fails closed.type autopilotDelegationFixture struct {Issue db.IssueLeaderAgentID string // the autopilot-dispatched agent authoring the comment@@ -92,13 +92,15 @@ func newAutopilotDelegationFixture(t *testing.T, targetAgentID, autopilotCreator// 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.+ // carries NO autopilot_run_id. Since MUL-6951 it DOES carry the trigger owner+ // as originator (accountable mirrors it — migrations 190/197 require the pair+ // to match), which is what the invoke gate now keys on.var leaderTaskID stringif 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 {+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority,+ originator_user_id, accountable_user_id, originator_source)+ VALUES ($1, $2, $3, 'running', 0, $4, $4, 'trigger_owner') RETURNING id+ `, leaderID, runtimeID, issueID, autopilotCreatorUserID).Scan(&leaderTaskID); err != nil {t.Fatalf("create leader task: %v", err)}@@ -147,26 +149,38 @@ func setCommentSourceTask(t *testing.T, fx *autopilotDelegationFixture, sourceTa}// 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 {+// and returns its id. Pass originatorUserID to give the run a human (what an+// autopilot chain carries since MUL-6951); omit it to build the no-human case the+// gate must fail closed on.+func seedTaskOnIssue(t *testing.T, agentID, issueID, runtimeID string, originatorUserID ...string) string {t.Helper()+ var originator any+ if len(originatorUserID) > 0 && originatorUserID[0] != "" {+ originator = originatorUserID[0]+ }var taskID stringif 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 {+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority,+ originator_user_id, accountable_user_id, originator_source)+ VALUES ($1, $2, $3, 'running', 0, $4, $4, CASE WHEN $4::uuid IS NULL THEN NULL ELSE 'trigger_owner' END) RETURNING id+ `, agentID, runtimeID, issueID, originator).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) {+// TestAutopilotCommentAuthority_KeysOnRunOriginator pins the post-MUL-6951 rule+// for an autopilot run delegating mid-chain: the invoke gate keys on the run's own+// originator — the human who armed the trigger — and nothing else. There is no+// autopilot-shaped borrow path left, so the issue's provenance, the autopilot's+// creator and the task/issue binding no longer enter the decision; what remains is+// "does THIS human hold invoke rights", which is the same question asked of a+// member acting directly.+//+// The negative cases that matter are therefore the two below: a human without+// rights, and no human at all.+func TestAutopilotCommentAuthority_KeysOnRunOriginator(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")}@@ -175,19 +189,15 @@ func TestAutopilotDelegationAuthority_LineageBinding(t *testing.T) {// 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 {+ // mentionTriggersTarget runs the trigger compute the way the live comment paths+ // do — with the originator resolved from the speaking run — and reports whether+ // the private target fires.+ mentionTriggersTarget := func(fx autopilotDelegationFixture, originatorUserID string) bool {triggers, _ := testHandler.computeCommentAgentTriggers(ctx, fx.Issue, fx.Comment.Content, nil, "agent", fx.LeaderAgentID,commentTriggerComputeOptions{- ExcludeTriggerCommentID: fx.Comment.ID,- AutopilotDelegationAuthorityUserID: authorityFor(fx),+ ExcludeTriggerCommentID: fx.Comment.ID,+ OriginatorUserID: originatorUserID,},)for _, tr := range triggers {@@ -198,78 +208,27 @@ func TestAutopilotDelegationAuthority_LineageBinding(t *testing.T) {return false}- t.Run("verified lineage + creator owns target -> triggers", func(t *testing.T) {+ t.Run("trigger owner owns the 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")+ if !mentionTriggersTarget(fx, ownerID) {+ t.Fatal("an autopilot run carrying its trigger owner must reach a private agent that owner owns")}})- 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.+ t.Run("trigger owner without invoke rights -> denied", func(t *testing.T) {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")+ if mentionTriggersTarget(fx, plainMemberID) {+ t.Fatal("a trigger owner with no 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.+ t.Run("no originator on the run -> fails closed", func(t *testing.T) {+ // A run that reached this gate with no human at the top of its chain (a+ // legacy row, or a broken originator chain N hops back) must be denied+ // rather than fall back to any autopilot-derived identity.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")+ if mentionTriggersTarget(fx, "") {+ t.Fatal("a run with no human originator must not reach a private agent")}})}@@ -317,17 +276,20 @@ func TestCreateComment_AutopilotLeaderMentionEnqueuesPrivateWorker(t *testing.T)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+ // MUL-6951 consequence: the delegated run INHERITS the trigger owner as its+ // originator (attribution's delegation rule copies the parent's human), so the+ // authorization travels down the chain exactly as it does under a manual "run+ // now". Under the previous design the parent had no originator to copy, so this+ // row came out unattributed and the chain had to re-borrow at every hop.+ var workerOriginator pgtype.UUIDif err := testPool.QueryRow(context.Background(), `- SELECT originator_user_id IS NOT NULL FROM agent_task_queue+ SELECT originator_user_id FROM agent_task_queueWHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'- `, issueID, workerID).Scan(&workerOriginatorValid); err != nil {+ `, issueID, workerID).Scan(&workerOriginator); 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")+ if uuidToString(workerOriginator) != ownerID {+ t.Fatalf("delegated worker originator = %q, want the trigger owner %q", uuidToString(workerOriginator), ownerID)}}@@ -431,24 +393,24 @@ func TestReconcileCommentsOnCompletion_AutopilotDelegationRestoresAuthority(t *treturn issueID, queued}- t.Run("creator owns busy target -> one unattributed follow-up", func(t *testing.T) {+ t.Run("trigger owner owns busy target -> one follow-up carrying that human", 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+ var originator pgtype.UUIDif err := testPool.QueryRow(ctx, `- SELECT originator_user_id IS NOT NULL FROM agent_task_queue+ SELECT originator_user_id FROM agent_task_queueWHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'- `, issueID, workerID).Scan(&originatorValid); err != nil {+ `, issueID, workerID).Scan(&originator); 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")+ if uuidToString(originator) != ownerID {+ t.Fatalf("reconcile follow-up originator = %q, want the trigger owner %q", uuidToString(originator), ownerID)}})- t.Run("creator without rights -> no follow-up", func(t *testing.T) {+ t.Run("trigger owner 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)}@@ -460,10 +422,9 @@ func TestReconcileCommentsOnCompletion_AutopilotDelegationRestoresAuthority(t *t// 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 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.+// closed (preview and save agree). Since MUL-6490 the lineage itself is always+// persisted; what denies the cross-issue edit here is simply that the EDITING run+// carries no human originator, so the gate has nobody to admit (MUL-6951).func TestUpdateComment_AutopilotAuthorityReStampedToEditingTask(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")@@ -510,13 +471,14 @@ func TestUpdateComment_AutopilotAuthorityReStampedToEditingTask(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.+ // The leader now runs a task with NO human on an unrelated issue and edits+ // its old autopilot comment from there. The edit is judged by that run, so+ // the old authoring run's human cannot be reached.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)+ t.Fatalf("an edit made by a run with no human must not reach the private worker; got %d queued", got)}// 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@@ -532,11 +494,11 @@ func TestUpdateComment_AutopilotAuthorityReStampedToEditingTask(t *testing.T) {})}-// 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.+// TestCreateComment_AutopilotWorkerResultWakesSquadLeader locks the accepted+// behavior that the run's originator reaches 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")@@ -585,8 +547,9 @@ func TestCreateComment_AutopilotWorkerResultWakesSquadLeader(t *testing.T) {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 runs on this autopilot issue carrying the chain's human, which is+ // what a delegated run inherits since MUL-6951.+ workerTaskID := seedTaskOnIssue(t, workerID, issueID, runtimeID, ownerID)// The worker posts a PLAIN result comment (no @mention) via HTTP.w := httptest.NewRecorder()diff --git a/server/internal/handler/autopilot_subscriber_test.go b/server/internal/handler/autopilot_subscriber_test.goindex 244962594c..b32c829d36 100644--- a/server/internal/handler/autopilot_subscriber_test.go+++ b/server/internal/handler/autopilot_subscriber_test.go@@ -634,7 +634,7 @@ func TestAutopilotDispatchFansOutSubscribersToIssue(t *testing.T) {if err != nil {t.Fatalf("GetAutopilot: %v", err)}- run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ run, _, err := testHandler.AutopilotService.DispatchAutopilotManual(ctx, ap, pgtype.UUID{}, nil, parseUUID(testUserID))if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}@@ -707,7 +707,7 @@ func TestAutopilotDispatchNotifiesSubscribersOnCreate(t *testing.T) {if err != nil {t.Fatalf("GetAutopilot: %v", err)}- run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ run, _, err := testHandler.AutopilotService.DispatchAutopilotManual(ctx, ap, pgtype.UUID{}, nil, parseUUID(testUserID))if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}@@ -789,7 +789,7 @@ func TestAutopilotDispatchSkipsInboxWhenNoSubscribers(t *testing.T) {if err != nil {t.Fatalf("GetAutopilot: %v", err)}- run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ run, _, err := testHandler.AutopilotService.DispatchAutopilotManual(ctx, ap, pgtype.UUID{}, nil, parseUUID(testUserID))if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex edde459933..8d44365a2e 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1541,31 +1541,6 @@ 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 {@@ -1671,7 +1646,6 @@ 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)),@@ -1932,15 +1906,10 @@ 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, delegationAuthority, suppressAgentIDs)+ resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, originatorUserID, suppressAgentIDs)writeJSON(w, http.StatusCreated, resp)}@@ -1981,14 +1950,13 @@ 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, delegationAuthorityUserID string, suppressAgentIDs []pgtype.UUID) []CommentTriggerOutcome {+func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID, originatorUserID 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,- AutopilotDelegationAuthorityUserID: delegationAuthorityUserID,+ ExcludeTriggerCommentID: comment.ID,+ OriginatorUserID: originatorUserID,})triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)h.noteBlockedRuntimeTargets(ctx, issue, targets)@@ -2657,7 +2625,7 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu}// Autopilot delegation authority (MUL-4857) is applied by the gate via- // opts.effectiveInvoker(): when a run carried no human originator, the gate+ // opts.OriginatorUserID: 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@@ -2777,7 +2745,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.effectiveInvoker(), uuidToString(issue.WorkspaceID)) {+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, uuidToString(issue.WorkspaceID)) {return commentAgentTrigger{}, false}hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, parent.AuthorID, opts)@@ -2951,7 +2919,7 @@ func (h *Handler) routeAssignedSquadLeaderFallback(ctx context.Context, issue dbif err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {return commentAgentTrigger{}, false}- if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.effectiveInvoker(), uuidToString(issue.WorkspaceID)) {+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, uuidToString(issue.WorkspaceID)) {return commentAgentTrigger{}, false}hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, squad.LeaderID, opts)@@ -3127,7 +3095,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.effectiveInvoker(), wsID) {+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, wsID) {blockTarget("squad", m.ID, ReasonInvocationNotAllowed)continue}@@ -3181,7 +3149,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issucontinue}// Private-agent gate first, before any archived/runtime state is read.- if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.effectiveInvoker(), wsID) {+ if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, wsID) {blockTarget("agent", m.ID, ReasonInvocationNotAllowed)continue}@@ -3447,16 +3415,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {}h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, existing.ID)- // 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 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)+ return h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), suppressAgentIDs)}// Fetch reactions and attachments for the updated comment.@@ -3660,17 +3619,12 @@ func (h *Handler) retriggerCancelledTaskSurvivors(ctx context.Context, issue db.actorType := comment.AuthorTypeactorID := uuidToString(comment.AuthorID)originatorUserID := actorID- var delegationAuthority stringif 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,- AutopilotDelegationAuthorityUserID: delegationAuthority,+ ExcludeTriggerCommentID: comment.ID,+ OriginatorUserID: originatorUserID,})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.goindex 3c1da1c96a..676759ce47 100644--- a/server/internal/handler/comment_reconcile_test.go+++ b/server/internal/handler/comment_reconcile_test.go@@ -291,7 +291,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.@@ -493,14 +493,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.goindex c8b36be247..03f0793a0a 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -4004,21 +4004,12 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.AgactorType := c.AuthorTypeactorID := uuidToString(c.AuthorID)originatorUserID := actorID- var delegationAuthority stringif 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,- AutopilotDelegationAuthorityUserID: delegationAuthority,+ ExcludeTriggerCommentID: c.ID,+ OriginatorUserID: originatorUserID,})// For an AGENT author, compensate ONLY explicit @agent/@squad mentions.// computeCommentAgentTriggers can also return the assigned-squad-leaderdiff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.goindex b5c833f213..0633316cff 100644--- a/server/internal/handler/handler_test.go+++ b/server/internal/handler/handler_test.go@@ -1042,7 +1042,17 @@ func TestScheduledAutopilotAllowsActiveDuplicateIssue(t *testing.T) {if err != nil {t.Fatalf("GetAutopilot: %v", err)}- run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "schedule", nil)+ // A scheduled dispatch always fires through a trigger, and since MUL-6951 that+ // trigger is what names the human the run acts as. Seed one rather than passing+ // a zero id, which is a shape the scheduler cannot produce.+ scheduleTriggerID := dbfx.Insert(t, "autopilot_trigger", testutil.Cols{+ "autopilot_id": autopilotID,+ "kind": "schedule",+ "cron_expression": "0 * * * *",+ "created_by_type": "member",+ "created_by_id": testUserID,+ })+ run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, parseUUID(scheduleTriggerID), "schedule", nil)if err != nil {t.Fatalf("DispatchAutopilot schedule duplicate: %v", err)}@@ -1115,7 +1125,7 @@ func TestAutopilotCreatedIssueCreatorIsAssigneeAgent(t *testing.T) {if err != nil {t.Fatalf("GetAutopilot: %v", err)}- run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ run, _, err := testHandler.AutopilotService.DispatchAutopilotManual(ctx, ap, pgtype.UUID{}, nil, parseUUID(testUserID))if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}@@ -1196,7 +1206,7 @@ func TestAutopilotCreateIssueAssociatesConfiguredProject(t *testing.T) {if err != nil {t.Fatalf("GetAutopilot: %v", err)}- run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ run, _, err := testHandler.AutopilotService.DispatchAutopilotManual(ctx, ap, pgtype.UUID{}, nil, parseUUID(testUserID))if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}@@ -1273,7 +1283,7 @@ func TestAutopilotDispatchUsesCurrentProjectBinding(t *testing.T) {req = withURLParam(req, "id", autopilotID)w = testutil.Call(t, testHandler.UpdateAutopilot, req).Want(http.StatusOK)- run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ run, _, err := testHandler.AutopilotService.DispatchAutopilotManual(ctx, ap, pgtype.UUID{}, nil, parseUUID(testUserID))if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 216386d9c6..a192b7741c 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -2557,7 +2557,6 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {r.Context(), r, workspaceID,pgtype.Text{String: "agent", Valid: true},agentUUID,- scopeNoDelegation(),); status != 0 {writeError(w, status, msg)return@@ -2855,13 +2854,17 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {var parentIssueID pgtype.UUIDvar projectID pgtype.UUID- var parentIssue *db.Issueif req.ParentIssueID != nil {id, ok := parseUUIDOrBadRequest(w, *req.ParentIssueID, "parent_issue_id")if !ok {return}parentIssueID = id+ // The parent is loaded only to reject a cross-workspace or missing one+ // BEFORE the assignee gate runs, so the caller gets 400 "parent issue not+ // found" rather than a 403 that leaks nothing about which input was wrong.+ // The row itself is no longer needed: the assignee gate keys on the actor's+ // originator, not on a scope bound to the parent (MUL-6951).if assigneeType.Valid && (assigneeType.String == "agent" || assigneeType.String == "squad") {parent, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: parentIssueID,@@ -2871,21 +2874,10 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "parent issue not found in this workspace")return}- parentIssue = &parent}}- // 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 {+ if status, msg := h.validateAssigneePair(r.Context(), r, workspaceID, assigneeType, assigneeID); status != 0 {writeError(w, status, msg)return}@@ -3544,7 +3536,7 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {_, touchedType := rawFields["assignee_type"]_, touchedID := rawFields["assignee_id"]if touchedType || touchedID {- if status, msg := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID, scopeExistingIssue(&prevIssue)); status != 0 {+ if status, msg := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID); status != 0 {writeError(w, status, msg)return}@@ -3698,16 +3690,14 @@ 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.-// 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.+// An autopilot run needs no special case here: since MUL-6951 a scheduled run+// carries its trigger owner's originator, so it is judged by exactly the same+// predicate as that human acting directly.//// 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, scope assignAuthorityScope) (int, string) {+func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, workspaceID string, assigneeType pgtype.Text, assigneeID pgtype.UUID) (int, string) {// Both unset → unassigned issue, valid.if !assigneeType.Valid && !assigneeID.Valid {return 0, ""@@ -3741,7 +3731,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, scope, actorType, actorID, workspaceID)+ effectiveInvoker := h.invokeOriginatorFromRequest(r, actorType, actorID)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@@ -3770,7 +3760,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, scope, actorType, actorID, workspaceID)+ effectiveInvoker := h.invokeOriginatorFromRequest(r, actorType, actorID)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.@@ -3818,7 +3808,7 @@ func (h *Handler) assigneeFallbackAgent(ctx context.Context, issue db.Issue, actif err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {return db.Agent{}, false, false}- if !h.canInvokeAgent(ctx, agent, actorType, actorID, opts.effectiveInvoker(), uuidToString(issue.WorkspaceID)) {+ if !h.canInvokeAgent(ctx, agent, actorType, actorID, opts.OriginatorUserID, uuidToString(issue.WorkspaceID)) {return db.Agent{}, false, false}// Coalescing queue: pending is still a valid route target, but callers@@ -4290,7 +4280,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {_, batchTouchedType := rawUpdates["assignee_type"]_, batchTouchedID := rawUpdates["assignee_id"]if batchTouchedType || batchTouchedID {- if status, _ := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID, scopeExistingIssue(&prevIssue)); status != 0 {+ if status, _ := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID); status != 0 {continue}}diff --git a/server/internal/handler/issue_autopilot_assignment_authority_test.go b/server/internal/handler/issue_autopilot_assignment_authority_test.goindex c84acc6a1a..4c0c00fc1b 100644--- a/server/internal/handler/issue_autopilot_assignment_authority_test.go+++ b/server/internal/handler/issue_autopilot_assignment_authority_test.go@@ -1,13 +1,127 @@package handlerimport (+ "fmt""net/http"- "strings"+ "sync/atomic""testing""github.com/multica-ai/multica/server/internal/testutil")+// MUL-6951. An autopilot run carries the human who armed its trigger as the run's+// ORIGINATOR, so the assign surfaces judge it with the ordinary invoke gate — the+// same predicate that human gets acting directly. There is no autopilot-shaped+// authority to borrow and no scope to bound it with.+//+// What that leaves worth testing is the gate itself at every surface an agent run+// can assign through (create top-level, create child, update, batch):+//+// - the run's human holds invoke rights -> assigned and dispatched once+// - the run's human holds none -> 403 / silently skipped in a batch+// - the run carries no human at all -> fail closed+//+// These files previously pinned the borrow bounds instead (MUL-4857's+// autopilot-created-issue binding, MUL-6691's authored-by-this-task binding).+// Those bounds existed only because the run had no human of its own; with one,+// they describe nothing.++var runOnlyFixtureSeq atomic.Int64++// runOnlyAutopilotFixture is the run_only shape: a member-created autopilot with+// a live run, and a dispatched leader task attributed to the trigger owner, with+// NO issue of its own — the state a scan run works in.+type runOnlyAutopilotFixture struct {+ LeaderAgentID string+ LeaderTaskID string+ AutopilotID string+ RunID string+ RuntimeID string+}++// newRunOnlyAutopilotFixture wires the fixture with triggerOwnerUserID as the+// run's human (originator AND accountable — migrations 190/197 require the pair to+// match) and targetAgentID as the autopilot's assignee. Pass an override to strip+// the attribution and build the no-human case.+func newRunOnlyAutopilotFixture(t *testing.T, targetAgentID, triggerOwnerUserID string, over ...testutil.Cols) runOnlyAutopilotFixture {+ t.Helper()++ runtimeID := handlerTestRuntimeID(t)+ leaderID := dbfx.Agent(t, fmt.Sprintf("mul6951-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-6951 run_only",+ "assignee_id": targetAgentID,+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": triggerOwnerUserID,+ })+ 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,+ "originator_user_id": triggerOwnerUserID,+ "accountable_user_id": triggerOwnerUserID,+ "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,+ }+}++// noHumanOnRun strips the run's attribution, producing the shape the gate must+// fail closed on: an agent run that reached this point with no human at the top+// of its chain.+func noHumanOnRun() testutil.Cols {+ return testutil.Cols{+ "originator_user_id": nil,+ "accountable_user_id": nil,+ "originator_source": nil,+ }+}++// 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-6951 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+}+func autopilotChildIssueRequest(t *testing.T, assigneeType, assigneeID, parentIssueID, status, actorAgentID, taskID string) *http.Request {t.Helper()@@ -35,183 +149,353 @@ func cleanupAutopilotChildIssue(t *testing.T, issueID string) {dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)}-func TestCreateIssue_AutopilotLeaderAssignsPrivateWorker(t *testing.T) {+// createUnassignedIssueAsRun has the run create a parentless issue with no+// assignee (always allowed) and returns its id.+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-6951 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+}++// seedMemberIssue inserts an issue created by a human member — the pre-existing+// record an autopilot may now be asked to route.+func seedMemberIssue(t *testing.T, creatorMemberID string) string {+ t.Helper()+ return dbfx.Insert(t, "issue", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "creator_type": "member",+ "creator_id": creatorMemberID,+ "title": "MUL-6951 member-created " + t.Name(),+ "status": "todo",+ "number": nextWorkspaceIssueNumber(t),+ })+}++// 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 run's human+// travel onto the dispatched task".+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+}++// 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+}++// 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 originator+// 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)+}++func TestCreateIssue_AutopilotRunAssignsPrivateAgent(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")}- t.Run("verified lineage parks backlog child without enqueue", func(t *testing.T) {+ t.Run("top-level create dispatches the private worker once", func(t *testing.T) {workerID, ownerID, _ := privateAgentTestFixture(t)- fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")- parentIssueID := uuidToString(fx.Issue.ID)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)var created IssueResponsetestutil.Call(t, testHandler.CreateIssue,- autopilotChildIssueRequest(t, "agent", workerID, parentIssueID, "backlog", fx.LeaderAgentID, fx.LeaderTaskID),+ topLevelIssueRequest(t, "agent", workerID, "todo", fx.LeaderAgentID, fx.LeaderTaskID),).Want(http.StatusCreated).JSON(&created)cleanupAutopilotChildIssue(t, created.ID)- if created.ParentIssueID == nil || *created.ParentIssueID != parentIssueID {- t.Fatalf("created child parent_issue_id = %v, want %q", created.ParentIssueID, parentIssueID)++ total, withOriginator := tasksFor(t, created.ID, workerID)+ if total != 1 {+ t.Fatalf("dispatched %d tasks, want 1", total)}- if created.AssigneeType == nil || *created.AssigneeType != "agent" || created.AssigneeID == nil || *created.AssigneeID != workerID {- t.Fatalf("created child assignee = (%v, %v), want (agent, %s)", created.AssigneeType, created.AssigneeID, workerID)+ // MUL-6951: the dispatched run inherits the trigger owner, so the chain no+ // longer has to re-establish authority at each hop. Under the previous+ // design this count was 0 and every hop re-borrowed.+ if withOriginator != 1 {+ t.Fatalf("%d of %d dispatched tasks carry an originator, want all", withOriginator, total)}+ })- var queued int- dbfx.QueryRow(t, `- SELECT count(*) FROM agent_task_queue- WHERE issue_id = $1 AND agent_id = $2- `, created.ID, workerID).Scan(&queued)- if queued != 0 {- t.Fatalf("backlog child must not enqueue the private worker, got %d tasks", queued)- }+ t.Run("top-level create accepts a private-leader squad", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ squadID := dbfx.Squad(t, "MUL-6951 squad "+t.Name(), workerID, testutil.Cols{"creator_id": ownerID})+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)++ 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)})- t.Run("verified lineage creates active child and enqueues once", func(t *testing.T) {+ t.Run("backlog child parks without enqueueing", func(t *testing.T) {workerID, ownerID, _ := privateAgentTestFixture(t)- fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ parentID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)var created IssueResponsetestutil.Call(t, testHandler.CreateIssue,- autopilotChildIssueRequest(t, "agent", workerID, uuidToString(fx.Issue.ID), "todo", fx.LeaderAgentID, fx.LeaderTaskID),+ autopilotChildIssueRequest(t, "agent", workerID, parentID, "backlog", fx.LeaderAgentID, fx.LeaderTaskID),).Want(http.StatusCreated).JSON(&created)cleanupAutopilotChildIssue(t, created.ID)- var taskCount int- var originatorCount int- dbfx.QueryRow(t, `- SELECT count(*), count(originator_user_id) FROM agent_task_queue- WHERE issue_id = $1 AND agent_id = $2- `, created.ID, workerID).Scan(&taskCount, &originatorCount)- if taskCount != 1 {- t.Fatalf("active child must enqueue the private worker exactly once, got %d tasks", taskCount)- }- if originatorCount != 0 {- t.Fatal("autopilot creator authority is authorization-only; worker task must remain unattributed")+ if total, _ := tasksFor(t, created.ID, workerID); total != 0 {+ t.Fatalf("a backlog child must not enqueue, got %d tasks", total)}})- t.Run("verified lineage creates squad child and enqueues its private leader once", func(t *testing.T) {- workerID, ownerID, _ := privateAgentTestFixture(t)- fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")- squadID := dbfx.Squad(t, "Autopilot Private Leader Squad", workerID)+ t.Run("child under an issue the run did not create is admitted", func(t *testing.T) {+ // The old binding refused this: the parent was neither autopilot-created+ // nor authored by this task. The run's human owns the worker, so it is+ // simply allowed now.+ workerID, ownerID, otherMemberID := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ parentID := seedMemberIssue(t, otherMemberID)var created IssueResponsetestutil.Call(t, testHandler.CreateIssue,- autopilotChildIssueRequest(t, "squad", squadID, uuidToString(fx.Issue.ID), "todo", fx.LeaderAgentID, fx.LeaderTaskID),+ autopilotChildIssueRequest(t, "agent", workerID, parentID, "todo", fx.LeaderAgentID, fx.LeaderTaskID),).Want(http.StatusCreated).JSON(&created)cleanupAutopilotChildIssue(t, created.ID)- if created.AssigneeType == nil || *created.AssigneeType != "squad" || created.AssigneeID == nil || *created.AssigneeID != squadID {- t.Fatalf("created child assignee = (%v, %v), want (squad, %s)", created.AssigneeType, created.AssigneeID, squadID)- }- var taskCount int- var originatorCount int- var squadTaskCount int- dbfx.QueryRow(t, `- SELECT count(*), count(originator_user_id), count(*) FILTER (WHERE squad_id = $3)- FROM agent_task_queue- WHERE issue_id = $1 AND agent_id = $2- `, created.ID, workerID, squadID).Scan(&taskCount, &originatorCount, &squadTaskCount)- if taskCount != 1 || squadTaskCount != 1 {- t.Fatalf("active squad child must enqueue its private leader exactly once with squad lineage, got %d tasks (%d with squad_id)", taskCount, squadTaskCount)- }- if originatorCount != 0 {- t.Fatal("autopilot creator authority is authorization-only; squad leader task must remain unattributed")+ if total, _ := tasksFor(t, created.ID, workerID); total != 1 {+ t.Fatalf("dispatched %d tasks, want 1", total)}})- t.Run("creator without invoke rights is denied", func(t *testing.T) {- workerID, _, plainMemberID := privateAgentTestFixture(t)- fx := newAutopilotDelegationFixture(t, workerID, plainMemberID, "autopilot")+ t.Run("denials", func(t *testing.T) {+ t.Run("run's human holds no invoke rights", func(t *testing.T) {+ workerID, _, plainMemberID := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, plainMemberID)- testutil.Call(t, testHandler.CreateIssue,- autopilotChildIssueRequest(t, "agent", workerID, uuidToString(fx.Issue.ID), "backlog", fx.LeaderAgentID, fx.LeaderTaskID),- ).Want(http.StatusForbidden)+ testutil.Call(t, testHandler.CreateIssue,+ topLevelIssueRequest(t, "agent", workerID, "todo", fx.LeaderAgentID, fx.LeaderTaskID),+ ).Want(http.StatusForbidden)+ })++ t.Run("run carries no human", func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID, noHumanOnRun())++ testutil.Call(t, testHandler.CreateIssue,+ topLevelIssueRequest(t, "agent", workerID, "todo", fx.LeaderAgentID, fx.LeaderTaskID),+ ).Want(http.StatusForbidden)+ })++ t.Run("cross-workspace parent is rejected before the assignee gate", func(t *testing.T) {+ // 400, not 403: the parent lookup still runs first so the caller learns+ // which input was wrong. This is the reason CreateIssue keeps loading the+ // parent even though the gate no longer needs it.+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ foreignUserID := dbfx.User(t, "MUL-6951 Foreign", fmt.Sprintf("mul6951-foreign-%[email protected]", runOnlyFixtureSeq.Add(1)))+ foreignWorkspaceID := dbfx.Workspace(t, "MUL-6951 Foreign WS", fmt.Sprintf("mul6951-foreign-ws-%d", runOnlyFixtureSeq.Add(1)))+ var foreignIssueID string+ dbfx.QueryRow(t, `+ INSERT INTO issue (workspace_id, creator_type, creator_id, title, status, number)+ VALUES ($1, 'member', $2, 'MUL-6951 foreign parent', 'todo', 1) RETURNING id+ `, foreignWorkspaceID, foreignUserID).Scan(&foreignIssueID)+ dbfx.Cleanup(t, `DELETE FROM issue WHERE id = $1`, foreignIssueID)++ testutil.Call(t, testHandler.CreateIssue,+ autopilotChildIssueRequest(t, "agent", workerID, foreignIssueID, "todo", fx.LeaderAgentID, fx.LeaderTaskID),+ ).Want(http.StatusBadRequest)+ })})+}- t.Run("real originator takes precedence over autopilot creator", func(t *testing.T) {- workerID, ownerID, plainMemberID := privateAgentTestFixture(t)- fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")- dbfx.Exec(t, `- UPDATE agent_task_queue- SET originator_user_id = $1, accountable_user_id = $1, originator_source = 'direct_human'- WHERE id = $2- `, plainMemberID, fx.LeaderTaskID)+func TestUpdateIssue_AutopilotRunAssignsPrivateAgent(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }- testutil.Call(t, testHandler.CreateIssue,- autopilotChildIssueRequest(t, "agent", workerID, uuidToString(fx.Issue.ID), "backlog", fx.LeaderAgentID, fx.LeaderTaskID),- ).Want(http.StatusForbidden)+ t.Run("assigns an issue created by another member", func(t *testing.T) {+ // The capability #7902 tried to reach with a fourth borrow scope. With a+ // real originator it needs no special case: the run's human may assign any+ // issue in the workspace they could assign by hand.+ workerID, ownerID, otherMemberID := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ issueID := seedMemberIssue(t, otherMemberID)++ agentAssigns(t, fx.LeaderAgentID, fx.LeaderTaskID, issueID, workerID).Want(http.StatusOK)++ if got := assigneeOf(t, issueID); got != workerID {+ t.Fatalf("assignee = %q, want %q", got, workerID)+ }+ if total, _ := tasksFor(t, issueID, workerID); total != 1 {+ t.Fatalf("enqueued %d tasks, want 1", total)+ }})- t.Run("missing task lineage is denied", func(t *testing.T) {+ t.Run("assigns an issue it created itself", func(t *testing.T) {workerID, ownerID, _ := privateAgentTestFixture(t)- fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ issueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)- testutil.Call(t, testHandler.CreateIssue,- autopilotChildIssueRequest(t, "agent", workerID, uuidToString(fx.Issue.ID), "backlog", fx.LeaderAgentID, ""),- ).Want(http.StatusForbidden)+ agentAssigns(t, fx.LeaderAgentID, fx.LeaderTaskID, issueID, workerID).Want(http.StatusOK)++ if got := assigneeOf(t, issueID); got != workerID {+ t.Fatalf("assignee = %q, want %q", got, workerID)+ }})- t.Run("task actor mismatch is denied", func(t *testing.T) {- workerID, ownerID, _ := privateAgentTestFixture(t)- fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")- workerTaskID := seedTaskOnIssue(t, workerID, uuidToString(fx.Issue.ID), fx.RuntimeID)+ t.Run("run's human holds no invoke rights", func(t *testing.T) {+ workerID, _, plainMemberID := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, plainMemberID)+ issueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)- testutil.Call(t, testHandler.CreateIssue,- autopilotChildIssueRequest(t, "agent", workerID, uuidToString(fx.Issue.ID), "backlog", fx.LeaderAgentID, workerTaskID),- ).Want(http.StatusForbidden)+ agentAssigns(t, fx.LeaderAgentID, fx.LeaderTaskID, issueID, workerID).Want(http.StatusForbidden)++ if got := assigneeOf(t, issueID); got != "" {+ t.Fatalf("issue was assigned to %q", got)+ }})- t.Run("task bound to another issue is denied", func(t *testing.T) {+ t.Run("run carries no human", func(t *testing.T) {workerID, ownerID, _ := privateAgentTestFixture(t)- fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")- otherIssueID := seedBareIssue(t, fx.LeaderAgentID)- otherTaskID := seedTaskOnIssue(t, fx.LeaderAgentID, otherIssueID, fx.RuntimeID)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID, noHumanOnRun())+ issueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)- testutil.Call(t, testHandler.CreateIssue,- autopilotChildIssueRequest(t, "agent", workerID, uuidToString(fx.Issue.ID), "backlog", fx.LeaderAgentID, otherTaskID),- ).Want(http.StatusForbidden)+ agentAssigns(t, fx.LeaderAgentID, fx.LeaderTaskID, issueID, workerID).Want(http.StatusForbidden)++ if got := assigneeOf(t, issueID); got != "" {+ t.Fatalf("issue was assigned to %q", got)+ }})- t.Run("cross-workspace parent is rejected before assignee authorization", func(t *testing.T) {- workerID, ownerID, _ := privateAgentTestFixture(t)- fx := newAutopilotDelegationFixture(t, workerID, ownerID, "autopilot")- squadID := dbfx.Squad(t, "Autopilot Cross-Workspace Squad", workerID)- foreignWorkspaceID := dbfx.Workspace(t, "Autopilot Foreign Parent", "autopilot-foreign-parent-"+workerID[:8])- foreignParentID := dbfx.Issue(t, "Autopilot foreign parent", testutil.Cols{- "workspace_id": foreignWorkspaceID,- "number": 1,+ // MUL-6951 (Elon review). A run represents its human only while it is live.+ // Task-token revocation at the terminal transition is the primary guard, but it+ // is best-effort and non-fatal on failure with a 24h expiry behind it, so a+ // failed revocation would otherwise leave a finished run spending a member's+ // invoke rights. Every terminal status must be refused.+ for _, status := range []string{"completed", "failed", "cancelled"} {+ t.Run("run already "+status, func(t *testing.T) {+ workerID, ownerID, _ := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ issueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)++ // The originator is intact and would otherwise admit — only the task+ // reaching a terminal state withdraws it.+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = $1 WHERE id = $2`, status, fx.LeaderTaskID)++ agentAssigns(t, fx.LeaderAgentID, fx.LeaderTaskID, issueID, workerID).Want(http.StatusForbidden)++ if got := assigneeOf(t, issueID); got != "" {+ t.Fatalf("a %s run assigned the issue to %q", status, got)+ }+ if total, _ := tasksFor(t, issueID, workerID); total != 0 {+ t.Fatalf("a %s run enqueued %d tasks", status, total)+ }})+ }++ t.Run("plain member is still refused", func(t *testing.T) {+ workerID, _, plainMemberID := privateAgentTestFixture(t)+ issueID := seedMemberIssue(t, plainMemberID)++ 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)+ })+}++// BatchUpdateIssues is a real agent-reachable authorization point, so it needs its+// own coverage even though it now runs the same predicate as the single update.+func TestBatchUpdateIssues_AutopilotRunAssign(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ t.Run("assigns every issue when the run's human holds rights", func(t *testing.T) {+ workerID, ownerID, otherMemberID := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID)+ ownIssueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)+ otherIssueID := seedMemberIssue(t, otherMemberID)++ batchAssignAsRun(t, otherMemberID, fx.LeaderAgentID, fx.LeaderTaskID, workerID, ownIssueID, otherIssueID).+ Want(http.StatusOK)- for _, target := range []struct {- name, assigneeType, assigneeID string- }{- {name: "agent", assigneeType: "agent", assigneeID: workerID},- {name: "squad", assigneeType: "squad", assigneeID: squadID},- } {- t.Run(target.name, func(t *testing.T) {- resp := testutil.Call(t, testHandler.CreateIssue,- autopilotChildIssueRequest(t, target.assigneeType, target.assigneeID, foreignParentID, "backlog", fx.LeaderAgentID, fx.LeaderTaskID),- ).Want(http.StatusBadRequest)- if !strings.Contains(resp.Text(), "parent issue not found in this workspace") {- t.Fatalf("cross-workspace parent rejection = %q, want workspace boundary error", resp.Text())- }-- title := "autopilot private-assignee child " + t.Name()- if count := dbfx.Count(t, `SELECT count(*) FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title); count != 0 {- t.Fatalf("cross-workspace parent rejection created %d issue rows", count)- }- })+ for _, id := range []string{ownIssueID, otherIssueID} {+ if got := assigneeOf(t, id); got != workerID {+ t.Fatalf("issue %s assignee = %q, want %q", id, got, workerID)+ }}})- t.Run("non-autopilot parent is denied", func(t *testing.T) {- workerID, ownerID, _ := privateAgentTestFixture(t)- fx := newAutopilotDelegationFixture(t, workerID, ownerID, "")+ t.Run("assigns nothing when the run's human holds no rights", func(t *testing.T) {+ // The batch endpoint SKIPS an issue whose assignee validation fails and+ // still answers 200 — a partial success the caller is not told about. That+ // is pre-existing behaviour, pinned here because the mixed-outcome case is+ // now reachable through ordinary permissions rather than a borrow scope.+ workerID, _, plainMemberID := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, plainMemberID)+ issueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)- testutil.Call(t, testHandler.CreateIssue,- autopilotChildIssueRequest(t, "agent", workerID, uuidToString(fx.Issue.ID), "backlog", fx.LeaderAgentID, fx.LeaderTaskID),- ).Want(http.StatusForbidden)+ batchAssignAsRun(t, plainMemberID, fx.LeaderAgentID, fx.LeaderTaskID, workerID, issueID).+ Want(http.StatusOK)++ if got := assigneeOf(t, issueID); got != "" {+ t.Fatalf("issue was assigned to %q despite no invoke rights", got)+ }+ if total, _ := tasksFor(t, issueID, workerID); total != 0 {+ t.Fatalf("enqueued %d tasks despite no invoke rights", total)+ }+ })++ t.Run("assigns nothing when the run carries no human", func(t *testing.T) {+ workerID, ownerID, plainMemberID := privateAgentTestFixture(t)+ fx := newRunOnlyAutopilotFixture(t, workerID, ownerID, noHumanOnRun())+ issueID := createUnassignedIssueAsRun(t, fx.LeaderAgentID, fx.LeaderTaskID)++ batchAssignAsRun(t, plainMemberID, fx.LeaderAgentID, fx.LeaderTaskID, workerID, issueID).+ Want(http.StatusOK)++ if got := assigneeOf(t, issueID); got != "" {+ t.Fatalf("issue was assigned to %q by a run with no human", got)+ }})}diff --git a/server/internal/handler/issue_autopilot_run_only_assignment_test.go b/server/internal/handler/issue_autopilot_run_only_assignment_test.godeleted file mode 100644index e531718aef..0000000000--- a/server/internal/handler/issue_autopilot_run_only_assignment_test.go+++ /dev/null@@ -1,598 +0,0 @@-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/issue_create_position_test.go b/server/internal/handler/issue_create_position_test.goindex 3adf250269..e0dfef09eb 100644--- a/server/internal/handler/issue_create_position_test.go+++ b/server/internal/handler/issue_create_position_test.go@@ -175,7 +175,7 @@ func TestAutopilotCreateIssuePositionBelowCurrentMinimum(t *testing.T) {if err != nil {t.Fatalf("GetAutopilot: %v", err)}- run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)+ run, _, err := testHandler.AutopilotService.DispatchAutopilotManual(ctx, ap, pgtype.UUID{}, nil, parseUUID(testUserID))if err != nil {t.Fatalf("DispatchAutopilot: %v", err)}diff --git a/server/internal/handler/quick_action.go b/server/internal/handler/quick_action.goindex 7f6580f469..c1bca86326 100644--- a/server/internal/handler/quick_action.go+++ b/server/internal/handler/quick_action.go@@ -918,8 +918,7 @@ func (h *Handler) RunQuickAction(w http.ResponseWriter, r *http.Request) {"issue_revision": created.IssueRevision,})- delegationAuthority := h.autopilotDelegationAuthorityFromRequest(r, issue, actorType, actorID)- resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, nil, actorType, actorID, originatorUserID, delegationAuthority, nil)+ resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, nil, actorType, actorID, originatorUserID, nil)// Usage telemetry is best-effort and deliberately outside the run's// success path: a failed counter must never cost the user the run.diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.goindex 29d96a3c08..4b660d5a34 100644--- a/server/internal/handler/source_context.go+++ b/server/internal/handler/source_context.go@@ -653,7 +653,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, scopeNoDelegation()); code != 0 {+ if code, message := h.validateAssigneePair(r.Context(), r, util.UUIDToString(workspaceID), assigneeType, assigneeID); code != 0 {writeError(w, code, message)return errSourceContextResponseWritten}@@ -766,7 +766,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, scopeNoDelegation()); status != 0 {+ if status, message := h.validateAssigneePair(r.Context(), r, util.UUIDToString(workspaceID), pgtype.Text{String: "agent", Valid: true}, agentID); status != 0 {writeError(w, status, message)return nil, errSourceContextResponseWritten}diff --git a/server/internal/handler/trigger_test.go b/server/internal/handler/trigger_test.goindex c066606cad..61295747d5 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/admission_mul4525_test.go b/server/internal/service/admission_mul4525_test.goindex ddc1abbe6b..27a0fee457 100644--- a/server/internal/service/admission_mul4525_test.go+++ b/server/internal/service/admission_mul4525_test.go@@ -128,19 +128,19 @@ func TestAutopilotDispatchAdmitsClickerNotCreator(t *testing.T) {svc := &AutopilotService{Queries: q}// Manual dispatch by the agent owner (the clicker) is admitted.- if reason, _, skip := svc.shouldSkipDispatch(ctx, ap, util.MustParseUUID(ownerID)); skip {+ if reason, _, skip := svc.shouldSkipDispatch(ctx, ap, util.MustParseUUID(ownerID), pgtype.UUID{}); skip {t.Fatalf("manual dispatch by the agent owner should be admitted, got skip: %q", reason)}- // Automation (no human actor) falls back to the creator gate, which denies- // the admin-but-non-owner creator on a private agent — and the typed reason- // code is decided at that branch, not guessed from text.- reason, code, skip := svc.shouldSkipDispatch(ctx, ap, pgtype.UUID{})+ // Automation (no human actor) resolves the trigger's creator (MUL-6951). With+ // no trigger id there is no principal at all, so it denies — and the typed+ // reason code is decided at that branch, not guessed from text.+ reason, code, skip := svc.shouldSkipDispatch(ctx, ap, pgtype.UUID{}, pgtype.UUID{})if !skip {- t.Fatalf("automation dispatch should be blocked by the creator gate")+ t.Fatalf("automation dispatch with no resolvable principal should be blocked")}- if !strings.Contains(strings.ToLower(reason), "creator") {- t.Errorf("automation skip reason = %q, want creator-gate phrasing", reason)+ if !strings.Contains(strings.ToLower(reason), "trigger") {+ t.Errorf("automation skip reason = %q, want the trigger-principal phrasing", reason)}if code != dispatch.ReasonInvocationNotAllowed {t.Errorf("skip reason_code = %q, want invocation_not_allowed", code)diff --git a/server/internal/service/attribution_stamp_test.go b/server/internal/service/attribution_stamp_test.goindex 01225c678d..1b6812331c 100644--- a/server/internal/service/attribution_stamp_test.go+++ b/server/internal/service/attribution_stamp_test.go@@ -395,8 +395,9 @@ func TestTriggerOwnerAttribution_ScheduleTriggerCreator(t *testing.T) {// Schedule trigger whose responsible publisher is the creating member.var triggerID stringif err := pool.QueryRow(ctx, `- INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, published_by_type, published_by_id)- VALUES ($1, 'schedule', true, '0 * * * *', 'member', $2) RETURNING id`,+ INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression,+ published_by_type, published_by_id, created_by_type, created_by_id)+ VALUES ($1, 'schedule', true, '0 * * * *', 'member', $2, 'member', $2) RETURNING id`,autopilotID, creatorID).Scan(&triggerID); err != nil {t.Fatalf("seed trigger: %v", err)}@@ -407,8 +408,10 @@ func TestTriggerOwnerAttribution_ScheduleTriggerCreator(t *testing.T) {if got.Source != attribution.SourceTriggerOwner {t.Fatalf("source = %q, want trigger_owner", got.Source)}- if got.UserID.Valid {- t.Errorf("trigger_owner is audit-only; originator must stay NULL, got %s", util.UUIDToString(got.UserID))+ // MUL-6951: the trigger owner is the ORIGINATOR, not an audit-only accountable —+ // arming a trigger authorizes its runs the same way clicking "run now" does.+ if !got.UserID.Valid || got.UserID.Bytes != util.MustParseUUID(creatorID).Bytes {+ t.Errorf("originator = %s, want trigger creator %s", util.UUIDToString(got.UserID), creatorID)}if !got.AccountableUserID.Valid || got.AccountableUserID.Bytes != util.MustParseUUID(creatorID).Bytes {t.Errorf("accountable = %s, want trigger creator %s", util.UUIDToString(got.AccountableUserID), creatorID)@@ -482,11 +485,17 @@ func seedExtraMember(t *testing.T, pool *pgxpool.Pool, workspaceID, label string// TestTriggerOwnerAttribution_TransfersToSubstantiveEditor is Elon's must-fix// acceptance test: it drives the REAL triggerOwnerAttribution resolver (not the// ruleOwnerAttribution helper) across the SAME queries the handlers use, and proves-// both halves of the pinned model — (1) responsibility TRANSFERS from the creator to-// whoever substantively edits the trigger, and (2) a trigger-scoped edit re-stamps-// ONLY that trigger, never a sibling. It also proves an autopilot-level edit bumps-// every trigger together (MUL-4302).-func TestTriggerOwnerAttribution_TransfersToSubstantiveEditor(t *testing.T) {+// the model MUL-6951 settled: the run's human is the trigger's IMMUTABLE creator and+// a substantive edit does NOT move it, while published_by still transfers so the+// trigger row keeps recording who last took responsibility for its config.+//+// Bohan's ruling on the MUL-6951 thread: collaborative editing is an edge case, and+// making an edit silently re-authorize the automation as the editor is worse than+// keeping it on the creator. Note the consequence this locks in — because the DB+// invariant (migrations 190/197) forces accountable == originator whenever the+// originator is set, the TASK row now names the creator on both columns. The+// editor's responsibility is still recorded, on autopilot_trigger.published_by.+func TestTriggerOwnerAttribution_StaysWithTriggerCreator(t *testing.T) {pool := newResolveOriginatorPool(t)ctx := context.Background()q := db.New(pool)@@ -507,8 +516,9 @@ func TestTriggerOwnerAttribution_TransfersToSubstantiveEditor(t *testing.T) {seedTrigger := func(cron string) string {var id stringif err := pool.QueryRow(ctx, `- INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, published_by_type, published_by_id)- VALUES ($1, 'schedule', true, $2, 'member', $3) RETURNING id`,+ INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression,+ published_by_type, published_by_id, created_by_type, created_by_id)+ VALUES ($1, 'schedule', true, $2, 'member', $3, 'member', $3) RETURNING id`,autopilotID, cron, creatorA).Scan(&id); err != nil {t.Fatalf("seed trigger: %v", err)}@@ -517,25 +527,26 @@ func TestTriggerOwnerAttribution_TransfersToSubstantiveEditor(t *testing.T) {trigger1 := seedTrigger("0 * * * *")trigger2 := seedTrigger("0 0 * * *")- accountableOf := func(triggerID string) string {+ principalOf := func(triggerID string) string {got := triggerOwnerAttribution(ctx, q,util.MustParseUUID(triggerID), util.MustParseUUID(workspaceID), util.MustParseUUID(autopilotID),attribution.EvidenceAutopilotRun, util.MustParseUUID(autopilotID))if got.Source != attribution.SourceTriggerOwner {t.Fatalf("trigger %s: source = %q, want trigger_owner", triggerID, got.Source)}- if got.UserID.Valid {- t.Fatalf("trigger_owner is audit-only; originator must stay NULL, got %s", util.UUIDToString(got.UserID))+ if got.UserID != got.AccountableUserID {+ t.Fatalf("trigger %s: originator %s and accountable %s must be the same human",+ triggerID, util.UUIDToString(got.UserID), util.UUIDToString(got.AccountableUserID))}- return util.UUIDToString(got.AccountableUserID)+ return util.UUIDToString(got.UserID)}- // Baseline: both triggers attribute to creator A.- if a := accountableOf(trigger1); a != creatorA {- t.Fatalf("trigger1 baseline accountable = %s, want creator %s", a, creatorA)+ // Baseline: both triggers run as creator A.+ if a := principalOf(trigger1); a != creatorA {+ t.Fatalf("trigger1 baseline principal = %s, want creator %s", a, creatorA)}- if a := accountableOf(trigger2); a != creatorA {- t.Fatalf("trigger2 baseline accountable = %s, want creator %s", a, creatorA)+ if a := principalOf(trigger2); a != creatorA {+ t.Fatalf("trigger2 baseline principal = %s, want creator %s", a, creatorA)}// B substantively edits trigger1 — the SAME query UpdateAutopilotTrigger runs.@@ -547,13 +558,23 @@ func TestTriggerOwnerAttribution_TransfersToSubstantiveEditor(t *testing.T) {t.Fatalf("SetAutopilotTriggerPublisher: %v", err)}- // Transfer: trigger1 now attributes to editor B, NOT the original creator.- if a := accountableOf(trigger1); a != editorB {- t.Fatalf("after edit, trigger1 accountable = %s, want editor %s (responsibility must transfer)", a, editorB)+ // The edit moves published_by but NOT the run's human: an editor must not be+ // able to re-point the automation at their own rights (MUL-6951).+ var published1 pgtype.UUID+ if err := pool.QueryRow(ctx, `SELECT published_by_id FROM autopilot_trigger WHERE id = $1`,+ util.MustParseUUID(trigger1)).Scan(&published1); err != nil {+ t.Fatalf("read published_by: %v", err)}- // Isolation: editing trigger1 must NOT move trigger2 — it stays with creator A.- if a := accountableOf(trigger2); a != creatorA {- t.Fatalf("trigger2 accountable = %s, want creator %s (editing a sibling must not transfer)", a, creatorA)+ if util.UUIDToString(published1) != editorB {+ t.Fatalf("published_by = %s, want editor %s (trigger-level responsibility must still transfer)",+ util.UUIDToString(published1), editorB)+ }+ if a := principalOf(trigger1); a != creatorA {+ t.Fatalf("after edit, trigger1 principal = %s, want creator %s (an edit must not re-authorize)", a, creatorA)+ }+ // Isolation is unchanged: neither trigger's principal moves.+ if a := principalOf(trigger2); a != creatorA {+ t.Fatalf("trigger2 principal = %s, want creator %s", a, creatorA)}// C makes an autopilot-level substantive edit — the SAME bump-all query@@ -565,12 +586,15 @@ func TestTriggerOwnerAttribution_TransfersToSubstantiveEditor(t *testing.T) {}); err != nil {t.Fatalf("SetAutopilotTriggerPublishersByAutopilot: %v", err)}- if a := accountableOf(trigger1); a != editorC {- t.Fatalf("after autopilot-level edit, trigger1 accountable = %s, want %s", a, editorC)+ // Same rule at the autopilot level: the bump-all edit moves published_by on both+ // triggers, and neither run's human moves with it.+ if a := principalOf(trigger1); a != creatorA {+ t.Fatalf("after autopilot-level edit, trigger1 principal = %s, want creator %s", a, creatorA)}- if a := accountableOf(trigger2); a != editorC {- t.Fatalf("after autopilot-level edit, trigger2 accountable = %s, want %s", a, editorC)+ if a := principalOf(trigger2); a != creatorA {+ t.Fatalf("after autopilot-level edit, trigger2 principal = %s, want creator %s", a, creatorA)}+ _ = editorC}// TestEnqueueTaskForIssueAutopilotOriginStampsRuleOwner is the acceptance test for@@ -631,8 +655,12 @@ func TestEnqueueTaskForIssueAutopilotOriginStampsRuleOwner(t *testing.T) {if source.String != string(attribution.SourceRuleOwner) {t.Errorf("originator_source = %q, want rule_owner", source.String)}+ // rule_owner stays AUDIT-ONLY (MUL-6951, Elon review): the rule publisher never+ // armed anything, so promoting that guess to an authorization identity would+ // hand a legacy trigger somebody's invoke rights. Originator stays NULL and the+ // invoke gate fails closed.if originator.Valid {- t.Errorf("autopilot run must NOT set originator (authorization stays NULL), got %s", util.UUIDToString(originator))+ t.Errorf("rule_owner must not set originator, got %s", util.UUIDToString(originator))}if !accountable.Valid || accountable.Bytes != util.MustParseUUID(publisherID).Bytes {t.Errorf("accountable_user_id = %s, want rule publisher %s", util.UUIDToString(accountable), publisherID)@@ -809,8 +837,9 @@ func TestDispatchRunOnlyScheduleStampsRuleOwnerRow(t *testing.T) {if source.String != string(attribution.SourceRuleOwner) {t.Errorf("originator_source = %q, want rule_owner", source.String)}+ // rule_owner stays AUDIT-ONLY — see the create_issue case above (MUL-6951).if originator.Valid {- t.Errorf("run_only autopilot must NOT set originator, got %s", util.UUIDToString(originator))+ t.Errorf("rule_owner must not set originator, got %s", util.UUIDToString(originator))}if !accountable.Valid || accountable.Bytes != util.MustParseUUID(publisherID).Bytes {t.Errorf("accountable_user_id = %s, want publisher %s", util.UUIDToString(accountable), publisherID)@@ -883,15 +912,13 @@ func TestDispatchRunOnlyManualStampsDirectHuman(t *testing.T) {}}-// TestDispatchRunOnlyScheduleTransfersToEditor is Elon's must-fix REAL dispatch test:-// it drives dispatchRunOnly end to end (schedule-style, no member actor) and asserts-// the PERSISTED agent_task_queue row's accountable_user_id follows the trigger's-// current responsible publisher after a substantive edit — the creator seeds it, then-// a later editor's re-stamp (the same SetAutopilotTriggerPublisher the UpdateTrigger-// handler runs) makes future runs attribute to the editor, with originator still NULL-// (MUL-4302). The resolver-level before/after and per-trigger isolation are covered by-// TestTriggerOwnerAttribution_TransfersToSubstantiveEditor.-func TestDispatchRunOnlyScheduleTransfersToEditor(t *testing.T) {+// TestDispatchRunOnlyScheduleStaysWithTriggerCreator drives dispatchRunOnly end to+// end (schedule-style, no member actor) and asserts the PERSISTED+// agent_task_queue row names the trigger's CREATOR on both attribution columns even+// after a substantive edit re-stamped published_by to someone else — the run must not+// be re-authorized by an edit (MUL-6951). The resolver-level before/after and+// per-trigger isolation are covered by TestTriggerOwnerAttribution_StaysWithTriggerCreator.+func TestDispatchRunOnlyScheduleStaysWithTriggerCreator(t *testing.T) {pool := newResolveOriginatorPool(t)ctx := context.Background()q := db.New(pool)@@ -910,8 +937,9 @@ func TestDispatchRunOnlyScheduleTransfersToEditor(t *testing.T) {// Schedule trigger initially published by creator A, then edited by B.var triggerID stringif err := pool.QueryRow(ctx, `- INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, published_by_type, published_by_id)- VALUES ($1, 'schedule', true, '0 * * * *', 'member', $2) RETURNING id`,+ INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression,+ published_by_type, published_by_id, created_by_type, created_by_id)+ VALUES ($1, 'schedule', true, '0 * * * *', 'member', $2, 'member', $2) RETURNING id`,autopilotID, creatorA).Scan(&triggerID); err != nil {t.Fatalf("seed trigger: %v", err)}@@ -956,12 +984,15 @@ func TestDispatchRunOnlyScheduleTransfersToEditor(t *testing.T) {if source.String != string(attribution.SourceTriggerOwner) {t.Errorf("originator_source = %q, want trigger_owner", source.String)}- if originator.Valid {- t.Errorf("schedule dispatch must NOT set originator, got %s", util.UUIDToString(originator))+ // MUL-6951: B's edit re-stamped published_by, but the run still executes with+ // A's rights. An editor changing a cron expression must not be able to hand the+ // automation their own access.+ if !originator.Valid || originator.Bytes != util.MustParseUUID(creatorA).Bytes {+ t.Errorf("originator_user_id = %s, want trigger creator %s (not editor %s)",+ util.UUIDToString(originator), creatorA, editorB)}- if !accountable.Valid || accountable.Bytes != util.MustParseUUID(editorB).Bytes {- t.Errorf("accountable_user_id = %s, want editor %s (dispatch must follow the transferred publisher, not creator %s)",- util.UUIDToString(accountable), editorB, creatorA)+ if !accountable.Valid || accountable.Bytes != util.MustParseUUID(creatorA).Bytes {+ t.Errorf("accountable_user_id = %s, want trigger creator %s", util.UUIDToString(accountable), creatorA)}}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 8a81394de1..2cc627b84b 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -124,8 +124,11 @@ func (s *AutopilotService) DispatchAutopilot(payload []byte,) (*db.AutopilotRun, error) {// No member actor on this entry point (schedule / webhook / api, or a manual- // trigger without a resolved member): attribution resolves rule_owner. These- // callers don't surface a per-run reason code to a human, so it is dropped.+ // trigger without a resolved member): the run acts as the trigger's creator+ // (trigger_owner), degrading to the audit-only rule_owner when no creator is+ // recoverable — in which case it carries no authorization at all (MUL-6951).+ // These callers don't surface a per-run reason code to a human, so it is+ // dropped.// webhookDeliveryID is invalid here — durable webhook deliveries admit through// AdmitAutopilotWebhookDelivery instead of this entry point.run, _, err := s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, pgtype.Timestamptz{}, pgtype.UUID{}, pgtype.UUID{}, source+":"+newAutopilotIdempotencyKey())@@ -133,8 +136,9 @@ func (s *AutopilotService) DispatchAutopilot(}// DispatchAutopilotManual is the "run now" entry point for a member manually-// triggering an autopilot. Unlike scheduled / webhook / api dispatch (no human in-// the loop → rule_owner), a manual trigger is a direct human action: the run is+// triggering an autopilot. Scheduled / webhook / api dispatch acts as the firing+// trigger's creator (MUL-6951); a manual trigger is a direct human action by the+// CLICKER instead, so it need not consult the trigger at all: the run is// attributed direct_human to actorUserID, which becomes BOTH its originator// (authorization) and accountable human (MUL-4302 §4), across both execution modes.// An invalid actorUserID behaves exactly like DispatchAutopilot(source="manual").@@ -189,9 +193,10 @@ func (s *AutopilotService) AdmitAutopilotWebhookDelivery(return nil, fmt.Errorf("admit webhook delivery: lookup existing run: %w", err)}- // Webhook admission has no member actor → automation principal (rule_owner);- // the per-run reason code is not surfaced to a human here, so it is dropped.- if reason, _, skip := s.shouldSkipDispatch(ctx, autopilot, pgtype.UUID{}); skip {+ // Webhook admission has no member actor → the automation principal is this+ // trigger's creator (MUL-6951); the per-run reason code is not surfaced to a+ // human here, so it is dropped.+ if reason, _, skip := s.shouldSkipDispatch(ctx, autopilot, pgtype.UUID{}, triggerID); skip {run, err := s.recordSkippedRun(ctx,autopilot,@@ -463,9 +468,9 @@ func (s *AutopilotService) DispatchAutopilotForPlan(return nil, fmt.Errorf("dispatch for plan: lookup existing run: %w", err)}- // Scheduled dispatch has no member actor → rule_owner attribution, and no- // human surface for a per-run reason code, so it is dropped. No webhook- // delivery on the scheduled-plan path.+ // Scheduled dispatch has no member actor → it acts as the trigger's creator+ // (trigger_owner, MUL-6951), and has no human surface for a per-run reason+ // code, so it is dropped. No webhook delivery on the scheduled-plan path.key := "schedule:" + util.UUIDToString(triggerID) + ":" + plannedAt.UTC().Format(time.RFC3339Nano)run, _, err := s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, plannedTS, pgtype.UUID{}, pgtype.UUID{}, key)return run, err@@ -522,7 +527,7 @@ func (s *AutopilotService) dispatchAutopilot(actorUserID pgtype.UUID,idempotencyKey string,) (*db.AutopilotRun, dispatch.ReasonCode, error) {- if reason, code, skip := s.shouldSkipDispatch(ctx, autopilot, actorUserID); skip {+ if reason, code, skip := s.shouldSkipDispatch(ctx, autopilot, actorUserID, triggerID); skip {run, err := s.recordSkippedRun(ctx, autopilot, triggerID, source, payload, plannedAt, webhookDeliveryID, reason)return run, code, err}@@ -795,14 +800,15 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi// actor-carrying entry points so attribution resolves direct_human to the// triggering member (originator == accountable == actor, MUL-4302 §4). Schedule /// webhook dispatch has no actor and takes the plain entry points, where the- // autopilot-origin issue resolves to rule_owner. The *WithHandoff variants are- // the existing actor-carrying enqueue methods; the handoff note is empty here.+ // autopilot-origin issue resolves to the trigger's creator (MUL-6951). The+ // *WithHandoff variants are the existing actor-carrying enqueue methods; the+ // handoff note is empty here.if ap.AssigneeType == "squad" {// Fail-closed invocation gate: verify the admission principal (manual// clicker, else creator — see autopilotAdmitInvoke) may still invoke the// leader. Catches configs that predate the save-time gate, and configs// that no longer pass (MUL-3963 / MUL-4525).- if !s.autopilotAdmitInvoke(ctx, ap, leader, actorUserID) {+ if !s.autopilotAdmitInvoke(ctx, ap, leader, actorUserID, run.TriggerID) {return fmt.Errorf("not allowed to invoke private squad leader")}if actorUserID.Valid {@@ -959,20 +965,23 @@ func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot,// Fail-closed invocation gate for squad autopilots (admission principal =// manual clicker, else creator — see autopilotAdmitInvoke).- if ap.AssigneeType == "squad" && !s.autopilotAdmitInvoke(ctx, ap, agent, actorUserID) {+ if ap.AssigneeType == "squad" && !s.autopilotAdmitInvoke(ctx, ap, agent, actorUserID, run.TriggerID) {return &errDispatchSkipped{reason: formatAdmissionReason(ap, "not allowed to invoke private squad leader"), code: dispatch.ReasonInvocationNotAllowed}}- // Attribution splits on the trigger. A MANUAL trigger is a direct human action:- // the triggering member is direct_human and becomes BOTH originator (so the run- // carries their authorization context) and accountable (MUL-4302 §4). A- // schedule / webhook trigger has no human — originator_user_id stays NULL and- // the audit-accountable human is the member currently RESPONSIBLE for the firing- // trigger's effective config (its creator, then whoever last substantively edited- // it) — trigger_owner, resolved from run.TriggerID (MUL-4302; Elon must-fix) —- // degrading to the rule version publisher (rule_owner) when no such member is- // recoverable, then to unattributed. Either way evidence points at the autopilot- // run and the row is never a NULL-source bypass.+ // Attribution splits on the trigger only to pick WHICH human and which source+ // label; both branches now produce a real originator. A MANUAL trigger is a+ // direct human action: the triggering member is direct_human (MUL-4302 §4). A+ // schedule / webhook trigger resolves the firing trigger's immutable CREATOR —+ // trigger_owner, from run.TriggerID (MUL-4302; MUL-6951) — degrading to the rule+ // version publisher (rule_owner, audit-only) when no creator is recoverable, then+ // to unattributed. An edit of the trigger does NOT move this: published_by+ // transfers, created_by does not. Since MUL-6951 that human is the originator+ // too, so an armed autopilot runs with its creator's authorization instead of+ // borrowing narrowly-scoped capabilities per surface; the source label is what+ // keeps "fired on a schedule" distinguishable from "a human clicked run". Either+ // way evidence points at the autopilot run and the row is never a NULL-source+ // bypass.var autopilotAttr attribution.Resultif actorUserID.Valid {autopilotAttr = attribution.DirectHumanRun(actorUserID, attribution.EvidenceAutopilotRun, run.ID)@@ -1275,7 +1284,7 @@ func (s *AutopilotService) failRun(ctx context.Context, runID pgtype.UUID, reaso// scheduled run. Migration 096 removed the agent FK on autopilot, so an// agent assignee being missing is now a real condition the gate must// handle (previously cascade-deleted).-func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopilot, actorUserID pgtype.UUID) (string, dispatch.ReasonCode, bool) {+func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopilot, actorUserID, triggerID pgtype.UUID) (string, dispatch.ReasonCode, bool) {if !ap.AssigneeID.Valid {return "autopilot has no assignee", dispatch.ReasonTargetUnavailable, true}@@ -1342,15 +1351,16 @@ func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopil// "run now" (actorUserID valid) is a direct human action gated by the// current CLICKER's access — not the autopilot creator's — so admission and// attribution credit the same member and never fork. Automation (schedule /- // webhook / api, actorUserID invalid) has no human in the loop and falls- // back to the creator. Admins do NOT bypass a private agent they do not own;+ // webhook / api, actorUserID invalid) preserves that same property by+ // resolving the trigger's creator, which is also the human the run will act+ // as (MUL-6951). Admins do NOT bypass a private agent they do not own;// agent-created autopilots are judged as workspace principals. For squad// autopilots the gate runs against the resolved leader.- if !s.autopilotAdmitInvoke(ctx, ap, agent, actorUserID) {+ if !s.autopilotAdmitInvoke(ctx, ap, agent, actorUserID, triggerID) {if actorUserID.Valid {return "you are not allowed to trigger this autopilot's assignee agent", dispatch.ReasonInvocationNotAllowed, true}- return "autopilot creator lacks access to private assignee agent", dispatch.ReasonInvocationNotAllowed, true+ return "this trigger's owner lacks access to the private assignee agent, or the trigger records no owner", dispatch.ReasonInvocationNotAllowed, true}return "", "", false}@@ -1842,27 +1852,27 @@ func (s *AutopilotService) getIssuePrefix(workspaceID pgtype.UUID) string {return ws.IssuePrefix}-// canCreatorInvokeAgent checks whether the autopilot's creator may invoke the-// target agent under the invocation-permission model (MUL-3963). It mirrors-// handler.canInvokeAgent with the autopilot creator as the effective user:-// - member creator who owns the agent -> always-// - private agent -> only the owner (NO admin bypass, NO agent-created bypass)-// - public_to agent -> workspace target admits any workspace-member creator-// (and agent-created autopilots as workspace principals); member target-// admits the matching creator; team targets are inert.-//-// Fail-closed on any lookup error.// autopilotAdmitInvoke decides whether the dispatch's admission principal may// invoke the target agent (MUL-4525). A MANUAL "run now" (actorUserID valid) is// a direct human action gated by the CURRENT clicker's access, so admission and// attribution credit the same member. Automation (schedule / webhook / api,-// actorUserID invalid) has no human in the loop and falls back to the autopilot-// creator. Both branches fail closed and never grant an admin bypass.-func (s *AutopilotService) autopilotAdmitInvoke(ctx context.Context, ap db.Autopilot, agent db.Agent, actorUserID pgtype.UUID) bool {+// actorUserID invalid) resolves the trigger's creator — the same human the run+// itself will act as (MUL-6951). Both branches fail closed and never grant an admin bypass.+func (s *AutopilotService) autopilotAdmitInvoke(ctx context.Context, ap db.Autopilot, agent db.Agent, actorUserID, triggerID pgtype.UUID) bool {if actorUserID.Valid {return s.canMemberInvokeAgent(ctx, agent, actorUserID, ap.WorkspaceID)}- return s.canCreatorInvokeAgent(ctx, ap, agent)+ // Automation admits as the SAME human the run will act as (MUL-6951). Before+ // that, admission used the autopilot CREATOR while the run took its identity+ // from the trigger, so A creating an autopilot over A's private agent and B+ // owning the trigger produced a dispatch admitted as A but running as B —+ // rights neither of them holds alone. Resolving both from+ // ResolveAutopilotTriggerPrincipal makes that fork unrepresentable.+ principal := ResolveAutopilotTriggerPrincipal(ctx, s.Queries, triggerID, ap.ID, ap.WorkspaceID)+ if !principal.Valid {+ return false+ }+ return s.canMemberInvokeAgent(ctx, agent, principal, ap.WorkspaceID)}// canMemberInvokeAgent checks whether a specific member may invoke the agent@@ -1906,44 +1916,3 @@ func (s *AutopilotService) canMemberInvokeAgent(ctx context.Context, agent db.Ag}return false}--func (s *AutopilotService) canCreatorInvokeAgent(ctx context.Context, ap db.Autopilot, agent db.Agent) bool {- creatorID := util.UUIDToString(ap.CreatedByID)- if ap.CreatedByType == "member" && util.UUIDToString(agent.OwnerID) == creatorID {- return true- }- if agent.PermissionMode != "public_to" {- // private (or unknown mode): deny-by-default; only the owner branch- // above passes. Admins and agent-created autopilots do not bypass.- return false- }- targets, err := s.Queries.ListAgentInvocationTargets(ctx, agent.ID)- if err != nil {- return false- }- // Agent-created autopilots are workspace-internal principals: a workspace- // target admits them. Member creators must be workspace members.- workspaceBroad := ap.CreatedByType == "agent"- isWorkspaceMember := false- if ap.CreatedByType == "member" {- if _, err := s.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{- UserID: ap.CreatedByID,- WorkspaceID: ap.WorkspaceID,- }); err == nil {- isWorkspaceMember = true- }- }- for _, t := range targets {- switch t.TargetType {- case "workspace":- if isWorkspaceMember || workspaceBroad {- return true- }- case "member":- if ap.CreatedByType == "member" && util.UUIDToString(t.TargetID) == creatorID {- return true- }- }- }- return false-}diff --git a/server/internal/service/autopilot_quota_test.go b/server/internal/service/autopilot_quota_test.goindex 8da1ca0acf..a9803aad8c 100644--- a/server/internal/service/autopilot_quota_test.go+++ b/server/internal/service/autopilot_quota_test.go@@ -1026,8 +1026,8 @@ func TestAutopilotQuotaSchedulePersistsSkippedRun(t *testing.T) {}var triggerID pgtype.UUIDif err := pool.QueryRow(ctx, `- INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, timezone)- VALUES ($1, 'schedule', true, '0 * * * *', 'UTC') RETURNING id`, autopilot.ID).Scan(&triggerID); err != nil {+ INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, timezone, created_by_type, created_by_id)+ VALUES ($1, 'schedule', true, '0 * * * *', 'UTC', 'member', $2) RETURNING id`, autopilot.ID, publisherID).Scan(&triggerID); err != nil {t.Fatalf("create schedule trigger: %v", err)}svc := &AutopilotService{diff --git a/server/internal/service/autopilot_run_principal_test.go b/server/internal/service/autopilot_run_principal_test.gonew file mode 100644index 0000000000..97b4474085--- /dev/null+++ b/server/internal/service/autopilot_run_principal_test.go@@ -0,0 +1,264 @@+package service++import (+ "context"+ "fmt"+ "sync/atomic"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// MUL-6951 (Elon review). One automatic dispatch must resolve exactly ONE human+// and use it for everything: admitting the first agent, stamping the task, and+// every run delegated from it.+//+// The bug these tests exist for: admission used to ask "may the AUTOPILOT CREATOR+// invoke this agent?" while the task took its identity from the trigger. With A+// owning both the autopilot and a private agent, and B owning the trigger, the+// dispatch was admitted as A and then executed as B — a combination neither of+// them can produce by hand. The previous suite missed it because it called+// dispatchRunOnly directly, which skips admission entirely; these drive+// DispatchAutopilot so the gate actually runs.++// principalSeq keeps generated names and emails unique across parallel subtests.+var principalSeq atomic.Int64++// principalFixture is the service-package equivalent of the handler suite's dbfx:+// every row these tests create goes through testutil.Fixture, which registers its+// own cleanup, so this file open-codes no INSERT / DELETE pairs.+//+// It deliberately does NOT reuse this package's seedAttributionFixture: that+// helper raw-inserts its user / workspace / member / runtime / agent with matching+// hand-written cleanups, which is the pattern CLAUDE.md prohibits for new tests,+// and it builds an agent and issue these tests do not use.+type principalFixture struct {+ *testutil.Fixture+ svc *AutopilotService+ q *db.Queries+}++func newPrincipalFixture(t *testing.T) (principalFixture, string) {+ t.Helper()+ pool := newResolveOriginatorPool(t)+ q := db.New(pool)++ // Bootstrap: Fixture.User and Fixture.Workspace do not read the fixture's own+ // WorkspaceID / UserID, so an unbound fixture can create the base identity and+ // then adopt it. Cleanup runs in reverse creation order, so the member row goes+ // before the workspace and user it references.+ n := principalSeq.Add(1)+ fx := testutil.New(pool, "", "")+ ownerUserID := fx.User(t, "principal owner", fmt.Sprintf("principal-owner-%[email protected]", n))+ workspaceID := fx.Workspace(t, "principal ws", fmt.Sprintf("principal-ws-%d", n))+ fx.Member(t, workspaceID, ownerUserID, "owner")+ fx.WorkspaceID = workspaceID+ fx.UserID = ownerUserID++ return principalFixture{+ Fixture: fx,+ q: q,+ svc: &AutopilotService{+ Queries: q, TxStarter: pool, Bus: events.New(),+ TaskSvc: &TaskService{Queries: q, TxStarter: pool, Bus: events.New()},+ },+ }, ownerUserID+}++// member adds a fresh workspace member and returns their user id.+func (f principalFixture) member(t *testing.T, label string) string {+ t.Helper()+ n := principalSeq.Add(1)+ userID := f.User(t, label, fmt.Sprintf("%s-%[email protected]", label, n))+ f.Member(t, f.WorkspaceID, userID, "member")+ return userID+}++// privateAgentOwnedBy builds a PRIVATE agent, so only its owner may invoke it and+// the gate's verdict names exactly which human was consulted. Fixture.Agent+// already defaults permission_mode/visibility to private; only the owner moves.+func (f principalFixture) privateAgentOwnedBy(t *testing.T, ownerID, label string) string {+ t.Helper()+ n := principalSeq.Add(1)+ runtimeID := f.Runtime(t, fmt.Sprintf("rt-%s-%d", label, n), testutil.Cols{"owner_id": ownerID})+ return f.Agent(t, fmt.Sprintf("agent-%s-%d", label, n), runtimeID, testutil.Cols{"owner_id": ownerID})+}++// autopilotWithTrigger wires a run_only autopilot created by apCreatorID over+// agentID, with one schedule trigger created by trigCreatorID. The two creators+// are independent — that separation is where the fork lived.+func (f principalFixture) autopilotWithTrigger(t *testing.T, agentID, apCreatorID, trigCreatorID string) (string, string) {+ t.Helper()+ n := principalSeq.Add(1)+ autopilotID := f.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": f.WorkspaceID,+ "title": fmt.Sprintf("principal-ap-%d", n),+ "assignee_type": "agent",+ "assignee_id": agentID,+ "status": "active",+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": apCreatorID,+ })+ triggerID := f.trigger(t, autopilotID, "member", trigCreatorID)+ return autopilotID, triggerID+}++// trigger inserts a schedule trigger. createdByType / createdByID are passed+// through untouched so a test can build the legacy (NULL) shape.+func (f principalFixture) trigger(t *testing.T, autopilotID string, createdByType, createdByID any) string {+ t.Helper()+ n := principalSeq.Add(1)+ return f.Insert(t, "autopilot_trigger", testutil.Cols{+ "autopilot_id": autopilotID,+ "kind": "schedule",+ "enabled": true,+ "cron_expression": fmt.Sprintf("%d * * * *", n%60),+ "published_by_type": "member",+ "published_by_id": f.UserID,+ "created_by_type": createdByType,+ "created_by_id": createdByID,+ })+}++func (f principalFixture) dispatch(t *testing.T, autopilotID, triggerID string) *db.AutopilotRun {+ t.Helper()+ ap, err := f.q.GetAutopilot(context.Background(), util.MustParseUUID(autopilotID))+ if err != nil {+ t.Fatalf("load autopilot: %v", err)+ }+ run, err := f.svc.DispatchAutopilot(context.Background(), ap, util.MustParseUUID(triggerID), "schedule", nil)+ if err != nil {+ t.Fatalf("DispatchAutopilot: %v", err)+ }+ if run == nil {+ t.Fatal("dispatch returned no run")+ }+ return run+}++func TestAutopilotDispatch_AdmitsAsTheTriggerCreatorNotTheAutopilotCreator(t *testing.T) {+ fx, creatorA := newPrincipalFixture(t)+ triggerOwnerB := fx.member(t, "principal-b")++ // THE FORK: the private agent and the autopilot both belong to A; the trigger+ // belongs to B. Admission used to consult A and pass, while the run took B's+ // identity. It must now consult B — who cannot invoke A's private agent.+ agentID := fx.privateAgentOwnedBy(t, creatorA, "fork-a")+ autopilotID, triggerID := fx.autopilotWithTrigger(t, agentID, creatorA, triggerOwnerB)++ run := fx.dispatch(t, autopilotID, triggerID)+ if run.Status != "skipped" {+ t.Fatalf("dispatch status = %q, want skipped: the trigger's creator cannot invoke the autopilot creator's private agent", run.Status)+ }+ if !run.FailureReason.Valid {+ t.Error("a refused dispatch must record why")+ }+ if n := fx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE autopilot_run_id = $1`, run.ID); n != 0 {+ t.Fatalf("refused dispatch still enqueued %d tasks", n)+ }+}++func TestAutopilotDispatch_TriggerCreatorOwningTheAgentIsAdmittedAndStamped(t *testing.T) {+ fx, creatorA := newPrincipalFixture(t)+ triggerOwnerB := fx.member(t, "principal-owner-b")++ // The mirror image: B owns both the trigger and the private agent, while the+ // autopilot belongs to A. Admission must consult B and pass, and the task must+ // be stamped with B — proving both halves read the same human.+ agentID := fx.privateAgentOwnedBy(t, triggerOwnerB, "mirror-b")+ autopilotID, triggerID := fx.autopilotWithTrigger(t, agentID, creatorA, triggerOwnerB)++ run := fx.dispatch(t, autopilotID, triggerID)+ if run.Status == "skipped" {+ t.Fatalf("dispatch was refused (%q), want admitted: the trigger creator owns the agent", run.FailureReason.String)+ }++ var originator, accountable pgtype.UUID+ var source pgtype.Text+ fx.QueryRow(t, `+ SELECT originator_user_id, accountable_user_id, originator_source+ FROM agent_task_queue WHERE autopilot_run_id = $1`, run.ID).Scan(&originator, &accountable, &source)++ if source.String != "trigger_owner" {+ t.Errorf("originator_source = %q, want trigger_owner", source.String)+ }+ // The whole point: the human admission consulted is the human the task carries.+ if util.UUIDToString(originator) != triggerOwnerB {+ t.Errorf("originator = %q, want the admitted trigger creator %q", util.UUIDToString(originator), triggerOwnerB)+ }+ if accountable != originator {+ t.Errorf("accountable %q must equal originator %q", util.UUIDToString(accountable), util.UUIDToString(originator))+ }+}++func TestResolveAutopilotTriggerPrincipal_FailsClosed(t *testing.T) {+ fx, creatorID := newPrincipalFixture(t)+ ctx := context.Background()++ agentID := fx.privateAgentOwnedBy(t, creatorID, "resolve")+ autopilotID, _ := fx.autopilotWithTrigger(t, agentID, creatorID, creatorID)+ apUUID := util.MustParseUUID(autopilotID)+ wsUUID := util.MustParseUUID(fx.WorkspaceID)++ t.Run("resolves the trigger creator", func(t *testing.T) {+ triggerID := util.MustParseUUID(fx.trigger(t, autopilotID, "member", creatorID))+ if got := ResolveAutopilotTriggerPrincipal(ctx, fx.q, triggerID, apUUID, wsUUID); util.UUIDToString(got) != creatorID {+ t.Fatalf("principal = %q, want %q", util.UUIDToString(got), creatorID)+ }+ })++ t.Run("legacy trigger with no creator resolves nobody", func(t *testing.T) {+ // published_by IS set here, so the pre-MUL-6951 resolver would have returned+ // a human. It must not be promoted to an authorization principal — that is+ // the rule_owner guess, and guessing is what fails closed now.+ triggerID := util.MustParseUUID(fx.trigger(t, autopilotID, nil, nil))+ if got := ResolveAutopilotTriggerPrincipal(ctx, fx.q, triggerID, apUUID, wsUUID); got.Valid {+ t.Fatalf("legacy trigger resolved %q; must fail closed", util.UUIDToString(got))+ }+ })++ t.Run("trigger belonging to another autopilot resolves nobody", func(t *testing.T) {+ otherAutopilotID, _ := fx.autopilotWithTrigger(t, agentID, creatorID, creatorID)+ triggerID := util.MustParseUUID(fx.trigger(t, autopilotID, "member", creatorID))+ got := ResolveAutopilotTriggerPrincipal(ctx, fx.q, triggerID, util.MustParseUUID(otherAutopilotID), wsUUID)+ if got.Valid {+ t.Fatalf("cross-autopilot trigger resolved %q; the binding check did not run", util.UUIDToString(got))+ }+ })++ t.Run("autopilot in another workspace resolves nobody", func(t *testing.T) {+ // The membership check alone cannot catch this: it only proves the resolved+ // human belongs to the workspace passed in. The SAME human is a member of+ // BOTH workspaces here, so membership passes on either side and only the+ // autopilot-to-workspace binding in the lookup can reject (Elon review).+ n := principalSeq.Add(1)+ otherWorkspaceID := fx.Workspace(t, "other ws", fmt.Sprintf("other-ws-%d", n))+ fx.Member(t, otherWorkspaceID, creatorID, "owner")++ triggerID := util.MustParseUUID(fx.trigger(t, autopilotID, "member", creatorID))+ if got := ResolveAutopilotTriggerPrincipal(ctx, fx.q, triggerID, apUUID, wsUUID); !got.Valid {+ t.Fatal("precondition: the trigger must resolve in its own workspace")+ }+ got := ResolveAutopilotTriggerPrincipal(ctx, fx.q, triggerID, apUUID, util.MustParseUUID(otherWorkspaceID))+ if got.Valid {+ t.Fatalf("a foreign workspace resolved %q; the autopilot is not bound to it", util.UUIDToString(got))+ }+ })++ t.Run("creator removed from the workspace resolves nobody", func(t *testing.T) {+ removed := fx.member(t, "principal-removed")+ triggerID := util.MustParseUUID(fx.trigger(t, autopilotID, "member", removed))+ if got := ResolveAutopilotTriggerPrincipal(ctx, fx.q, triggerID, apUUID, wsUUID); !got.Valid {+ t.Fatal("precondition: an in-workspace creator must resolve")+ }+ fx.Exec(t, `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, fx.WorkspaceID, removed)+ if got := ResolveAutopilotTriggerPrincipal(ctx, fx.q, triggerID, apUUID, wsUUID); got.Valid {+ t.Fatalf("removed member still resolved %q; membership must be re-checked per dispatch", util.UUIDToString(got))+ }+ })+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 346d916daf..7eccbce757 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -541,14 +541,16 @@ func (s *TaskService) attributionForIssueTask(ctx context.Context, issue db.Issu}}// Autopilot-origin issues (origin_id is the autopilot id) from a schedule /- // webhook trigger: no human authorized the run, so originator stays NULL, but it- // is accountable to the human currently RESPONSIBLE for the firing trigger's- // effective config (creator, then last substantive editor) — trigger_owner- // (MUL-4302; Elon must-fix), degrading to the rule publisher when no such member- // is recoverable. Resolved the same way run_only dispatch resolves- // it, so both autopilot execution modes attribute identically. (A manual trigger- // carries an actor and is already handled above.) The issue only stores the- // autopilot id, so bridge issue → active run → trigger_id to find the trigger.+ // webhook trigger attribute to the firing trigger's CREATOR — trigger_owner+ // (MUL-4302; MUL-6951) — degrading to the audit-only rule publisher when no+ // creator is recoverable. That human is the originator as well as the+ // accountable, so a create_issue-mode run carries the same authorization a+ // manual "run now" by that member would; an edit of the trigger does not move+ // it. Resolved the same way+ // run_only dispatch resolves it, so both autopilot execution modes attribute+ // identically. (A manual trigger carries an actor and is already handled above.)+ // The issue only stores the autopilot id, so bridge issue → active run →+ // trigger_id to find the trigger.if s != nil && s.Queries != nil && issue.OriginType.Valid &&issue.OriginType.String == "autopilot" && issue.OriginID.Valid {var triggerID pgtype.UUID@@ -584,9 +586,10 @@ func (s *TaskService) attributionForIssueTask(ctx context.Context, issue db.Issu// ruleOwnerAttribution resolves the rule_owner attribution for an autopilot run// from its active (latest) rule version snapshot (MUL-4302 §3.4). Shared by both// autopilot execution modes — run_only dispatch and the create_issue enqueue path —-// so they attribute identically. originator stays NULL (an autopilot carries no-// human's authority); only the audit-accountable side is set, to the version's-// member publisher. A missing version (autopilot published before this feature, or+// so they attribute identically. originator stays NULL: an autopilot DOES carry a+// human's authority since MUL-6951, but it comes from the trigger's creator, and+// this is the fallback for when that creator cannot be proven. Only the+// audit-accountable side is set, to the version's member publisher. A missing version (autopilot published before this feature, or// none yet) or a non-member/absent publisher degrades to unattributed rather than// fabricating a human. Never returns an error: attribution must not fail an// enqueue, and a degraded label is the honest fallback.@@ -608,31 +611,82 @@ func ruleOwnerAttribution(ctx context.Context, q *db.Queries, workspaceID, autopreturn attribution.RuleOwner(publisher, ver.ID, evidenceKind, evidenceRefID)}-// triggerOwnerAttribution resolves an autopilot schedule/webhook run to the human-// currently RESPONSIBLE for the firing trigger's effective config (MUL-4302; Bohan +-// Elon must-fix). triggerID is the autopilot_run's trigger_id. The trigger row's-// published_by starts at the creator and transfers to whoever later substantively-// edits it, so the run attributes to whoever last shaped what fires it — not the-// original creator. A trigger with no recorded publisher (predating this migration)-// or an agent publisher degrades to ruleOwnerAttribution (rule publisher, then-// owner_fallback) — the same coarser behavior autopilots had before, so nothing-// regresses. Never errors: attribution must not fail an enqueue.+// triggerOwnerAttribution resolves an autopilot schedule/webhook run to the firing+// trigger's CREATOR (MUL-4302; MUL-6951). triggerID is the autopilot_run's+// trigger_id.+//+// The creator is immutable — a substantive edit re-stamps published_by, not+// created_by, so it cannot re-authorize the automation as the editor (MUL-6951,+// Bohan's ruling). Because the DB invariant forces accountable == originator once+// the originator is set, BOTH columns on the task name the creator; the editor's+// responsibility for the config lives on autopilot_trigger.published_by.+//+// A trigger with no recoverable creator degrades to ruleOwnerAttribution, which is+// audit-only — the run then carries no originator and the invoke gate fails closed.+// Never errors: attribution must not fail an enqueue.func triggerOwnerAttribution(ctx context.Context, q *db.Queries, triggerID, workspaceID, autopilotID pgtype.UUID, evidenceKind attribution.EvidenceKind, evidenceRefID pgtype.UUID) attribution.Result {- if q != nil && triggerID.Valid {- // published_by is the member CURRENTLY responsible for this trigger's- // effective config: the creator until someone substantively edits it (that- // trigger's cron/filter/webhook, or an autopilot-level change that bumps all- // its triggers), then the editor. So a run attributes to whoever last shaped- // what fires it, not the original creator — and editing another trigger never- // moves this one (MUL-4302; Elon must-fix).- if trig, err := q.GetAutopilotTrigger(ctx, triggerID); err == nil &&- trig.PublishedByType.Valid && trig.PublishedByType.String == "member" && trig.PublishedByID.Valid {- return attribution.TriggerOwner(trig.PublishedByID, evidenceKind, evidenceRefID)- }- }+ if principal := ResolveAutopilotTriggerPrincipal(ctx, q, triggerID, autopilotID, workspaceID); principal.Valid {+ return attribution.TriggerOwner(principal, evidenceKind, evidenceRefID)+ }+ // No provable principal: degrade to the rule publisher, which is AUDIT-ONLY.+ // rule_owner must never become an authorization identity — it is a guess at+ // "who probably owns this rule", and promoting it would hand a legacy trigger+ // somebody's invoke rights without that person ever arming anything. The run+ // then carries no originator and the invoke gate fails closed (MUL-6951).return ruleOwnerAttribution(ctx, q, workspaceID, autopilotID, evidenceKind, evidenceRefID)}+// ResolveAutopilotTriggerPrincipal returns the human a schedule/webhook dispatch+// ACTS AS, or an invalid UUID when none can be proven — in which case every+// caller must fail closed rather than substitute a different human.+//+// This is the single source of that answer (MUL-6951). Admission+// (autopilotAdmitInvoke), the originator stamped on the task, and every run+// delegated from it all resolve through here, so one dispatch can never admit as+// person A and then run with person B's rights — a combination neither of them+// could produce by hand, and the exact fork Elon's review found.+//+// The principal is the trigger's IMMUTABLE created_by, not published_by:+// published_by transfers to whoever last substantively edits the trigger, so+// using it would let a collaborator adjusting a cron expression silently hand the+// automation their own rights (MUL-6951, Bohan's ruling: the run always acts as+// the trigger's creator).+//+// Three conditions, all required, all fail-closed:+//+// - the trigger row is fetched BOUND to this autopilot AND its workspace, so a+// trigger id from another autopilot, or from an autopilot in another tenant,+// cannot select the principal. The membership check below is not a substitute:+// it proves the resolved human is in the workspace passed in, which a member of+// two workspaces satisfies even when the trigger came from the other one;+// - created_by names a member — a legacy trigger predating the column (and with+// no published_by to backfill from) resolves nobody rather than a guess;+// - that member is STILL in the autopilot's workspace, re-checked on every+// dispatch, so removing someone actually revokes what their triggers can do.+func ResolveAutopilotTriggerPrincipal(ctx context.Context, q *db.Queries, triggerID, autopilotID, workspaceID pgtype.UUID) pgtype.UUID {+ if q == nil || !triggerID.Valid || !autopilotID.Valid || !workspaceID.Valid {+ return pgtype.UUID{}+ }+ trig, err := q.GetAutopilotTriggerForAutopilot(ctx, db.GetAutopilotTriggerForAutopilotParams{+ ID: triggerID,+ AutopilotID: autopilotID,+ WorkspaceID: workspaceID,+ })+ if err != nil {+ return pgtype.UUID{}+ }+ if !trig.CreatedByType.Valid || trig.CreatedByType.String != "member" || !trig.CreatedByID.Valid {+ return pgtype.UUID{}+ }+ if _, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{+ UserID: trig.CreatedByID,+ WorkspaceID: workspaceID,+ }); err != nil {+ return pgtype.UUID{}+ }+ return trig.CreatedByID+}+// ErrAttributionFailClosed signals that a run resolved to no precise accountable// human and the enqueue is REFUSED rather than started. It covers three cases, all// of which mean "we cannot guarantee an accountable human for this run" (MUL-4302diff --git a/server/migrations/449_autopilot_trigger_created_by.down.sql b/server/migrations/449_autopilot_trigger_created_by.down.sqlnew file mode 100644index 0000000000..812da994e7--- /dev/null+++ b/server/migrations/449_autopilot_trigger_created_by.down.sql@@ -0,0 +1,12 @@+-- Reverting drops the immutable creator. Dispatch then falls back to the+-- pre-MUL-6951 resolution, which reads published_by, so restore migration 189's+-- original column comments verbatim rather than leaving MUL-6951 text describing+-- a model this database no longer runs.+COMMENT ON COLUMN autopilot_trigger.published_by_type IS+ 'Actor type of the trigger''s current responsible publisher: member | agent. Set to the creator at creation and re-stamped to the editor on any substantive edit governing this trigger. Consumed only for attribution (source=trigger_owner) — never authorization. NULL on pre-migration triggers (MUL-4302).';++COMMENT ON COLUMN autopilot_trigger.published_by_id IS+ 'The member/agent currently responsible for this trigger''s effective config (creator, then last substantive editor). For a member this is the accountable human of runs the trigger fires (source=trigger_owner). No FK, app-layer integrity. NULL on pre-migration triggers, which degrade to rule_owner (MUL-4302).';++ALTER TABLE autopilot_trigger DROP COLUMN IF EXISTS created_by_id;+ALTER TABLE autopilot_trigger DROP COLUMN IF EXISTS created_by_type;diff --git a/server/migrations/449_autopilot_trigger_created_by.up.sql b/server/migrations/449_autopilot_trigger_created_by.up.sqlnew file mode 100644index 0000000000..112fb11438--- /dev/null+++ b/server/migrations/449_autopilot_trigger_created_by.up.sql@@ -0,0 +1,67 @@+-- MUL-6951: give autopilot_trigger an IMMUTABLE creator, distinct from+-- published_by.+--+-- Since MUL-6951 a schedule/webhook run acts as a human, so the column naming+-- that human is an authorization input, not an audit label. published_by cannot+-- serve that role: it means "who is currently responsible for this trigger's+-- effective config" and TRANSFERS to whoever last substantively edits the+-- trigger (MUL-4302). Using it would mean a collaborator adjusting a cron+-- expression silently hands the automation their own invoke rights — a change+-- nothing in the UI expresses. Bohan's ruling on the MUL-6951 thread is that the+-- run always acts as the trigger's CREATOR.+--+-- created_by_* is written once at creation and never rewritten by the edit+-- paths; published_by keeps its existing audit meaning unchanged.+--+-- BACKFILL is best-effort and knowingly imprecise. For a trigger nobody has+-- edited, published_by IS the creator and this recovers the right human. For an+-- ALREADY-EDITED trigger it freezes the last recoverable EDITOR as the immutable+-- creator — not necessarily the historical creator, which the schema never+-- recorded and which is therefore unrecoverable.+--+-- This IS a widening, and is accepted as a compatibility tradeoff (MUL-6951, Elon+-- review). Before MUL-6951 an automatic run carried no originator at all, only a+-- set of narrowly-scoped borrow paths; after it, a backfilled editor becomes the+-- run's full originator and it acts with that member's own rights. The+-- alternative — backfilling nothing — stops every existing autopilot, which is+-- why this is preferred over precision here.+--+-- A trigger with no published_by at all (predating migration 189, which added+-- published_by_* to this table) stays NULL.+-- Dispatch then fails closed rather than guessing a principal, and there is+-- deliberately NO recovery path — re-saving such a trigger re-stamps published_by,+-- not created_by, so it stays unresolvable (Bohan: leave them empty). Its runs are+-- refused with a recorded failure_reason.+--+-- The table holds one row per configured trigger (small, bounded by autopilot+-- count), so this runs as a single statement rather than a batched backfill.+--+-- No foreign key by house rule; the referenced member is re-validated in+-- application code on every dispatch, which is what actually matters here since+-- a member can be removed from the workspace long after the row is written.+ALTER TABLE autopilot_trigger ADD COLUMN IF NOT EXISTS created_by_type TEXT;+ALTER TABLE autopilot_trigger ADD COLUMN IF NOT EXISTS created_by_id UUID;++UPDATE autopilot_trigger+SET created_by_type = published_by_type,+ created_by_id = published_by_id+WHERE created_by_id IS NULL+ AND published_by_id IS NOT NULL+ AND published_by_type IS NOT NULL;++-- Migration 189 documented published_by_* as deciding the accountable human of the+-- runs a trigger fires. That is no longer true and the text is generated into+-- pkg/db/generated/models.go, so it would keep asserting the old authorization+-- model to every reader. 189 is already released and must not be edited; override+-- the comments here instead.+COMMENT ON COLUMN autopilot_trigger.published_by_type IS+ 'Actor type of the trigger''s current responsible publisher: member | agent. Set to the creator at creation and re-stamped to the editor on any substantive edit governing this trigger. CONFIG audit only — since MUL-6951 it decides nothing about the runs this trigger fires. NULL on triggers predating MUL-4302.';++COMMENT ON COLUMN autopilot_trigger.published_by_id IS+ 'The member/agent currently responsible for this trigger''s effective config (creator, then last substantive editor). CONFIG audit only: since MUL-6951 the runs this trigger fires act as, and are accountable to, created_by_id instead, so an edit recorded here never moves a run''s authority. No FK, app-layer integrity (MUL-4302).';++COMMENT ON COLUMN autopilot_trigger.created_by_type IS+ 'Actor type of the trigger''s immutable creator: member | agent. Only ''member'' yields a run principal. NULL for triggers created before MUL-6951 that had no published_by to backfill from.';++COMMENT ON COLUMN autopilot_trigger.created_by_id IS+ 'The member a schedule/webhook run fires AS: dispatch admission, the task''s originator/accountable, and every delegated run all resolve to this one human (MUL-6951). Written once at creation and never re-stamped, so editing the trigger cannot re-authorize its runs as the editor. NULL means no provable principal and the dispatch fails closed. No FK; workspace membership is re-validated on every dispatch.';diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 74ba595a52..96879930df 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -416,14 +416,16 @@ const createAutopilotTrigger = `-- name: CreateAutopilotTrigger :oneINSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, timezone,next_run_at, webhook_token, label, provider, event_filters,- published_by_type, published_by_id+ published_by_type, published_by_id,+ created_by_type, created_by_id) VALUES ($1, $2, $3, $4, $5,$6, $7, $8,COALESCE($9::text, 'generic'),$10,- $11, $12-) RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id+ $11, $12,+ $13, $14+) RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id, created_by_type, created_by_id`type CreateAutopilotTriggerParams struct {@@ -439,6 +441,8 @@ type CreateAutopilotTriggerParams struct {EventFilters []byte `json:"event_filters"`PublishedByType pgtype.Text `json:"published_by_type"`PublishedByID pgtype.UUID `json:"published_by_id"`+ CreatedByType pgtype.Text `json:"created_by_type"`+ CreatedByID pgtype.UUID `json:"created_by_id"`}func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilotTriggerParams) (AutopilotTrigger, error) {@@ -455,6 +459,8 @@ func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopiloarg.EventFilters,arg.PublishedByType,arg.PublishedByID,+ arg.CreatedByType,+ arg.CreatedByID,)var i AutopilotTriggererr := row.Scan(@@ -475,6 +481,8 @@ func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilo&i.EventFilters,&i.PublishedByType,&i.PublishedByID,+ &i.CreatedByType,+ &i.CreatedByID,)return i, err}@@ -996,7 +1004,7 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty}const getAutopilotTrigger = `-- name: GetAutopilotTrigger :one-SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id FROM autopilot_trigger+SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id, created_by_type, created_by_id FROM autopilot_triggerWHERE id = $1`@@ -1021,12 +1029,61 @@ func (q *Queries) GetAutopilotTrigger(ctx context.Context, id pgtype.UUID) (Auto&i.EventFilters,&i.PublishedByType,&i.PublishedByID,+ &i.CreatedByType,+ &i.CreatedByID,+ )+ return i, err+}++const getAutopilotTriggerForAutopilot = `-- name: GetAutopilotTriggerForAutopilot :one+SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, t.event_filters, t.published_by_type, t.published_by_id, t.created_by_type, t.created_by_id FROM autopilot_trigger t+JOIN autopilot a ON a.id = t.autopilot_id+WHERE t.id = $1 AND t.autopilot_id = $2 AND a.workspace_id = $3+`++type GetAutopilotTriggerForAutopilotParams struct {+ ID pgtype.UUID `json:"id"`+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Trigger lookup BOUND to both the autopilot it must belong to AND that+// autopilot's workspace. Since MUL-6951 the trigger row decides which human a run+// acts as, so an unbound `WHERE id = $1` would let a trigger id from another+// autopilot select the principal. The workspace join closes the other half: the+// caller's membership check proves the resolved human belongs to the workspace it+// passed, not that the AUTOPILOT does, and a member of two workspaces would+// satisfy the former while the trigger came from the other tenant. Callers+// resolving an authorization principal must use this, not GetAutopilotTrigger.+func (q *Queries) GetAutopilotTriggerForAutopilot(ctx context.Context, arg GetAutopilotTriggerForAutopilotParams) (AutopilotTrigger, error) {+ row := q.db.QueryRow(ctx, getAutopilotTriggerForAutopilot, arg.ID, arg.AutopilotID, arg.WorkspaceID)+ var i AutopilotTrigger+ err := row.Scan(+ &i.ID,+ &i.AutopilotID,+ &i.Kind,+ &i.Enabled,+ &i.CronExpression,+ &i.Timezone,+ &i.NextRunAt,+ &i.WebhookToken,+ &i.Label,+ &i.LastFiredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Provider,+ &i.SigningSecret,+ &i.EventFilters,+ &i.PublishedByType,+ &i.PublishedByID,+ &i.CreatedByType,+ &i.CreatedByID,)return i, err}const getWebhookTriggerByToken = `-- name: GetWebhookTriggerByToken :one-SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, t.event_filters, t.published_by_type, t.published_by_id, a.workspace_id AS autopilot_workspace_id+SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, t.event_filters, t.published_by_type, t.published_by_id, t.created_by_type, t.created_by_id, a.workspace_id AS autopilot_workspace_idFROM autopilot_trigger tJOIN autopilot a ON a.id = t.autopilot_idWHERE t.kind = 'webhook'@@ -1051,6 +1108,8 @@ type GetWebhookTriggerByTokenRow struct {EventFilters []byte `json:"event_filters"`PublishedByType pgtype.Text `json:"published_by_type"`PublishedByID pgtype.UUID `json:"published_by_id"`+ CreatedByType pgtype.Text `json:"created_by_type"`+ CreatedByID pgtype.UUID `json:"created_by_id"`AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`}@@ -1080,6 +1139,8 @@ func (q *Queries) GetWebhookTriggerByToken(ctx context.Context, webhookToken pgt&i.EventFilters,&i.PublishedByType,&i.PublishedByID,+ &i.CreatedByType,+ &i.CreatedByID,&i.AutopilotWorkspaceID,)return i, err@@ -1308,7 +1369,7 @@ func (q *Queries) ListAutopilotSubscribersForAutopilots(ctx context.Context, dolconst listAutopilotTriggers = `-- name: ListAutopilotTriggers :many-SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id FROM autopilot_trigger+SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id, created_by_type, created_by_id FROM autopilot_triggerWHERE autopilot_id = $1ORDER BY created_at ASC`@@ -1343,6 +1404,8 @@ func (q *Queries) ListAutopilotTriggers(ctx context.Context, autopilotID pgtype.&i.EventFilters,&i.PublishedByType,&i.PublishedByID,+ &i.CreatedByType,+ &i.CreatedByID,); err != nil {return nil, err}@@ -1742,7 +1805,7 @@ SET webhook_token = $2,updated_at = now()WHERE id = $1AND kind = 'webhook'-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id, created_by_type, created_by_id`type RotateAutopilotTriggerWebhookTokenParams struct {@@ -1774,6 +1837,8 @@ func (q *Queries) RotateAutopilotTriggerWebhookToken(ctx context.Context, arg Ro&i.EventFilters,&i.PublishedByType,&i.PublishedByID,+ &i.CreatedByType,+ &i.CreatedByID,)return i, err}@@ -1873,8 +1938,14 @@ type SetAutopilotTriggerPublisherParams struct {}// Re-stamp a single trigger's responsible publisher after a substantive edit of-// THAT trigger (cron / filter / enabled / webhook security). Future runs it fires-// become accountable to this member (MUL-4302 trigger_owner transfer).+// THAT trigger (cron / filter / enabled / webhook security), recording who is now+// responsible for its config (MUL-4302).+//+// Since MUL-6951 this changes NOTHING about the runs it fires: they act as, and+// are accountable to, the trigger's immutable created_by. An edit must not be able+// to re-authorize the automation as the editor (Bohan's ruling), so this statement+// deliberately does not touch created_by, and published_by is now a config-audit+// column only.func (q *Queries) SetAutopilotTriggerPublisher(ctx context.Context, arg SetAutopilotTriggerPublisherParams) error {_, err := q.db.Exec(ctx, setAutopilotTriggerPublisher, arg.ID, arg.PublishedByType, arg.PublishedByID)return err@@ -1908,7 +1979,7 @@ SET signing_secret = $2,updated_at = now()WHERE id = $1AND kind = 'webhook'-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id, created_by_type, created_by_id`type SetAutopilotTriggerSigningSecretParams struct {@@ -1942,6 +2013,8 @@ func (q *Queries) SetAutopilotTriggerSigningSecret(ctx context.Context, arg SetA&i.EventFilters,&i.PublishedByType,&i.PublishedByID,+ &i.CreatedByType,+ &i.CreatedByID,)return i, err}@@ -1951,7 +2024,7 @@ UPDATE autopilot_triggerSET webhook_token = $2,updated_at = now()WHERE id = $1-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id, created_by_type, created_by_id`type SetAutopilotTriggerWebhookTokenParams struct {@@ -1985,6 +2058,8 @@ func (q *Queries) SetAutopilotTriggerWebhookToken(ctx context.Context, arg SetAu&i.EventFilters,&i.PublishedByType,&i.PublishedByID,+ &i.CreatedByType,+ &i.CreatedByID,)return i, err}@@ -2498,7 +2573,7 @@ UPDATE autopilot_trigger SETevent_filters = COALESCE($7, event_filters),updated_at = now()WHERE id = $1-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id, created_by_type, created_by_id`type UpdateAutopilotTriggerParams struct {@@ -2540,6 +2615,8 @@ func (q *Queries) UpdateAutopilotTrigger(ctx context.Context, arg UpdateAutopilo&i.EventFilters,&i.PublishedByType,&i.PublishedByID,+ &i.CreatedByType,+ &i.CreatedByID,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 697e258ca2..0474f390ca 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -306,10 +306,14 @@ type AutopilotTrigger struct {Provider string `json:"provider"`SigningSecret pgtype.Text `json:"signing_secret"`EventFilters []byte `json:"event_filters"`- // Actor type of the trigger's current responsible publisher: member | agent. Set to the creator at creation and re-stamped to the editor on any substantive edit governing this trigger. Consumed only for attribution (source=trigger_owner) — never authorization. NULL on pre-migration triggers (MUL-4302).+ // Actor type of the trigger's current responsible publisher: member | agent. Set to the creator at creation and re-stamped to the editor on any substantive edit governing this trigger. CONFIG audit only — since MUL-6951 it decides nothing about the runs this trigger fires. NULL on triggers predating MUL-4302.PublishedByType pgtype.Text `json:"published_by_type"`- // The member/agent currently responsible for this trigger's effective config (creator, then last substantive editor). For a member this is the accountable human of runs the trigger fires (source=trigger_owner). No FK, app-layer integrity. NULL on pre-migration triggers, which degrade to rule_owner (MUL-4302).+ // The member/agent currently responsible for this trigger's effective config (creator, then last substantive editor). CONFIG audit only: since MUL-6951 the runs this trigger fires act as, and are accountable to, created_by_id instead, so an edit recorded here never moves a run's authority. No FK, app-layer integrity (MUL-4302).PublishedByID pgtype.UUID `json:"published_by_id"`+ // Actor type of the trigger's immutable creator: member | agent. Only 'member' yields a run principal. NULL for triggers created before MUL-6951 that had no published_by to backfill from.+ CreatedByType pgtype.Text `json:"created_by_type"`+ // The member a schedule/webhook run fires AS: dispatch admission, the task's originator/accountable, and every delegated run all resolve to this one human (MUL-6951). Written once at creation and never re-stamped, so editing the trigger cannot re-authorize its runs as the editor. NULL means no provable principal and the dispatch fails closed. No FK; workspace membership is re-validated on every dispatch.+ CreatedByID pgtype.UUID `json:"created_by_id"`}type ChannelBindingToken struct {diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex 3086a544ae..fdb71b103d 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -168,23 +168,44 @@ ORDER BY created_at ASC;SELECT * FROM autopilot_triggerWHERE id = $1;+-- name: GetAutopilotTriggerForAutopilot :one+-- Trigger lookup BOUND to both the autopilot it must belong to AND that+-- autopilot's workspace. Since MUL-6951 the trigger row decides which human a run+-- acts as, so an unbound `WHERE id = $1` would let a trigger id from another+-- autopilot select the principal. The workspace join closes the other half: the+-- caller's membership check proves the resolved human belongs to the workspace it+-- passed, not that the AUTOPILOT does, and a member of two workspaces would+-- satisfy the former while the trigger came from the other tenant. Callers+-- resolving an authorization principal must use this, not GetAutopilotTrigger.+SELECT t.* FROM autopilot_trigger t+JOIN autopilot a ON a.id = t.autopilot_id+WHERE t.id = $1 AND t.autopilot_id = $2 AND a.workspace_id = $3;+-- name: CreateAutopilotTrigger :oneINSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, timezone,next_run_at, webhook_token, label, provider, event_filters,- published_by_type, published_by_id+ published_by_type, published_by_id,+ created_by_type, created_by_id) VALUES ($1, $2, $3, sqlc.narg('cron_expression'), sqlc.narg('timezone'),sqlc.narg('next_run_at'), sqlc.narg('webhook_token'), sqlc.narg('label'),COALESCE(sqlc.narg('provider')::text, 'generic'),sqlc.narg('event_filters'),- sqlc.narg('published_by_type'), sqlc.narg('published_by_id')+ sqlc.narg('published_by_type'), sqlc.narg('published_by_id'),+ sqlc.narg('created_by_type'), sqlc.narg('created_by_id')) RETURNING *;-- name: SetAutopilotTriggerPublisher :exec-- Re-stamp a single trigger's responsible publisher after a substantive edit of--- THAT trigger (cron / filter / enabled / webhook security). Future runs it fires--- become accountable to this member (MUL-4302 trigger_owner transfer).+-- THAT trigger (cron / filter / enabled / webhook security), recording who is now+-- responsible for its config (MUL-4302).+--+-- Since MUL-6951 this changes NOTHING about the runs it fires: they act as, and+-- are accountable to, the trigger's immutable created_by. An edit must not be able+-- to re-authorize the automation as the editor (Bohan's ruling), so this statement+-- deliberately does not touch created_by, and published_by is now a config-audit+-- column only.UPDATE autopilot_triggerSET published_by_type = $2, published_by_id = $3, updated_at = now()WHERE id = $1;