Skip to content

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

Go

feat(issues): tell the caller why an issue write started no run (#10858)

xiaoke1234567875e06b144625
diff --git a/apps/docs/content/docs/assigning-issues.fr.mdx b/apps/docs/content/docs/assigning-issues.fr.mdx
index 409a22d7fa..2787002031 100644
--- a/apps/docs/content/docs/assigning-issues.fr.mdx
+++ b/apps/docs/content/docs/assigning-issues.fr.mdx
@@ -97,6 +97,8 @@ Dans les scripts, utilisez `--to-id <uuid>` pour éviter de cibler un mauvais ob
Utilisez `--no-start` lorsque l'assignation doit enregistrer le responsable sans créer de nouvelle exécution — par exemple lorsque le même agent traite déjà la tâche depuis une autre exécution. La même option est disponible sur `issue update` et `issue status`. Si un flux qui ne fait qu'enregistrer le responsable modifie à la fois l'assignation et le statut, passez-la aux deux commandes : neutraliser le déclenchement de l'assignation ne neutralise pas une exécution déclenchée ensuite par le changement de statut.
+Si une assignation ou un changement de statut ne démarre aucune exécution — par exemple parce que la tâche est en Triage ou que l'agent n'a pas de runtime — la commande en indique la raison sur stderr. `issue batch update` affiche la même indication dans sa colonne de raison.
+
## Étapes suivantes
- [@mentionner des agents dans les commentaires](/mentioning-agents) — traitez une nouvelle question sans changer l'assigné.
diff --git a/apps/docs/content/docs/assigning-issues.ja.mdx b/apps/docs/content/docs/assigning-issues.ja.mdx
index a15bf3b07f..8a54f693a9 100644
--- a/apps/docs/content/docs/assigning-issues.ja.mdx
+++ b/apps/docs/content/docs/assigning-issues.ja.mdx
@@ -97,6 +97,8 @@ multica issue assign MUL-42 --unassign
割り当てで担当だけを記録し、新しい実行を作成しない場合(たとえば同じエージェントが別の実行ですでにそのタスクを処理している場合)は、`--no-start` を使用します。`issue update` と `issue status` でも同じフラグを使用できます。担当とステータスの両方を変更する所有権のみのフローでは、両方のコマンドにこのフラグを指定してください。割り当てを抑止しても、後続のステータス変更による実行は自動では抑止されません。
+割り当てやステータス変更で実行が始まらなかった場合(たとえばタスクが Triage にある、エージェントにランタイムがない場合)は、コマンドがその理由を stderr に表示します。`issue batch update` では理由の列に同じ説明が表示されます。
+
## 次のステップ
- [コメントでエージェントを @メンション](/mentioning-agents) — 担当者を変えずに、新しい依頼を処理します。
diff --git a/apps/docs/content/docs/assigning-issues.ko.mdx b/apps/docs/content/docs/assigning-issues.ko.mdx
index e7ac0e73c0..c77578a861 100644
--- a/apps/docs/content/docs/assigning-issues.ko.mdx
+++ b/apps/docs/content/docs/assigning-issues.ko.mdx
@@ -97,6 +97,8 @@ multica issue assign MUL-42 --unassign
할당이 담당자만 기록하고 새 실행을 만들면 안 되는 경우(예: 같은 에이전트가 다른 실행에서 이미 해당 태스크를 처리 중인 경우)에는 `--no-start`를 사용하세요. `issue update`와 `issue status`에서도 같은 플래그를 사용할 수 있습니다. 담당자와 상태를 모두 바꾸는 소유권 전용 흐름이라면 두 명령 모두에 이 플래그를 전달해야 합니다. 할당을 억제해도 이후 상태 변경이 시작하는 실행까지 자동으로 억제되지는 않습니다.
+할당이나 상태 변경으로 실행이 시작되지 않으면(예: 태스크가 Triage에 있거나 에이전트에 런타임이 없는 경우) 명령이 그 이유를 stderr에 출력합니다. `issue batch update`는 이유 열에 같은 설명을 표시합니다.
+
## 다음 단계
- [댓글에서 에이전트 @멘션하기](/mentioning-agents) — 담당자를 바꾸지 않고 새 문제를 처리합니다.
diff --git a/apps/docs/content/docs/assigning-issues.mdx b/apps/docs/content/docs/assigning-issues.mdx
index fc1516b39d..b52239b792 100644
--- a/apps/docs/content/docs/assigning-issues.mdx
+++ b/apps/docs/content/docs/assigning-issues.mdx
@@ -97,6 +97,8 @@ In scripts, use `--to-id <uuid>` to avoid matching the wrong object with the sam
Use `--no-start` when the assignment should record ownership without creating a new run — for example, when the same agent is already handling the issue from another run. The same flag is available on `issue update` and `issue status`. If an ownership-only flow changes both assignment and status, pass it to both commands; suppressing the assignment does not suppress a later status-triggered run.
+If an assignment or status change starts no run — for example because the issue is in Triage or the agent has no runtime — the command says why on stderr. `issue batch update` shows the same note in its reason column.
+
## Next steps
- [@-mention agents in comments](/mentioning-agents) — handle a new question without changing the assignee.
diff --git a/apps/docs/content/docs/assigning-issues.zh-Hant.mdx b/apps/docs/content/docs/assigning-issues.zh-Hant.mdx
index 9bee2bb813..513c38464b 100644
--- a/apps/docs/content/docs/assigning-issues.zh-Hant.mdx
+++ b/apps/docs/content/docs/assigning-issues.zh-Hant.mdx
@@ -97,6 +97,8 @@ multica issue assign MUL-42 --unassign
如果指派只用於記錄負責人、不應建立新執行(例如同一 AI 代理已在另一次執行中處理該任務),請使用 `--no-start`。`issue update` 和 `issue status` 同樣支援這個 flag。如果只記錄歸屬的流程同時修改負責人和狀態,兩條命令都要傳入該 flag;抑制指派不會自動抑制後續狀態變更觸發的執行。
+如果指派或狀態變更沒有啟動執行(例如任務仍在 Triage 中,或 AI 代理沒有綁定執行時),命令會在 stderr 中說明原因。`issue batch update` 會在原因欄位顯示同樣的說明。
+
## 接下來
- [在評論中 @ AI 代理](/mentioning-agents) — 不改變負責人,處理新的問題。
diff --git a/apps/docs/content/docs/assigning-issues.zh.mdx b/apps/docs/content/docs/assigning-issues.zh.mdx
index 20d84f604e..101aa54e97 100644
--- a/apps/docs/content/docs/assigning-issues.zh.mdx
+++ b/apps/docs/content/docs/assigning-issues.zh.mdx
@@ -97,6 +97,8 @@ multica issue assign MUL-42 --unassign
如果指派只用于记录负责人、不应创建新运行(例如同一智能体已在另一次运行中处理该任务),请使用 `--no-start`。`issue update` 和 `issue status` 同样支持这个 flag。如果只记录归属的流程同时修改负责人和状态,两条命令都要传入该 flag;抑制指派不会自动抑制后续状态变更触发的运行。
+如果指派或状态变更没有启动运行(例如任务还在 Triage 中,或智能体没有绑定运行时),命令会在 stderr 中说明原因。`issue batch update` 会在原因一列显示同样的说明。
+
## 接下来
- [在评论中 @智能体](/mentioning-agents) — 不改变负责人,处理新的问题。
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index ab58827923..287841a50f 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -2174,6 +2174,7 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {
}
result["pr_auto_complete_disabled"] = *prAutoCompleteDisabled
}
+ reportIssueRunOutcome(os.Stderr, result, noStart)
output, _ := cmd.Flags().GetString("output")
if output == "table" {
@@ -2251,6 +2252,7 @@ func runIssueAssign(cmd *cobra.Command, args []string) error {
} else {
fmt.Fprintf(os.Stderr, "Issue %s assigned to %s.\n", issueDisplayKey(result), displayTarget)
}
+ reportIssueRunOutcome(os.Stderr, result, noStart)
output, _ := cmd.Flags().GetString("output")
if output == "table" {
@@ -2310,6 +2312,7 @@ func runIssueStatus(cmd *cobra.Command, args []string) error {
} else {
fmt.Fprintf(os.Stderr, "Issue %s status changed to %s.\n", issueDisplayKey(result), status)
}
+ reportIssueRunOutcome(os.Stderr, result, noStart)
output, _ := cmd.Flags().GetString("output")
if output == "json" {
diff --git a/server/cmd/multica/cmd_issue_batch.go b/server/cmd/multica/cmd_issue_batch.go
index 2f2d0f553d..569ecab8d1 100644
--- a/server/cmd/multica/cmd_issue_batch.go
+++ b/server/cmd/multica/cmd_issue_batch.go
@@ -77,6 +77,8 @@ type issueBatchResult struct {
Outcome string `json:"outcome"`
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
+ // RunOutcome is kept so --output json passes it through.
+ RunOutcome *issueRunOutcome `json:"run_outcome,omitempty"`
}
type issueBatchResponse struct {
@@ -368,6 +370,7 @@ func printIssueBatchResults(cmd *cobra.Command, resp issueBatchResponse) error {
if output == "json" {
return cli.PrintJSON(os.Stdout, resp)
}
+ noStart, _ := cmd.Flags().GetBool("no-start")
rows := make([][]string, 0, len(resp.Results))
counts := map[string]int{}
for _, r := range resp.Results {
@@ -379,6 +382,9 @@ func printIssueBatchResults(cmd *cobra.Command, resp issueBatchResponse) error {
if r.Code != "" && reason == "" {
reason = r.Code
}
+ if reason == "" {
+ reason = issueRunOutcomeNote(r.RunOutcome, noStart)
+ }
rows = append(rows, []string{key, strings.ReplaceAll(r.Outcome, "_", " "), reason})
counts[r.Outcome]++
}
diff --git a/server/cmd/multica/cmd_issue_run_outcome.go b/server/cmd/multica/cmd_issue_run_outcome.go
new file mode 100644
index 0000000000..5351bc36ef
--- /dev/null
+++ b/server/cmd/multica/cmd_issue_run_outcome.go
@@ -0,0 +1,73 @@
+package main
+
+import (
+ "fmt"
+ "io"
+ "strings"
+)
+
+// issueRunOutcome is what an issue write did about the run it could have
+// started: queued, coalesced, deferred or blocked, with a stable reason code.
+// Servers before #10845 send none.
+type issueRunOutcome struct {
+ TargetType string `json:"target_type"`
+ TargetID string `json:"target_id"`
+ Status string `json:"status"`
+ ReasonCode string `json:"reason_code"`
+}
+
+// issueRunOutcomeNote says why an issue write started no new run, or returns
+// "" when there is nothing to say: a run started, the server sent no outcome,
+// or the caller passed --no-start and so already knows. An agent that assigned
+// or promoted an issue reads this instead of assuming its run started.
+func issueRunOutcomeNote(o *issueRunOutcome, noStart bool) string {
+ if o == nil || noStart {
+ return ""
+ }
+ switch o.Status {
+ case "", "queued":
+ return ""
+ case "coalesced":
+ return "no new run started: a pending run on this issue already covers it"
+ case "deferred":
+ if o.ReasonCode == "already_active" {
+ return "no new run started: the assignee's active run on this issue covers it"
+ }
+ return "no run started: the issue is in backlog and runs once it moves to an active status"
+ }
+ return "no run started: " + blockedRunReason(o.ReasonCode)
+}
+
+func blockedRunReason(code string) string {
+ text := map[string]string{
+ "issue_in_triage": "the issue is in Triage; accept it first",
+ "agent_runtime_required": "the assignee has no runtime; bind it to one",
+ "target_unavailable": "the assignee is archived or no longer exists",
+ "runtime_offline": "the assignee's runtime is offline",
+ "runtime_unusable": "the assignee's agent CLI cannot run on its runtime",
+ "runtime_profile_missing": "the assignee's runtime is missing a required profile",
+ "runtime_access_denied": "the assignee's owner cannot use its runtime",
+ "invocation_not_allowed": "you may not invoke the assignee",
+ "attribution_blocked": "no responsible person could be resolved for the run",
+ "project_access_blocked": "the run's people cannot access the issue's project",
+ }[code]
+ if text == "" {
+ return code
+ }
+ return fmt.Sprintf("%s (%s)", text, code)
+}
+
+// reportIssueRunOutcome prints the note for a single-issue write to w.
+func reportIssueRunOutcome(w io.Writer, result map[string]any, noStart bool) {
+ raw, _ := result["run_outcome"].(map[string]any)
+ if raw == nil {
+ return
+ }
+ note := issueRunOutcomeNote(&issueRunOutcome{
+ Status: strVal(raw, "status"),
+ ReasonCode: strVal(raw, "reason_code"),
+ }, noStart)
+ if note != "" {
+ fmt.Fprintf(w, "%s%s.\n", strings.ToUpper(note[:1]), note[1:])
+ }
+}
diff --git a/server/cmd/multica/cmd_issue_run_outcome_test.go b/server/cmd/multica/cmd_issue_run_outcome_test.go
new file mode 100644
index 0000000000..3e87a9d6ee
--- /dev/null
+++ b/server/cmd/multica/cmd_issue_run_outcome_test.go
@@ -0,0 +1,106 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+)
+
+func TestIssueRunOutcomeNote(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ outcome *issueRunOutcome
+ noStart bool
+ want string
+ }{
+ {name: "older server", outcome: nil, want: ""},
+ {name: "run started", outcome: &issueRunOutcome{Status: "queued", ReasonCode: "queued"}, want: ""},
+ {name: "pending run covers it", outcome: &issueRunOutcome{Status: "coalesced", ReasonCode: "coalesced"}, want: "no new run started: a pending run on this issue already covers it"},
+ {name: "active run covers it", outcome: &issueRunOutcome{Status: "deferred", ReasonCode: "already_active"}, want: "no new run started: the assignee's active run on this issue covers it"},
+ {name: "backlog", outcome: &issueRunOutcome{Status: "deferred", ReasonCode: "deferred"}, want: "no run started: the issue is in backlog and runs once it moves to an active status"},
+ {name: "caller asked for no run", outcome: &issueRunOutcome{Status: "deferred", ReasonCode: "deferred"}, noStart: true, want: ""},
+ {name: "blocked", outcome: &issueRunOutcome{Status: "blocked", ReasonCode: "issue_in_triage"}, want: "no run started: the issue is in Triage; accept it first (issue_in_triage)"},
+ {name: "blocked for a newer reason", outcome: &issueRunOutcome{Status: "blocked", ReasonCode: "quota_exceeded"}, want: "no run started: quota_exceeded"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := issueRunOutcomeNote(tc.outcome, tc.noStart); got != tc.want {
+ t.Fatalf("note = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+// `issue status` tells an agent caller when its write started no run, so it
+// does not report the run as started (#10845).
+func TestRunIssueStatusReportsWhyNoRunStarted(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ runOutcome any
+ want string
+ }{
+ {name: "blocked", runOutcome: map[string]any{"target_type": "agent", "target_id": "agent-1", "status": "blocked", "reason_code": "issue_in_triage"},
+ want: "No run started: the issue is in Triage; accept it first (issue_in_triage).\n"},
+ {name: "older server", runOutcome: nil, want: ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/MUL-1":
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "backlog"})
+ case r.Method == http.MethodPut && r.URL.Path == "/api/issues/issue-1":
+ resp := map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "todo"}
+ if tc.runOutcome != nil {
+ resp["run_outcome"] = tc.runOutcome
+ }
+ _ = json.NewEncoder(w).Encode(resp)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ setCLITestServerEnv(t, srv.URL)
+ t.Setenv("MULTICA_TASK_CONFIG_ROOT", t.TempDir())
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+
+ stderr := captureStderr(t)
+ defer stderr.restore()
+ if err := runIssueStatus(newIssueStatusTestCmd(), []string{"MUL-1", "todo"}); err != nil {
+ t.Fatalf("runIssueStatus: %v", err)
+ }
+ report := strings.TrimPrefix(stderr.read(), "Issue MUL-1 status changed to todo.\n")
+ if report != tc.want {
+ t.Fatalf("stderr after the status line = %q, want %q", report, tc.want)
+ }
+ })
+ }
+}
+
+// A batch row with no reason of its own shows why its write started no run,
+// and --output json keeps the outcome.
+func TestPrintIssueBatchResultsShowsRunOutcome(t *testing.T) {
+ var resp issueBatchResponse
+ if err := json.Unmarshal([]byte(`{"updated":1,"results":[{"issue_id":"issue-1","identifier":"MUL-1","outcome":"updated",
+ "run_outcome":{"target_type":"agent","target_id":"agent-1","status":"blocked","reason_code":"issue_in_triage"}}]}`), &resp); err != nil {
+ t.Fatal(err)
+ }
+ for _, output := range []string{"table", "json"} {
+ cmd := &cobra.Command{Use: "update"}
+ cmd.Flags().String("output", output, "")
+ cmd.Flags().Bool("no-start", false, "")
+ stdout, err := captureStdout(t, func() error { return printIssueBatchResults(cmd, resp) })
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "no run started: the issue is in Triage; accept it first (issue_in_triage)"
+ if output == "json" {
+ want = `"reason_code": "issue_in_triage"`
+ }
+ if !strings.Contains(stdout, want) {
+ t.Fatalf("%s output = %q, want it to contain %q", output, stdout, want)
+ }
+ }
+}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 2e93c22c52..05e80161fe 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -109,6 +109,9 @@ type IssueResponse struct {
// SourceContext is detail-only. List, board, search, and children responses
// deliberately omit the potentially large immutable snapshot.
SourceContext *sourceContextDetailResponse `json:"source_context,omitempty"`
+ // RunOutcome is set only on the response to the caller's own update
+ // (#10845); see IssueRunOutcome.
+ RunOutcome *IssueRunOutcome `json:"run_outcome,omitempty"`
// duplicateOfIssueID is the raw mark, kept off the wire; see DuplicateOf.
duplicateOfIssueID pgtype.UUID
}
@@ -4364,6 +4367,7 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
h.issueTriggerWriteProbe(r, actorType, actorID, issue),
)
logDeclinedIssueRun(r.Context(), issue, trigger)
+ runDecided := willRun
willRun = willRun && !req.SuppressRun
updatedPayload := map[string]any{
@@ -4431,9 +4435,7 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
if handoff != nil && req.StopPreviousAssigneeRuns {
h.stopPreviousAssigneeRuns(r.Context(), prevIssue, issue, actorType, actorID)
}
- if willRun {
- h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, handoffNote)
- }
+ resp.RunOutcome = h.resolveIssueRun(r, issue, trigger, runDecided, req.SuppressRun, actorType, actorID, workspaceID, handoffNote)
// Sub-issue rules on the parent (the child_done system rule and sub-issue
// conditions): the write recorded the change; process it now. A failure
@@ -5207,6 +5209,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
}
actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ var runOutcome *IssueRunOutcome
if hasFieldUpdate {
resp := issueToResponse(issue, prefix)
h.advanceRunStep(r.Context(), callerRun, prevIssue, issue)
@@ -5230,6 +5233,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
h.issueTriggerWriteProbe(r, actorType, actorID, issue),
)
logDeclinedIssueRun(r.Context(), issue, trigger)
+ runDecided := willRun
willRun = willRun && !req.Updates.SuppressRun
batchPayload := map[string]any{
"issue": resp,
@@ -5259,9 +5263,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if handoff != nil && req.Updates.StopPreviousAssigneeRuns {
h.stopPreviousAssigneeRuns(r.Context(), prevIssue, issue, actorType, actorID)
}
- if willRun {
- h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, batchHandoffNote)
- }
+ runOutcome = h.resolveIssueRun(r, issue, trigger, runDecided, req.Updates.SuppressRun, actorType, actorID, workspaceID, batchHandoffNote)
// No status change — not even → cancelled — cancels active tasks here,
// mirroring UpdateIssue (MUL-4465). See that handler for the rationale.
@@ -5291,7 +5293,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if issue.Revision == prevIssue.Revision {
outcome = batchOutcomeUnchanged
}
- results = append(results, batchIssueResult{IssueID: issueID, Identifier: identifier, Outcome: outcome})
+ results = append(results, batchIssueResult{IssueID: issueID, Identifier: identifier, Outcome: outcome, RunOutcome: runOutcome})
updated++
}
diff --git a/server/internal/handler/issue_batch.go b/server/internal/handler/issue_batch.go
index 74f6a4ec40..754104e638 100644
--- a/server/internal/handler/issue_batch.go
+++ b/server/internal/handler/issue_batch.go
@@ -52,6 +52,9 @@ type batchIssueResult struct {
Outcome string `json:"outcome"`
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
+ // RunOutcome is set on an updated item whose write could have started a
+ // run; see IssueRunOutcome.
+ RunOutcome *IssueRunOutcome `json:"run_outcome,omitempty"`
}
// batchSkipError ends one issue's write with a reason the caller can act on,
diff --git a/server/internal/handler/issue_run_outcome_test.go b/server/internal/handler/issue_run_outcome_test.go
new file mode 100644
index 0000000000..4b533d4004
--- /dev/null
+++ b/server/internal/handler/issue_run_outcome_test.go
@@ -0,0 +1,254 @@
+package handler
+
+import (
+ "bytes"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func updateIssueForOutcome(t *testing.T, issueID string, body map[string]any) IssueResponse {
+ t.Helper()
+ var resp IssueResponse
+ testutil.Call(t, testHandler.UpdateIssue,
+ withURLParam(newRequest("PUT", "/api/issues/"+issueID, body), "id", issueID)).Want(http.StatusOK).JSON(&resp)
+ return resp
+}
+
+func wantRunOutcome(t *testing.T, got *IssueRunOutcome, targetType, targetID string, status DispatchStatus, reason DispatchReasonCode) {
+ t.Helper()
+ want := IssueRunOutcome{TargetType: targetType, TargetID: targetID, Status: status, ReasonCode: reason}
+ if got == nil || *got != want {
+ t.Fatalf("run_outcome = %+v, want %+v", got, want)
+ }
+}
+
+// An issue write tells its caller whether it started a run and, if not, why
+// (#10845). Only the caller gets the outcome: the issue:updated broadcast
+// reaches every member and carries none.
+func TestUpdateIssueReportsRunOutcome(t *testing.T) {
+ agentID := seededReadyAgentID(t)
+ assign := map[string]any{"assignee_type": "agent", "assignee_id": agentID}
+
+ var mu sync.Mutex
+ broadcastOutcomes := map[string]*IssueRunOutcome{}
+ testHandler.Bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {
+ payload, _ := e.Payload.(map[string]any)
+ if resp, ok := payload["issue"].(IssueResponse); ok {
+ mu.Lock()
+ broadcastOutcomes[resp.ID] = resp.RunOutcome
+ mu.Unlock()
+ }
+ })
+
+ t.Run("assignment that starts a run", func(t *testing.T) {
+ issue := createIssueForTest(t, map[string]any{"title": "outcome queued", "status": "todo"})
+ resp := updateIssueForOutcome(t, issue.ID, assign)
+ wantRunOutcome(t, resp.RunOutcome, "agent", agentID, DispatchQueued, ReasonQueued)
+ if got := taskCountFor(t, issue.ID, agentID); got != 1 {
+ t.Fatalf("tasks = %d, want 1", got)
+ }
+ mu.Lock()
+ broadcast, seen := broadcastOutcomes[issue.ID]
+ mu.Unlock()
+ if !seen || broadcast != nil {
+ t.Fatalf("issue:updated broadcast seen=%v run_outcome=%+v, want a broadcast without one", seen, broadcast)
+ }
+ })
+
+ t.Run("assignment to an agent that already has a pending run", func(t *testing.T) {
+ // The assign path skips the pending check, so the enqueue meets the
+ // pending-slot index and coalesces into the existing task.
+ issue := createIssueForTest(t, map[string]any{"title": "outcome coalesced", "status": "todo"})
+ var runtimeID string
+ dbfx.QueryRow(t, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID)
+ dbfx.Task(t, agentID, testutil.Cols{"issue_id": issue.ID, "runtime_id": runtimeID, "status": "queued"})
+ resp := updateIssueForOutcome(t, issue.ID, assign)
+ wantRunOutcome(t, resp.RunOutcome, "agent", agentID, DispatchCoalesced, ReasonCoalesced)
+ if got := taskCountFor(t, issue.ID, agentID); got != 1 {
+ t.Fatalf("tasks = %d, want the existing one only", got)
+ }
+ })
+
+ t.Run("assignment while in triage", func(t *testing.T) {
+ issue := createIssueForTest(t, map[string]any{"title": "outcome triage", "status": "todo"})
+ dbfx.Exec(t, `UPDATE issue SET triage_state = 'pending' WHERE id = $1`, issue.ID)
+ resp := updateIssueForOutcome(t, issue.ID, assign)
+ wantRunOutcome(t, resp.RunOutcome, "agent", agentID, DispatchBlocked, ReasonIssueInTriage)
+ })
+
+ t.Run("assignment with suppress_run", func(t *testing.T) {
+ issue := createIssueForTest(t, map[string]any{"title": "outcome suppressed", "status": "todo"})
+ body := map[string]any{"assignee_type": "agent", "assignee_id": agentID, "suppress_run": true}
+ resp := updateIssueForOutcome(t, issue.ID, body)
+ wantRunOutcome(t, resp.RunOutcome, "agent", agentID, DispatchDeferred, ReasonDeferred)
+ if got := taskCountFor(t, issue.ID, agentID); got != 0 {
+ t.Fatalf("tasks = %d, want none", got)
+ }
+ })
+
+ t.Run("edit that could not start a run", func(t *testing.T) {
+ issue := createIssueForTest(t, map[string]any{"title": "outcome edit", "status": "todo"})
+ updateIssueForOutcome(t, issue.ID, assign)
+ resp := updateIssueForOutcome(t, issue.ID, map[string]any{"title": "outcome edit renamed"})
+ if resp.RunOutcome != nil {
+ t.Fatalf("title edit run_outcome = %+v, want none", resp.RunOutcome)
+ }
+ })
+
+ t.Run("promotion that starts an agent the caller may not invoke", func(t *testing.T) {
+ // The write starts the run, but the outcome would expose a private
+ // agent's readiness to a caller who cannot invoke it.
+ var runtimeID string
+ dbfx.QueryRow(t, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID)
+ otherUser := dbfx.User(t, "outcome-other-owner", fmt.Sprintf("outcome-other-%[email protected]", time.Now().UnixNano()))
+ privateAgent := dbfx.Agent(t, "Outcome Private Agent", runtimeID, testutil.Cols{"owner_id": otherUser})
+ issue := createIssueForTest(t, map[string]any{"title": "outcome private", "status": "backlog"})
+ dbfx.Exec(t, `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, issue.ID, privateAgent)
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issue.ID)
+
+ resp := updateIssueForOutcome(t, issue.ID, map[string]any{"status": "todo"})
+ if resp.RunOutcome != nil {
+ t.Fatalf("run_outcome = %+v, want none for an agent the caller may not invoke", resp.RunOutcome)
+ }
+ if got := taskCountFor(t, issue.ID, privateAgent); got != 1 {
+ t.Fatalf("tasks = %d, want the promotion to start one run", got)
+ }
+ })
+}
+
+func TestBatchUpdateIssuesReportsRunOutcomePerIssue(t *testing.T) {
+ agentID := seededReadyAgentID(t)
+ ready := createIssueForTest(t, map[string]any{"title": "batch outcome queued", "status": "todo"})
+ triage := createIssueForTest(t, map[string]any{"title": "batch outcome triage", "status": "todo"})
+ dbfx.Exec(t, `UPDATE issue SET triage_state = 'pending' WHERE id = $1`, triage.ID)
+ body := func(dryRun bool) map[string]any {
+ return map[string]any{
+ "issue_ids": []string{ready.ID, triage.ID},
+ "updates": map[string]any{"assignee_type": "agent", "assignee_id": agentID},
+ "dry_run": dryRun,
+ }
+ }
+
+ code, preview, raw := batchUpdate(t, body(true))
+ if code != http.StatusOK {
+ t.Fatalf("dry run: %d %s", code, raw)
+ }
+ for _, issue := range []IssueResponse{ready, triage} {
+ if got := resultFor(t, preview, issue.ID).RunOutcome; got != nil {
+ t.Fatalf("dry-run item %s run_outcome = %+v, want none", issue.ID, got)
+ }
+ }
+
+ code, resp, raw := batchUpdate(t, body(false))
+ if code != http.StatusOK {
+ t.Fatalf("batch update: %d %s", code, raw)
+ }
+ wantRunOutcome(t, resultFor(t, resp, ready.ID).RunOutcome, "agent", agentID, DispatchQueued, ReasonQueued)
+ wantRunOutcome(t, resultFor(t, resp, triage.ID).RunOutcome, "agent", agentID, DispatchBlocked, ReasonIssueInTriage)
+}
+
+func TestIssueWritesOmitRunOutcomeForMemberAssignees(t *testing.T) {
+ for _, batch := range []bool{false, true} {
+ for _, tc := range []struct {
+ name string
+ status string
+ triage bool
+ promote bool
+ }{
+ {name: "backlog assignment", status: "backlog"},
+ {name: "triage assignment", status: "todo", triage: true},
+ {name: "active assignment", status: "todo"},
+ {name: "backlog promotion", status: "backlog", promote: true},
+ {name: "triage promotion", status: "backlog", triage: true, promote: true},
+ } {
+ t.Run(fmt.Sprintf("batch=%v/%s", batch, tc.name), func(t *testing.T) {
+ cols := testutil.Cols{"status": tc.status}
+ if tc.triage {
+ cols["triage_state"] = "pending"
+ }
+ updates := map[string]any{"assignee_type": "member", "assignee_id": testUserID}
+ if tc.promote {
+ cols["assignee_type"], cols["assignee_id"] = "member", testUserID
+ updates = map[string]any{"status": "todo"}
+ }
+ issueID := dbfx.Issue(t, "member outcome "+tc.name, cols)
+ var outcome *IssueRunOutcome
+ if batch {
+ code, resp, raw := batchUpdate(t, map[string]any{"issue_ids": []string{issueID}, "updates": updates})
+ if code != http.StatusOK {
+ t.Fatalf("batch update: %d %s", code, raw)
+ }
+ outcome = resultFor(t, resp, issueID).RunOutcome
+ } else {
+ resp := updateIssueForOutcome(t, issueID, updates)
+ outcome = resp.RunOutcome
+ }
+ if outcome != nil {
+ t.Errorf("member run_outcome = %+v, want none", outcome)
+ }
+ var assigneeType, assigneeID string
+ dbfx.QueryRow(t, `SELECT assignee_type, assignee_id FROM issue WHERE id = $1`, issueID).Scan(&assigneeType, &assigneeID)
+ if assigneeType != "member" || assigneeID != testUserID {
+ t.Fatalf("assignee = %s/%s, want member/%s", assigneeType, assigneeID, testUserID)
+ }
+ var tasks int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, issueID).Scan(&tasks)
+ if tasks != 0 {
+ t.Fatalf("member tasks = %d, want none", tasks)
+ }
+ })
+ }
+ }
+}
+
+func TestUpdateIssueOutcomeVisibilityDoesNotLogInvocationDenial(t *testing.T) {
+ readyAgent := seededReadyAgentID(t)
+ var runtimeID string
+ dbfx.QueryRow(t, `SELECT runtime_id FROM agent WHERE id = $1`, readyAgent).Scan(&runtimeID)
+ actor := dbfx.Agent(t, "outcome caller", runtimeID)
+ callerIssue := dbfx.Issue(t, "outcome caller issue")
+ // The request's delegation chain has no human, while the promoted issue
+ // has a member creator. Enqueue and outcome visibility judge those separately.
+ callerTask := dbfx.Task(t, actor, testutil.Cols{"issue_id": callerIssue, "runtime_id": runtimeID, "status": "running"})
+
+ for _, targetType := range []string{"agent", "squad"} {
+ t.Run(targetType, func(t *testing.T) {
+ leader := dbfx.Agent(t, "outcome private "+targetType, runtimeID)
+ targetID := leader
+ if targetType == "squad" {
+ targetID = dbfx.Squad(t, "outcome private squad", leader)
+ }
+ issueID := dbfx.Issue(t, "outcome promotion "+targetType, testutil.Cols{
+ "status": "backlog", "assignee_type": targetType, "assignee_id": targetID,
+ })
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ var logs bytes.Buffer
+ prev := slog.Default()
+ slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelWarn})))
+ t.Cleanup(func() { slog.SetDefault(prev) })
+
+ var resp IssueResponse
+ testutil.Call(t, testHandler.UpdateIssue, asRun(withURLParam(
+ newRequest("PUT", "/api/issues/"+issueID, map[string]any{"status": "todo"}), "id", issueID), actor, callerTask)).
+ Want(http.StatusOK).JSON(&resp)
+ if resp.RunOutcome != nil {
+ t.Errorf("run_outcome = %+v, want none without invocation permission", resp.RunOutcome)
+ }
+ if got := taskCountFor(t, issueID, leader); got != 1 {
+ t.Fatalf("tasks = %d, want promotion to start one run", got)
+ }
+ if strings.Contains(logs.String(), "agent invoke denied") {
+ t.Errorf("outcome visibility logged a denial after enqueue:\n%s", logs.String())
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/issue_trigger.go b/server/internal/handler/issue_trigger.go
index 889d3430ed..64400ebc51 100644
--- a/server/internal/handler/issue_trigger.go
+++ b/server/internal/handler/issue_trigger.go
@@ -98,29 +98,126 @@ func logDeclinedIssueRun(ctx context.Context, issue db.Issue, trigger service.Is
)
}
+// IssueRunOutcome tells the caller of an issue write what happened to the run
+// it could have started (#10845). It has the shape of CommentTriggerOutcome:
+// target_id is the assignee the issue names (the squad id for a squad) and
+// reason_code a stable dispatch code. Like trigger_outcomes it goes to the
+// caller only, never into the issue:updated broadcast.
+type IssueRunOutcome struct {
+ TargetType string `json:"target_type"` // "agent" | "squad"
+ TargetID string `json:"target_id"`
+ Status DispatchStatus `json:"status"` // queued | coalesced | deferred | blocked
+ ReasonCode DispatchReasonCode `json:"reason_code"`
+}
+
+// resolveIssueRun starts the run an issue write decided on and reports the
+// result. willRun is the predicate's decision before suppress_run; a write
+// that could not have started a run (no reason either) reports nothing.
+//
+// The write probe admits every caller, so a promotion can start a private
+// agent the caller may not invoke. Its outcome would then expose that agent's
+// readiness, so the caller gets no outcome; the server log keeps the cause.
+func (h *Handler) resolveIssueRun(r *http.Request, issue db.Issue, trigger service.IssueRunTrigger, willRun, suppressRun bool, actorType, actorID, workspaceID, handoffNote string) *IssueRunOutcome {
+ if issue.AssigneeType.String != "agent" && issue.AssigneeType.String != "squad" {
+ return nil
+ }
+ var status DispatchStatus
+ var reason DispatchReasonCode
+ switch {
+ case willRun && suppressRun:
+ status, reason = DispatchDeferred, ReasonDeferred
+ case willRun:
+ status, reason = h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, handoffNote)
+ case trigger.DeclineReason != "":
+ status, reason = declinedRunStatus(trigger.DeclineReason), trigger.DeclineReason
+ default:
+ return nil
+ }
+ if !h.callerCanInvokeIssueAssignee(r, issue, actorType, actorID, workspaceID) {
+ return nil
+ }
+ return &IssueRunOutcome{
+ TargetType: issue.AssigneeType.String,
+ TargetID: uuidToString(issue.AssigneeID),
+ Status: status,
+ ReasonCode: reason,
+ }
+}
+
+// declinedRunStatus maps a decline reason to its status, matching the comment
+// path: a run already pending or active covers the write, backlog parks it,
+// and anything else is blocked.
+func declinedRunStatus(reason DispatchReasonCode) DispatchStatus {
+ switch reason {
+ case ReasonCoalesced:
+ return DispatchCoalesced
+ case ReasonDeferred, ReasonAlreadyActive:
+ return DispatchDeferred
+ }
+ return DispatchBlocked
+}
+
+// callerCanInvokeIssueAssignee applies the preview probe's gate to the agent
+// that runs: the assignee, or a squad's leader. A target that no longer
+// resolves has no readiness to expose.
+func (h *Handler) callerCanInvokeIssueAssignee(r *http.Request, issue db.Issue, actorType, actorID, workspaceID string) bool {
+ agentID := issue.AssigneeID
+ if issue.AssigneeType.String == "squad" {
+ squad, err := h.Queries.GetSquadInWorkspace(r.Context(), db.GetSquadInWorkspaceParams{ID: issue.AssigneeID, WorkspaceID: issue.WorkspaceID})
+ if err != nil {
+ return true
+ }
+ agentID = squad.LeaderID
+ }
+ agent, err := h.Queries.GetAgent(r.Context(), agentID)
+ if err != nil {
+ return true
+ }
+ return h.invokeAgentDecision(r.Context(), agent, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID)
+}
+
// dispatchIssueRun executes the enqueue side effect for a decision produced by
-// WillEnqueueRun. handoffNote is a legacy API input retained for installed
-// clients and travels only with a run that actually starts. The squad path
-// still flows through enqueueSquadLeaderTask so the leader access gate and
-// pending dedup stay in one place.
-func (h *Handler) dispatchIssueRun(ctx context.Context, issue db.Issue, trigger service.IssueRunTrigger, actorType, actorID, handoffNote string) {
+// WillEnqueueRun and reports what happened. handoffNote is a legacy API input
+// retained for installed clients and travels only with a run that actually
+// starts. The squad path still flows through enqueueSquadLeaderTask so the
+// leader access gate and pending dedup stay in one place.
+func (h *Handler) dispatchIssueRun(ctx context.Context, issue db.Issue, trigger service.IssueRunTrigger, actorType, actorID, handoffNote string) (DispatchStatus, DispatchReasonCode) {
switch trigger.AssigneeType {
case "agent":
// The member who performed this assign/promote is the accountable human
// for the run (MUL-4302 §4). An agent actor is not a human, so only a
// member actor is threaded; otherwise attribution falls back to the chain.
- // A pending task that won the slot already covers this write; the
- // service logs that coalesce at debug.
- if _, err := h.TaskService.EnqueueTaskForIssueWithHandoff(ctx, issue, handoffNote, memberActorUserID(actorType, actorID)); err != nil && !errors.Is(err, service.ErrDuplicatePendingTask) {
- slog.Warn("issue write: run enqueue failed",
- "issue_id", uuidToString(issue.ID),
- "agent_id", uuidToString(issue.AssigneeID),
- "error", err,
- )
+ _, err := h.TaskService.EnqueueTaskForIssueWithHandoff(ctx, issue, handoffNote, memberActorUserID(actorType, actorID))
+ if err == nil {
+ return DispatchQueued, ReasonQueued
}
+ return issueEnqueueFailure(issue, issue.AssigneeID, err)
case "squad":
- h.enqueueSquadLeaderTask(ctx, issue, actorType, actorID, handoffNote, trigger.WorkflowHandoff)
+ return h.enqueueSquadLeaderTask(ctx, issue, actorType, actorID, handoffNote, trigger.WorkflowHandoff)
+ }
+ return DispatchBlocked, ReasonTargetUnavailable
+}
+
+// issueEnqueueFailure types an enqueue error on the issue write path. A
+// pending task that won the slot already covers the write; the service logs
+// that coalesce at debug. Anything else is logged here.
+func issueEnqueueFailure(issue db.Issue, agentID pgtype.UUID, err error) (DispatchStatus, DispatchReasonCode) {
+ if errors.Is(err, service.ErrDuplicatePendingTask) {
+ return DispatchCoalesced, ReasonCoalesced
+ }
+ log := slog.Default()
+ if issue.AssigneeType.String == "squad" {
+ log = log.With("squad_id", uuidToString(issue.AssigneeID))
+ }
+ log.Warn("issue write: run enqueue failed",
+ "issue_id", uuidToString(issue.ID),
+ "agent_id", uuidToString(agentID),
+ "error", err,
+ )
+ if errors.Is(err, service.ErrIssueInTriage) {
+ return DispatchBlocked, ReasonIssueInTriage
}
+ return DispatchBlocked, commentEnqueueFailureReason(err)
}
// memberActorUserID returns the acting member's user id as a pgtype.UUID when the
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index 1194d21917..1fda43d0ca 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -1230,14 +1230,14 @@ func commentMentionsAnyone(content string) bool {
// to a squad. Assign and backlog-promotion paths use this directly; comment
// paths go through computeCommentAgentTriggers so preview and create share the
// same trigger set.
-// It returns true only when a leader task was actually enqueued.
-func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, authorType, authorID, handoffNote string, workflowHandoff bool) bool {
+// It reports whether a leader task was enqueued and, if not, why.
+func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, authorType, authorID, handoffNote string, workflowHandoff bool) (DispatchStatus, DispatchReasonCode) {
squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{
ID: issue.AssigneeID,
WorkspaceID: issue.WorkspaceID,
})
if err != nil {
- return false
+ return DispatchBlocked, ReasonTargetUnavailable
}
// The gate must judge the SAME top-of-chain human the enqueue path will
@@ -1257,7 +1257,7 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, au
leaderOriginator = uuidToString(h.TaskService.OriginatorForIssueTask(ctx, issue, pgtype.UUID{}))
}
if !h.canEnqueueSquadLeader(ctx, squad.LeaderID, authorType, authorID, leaderOriginator, uuidToString(issue.WorkspaceID)) {
- return false
+ return DispatchBlocked, ReasonInvocationNotAllowed
}
if !workflowHandoff {
@@ -1267,8 +1267,17 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, au
// Key dedup on the reviewed head (TEN-356).
HeadSha: h.TaskService.ResolveIssueReviewSHAParam(ctx, issue.ID),
})
- if err != nil || hasPending {
- return false
+ if err != nil {
+ slog.WarnContext(ctx, "issue write: squad leader pending lookup failed",
+ "issue_id", uuidToString(issue.ID),
+ "squad_id", uuidToString(squad.ID),
+ "leader_id", uuidToString(squad.LeaderID),
+ "error", err,
+ )
+ return DispatchBlocked, ReasonInternalError
+ }
+ if hasPending {
+ return DispatchCoalesced, ReasonCoalesced
}
}
@@ -1281,12 +1290,7 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, au
_, err = h.TaskService.EnqueueTaskForSquadLeaderWithHandoff(ctx, issue, squad.LeaderID, squad.ID, handoffNote, memberActorUserID(authorType, authorID))
}
if err != nil {
- slog.Warn("enqueue squad leader task failed",
- "issue_id", uuidToString(issue.ID),
- "squad_id", uuidToString(squad.ID),
- "leader_id", uuidToString(squad.LeaderID),
- "error", err)
- return false
+ return issueEnqueueFailure(issue, squad.LeaderID, err)
}
- return true
+ return DispatchQueued, ReasonQueued
}