Skip to content

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

Go

MUL-7090 fix(autopilot): let an agent trigger a manual run for the human it acts for (#8099)

Bohan Jiang60408ef252ed
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 64b960d865..c4c4582f00 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -902,6 +902,19 @@ multica autopilot delete <id>
multica autopilot trigger <id> # Fires the autopilot once, returns the run
```
+The command exits non-zero unless the run actually started (`issue_created` or
+`running`). A `skipped` run — admission refused, runtime offline, quota
+exhausted, a duplicate already in flight — dispatched nothing; its
+`failure_reason` and `reason_code` are printed to stderr, and `--output json`
+still writes the full run to stdout first.
+
+Run as an agent (inside a task, or over A2A), the trigger is authorized as the
+human that run acts for, not as the owner of the machine it executes on. That
+human needs exactly the write access they would need to trigger it themselves —
+and it is the only access checked: the machine's owner needs no grant on the
+autopilot, only workspace membership. A run carrying no originator cannot
+trigger at all, and says so rather than failing generically.
+
### Run History
```bash
diff --git a/server/cmd/multica/cmd_autopilot.go b/server/cmd/multica/cmd_autopilot.go
index 2ae9f08bed..9b74008f91 100644
--- a/server/cmd/multica/cmd_autopilot.go
+++ b/server/cmd/multica/cmd_autopilot.go
@@ -3,6 +3,7 @@ package main
import (
"bufio"
"context"
+ "errors"
"fmt"
"net/url"
"os"
@@ -575,15 +576,66 @@ func runAutopilotTrigger(cmd *cobra.Command, args []string) error {
var run map[string]any
if err := client.PostJSON(ctx, "/api/autopilots/"+autopilotRef.ID+"/trigger", nil, &run); err != nil {
- return fmt.Errorf("trigger autopilot: %w", err)
+ return autopilotTriggerRequestError(err)
}
+ status := strVal(run, "status")
output, _ := cmd.Flags().GetString("output")
if output == "json" {
- return cli.PrintJSON(os.Stdout, run)
+ // Print the run either way: a caller parsing JSON still wants the row,
+ // including its failure_reason, before the non-zero exit below.
+ if err := cli.PrintJSON(os.Stdout, run); err != nil {
+ return err
+ }
+ } else if autopilotRunStarted(status) {
+ fmt.Printf("Autopilot triggered: run %s (status: %s)\n", strVal(run, "id"), status)
}
- fmt.Printf("Autopilot triggered: run %s (status: %s)\n", strVal(run, "id"), strVal(run, "status"))
- return nil
+ if autopilotRunStarted(status) {
+ return nil
+ }
+ // The server recorded a run but dispatched nothing. Reporting exit 0 with
+ // "Autopilot triggered" is what made #8078 look like a silent no-op for a
+ // day: the operator, and any agent running this on their behalf, read
+ // success and moved on. Surface it as the failure it is.
+ msg := fmt.Sprintf("autopilot did not run (status: %s)", status)
+ if reason := strVal(run, "failure_reason"); reason != "" {
+ msg += ": " + reason
+ }
+ if code := strVal(run, "reason_code"); code != "" {
+ msg += " [" + code + "]"
+ }
+ return errors.New(msg)
+}
+
+// autopilotTriggerRequestError turns a failed trigger request into what the
+// user should read.
+//
+// FormatError deliberately collapses every 403 into generic "no access" copy so
+// a refusal cannot confirm that a resource exists. For a manual trigger that
+// hides the one refusal a workspace can actually act on — the calling run having
+// no originating human — which is exactly the silence #8078 was about. These two
+// refusals opt out by carrying a stable server code; the branch is on that code,
+// never on the English sentence, which changes with copy edits and disappears
+// under translation.
+func autopilotTriggerRequestError(err error) error {
+ switch cli.ServerErrorCode(err) {
+ case "autopilot_trigger_no_originator":
+ return cli.WithUserMessage("this run has no originating human, so it cannot trigger an autopilot on anyone's behalf: a manual trigger is authorized as the person who asked for it", err)
+ case "autopilot_trigger_forbidden":
+ return cli.WithUserMessage("the person this run acts for cannot trigger this autopilot: triggering requires its creator, a workspace admin, or a granted collaborator", err)
+ }
+ return fmt.Errorf("trigger autopilot: %w", err)
+}
+
+// autopilotRunStarted reports whether a manual trigger actually dispatched work.
+//
+// Mirrors the web client's runNowToastKind whitelist (packages/views/autopilots):
+// success is an explicit start status, never "anything that is not skipped or
+// failed". The run schema accepts any status string for forward compatibility, so
+// a future or anomalous-but-parseable status must read as "did not start" rather
+// than be reported as a successful trigger.
+func autopilotRunStarted(status string) bool {
+ return status == "issue_created" || status == "running"
}
func runAutopilotRuns(cmd *cobra.Command, args []string) error {
diff --git a/server/cmd/multica/cmd_autopilot_test.go b/server/cmd/multica/cmd_autopilot_test.go
index 890c36cbd5..efb2ed4746 100644
--- a/server/cmd/multica/cmd_autopilot_test.go
+++ b/server/cmd/multica/cmd_autopilot_test.go
@@ -900,3 +900,86 @@ func TestRelativeTimestampAt(t *testing.T) {
})
}
}
+
+// TestAutopilotRunStarted pins the success whitelist for a manual trigger.
+//
+// Before #8078 the CLI printed "Autopilot triggered" and exited 0 for every
+// response the server returned, including a `skipped` run that dispatched
+// nothing — so an operator, and any agent running the command on their behalf,
+// read success and moved on. Success must therefore be an explicit start
+// status, never "anything that is not skipped or failed": the run schema accepts
+// any status string for forward compatibility, so an unknown one has to read as
+// "did not start". Mirrors runNowToastKind on the web client.
+func TestAutopilotRunStarted(t *testing.T) {
+ cases := []struct {
+ status string
+ want bool
+ }{
+ {"issue_created", true},
+ {"running", true},
+ {"skipped", false},
+ {"failed", false},
+ {"pending", false},
+ {"completed", false},
+ {"", false},
+ // A status this build has never heard of must not be reported as a
+ // successful trigger.
+ {"deferred", false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.status, func(t *testing.T) {
+ if got := autopilotRunStarted(tc.status); got != tc.want {
+ t.Errorf("autopilotRunStarted(%q) = %v, want %v", tc.status, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestAutopilotTriggerRequestError_SurfacesRefusalToTheUser is the end-to-end
+// assertion for what a person (or an agent reading its own output) actually sees
+// when a manual trigger is refused.
+//
+// It runs the real cli.FormatError, because the defect it guards is precisely
+// that FormatError collapses a 403 into generic "no access" copy: the handler
+// can name the cause perfectly and the user still learns nothing. Asserting only
+// that the code was matched would not catch a regression in that collapse.
+func TestAutopilotTriggerRequestError_SurfacesRefusalToTheUser(t *testing.T) {
+ forbidden := func(body string) error {
+ return &cli.HTTPError{
+ Method: "POST",
+ Path: "/api/autopilots/x/trigger",
+ StatusCode: 403,
+ Body: body,
+ }
+ }
+
+ t.Run("no originator names the missing human", func(t *testing.T) {
+ err := autopilotTriggerRequestError(forbidden(
+ `{"error":"no human authorized this trigger: the calling run records no originator","code":"autopilot_trigger_no_originator"}`))
+ got := cli.FormatError(err, false)
+ if !strings.Contains(got, "no originating human") {
+ t.Errorf("output = %q, want it to name the missing originator", got)
+ }
+ if cli.ExitCodeFor(err) == 0 {
+ t.Error("a refused trigger must not exit 0")
+ }
+ })
+
+ t.Run("forbidden names who may trigger", func(t *testing.T) {
+ got := cli.FormatError(autopilotTriggerRequestError(forbidden(
+ `{"error":"only the autopilot creator, a workspace admin, or a granted collaborator can trigger this autopilot","code":"autopilot_trigger_forbidden"}`)), false)
+ if !strings.Contains(got, "granted collaborator") {
+ t.Errorf("output = %q, want it to name who may trigger", got)
+ }
+ })
+
+ // A 403 this command has not opted into keeps the deliberately vague copy:
+ // the opt-out is per-code, not "surface every 403 body".
+ t.Run("unrecognized 403 keeps the generic copy", func(t *testing.T) {
+ got := cli.FormatError(autopilotTriggerRequestError(forbidden(
+ `{"error":"some other resource is off limits"}`)), false)
+ if strings.Contains(got, "some other resource is off limits") {
+ t.Errorf("output = %q, must not echo an un-opted-in 403 body", got)
+ }
+ })
+}
diff --git a/server/internal/cli/errors.go b/server/internal/cli/errors.go
index 0116a31367..3561b3db0b 100644
--- a/server/internal/cli/errors.go
+++ b/server/internal/cli/errors.go
@@ -550,6 +550,35 @@ func extractServerMessage(body string) string {
return code
}
+// ServerErrorCode returns the stable `code` a server error body carries, or ""
+// when err is not an HTTP failure or the body has no code.
+//
+// It exists so a command can recognize ONE specific refusal and print guidance
+// for it without matching on the English sentence, which changes with copy edits
+// and disappears under translation. Statuses whose generic copy is deliberately
+// vague — 403 above all, where naming the cause could confirm a resource exists —
+// keep that copy for every code a command has not explicitly opted into.
+func ServerErrorCode(err error) string {
+ var httpErr *HTTPError
+ if !errors.As(err, &httpErr) {
+ return ""
+ }
+ body := strings.TrimSpace(httpErr.Body)
+ if body == "" || body[0] != '{' {
+ return ""
+ }
+ var parsed struct {
+ Code string `json:"code"`
+ }
+ if jsonErr := json.Unmarshal([]byte(body), &parsed); jsonErr != nil {
+ return ""
+ }
+ if !looksLikeMachineCode(parsed.Code) {
+ return ""
+ }
+ return parsed.Code
+}
+
// looksLikeMachineCode reports whether s is a bare identifier such as
// "cursor_query_mismatch" rather than a sentence meant for a person. The test
// is deliberately narrow — lowercase word characters only — so that ordinary
diff --git a/server/internal/cli/errors_test.go b/server/internal/cli/errors_test.go
index 721475964a..85a496877d 100644
--- a/server/internal/cli/errors_test.go
+++ b/server/internal/cli/errors_test.go
@@ -579,3 +579,34 @@ func TestUserMessageError(t *testing.T) {
}
})
}
+
+// TestServerErrorCode pins the contract a command relies on when it opts a
+// specific refusal out of the generic kind-based copy.
+func TestServerErrorCode(t *testing.T) {
+ httpErr := func(body string) error {
+ return &HTTPError{Method: "POST", Path: "/x", StatusCode: 403, Body: body}
+ }
+ cases := []struct {
+ name string
+ err error
+ want string
+ }{
+ {"code present", httpErr(`{"error":"nope","code":"autopilot_trigger_no_originator"}`), "autopilot_trigger_no_originator"},
+ {"no code field", httpErr(`{"error":"nope"}`), ""},
+ {"empty body", httpErr(""), ""},
+ {"non-JSON body", httpErr("plain text refusal"), ""},
+ {"malformed JSON", httpErr(`{"code":`), ""},
+ // A server that put prose in `code` must not have it treated as an
+ // identifier a command can branch on.
+ {"prose in code", httpErr(`{"code":"You do not have access"}`), ""},
+ {"not an HTTP error", errors.New("local failure"), ""},
+ {"nil", nil, ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := ServerErrorCode(tc.err); got != tc.want {
+ t.Errorf("ServerErrorCode() = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.go
index 0549157b49..cc997c4d12 100644
--- a/server/internal/handler/autopilot.go
+++ b/server/internal/handler/autopilot.go
@@ -2171,6 +2171,68 @@ func (h *Handler) GetAutopilotRun(w http.ResponseWriter, r *http.Request) {
// ── Manual trigger ──────────────────────────────────────────────────────────
+// Machine-readable codes for the two ways a manual trigger can be refused. The
+// CLI keys its actionable output on these rather than on the English sentence,
+// which is what lets a refusal survive translation and copy edits.
+const (
+ autopilotTriggerNoOriginatorCode = "autopilot_trigger_no_originator"
+ autopilotTriggerForbiddenCode = "autopilot_trigger_forbidden"
+)
+
+// requireAutopilotTriggerInvoker resolves the human whose authority a manual
+// "run now" spends and enforces that they may spend it. It is this endpoint's
+// ONLY write gate — requireAutopilotWrite is deliberately not called alongside
+// it. On refusal it writes 403 and returns false; the caller must return early.
+//
+// A member acts for themselves. An agent — the CLI running inside a task, or an
+// A2A call — acts for its run's ORIGINATOR, the top-of-chain human. That is how
+// every other invoke surface in the codebase judges an agent actor (MUL-3963 /
+// canInvokeAgent), including this file's own private-leader gate on save.
+//
+// Judging the request's authenticated user instead resolves the RUNTIME OWNER
+// under a task token (middleware/auth.go stamps the token's bound user), which
+// is wrong in both directions. Too broad: it makes every agent a standing proxy
+// for its machine's owner, so anyone who can talk to the agent inherits that
+// owner's autopilot rights. Too narrow: keeping it as an ADDITIONAL condition
+// would refuse a member who may trigger this autopilot themselves merely because
+// the agent they asked happens to run on a third party's machine — the run would
+// then need two unrelated humans to hold the same grant, which is not what "act
+// for the ordering human" means and not what was decided for #8078. Workspace
+// tenancy for the authenticated caller is already enforced by the router's
+// RequireWorkspaceMember middleware, so dropping the second check loses no
+// isolation.
+//
+// No resolvable human → refuse. The alternative considered was the workspace-broad
+// exception invokeAgentDecision grants unattributed agent/system principals on a
+// public_to-workspace agent, which would have admitted an originator-less chain
+// here too. Rejected (Bohan's ruling on #8078): a manual trigger is by definition
+// somebody's decision, and a chain reaching this gate with no human at its top
+// means something upstream dropped it — that should surface, not be papered over.
+func (h *Handler) requireAutopilotTriggerInvoker(w http.ResponseWriter, r *http.Request, ap db.Autopilot, workspaceID, actorType, actorID string) (pgtype.UUID, bool) {
+ invoker := h.invokeOriginatorFromRequest(r, actorType, actorID)
+ invokerUserID, err := util.ParseUUID(invoker)
+ if invoker == "" || err != nil {
+ // Distinct from the permission refusal below: nothing was denied, there
+ // was simply nobody to judge. It carries its own code because it is the
+ // one refusal here a workspace can act on, and because the
+ // operator-visible half of #8078 was a message describing a trigger row
+ // that a manual run never has.
+ writeErrorCode(w, http.StatusForbidden, autopilotTriggerNoOriginatorCode,
+ "no human authorized this trigger: the calling run records no originator")
+ return pgtype.UUID{}, false
+ }
+ member, err := h.getWorkspaceMember(r.Context(), invoker, workspaceID)
+ if err != nil || !h.memberCanWriteAutopilot(r.Context(), ap, member) {
+ // Deliberately the same sentence and code whether the ordering human is
+ // a non-member or simply lacks the grant: a caller must not be able to
+ // probe workspace membership through this endpoint.
+ writeErrorCode(w, http.StatusForbidden, autopilotTriggerForbiddenCode,
+ "only the autopilot creator, a workspace admin, or a granted collaborator can trigger this autopilot")
+ return pgtype.UUID{}, false
+ }
+ return invokerUserID, true
+}
+
func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
workspaceID := h.resolveWorkspaceID(r)
@@ -2179,25 +2241,25 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if !h.requireAutopilotWrite(w, r, autopilot, workspaceID) {
- return
- }
- if autopilot.Status != "active" {
- writeError(w, http.StatusBadRequest, "autopilot is not active")
- return
- }
-
// 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, 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).
+ // direct_human to the human who authorized it (MUL-4302 §4). Resolve the actor
+ // the same way assign/promote does, then resolve the human that actor acts FOR
+ // — see requireAutopilotTriggerInvoker, which is this endpoint's only write
+ // gate. Authorization runs before the status check so an unauthorized caller
+ // cannot tell an inactive autopilot from an active one.
userID, ok := requireUserID(w, r)
if !ok {
return
}
actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ invokerUserID, ok := h.requireAutopilotTriggerInvoker(w, r, autopilot, workspaceID, actorType, actorID)
+ if !ok {
+ return
+ }
+ if autopilot.Status != "active" {
+ writeError(w, http.StatusBadRequest, "autopilot is not active")
+ return
+ }
idempotencyKey := strings.TrimSpace(r.Header.Get("Idempotency-Key"))
if len(idempotencyKey) > 255 {
@@ -2207,7 +2269,7 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {
if idempotencyKey == "" {
idempotencyKey = service.NewRequestIdempotencyKey()
}
- run, reasonCode, err := h.AutopilotService.DispatchAutopilotManualWithKey(r.Context(), autopilot, pgtype.UUID{}, nil, memberActorUserID(actorType, actorID), idempotencyKey)
+ run, reasonCode, err := h.AutopilotService.DispatchAutopilotManualWithKey(r.Context(), autopilot, pgtype.UUID{}, nil, invokerUserID, idempotencyKey)
if err != nil {
var quotaErr *service.AutopilotQuotaExceededError
if errors.As(err, &quotaErr) {
diff --git a/server/internal/handler/autopilot_manual_trigger_invoker_test.go b/server/internal/handler/autopilot_manual_trigger_invoker_test.go
new file mode 100644
index 0000000000..284848c8bb
--- /dev/null
+++ b/server/internal/handler/autopilot_manual_trigger_invoker_test.go
@@ -0,0 +1,255 @@
+package handler
+
+import (
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// A manual "run now" spends a human's authority. When the caller is an agent —
+// the CLI running inside a task, or an A2A call — that human is the agent's run
+// ORIGINATOR, not the runtime owner whose token authenticated the request.
+//
+// The regression these tests exist for (#8078): MUL-6951 replaced the
+// trigger-independent creator gate with one that resolves the FIRING TRIGGER's
+// creator whenever the actor is not a member. A manual trigger supplies no
+// trigger by construction, so every agent-initiated "run now" resolved no
+// principal and was refused — while the same request had already been accepted
+// by requireAutopilotWrite three lines earlier.
+
+// triggerInvokerFixture builds an active create_issue autopilot owned by
+// testUserID and returns it with the agent that will do the triggering.
+func triggerInvokerFixture(t *testing.T, titleSuffix string) (autopilotID, agentID string) {
+ t.Helper()
+
+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)
+
+ title := fmt.Sprintf("manual trigger invoker %s %d", titleSuffix, time.Now().UnixNano())
+ req := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{
+ "title": title,
+ "assignee_id": agentID,
+ "execution_mode": "create_issue",
+ "issue_title_template": title,
+ })
+ var ap AutopilotResponse
+ testutil.Call(t, testHandler.CreateAutopilot, req).Want(http.StatusCreated).JSON(&ap)
+
+ // A dispatched run leaves an issue and a task behind it; both outlive the
+ // autopilot row, so they are cleaned before it.
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id IN (SELECT id FROM issue WHERE workspace_id = $1 AND title = $2)`, testWorkspaceID, title)
+ dbfx.Cleanup(t, `DELETE FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title)
+ dbfx.Cleanup(t, `DELETE FROM autopilot_run WHERE autopilot_id = $1`, ap.ID)
+ dbfx.Cleanup(t, `DELETE FROM autopilot WHERE id = $1`, ap.ID)
+ return ap.ID, agentID
+}
+
+// callerTask is the running task the triggering agent speaks from. An empty
+// originatorUserID leaves the task carrying no human at all — the shape a legacy
+// or system-rooted run has.
+func callerTask(t *testing.T, agentID, originatorUserID string) string {
+ t.Helper()
+ if originatorUserID == "" {
+ return dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": testRuntimeID,
+ "status": "running",
+ "originator_source": "unattributed",
+ })
+ }
+ // originator == accountable: migrations 190/197 require the pair to match.
+ return dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": testRuntimeID,
+ "status": "running",
+ "originator_user_id": originatorUserID,
+ "accountable_user_id": originatorUserID,
+ "originator_source": "direct_human",
+ })
+}
+
+// triggerAsAgent issues the manual trigger the way the CLI does from inside a
+// task: authenticated by the runtime owner's bound user, but stamped by the auth
+// middleware as a task-token actor.
+func triggerAsAgent(t *testing.T, autopilotID, agentID, taskID string) *testutil.Response {
+ t.Helper()
+ return triggerAsAgentAuthedAs(t, testUserID, autopilotID, agentID, taskID)
+}
+
+// triggerAsAgentAuthedAs is triggerAsAgent with the authenticated (runtime
+// owner) identity spelled out, for the cases where it must differ from the
+// originator.
+func triggerAsAgentAuthedAs(t *testing.T, runtimeOwnerID, autopilotID, agentID, taskID string) *testutil.Response {
+ t.Helper()
+ r := newRequestAs(runtimeOwnerID, "POST", "/api/autopilots/"+autopilotID+"/trigger?workspace_id="+testWorkspaceID, nil)
+ r.Header.Set("X-Actor-Source", "task_token")
+ r.Header.Set("X-Agent-ID", agentID)
+ r.Header.Set("X-Task-ID", taskID)
+ r = withURLParam(r, "id", autopilotID)
+ return testutil.Call(t, testHandler.TriggerAutopilot, r)
+}
+
+// plainMember returns a workspace member holding no autopilot grants at all —
+// not a creator, not an admin, not a collaborator.
+func plainMember(t *testing.T, label string) string {
+ t.Helper()
+ userID := dbfx.User(t, label, fmt.Sprintf("%s-%[email protected]", label, time.Now().UnixNano()))
+ dbfx.Member(t, testWorkspaceID, userID, "member")
+ return userID
+}
+
+// TestTriggerAutopilot_AgentActsForItsOriginator is the acceptance test for the
+// 人 → agent → autopilot chain: an agent whose run carries a human who may
+// trigger this autopilot dispatches exactly as that human clicking "Run now".
+func TestTriggerAutopilot_AgentActsForItsOriginator(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ autopilotID, agentID := triggerInvokerFixture(t, "admitted")
+ taskID := callerTask(t, agentID, testUserID)
+
+ var run AutopilotRunResponse
+ triggerAsAgent(t, autopilotID, agentID, taskID).Want(http.StatusOK).JSON(&run)
+ if run.Status != "issue_created" {
+ // .Want() reports the status code; only this assertion knows that a 200
+ // carrying a skipped run is the exact shape the bug produced.
+ t.Fatalf("run status = %q (reason_code %v, failure_reason %v), want issue_created",
+ run.Status, derefStr(run.ReasonCode), derefStr(run.FailureReason))
+ }
+}
+
+// TestTriggerAutopilot_AgentWithNoOriginatorRefused pins the ruling on #8078: a
+// chain reaching this gate with no human at its top is refused outright, rather
+// than admitted through the workspace-broad exception invokeAgentDecision grants
+// unattributed agent/system principals. A manual trigger is somebody's decision;
+// no human means something upstream dropped it, and that should surface.
+func TestTriggerAutopilot_AgentWithNoOriginatorRefused(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ autopilotID, agentID := triggerInvokerFixture(t, "no originator")
+ taskID := callerTask(t, agentID, "")
+
+ var body triggerErrorBody
+ triggerAsAgent(t, autopilotID, agentID, taskID).Want(http.StatusForbidden).JSON(&body)
+ // The CLI keys its actionable output on this code, because FormatError
+ // collapses every other 403 into generic "no access" copy that would hide the
+ // one fact making this failure fixable.
+ if body.Code != autopilotTriggerNoOriginatorCode {
+ t.Errorf("error code = %q, want %q — the CLI cannot surface the cause without it", body.Code, autopilotTriggerNoOriginatorCode)
+ }
+
+ // Refused before dispatch, so no run row: a skipped run would report this as
+ // an admission outcome on the autopilot's own failure-rate history, which the
+ // auto-pause monitor reads.
+ if runs := dbfx.Count(t, `SELECT count(*) FROM autopilot_run WHERE autopilot_id = $1`, autopilotID); runs != 0 {
+ t.Errorf("autopilot_run rows = %d, want 0 for a pre-dispatch refusal", runs)
+ }
+}
+
+// TestTriggerAutopilot_RuntimeOwnerNeedsNoGrant is the cross-identity case: the
+// ordering human may trigger this autopilot, the machine the agent happens to
+// run on belongs to someone who may not, and the trigger goes through.
+//
+// This is the scenario the first cut of the fix still refused. It kept
+// requireAutopilotWrite in front of the originator check, so BOTH humans had to
+// hold the grant and a member could not delegate a "Run now" they were perfectly
+// entitled to press themselves. Authorization here is the ordering human's alone;
+// workspace tenancy for the authenticated caller stays with the router's
+// RequireWorkspaceMember middleware.
+func TestTriggerAutopilot_RuntimeOwnerNeedsNoGrant(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ var agentID string
+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)
+
+ // The ordering human owns the autopilot outright: they created it.
+ orderingHuman := plainMember(t, "ordering-human")
+ title := fmt.Sprintf("manual trigger cross identity %d", time.Now().UnixNano())
+ autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "title": title,
+ "assignee_id": agentID,
+ "assignee_type": "agent",
+ "execution_mode": "create_issue",
+ "issue_title_template": title,
+ "status": "active",
+ "created_by_type": "member",
+ "created_by_id": orderingHuman,
+ })
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id IN (SELECT id FROM issue WHERE workspace_id = $1 AND title = $2)`, testWorkspaceID, title)
+ dbfx.Cleanup(t, `DELETE FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title)
+ dbfx.Cleanup(t, `DELETE FROM autopilot_run WHERE autopilot_id = $1`, autopilotID)
+
+ // The machine's owner is a plain member with no grant on this autopilot.
+ runtimeOwner := plainMember(t, "runtime-owner")
+ taskID := callerTask(t, agentID, orderingHuman)
+
+ var run AutopilotRunResponse
+ triggerAsAgentAuthedAs(t, runtimeOwner, autopilotID, agentID, taskID).Want(http.StatusOK).JSON(&run)
+ if run.Status != "issue_created" {
+ t.Fatalf("run status = %q (reason_code %v, failure_reason %v), want issue_created — the ordering human created this autopilot; the runtime owner's lack of a grant must not block them",
+ run.Status, derefStr(run.ReasonCode), derefStr(run.FailureReason))
+ }
+}
+
+// TestTriggerAutopilot_AgentCannotExceedItsOriginator pins the other half of the
+// ruling: the agent may only press a "Run now" its ordering human could press
+// themselves. The request still authenticates as the runtime owner, who DOES
+// hold write here, so this can only fail because the ORIGINATOR does not —
+// proving the gate reads the originator and not the token's bound user.
+func TestTriggerAutopilot_AgentCannotExceedItsOriginator(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ autopilotID, agentID := triggerInvokerFixture(t, "originator lacks write")
+
+ outsiderID := dbfx.User(t, "Trigger Outsider", fmt.Sprintf("trigger-outsider-%[email protected]", time.Now().UnixNano()))
+ // A plain member: in the workspace, but neither the autopilot's creator nor
+ // an admin nor a granted collaborator.
+ dbfx.Member(t, testWorkspaceID, outsiderID, "member")
+
+ taskID := callerTask(t, agentID, outsiderID)
+ var body triggerErrorBody
+ triggerAsAgent(t, autopilotID, agentID, taskID).Want(http.StatusForbidden).JSON(&body)
+ if body.Code != autopilotTriggerForbiddenCode {
+ t.Errorf("error code = %q, want %q", body.Code, autopilotTriggerForbiddenCode)
+ }
+
+ if runs := dbfx.Count(t, `SELECT count(*) FROM autopilot_run WHERE autopilot_id = $1`, autopilotID); runs != 0 {
+ t.Errorf("autopilot_run rows = %d, want 0 for a pre-dispatch refusal", runs)
+ }
+}
+
+// TestTriggerAutopilot_MemberPathUnchanged guards the half of the manual path
+// that was never broken: a member triggering directly is judged as themselves,
+// with no originator lookup in the way.
+func TestTriggerAutopilot_MemberPathUnchanged(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ autopilotID, _ := triggerInvokerFixture(t, "member direct")
+
+ r := newRequestAs(testUserID, "POST", "/api/autopilots/"+autopilotID+"/trigger?workspace_id="+testWorkspaceID, nil)
+ r = withURLParam(r, "id", autopilotID)
+
+ var run AutopilotRunResponse
+ testutil.Call(t, testHandler.TriggerAutopilot, r).Want(http.StatusOK).JSON(&run)
+ if run.Status != "issue_created" {
+ t.Fatalf("run status = %q (reason_code %v), want issue_created", run.Status, derefStr(run.ReasonCode))
+ }
+}
+
+// triggerErrorBody is the refusal envelope writeErrorCode produces.
+type triggerErrorBody struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+}
+
+func derefStr(s *string) string {
+ if s == nil {
+ return "<nil>"
+ }
+ return *s
+}
diff --git a/server/internal/service/admission_mul4525_test.go b/server/internal/service/admission_mul4525_test.go
index 27a0fee457..9143a98acc 100644
--- a/server/internal/service/admission_mul4525_test.go
+++ b/server/internal/service/admission_mul4525_test.go
@@ -93,9 +93,9 @@ func TestRerunIssueBlockedBeforeMutationWhenInvokeDenied(t *testing.T) {
}
// TestAutopilotDispatchAdmitsClickerNotCreator is the acceptance test for
-// MUL-4525 §3: a MANUAL "run now" admits on the CURRENT clicker's invoke
-// permission (not the autopilot creator's), while automation (no human actor)
-// still falls back to the creator gate. The two must not fork.
+// MUL-4525 §3: a MANUAL "run now" admits on the invoke permission of the human
+// who ordered it (not the autopilot creator's), while a dispatch that resolves
+// no principal at all is refused. The two must not fork.
func TestAutopilotDispatchAdmitsClickerNotCreator(t *testing.T) {
pool := newResolveOriginatorPool(t)
ctx := context.Background()
@@ -127,20 +127,32 @@ func TestAutopilotDispatchAdmitsClickerNotCreator(t *testing.T) {
}
svc := &AutopilotService{Queries: q}
- // Manual dispatch by the agent owner (the clicker) is admitted.
+ // Manual dispatch by the agent owner is admitted. actorUserID is the human who
+ // ORDERED the run — the clicking member, or the originator an agent acts for;
+ // the handler resolves and authorizes it (requireAutopilotTriggerInvoker) before
+ // this gate ever sees it.
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) 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.
+ // Neither an actor nor a trigger: no principal exists to judge, so the gate
+ // denies. This argument shape reaches the service only from an automation path
+ // that lost its trigger — the manual entry point is refused upstream (#8078).
+ //
+ // The reason must NOT blame a trigger owner here. Until #8078 it did, and
+ // because a manual "run now" passes exactly this pair (no member actor, no
+ // trigger row), every agent-initiated trigger reported a broken trigger owner
+ // for a trigger that never existed — which is what made the regression cost a
+ // day to diagnose. Assert the phrasing, not just the skip.
reason, code, skip := svc.shouldSkipDispatch(ctx, ap, pgtype.UUID{}, pgtype.UUID{})
if !skip {
- t.Fatalf("automation dispatch with no resolvable principal should be blocked")
+ t.Fatalf("dispatch with no resolvable principal should be blocked")
}
- if !strings.Contains(strings.ToLower(reason), "trigger") {
- t.Errorf("automation skip reason = %q, want the trigger-principal phrasing", reason)
+ if !strings.Contains(strings.ToLower(reason), "no authorizing human") {
+ t.Errorf("no-principal skip reason = %q, want the no-authorizing-human phrasing", reason)
+ }
+ if strings.Contains(strings.ToLower(reason), "trigger's owner") {
+ t.Errorf("no-principal skip reason = %q, must not blame a trigger row that does not exist", reason)
}
if code != dispatch.ReasonInvocationNotAllowed {
t.Errorf("skip reason_code = %q, want invocation_not_allowed", code)
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 701bb385fc..31048c7aa6 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -135,13 +135,20 @@ func (s *AutopilotService) DispatchAutopilot(
return run, err
}
-// DispatchAutopilotManual is the "run now" entry point for a member manually
-// 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").
+// DispatchAutopilotManual is the "run now" entry point for a manual trigger.
+// Scheduled / webhook / api dispatch acts as the firing trigger's creator
+// (MUL-6951); a manual trigger is a direct human action by the human who ORDERED
+// it 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.
+//
+// actorUserID is that ordering human — the clicking member, or, when an agent
+// triggers on someone's behalf, the originator it acts for. The HTTP entry point
+// resolves and authorizes it (handler.requireAutopilotTriggerInvoker) and refuses
+// the request outright when no human resolves, so a manual dispatch reaching here
+// with an invalid actorUserID has no principal at all. It then behaves exactly
+// like DispatchAutopilot(source="manual") and, having no trigger to fall back to,
+// is refused by the admission gate (#8078).
func (s *AutopilotService) DispatchAutopilotManual(
ctx context.Context,
autopilot db.Autopilot,
@@ -1347,18 +1354,26 @@ func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopil
}
// Invocation gate at the autopilot layer (MUL-3963 / MUL-4525). The
// admission principal depends on how the dispatch was triggered: a MANUAL
- // "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) 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
+ // "run now" (actorUserID valid) is a direct human action gated by the human
+ // who ORDERED it — the clicking member, or the originator an agent acts for,
+ // resolved by the handler (requireAutopilotTriggerInvoker) — not the
+ // autopilot creator's, so admission and attribution credit the same human and
+ // never fork. Automation (schedule / webhook, 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, and no branch admits a principal-less dispatch. For squad
// autopilots the gate runs against the resolved leader.
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
}
+ if !triggerID.Valid {
+ // No actor AND no trigger: there is no trigger row whose owner could be
+ // at fault, so the trigger phrasing below would name a thing that does
+ // not exist. That message on the manual path is what sent #8078 hunting
+ // for a broken trigger owner for a day.
+ return "this dispatch resolved no authorizing human and carries no trigger to resolve one from", 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
diff --git a/server/internal/service/builtin_skills/multica-platform/references/autopilots.md b/server/internal/service/builtin_skills/multica-platform/references/autopilots.md
index 480dd40ac2..c48eaacc6f 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/autopilots.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/autopilots.md
@@ -42,6 +42,12 @@ test — those are real side effects. Use `trigger` only when the user explicitl
asks for a manual run, and `trigger-rotate-url` only when rotating a webhook
URL; the old URL stops being valid immediately.
+`trigger` exits non-zero when the run did not start. Only `issue_created` and
+`running` mean work was dispatched; a `skipped` run — admission refused, runtime
+offline, quota exhausted, a duplicate already in flight — dispatched nothing, and
+its `failure_reason` says which. Do not report a manual run as done without
+seeing one of those two statuses.
+
A schedule trigger without `--timezone` runs in **UTC**. Name the zone whenever
a human confirmed a wall-clock time, or they will confirm a morning job and
receive an afternoon one.
@@ -75,6 +81,14 @@ keeps write/execute but cannot re-grant or revoke peers. `get` stamps two
per-caller booleans — `can_write` and the narrower `can_manage_access` — read
those rather than inferring from role.
+When YOU run `trigger`, the run is authorized as the human who asked you to —
+your run's originator — not as the owner of the machine you execute on, whose
+grants are not consulted. So the person who gave you the instruction needs that
+write access, and you cannot trigger an autopilot they could not trigger
+themselves. A run that carries no originator at all cannot trigger anything: the
+server answers `403` naming the missing originator rather than skipping quietly,
+and the CLI prints that reason instead of a generic permission error.
+
## Side effects
These mutate durable state or start work: `create`, `update`, `delete`, trigger