Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7213: feat(server): Triage has no executor (#8373)
Bohan Jiang7ebe0bf58d99
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 3b2aac2349..84686d762f 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -308,6 +308,7 @@ var concurrentIndexCleanups = map[string]string{"474_dingtalk_bot_identity_workspace_index": "idx_dingtalk_bot_identity_workspace","480_instance_telemetry_state_singleton_index": "instance_telemetry_state_singleton_uidx","482_agent_task_queue_telemetry_started_index": "idx_agent_task_queue_telemetry_started",+ "484_issue_triage_state_index": "idx_issue_triage_state",}// concurrentDownIndexCleanups covers every migration whose down directiondiff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 968bd4061d..3b2dc8263a 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -224,8 +224,8 @@ var issueStatusCmd = &cobra.Command{"Built-in keys: backlog, todo, in_progress, in_review, done, blocked, cancelled.\n" +"A workspace may define custom statuses on top of these; their keys are shown in\n" +"Workspace Settings > Issue Statuses, and an unknown value errors with the full list.\n" +- "The key triage is reserved for issues waiting in Triage: it cannot be set here,\n" +- "and an issue in Triage keeps its status until it is accepted.",+ "The key triage is reserved and cannot be set: Triage is not a status, so an\n" ++ "issue enters and leaves it through Triage itself rather than a status write.",Args: exactArgs(2),RunE: runIssueStatus,}@@ -395,9 +395,9 @@ var issueSearchCmd = &cobra.Command{// validIssueStatuses are the 7 BUILT-IN status keys, present in every// workspace. Since MUL-6243 a workspace may define additional custom statuses,// so this is the list shown in help text and error messages, not the set of-// accepted values — see validateIssueStatus. The reserved `triage` key is-// left out on purpose: it is readable (`issue list --status triage`) but never-// a value a write may set.+// accepted values — see validateIssueStatus. The reserved `triage` key is left+// out on purpose: Triage is not a status an issue can hold, so it is never a+// value a write may set.var validIssueStatuses = []string{"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled",}diff --git a/server/cmd/server/delegated_subscriber_test.go b/server/cmd/server/delegated_subscriber_test.goindex 2fd5a83ba6..d582cfa740 100644--- a/server/cmd/server/delegated_subscriber_test.go+++ b/server/cmd/server/delegated_subscriber_test.go@@ -544,10 +544,6 @@ func TestIssueStatusIsHandoff(t *testing.T) {{"custom started is a review gate", custom("awaiting_response", issuestatus.CategoryStarted), true},{"custom done is terminal", custom("shipped", issuestatus.CategoryDone), true},{"custom closed is terminal", custom("wont_do", issuestatus.CategoryClosed), true},-- // Reserved intake key: its own category, and nobody is waiting on an- // issue that has not been accepted yet.- {"triage is not a handoff", issuestatus.Triage, false},}for _, tc := range cases {diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.goindex 2b38a2a2fa..a00f4ad825 100644--- a/server/cmd/server/notification_listeners.go+++ b/server/cmd/server/notification_listeners.go@@ -30,7 +30,6 @@ var statusLabels = map[string]string{"done": "Done","blocked": "Blocked","cancelled": "Cancelled",- "triage": "Triage",}// priorityLabels maps DB priority values to human-readable labels for notifications.@@ -111,8 +110,10 @@ var delegatedAlwaysNotifTypes = map[string]bool{// in_progress synonym now notifies where it did not — an accepted cost, since a// missed handoff strands the issue while a spare inbox row costs one dismissal.//-// Triage resolves to its own category and is not a handoff: intake nobody has-// accepted is not work anybody is waiting on.+// Triage never reaches this predicate: it is not a status but a column of its+// own (MUL-7213), so an entry waiting in Triage carries whatever status the+// triager has proposed and is answered on that. Suppressing notifications for+// Triage entries is a separate rule and belongs to MUL-7219.//// The error is preserved rather than swallowed so each caller can choose its// own failure direction; built-ins answer without touching the catalog, so onlydiff --git a/server/cmd/server/triage_session_test.go b/server/cmd/server/triage_session_test.gonew file mode 100644index 0000000000..75a9e3f817--- /dev/null+++ b/server/cmd/server/triage_session_test.go@@ -0,0 +1,231 @@+package main++import (+ "context"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Triage session isolation (MUL-7189 §5.6).+//+// A triage run and the execution run that follows accept share an+// (agent_id, issue_id) pair, which is the whole key GetLastTaskSession resumes+// on. Without the exclusion the first execution run would pick up the+// conversation in which the agent was still deciding whether the entry was+// worth keeping. From the execution side an accepted issue is a new issue, so+// it starts cold.++func insertTriageTask(t *testing.T, agentID, runtimeID, issueID, sessionID string) {+ t.Helper()+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, session_id, work_dir, context)+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 minute', now() - interval '1 minute', $4, '/tmp/triage', '{"type":"triage"}'::jsonb)+ `, agentID, runtimeID, issueID, sessionID); err != nil {+ t.Fatalf("insert triage task: %v", err)+ }+}++func lastTaskSession(t *testing.T, agentID, issueID string) (db.GetLastTaskSessionRow, error) {+ t.Helper()+ return db.New(testPool).GetLastTaskSession(context.Background(), db.GetLastTaskSessionParams{+ AgentID: pgtype.UUID{Bytes: parseUUIDBytes(agentID), Valid: true},+ IssueID: pgtype.UUID{Bytes: parseUUIDBytes(issueID), Valid: true},+ })+}++// The triage session is the newest one on the issue, so before the exclusion+// this lookup returned it.+func TestGetLastTaskSessionExcludesTriageRuns(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ issueID, agentID, runtimeID := setupRerunTestFixture(t)+ t.Cleanup(func() { cleanupRerunFixture(t, issueID) })++ insertTriageTask(t, agentID, runtimeID, issueID, "TRIAGE-SESSION")++ prior, err := lastTaskSession(t, agentID, issueID)+ requireSessionExcluded(t, prior.SessionID, err)+}++// An execution session next to a triage one is still resumable: the filter+// removes triage runs, not the issue.+func TestGetLastTaskSessionKeepsExecutionSessionBesideTriage(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ issueID, agentID, runtimeID := setupRerunTestFixture(t)+ t.Cleanup(func() { cleanupRerunFixture(t, issueID) })++ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, session_id, work_dir)+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '5 minutes', now() - interval '5 minutes', 'EXECUTION-SESSION', '/tmp/execution')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert execution task: %v", err)+ }+ insertTriageTask(t, agentID, runtimeID, issueID, "TRIAGE-SESSION")++ prior, err := lastTaskSession(t, agentID, issueID)+ if err != nil {+ t.Fatalf("GetLastTaskSession failed: %v", err)+ }+ if prior.SessionID.String != "EXECUTION-SESSION" {+ t.Fatalf("resumed session = %q, want EXECUTION-SESSION", prior.SessionID.String)+ }+}++// The three CTEs are excluded independently, so each needs its own proof that a+// triage run cannot reach through it and invalidate a healthy session.+func TestTriageRunsCannotInvalidateAnExecutionSession(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()++ // retired_sessions: a triage run retiring the execution session must not+ // remove it. Only a run that actually abandoned it may.+ t.Run("retired_sessions", func(t *testing.T) {+ issueID, agentID, runtimeID := setupRerunTestFixture(t)+ t.Cleanup(func() { cleanupRerunFixture(t, issueID) })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, session_id, work_dir)+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '5 minutes', now() - interval '5 minutes', 'EXECUTION-SESSION', '/tmp/execution')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert execution task: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, session_id, work_dir, retired_session_id, context)+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 minute', now() - interval '1 minute', 'TRIAGE-SESSION', '/tmp/triage', 'EXECUTION-SESSION', '{"type":"triage"}'::jsonb)+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert triage task: %v", err)+ }++ prior, err := lastTaskSession(t, agentID, issueID)+ if err != nil {+ t.Fatalf("GetLastTaskSession failed: %v", err)+ }+ if prior.SessionID.String != "EXECUTION-SESSION" {+ t.Fatalf("resumed session = %q, want EXECUTION-SESSION", prior.SessionID.String)+ }+ })++ // resume_overflow_at blocks by TIME, so a failed triage run would otherwise+ // blank every execution session that terminated before it.+ t.Run("resume_overflow_at", func(t *testing.T) {+ issueID, agentID, runtimeID := setupRerunTestFixture(t)+ t.Cleanup(func() { cleanupRerunFixture(t, issueID) })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, session_id, work_dir)+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '5 minutes', now() - interval '5 minutes', 'EXECUTION-SESSION', '/tmp/execution')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert execution task: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, work_dir, failure_reason, context)+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '1 minute', now() - interval '1 minute', '/tmp/triage', 'codex_resume_oversized', '{"type":"triage"}'::jsonb)+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert overflowed triage task: %v", err)+ }++ prior, err := lastTaskSession(t, agentID, issueID)+ if err != nil {+ t.Fatalf("GetLastTaskSession failed: %v", err)+ }+ if prior.SessionID.String != "EXECUTION-SESSION" {+ t.Fatalf("resumed session = %q, want EXECUTION-SESSION", prior.SessionID.String)+ }+ })++ // latest_per_session judges a session by its newest terminal row. A triage+ // run reusing an execution session id must not be that row.+ t.Run("latest_per_session", func(t *testing.T) {+ issueID, agentID, runtimeID := setupRerunTestFixture(t)+ t.Cleanup(func() { cleanupRerunFixture(t, issueID) })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, session_id, work_dir)+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '5 minutes', now() - interval '5 minutes', 'SHARED-SESSION', '/tmp/execution')+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert execution task: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, session_id, work_dir, failure_reason, context)+ VALUES ($1, $2, $3, 'failed', 0, now() - interval '1 minute', now() - interval '1 minute', 'SHARED-SESSION', '/tmp/triage', 'iteration_limit', '{"type":"triage"}'::jsonb)+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert poisoned triage task: %v", err)+ }++ prior, err := lastTaskSession(t, agentID, issueID)+ if err != nil {+ t.Fatalf("GetLastTaskSession failed: %v", err)+ }+ if prior.SessionID.String != "SHARED-SESSION" {+ t.Fatalf("resumed session = %q, want SHARED-SESSION", prior.SessionID.String)+ }+ })+}++// GetLatestTaskRolloutMissing only reports whether GetLastTaskSession fell+// back, so the two must exclude the same rows. A triage run is invisible to+// that lookup, and reporting one here would tell the first execution run after+// accept that it lost the previous turn's context — about a turn it was never+// entitled to (MUL-7189 §5.6).+func TestGetLatestTaskRolloutMissingIgnoresTriageRuns(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ issueID, agentID, runtimeID := setupRerunTestFixture(t)+ t.Cleanup(func() { cleanupRerunFixture(t, issueID) })++ rolloutMissing := func() bool {+ t.Helper()+ missing, err := db.New(testPool).GetLatestTaskRolloutMissing(ctx, db.GetLatestTaskRolloutMissingParams{+ AgentID: pgtype.UUID{Bytes: parseUUIDBytes(agentID), Valid: true},+ IssueID: pgtype.UUID{Bytes: parseUUIDBytes(issueID), Valid: true},+ })+ if err != nil {+ t.Fatalf("GetLatestTaskRolloutMissing failed: %v", err)+ }+ return missing+ }++ // An ordinary execution run that carried its context over cleanly.+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, session_id, work_dir, session_rollout_missing)+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '5 minutes', now() - interval '5 minutes', 'EXECUTION-SESSION', '/tmp/execution', FALSE)+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert execution task: %v", err)+ }+ if rolloutMissing() {+ t.Fatal("a clean execution run already reports a continuity gap, so the triage case below proves nothing")+ }++ // A newer triage run whose rollout was missing. Before the exclusion this+ // became the most-recent row and flipped the disclosure to true.+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, work_dir, session_rollout_missing, context)+ VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 minute', now() - interval '1 minute', '/tmp/triage', TRUE, '{"type":"triage"}'::jsonb)+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert triage task: %v", err)+ }+ if rolloutMissing() {+ t.Error("a triage run reported a continuity gap to the execution run after accept")+ }++ // The signal still works for an execution run that really did lose one.+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at, work_dir, session_rollout_missing)+ VALUES ($1, $2, $3, 'completed', 0, now(), now(), '/tmp/execution', TRUE)+ `, agentID, runtimeID, issueID); err != nil {+ t.Fatalf("insert rollout-missing execution task: %v", err)+ }+ if !rolloutMissing() {+ t.Error("the exclusion also silenced a real execution-side continuity gap")+ }+}diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.goindex aa4dd4d447..e1e7d7f9df 100644--- a/server/internal/dispatch/reason.go+++ b/server/internal/dispatch/reason.go@@ -70,6 +70,18 @@ const (// success: nothing new runs. (Named to avoid implying the NEW comment was// already processed.)ReasonSelfTriggerSuppressed ReasonCode = "self_trigger_suppressed"+ // ReasonIssueInTriage: the issue is waiting in Triage, which has no executor+ // to act on (MUL-7189 §2.3). Returned when a trigger would have had to+ // derive one from the issue — running its assignee again, or asking it to+ // perform an action. An @mention is not refused: naming an agent by hand is+ // a conversation, and it dispatches normally.+ //+ // It is a property of the ISSUE, not of the target, so it is+ // enumeration-safe by construction: every target on the same issue gets the+ // same code, and the caller already sees the issue. Nothing is queued and+ // nothing is pending — the trigger is answered by accepting the issue out of+ // Triage, not by waiting.+ ReasonIssueInTriage ReasonCode = "issue_in_triage"// ReasonQuotaExceeded is a policy-neutral refusal for an exhausted// Cloud-provided autopilot interval.ReasonQuotaExceeded ReasonCode = "quota_exceeded"diff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.goindex b1f17e645a..be6437bd56 100644--- a/server/internal/handler/admission.go+++ b/server/internal/handler/admission.go@@ -62,6 +62,7 @@ const (ReasonAttributionBlocked = dispatch.ReasonAttributionBlockedReasonAlreadyActive = dispatch.ReasonAlreadyActiveReasonSelfTriggerSuppressed = dispatch.ReasonSelfTriggerSuppressed+ ReasonIssueInTriage = dispatch.ReasonIssueInTriageReasonInternalError = dispatch.ReasonInternalError)@@ -128,6 +129,8 @@ func dispatchBlockedFallbackMessage(code DispatchReasonCode) string {return "the run couldn't be attributed to a responsible member"case ReasonAlreadyActive:return "a run is already active for this target"+ case ReasonIssueInTriage:+ return "the issue is in Triage and has no owner to run yet; accept it out of Triage first"default:return "the run was blocked"}diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 49a0723cb9..8fd754087a 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -2588,7 +2588,7 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issuswitch trigger.Source {case commentTriggerSourceIssueAssignee:if trigger.Squad != nil {- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID, service.OriginDerived); err != nil {logCommentEnqueueFailure("enqueue squad leader task failed", err,"issue_id", uuidToString(issue.ID),"squad_id", uuidToString(trigger.Squad.ID),@@ -2608,14 +2608,14 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issureturn err}case commentTriggerSourceMentionSquadLeader:- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID, service.OriginNamed); err != nil {logCommentEnqueueFailure("enqueue squad leader mention task failed", err,"issue_id", uuidToString(issue.ID),"agent_id", uuidToString(trigger.Agent.ID))return err}case commentTriggerSourceMentionAgent:- if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, trigger.Agent.ID, triggerCommentID); err != nil {+ if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, trigger.Agent.ID, triggerCommentID, service.OriginNamed); err != nil {logCommentEnqueueFailure("enqueue mention agent task failed", err,"issue_id", uuidToString(issue.ID),"agent_id", uuidToString(trigger.Agent.ID))@@ -2629,7 +2629,7 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu// for the thread-parent path. Gating on the source as well would keep// the thread-parent path demoted for no reason (MUL-7006).if trigger.Squad != nil {- _, err = h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID)+ _, err = h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID, service.OriginNamed)} else {_, err = h.TaskService.EnqueueTaskForThreadParent(ctx, issue, trigger.Agent.ID, triggerCommentID)}@@ -2964,6 +2964,17 @@ func (h *Handler) routeAssigneeFallback(ctx context.Context, issue db.Issue, autif !issue.AssigneeType.Valid || !issue.AssigneeID.Valid {return commentAgentTrigger{}, false}+ // In Triage the assignee is a proposal the triager is still making, not an+ // owner, so there is nobody to fall back TO (MUL-7189 §2.3). This route and+ // the squad-leader one below are the two that derive an executor from the+ // issue; a comment naming an agent by hand is routed above and still runs.+ //+ // The queue door refuses these anyway. Stopping here is what keeps the+ // server from attempting an enqueue it already knows will be refused, and+ // logging a failure for every comment on a Triage entry.+ if issue.TriageState.Valid {+ return commentAgentTrigger{}, false+ }switch issue.AssigneeType.String {case "agent":agent, hasPending, ok := h.assigneeFallbackAgent(ctx, issue, authorType, authorID, opts)@@ -2979,6 +2990,11 @@ func (h *Handler) routeAssigneeFallback(ctx context.Context, issue db.Issue, aut}func (h *Handler) routeAssignedSquadLeaderFallback(ctx context.Context, issue db.Issue, authorType, authorID string, opts commentTriggerComputeOptions) (commentAgentTrigger, bool) {+ // Checked here as well as in routeAssigneeFallback: an agent-authored+ // comment reaches this one directly, without passing through that caller.+ if issue.TriageState.Valid {+ return commentAgentTrigger{}, false+ }squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: issue.AssigneeID,WorkspaceID: issue.WorkspaceID,diff --git a/server/internal/handler/comment_duplicate_enqueue_race_test.go b/server/internal/handler/comment_duplicate_enqueue_race_test.goindex 6e93f9fa37..5095a4b02d 100644--- a/server/internal/handler/comment_duplicate_enqueue_race_test.go+++ b/server/internal/handler/comment_duplicate_enqueue_race_test.go@@ -10,6 +10,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service""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"@@ -98,7 +99,7 @@ func TestCommentEnqueueRaceQueuedWinnerFoldsLoser(t *testing.T) {issueNumber: 999311,source: commentTriggerSourceMentionAgent,enqueueWinner: func(ctx context.Context, issue db.Issue, agentID, commentID pgtype.UUID) error {- _, err := testHandler.TaskService.EnqueueTaskForMention(ctx, issue, agentID, commentID)+ _, err := testHandler.TaskService.EnqueueTaskForMention(ctx, issue, agentID, commentID, service.OriginNamed)return err},},@@ -437,7 +438,7 @@ func TestCommentEnqueueRaceQueuedWinnerReattributesOriginator(t *testing.T) {// Winner: a queued task attributed to M1 (testUserID) via its own comment.winnerCommentID := insertDupRaceComment(t, issueID, "M1 instruction", "6 minutes")- if _, err := testHandler.TaskService.EnqueueTaskForMention(ctx, issue, agentUUID, util.MustParseUUID(winnerCommentID)); err != nil {+ if _, err := testHandler.TaskService.EnqueueTaskForMention(ctx, issue, agentUUID, util.MustParseUUID(winnerCommentID), service.OriginNamed); err != nil {t.Fatalf("enqueue winning task: %v", err)}// Losing comment authored by M2 in the same thread.diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 479f0f27a6..79cb9a3545 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -2150,6 +2150,15 @@ func rerunSourceMatchesTaskScope(task, source db.AgentTaskQueue) bool {if task.AgentID != source.AgentID {return false}+ // A triage run is never a source to continue from (MUL-7189 §5.6). The+ // exclusion GetLastTaskSession applies cannot reach this branch, which+ // resolves the session from the task the user named rather than from the+ // (agent, issue) lookup. RerunIssue already refuses a triage source, so this+ // is the second lock on the same door — and the one that still holds for a+ // row written by an older server mid rolling-deploy.+ if service.IsTriageTask(source) {+ return false+ }if task.IssueID.Valid {return source.IssueID.Valid && task.IssueID == source.IssueID}@@ -5559,9 +5568,12 @@ type batchIssueGCCheckItem struct {// status onto a built-in key here grants it no built-in behavior anywhere else.//// A status with no lifecycle category — an unresolvable key after a failed-// catalog read or a status created since the resolver's snapshot, and Triage,-// which is deliberately outside the four — is returned raw with no category, so-// every daemon fails closed and reclaims artifacts only. (MUL-7364)+// catalog read, or a status created since the resolver's snapshot — is returned+// raw with no category, so every daemon fails closed and reclaims artifacts+// only. (MUL-7364)+//+// Triage does not reach this: it is not a status, and a Triage entry carries an+// ordinary non-terminal one, which already reclaims artifacts only.func issueGCWire(status, category string) (wireStatus, wireCategory string) {if !issuestatus.IsCategory(category) {return status, ""diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex fde2b8d97f..85f5a29566 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -1921,7 +1921,7 @@ func (h *Handler) lookupIssueByIdentifier(ctx context.Context, workspaceID pgtypfunc (h *Handler) advanceIssueToDone(ctx context.Context, issue db.Issue, workspaceID string) {// An issue leaves Triage only by being accepted; a merged "Closes" PR// links to it but must not move it out. (MUL-7189 §2.2)- if issue.Status == issuestatus.Triage {+ if issue.TriageState.Valid {return}updated, err := h.Queries.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex bd020e62b2..7c0a685dbb 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -3459,8 +3459,8 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {var rawFields map[string]json.RawMessagejson.Unmarshal(bodyBytes, &rawFields)- if prevIssue.Status == issuestatus.Triage {- if field := triageLockedField(req.Status != nil, rawFields); field != "" {+ if prevIssue.TriageState.Valid {+ if field := triageLockedField(rawFields); field != "" {writeIssueInTriage(w, field)return}@@ -3890,7 +3890,9 @@ func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, wor// UpdateIssue.func (h *Handler) shouldEnqueueAgentTask(ctx context.Context, issue db.Issue) bool {// Only the fixed backlog key parks work; custom unstarted statuses do not.- if issuestatus.Effective(ctx, h.Queries, issue.WorkspaceID, issue.Status) == "backlog" {+ // An issue in Triage is not parked but refused: it produces no run from any+ // entry point until it is accepted (MUL-7189 §2.3).+ if issue.TriageState.Valid || issuestatus.Effective(ctx, h.Queries, issue.WorkspaceID, issue.Status) == "backlog" {return false}return h.isAgentAssigneeReady(ctx, issue)@@ -4212,7 +4214,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {return}}- if !h.validateBatchTriageLocks(w, r, wsUUID, req.IssueIDs, req.Updates.Status != nil, rawUpdates) {+ if !h.validateBatchTriageLocks(w, r, wsUUID, req.IssueIDs, rawUpdates) {return}// The batch shares one project_id, so it is checked once here rather thandiff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.goindex 90e6dc5d97..677c0de4d7 100644--- a/server/internal/handler/issue_child_done.go+++ b/server/internal/handler/issue_child_done.go@@ -10,6 +10,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/dbid""github.com/multica-ai/multica/server/pkg/protocol"@@ -755,7 +756,7 @@ func (h *Handler) triggerChildDoneAgent(ctx context.Context, parent db.Issue, trreturn}- if _, err := h.TaskService.EnqueueTaskForMention(ctx, parent, parent.AssigneeID, triggerCommentID); err != nil {+ if _, err := h.TaskService.EnqueueTaskForMention(ctx, parent, parent.AssigneeID, triggerCommentID, service.OriginDerived); err != nil {slog.Warn("child done: enqueue parent agent task failed","error", err,"parent_id", uuidToString(parent.ID),@@ -812,7 +813,7 @@ func (h *Handler) triggerChildDoneSquad(ctx context.Context, parent db.Issue, trreturn}- if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, parent, squad.LeaderID, squad.ID, triggerCommentID); err != nil {+ if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, parent, squad.LeaderID, squad.ID, triggerCommentID, service.OriginDerived); err != nil {slog.Warn("child done: enqueue parent squad leader task failed","error", err,"parent_id", uuidToString(parent.ID),diff --git a/server/internal/handler/issue_table_group.go b/server/internal/handler/issue_table_group.goindex 94bf3db008..4a244060c6 100644--- a/server/internal/handler/issue_table_group.go+++ b/server/internal/handler/issue_table_group.go@@ -115,10 +115,9 @@ func statusValueCategoryExpr(valueExpr string, customKeys map[string]string, addreturn b.String()}-// statusOrderExpression ranks a category in board order. Triage, which has no-// board column, sorts ahead of Unstarted: it is work nobody has taken on yet.+// statusOrderExpression ranks a category in board order.func statusOrderExpression(categoryExpr string) string {- return "CASE " + categoryExpr + " WHEN 'triage' THEN -1 WHEN 'unstarted' THEN 0 WHEN 'started' THEN 1 WHEN 'done' THEN 2 WHEN 'closed' THEN 3 ELSE 4 END"+ return "CASE " + categoryExpr + " WHEN 'unstarted' THEN 0 WHEN 'started' THEN 1 WHEN 'done' THEN 2 WHEN 'closed' THEN 3 ELSE 4 END"}// resolveStatusCategoryMaps derives BOTH shapes a category grouping needs fromdiff --git a/server/internal/handler/issue_triage_guard.go b/server/internal/handler/issue_triage_guard.goindex d3dc2bd68d..2b0787fdae 100644--- a/server/internal/handler/issue_triage_guard.go+++ b/server/internal/handler/issue_triage_guard.go@@ -6,61 +6,59 @@ import ("net/http""github.com/jackc/pgx/v5/pgtype"- "github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/logger""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")-// Write protection for the reserved Triage status (MUL-7189 §2.2).+// Write protection for a Triage entry (MUL-7189 §2.1, §2.2).//-// An issue enters Triage only through Triage intake and leaves it only by being-// accepted, so ordinary issue writes are held to two rules:+// Triage is not a status — it lives in issue.triage_state — so status, project,+// assignee, priority and labels on a Triage entry are the triager's PROPOSAL,+// and accept is what confirms them. Ordinary writes reach all of those.//-// - no write may name `triage` as its target status. issuestatus.Resolve-// refuses the key, and resolveIssueStatusKeyKind renders that refusal, so-// every create, update and batch path is covered by the one resolver;-// - an issue in Triage keeps its status, project and parent. Those are what-// accept decides, so writing them here would bypass it. Assignee, priority,-// labels and content stay editable.+// The parent is not a proposal, and is the one field held back. Two reasons,+// and the second is behavior rather than display://-// A field counts as written when the request carries it, even with the value-// the issue already has. The rule stays one a client can predict — "these-// fields are read-only in Triage" — instead of depending on the current value,-// and a client showing an issue in Triage has no reason to send them.+// - the routing panel has no parent field. "Merge into an existing issue" is+// a separate action that links rather than re-parents, so a Triage entry+// hanging off a parent is a half-state the product never asks for;+// - a child in Triage carries a proposed status, so it is never terminal.+// stageBarrierClosed would wait on it forever — holding the whole sibling+// set, or one stage's frontier — and ChildIssueProgress would count it in+// the denominator. Both read through parent_issue_id, so refusing the write+// is what keeps them out of reach.+//+// Carrying the field counts as writing it, even with the value already stored+// and even when null (which clears). The rule stays one a client can predict.-// triageLockedField returns the first Triage-locked field a write carries, or-// "" when it carries none. statusSet reports whether the request sets a status-// (a null status leaves it unchanged); project_id and parent_issue_id count-// when present at all, because null clears them.-func triageLockedField(statusSet bool, raw map[string]json.RawMessage) string {- if statusSet {- return "status"- }- for _, field := range []string{"project_id", "parent_issue_id"} {- if _, ok := raw[field]; ok {- return field- }+// triageLockedField returns the Triage-locked field a write carries, or "" when+// it carries none.+func triageLockedField(raw map[string]json.RawMessage) string {+ if _, ok := raw["parent_issue_id"]; ok {+ return "parent_issue_id"}return ""}-func writeStatusReservedForTriage(w http.ResponseWriter) {- writeErrorCode(w, http.StatusBadRequest, "status_reserved_for_triage",- `status "triage" is reserved: an issue enters Triage only through Triage intake and leaves it only by being accepted`)-}-func writeIssueInTriage(w http.ResponseWriter, field string) {writeErrorCode(w, http.StatusBadRequest, "issue_in_triage",- "the issue is in Triage, so its "+field+" cannot be changed; accept it out of Triage first")+ "the issue is in Triage, so its "+field+" cannot be set; accept it out of Triage first")}-// validateBatchTriageLocks rejects a batch that would write a Triage-locked-// field on any issue in Triage, before anything is written. A silent per-issue-// skip would report a short `{"updated": N}` with no reason attached, which is-// the same failure the batch status check rejects up front for.-func (h *Handler) validateBatchTriageLocks(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, issueIDs []string, statusSet bool, rawUpdates map[string]json.RawMessage) bool {- field := triageLockedField(statusSet, rawUpdates)+// writeStatusReservedForTriage renders issuestatus.Resolve's refusal of the+// reserved `triage` key. The catalog carries the same rule as a CHECK+// (migration 475), so no custom status can take the name either.+func writeStatusReservedForTriage(w http.ResponseWriter) {+ writeErrorCode(w, http.StatusBadRequest, "status_reserved_for_triage",+ `status "triage" is reserved: Triage is not a status, so no issue can be moved into or out of it by a status write`)+}++// validateBatchTriageLocks rejects a batch that would set a Triage-locked field+// on any issue in Triage, before anything is written. A silent per-issue skip+// would report a short `{"updated": N}` with no reason attached.+func (h *Handler) validateBatchTriageLocks(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, issueIDs []string, rawUpdates map[string]json.RawMessage) bool {+ field := triageLockedField(rawUpdates)if field == "" {return true}@@ -74,20 +72,18 @@ func (h *Handler) validateBatchTriageLocks(w http.ResponseWriter, r *http.Requesif len(ids) == 0 {return true}- rows, err := h.Queries.ListIssueGCStatuses(r.Context(), db.ListIssueGCStatusesParams{+ inTriage, err := h.Queries.CountIssuesInTriage(r.Context(), db.CountIssuesInTriageParams{WorkspaceID: workspaceID,IssueIds: ids,})if err != nil {- slog.Warn("batch update issues: load statuses for triage check", append(logger.RequestAttrs(r), "error", err)...)+ slog.Warn("batch update issues: count triage entries", append(logger.RequestAttrs(r), "error", err)...)writeError(w, http.StatusInternalServerError, "failed to validate issues")return false}- for _, row := range rows {- if row.Status == issuestatus.Triage {- writeIssueInTriage(w, field)- return false- }+ if inTriage > 0 {+ writeIssueInTriage(w, field)+ return false}return true}diff --git a/server/internal/handler/issue_triage_guard_test.go b/server/internal/handler/issue_triage_guard_test.goindex 6a0345b0c1..0485e321df 100644--- a/server/internal/handler/issue_triage_guard_test.go+++ b/server/internal/handler/issue_triage_guard_test.go@@ -6,21 +6,26 @@ import ("net/http""testing"+ "github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/testutil")-// Triage write protection (MUL-7212). A triage issue can only be made by-// Triage intake, which does not exist yet, so these tests insert one directly.+// The reserved `triage` status key (MUL-7212, narrowed by MUL-7213).+//+// Triage itself lives in issue.triage_state, so there is no "issue in Triage is+// read-only" rule left here — what remains is that no status may be named+// `triage`. A Triage entry can only be made by Triage intake, which does not+// exist yet, so these tests set the column directly.// The number comes from the workspace counter, not the fixture's MAX+1, so an// HTTP create later in the same test cannot be handed the same number.func triageIssueForTest(t *testing.T, title string) string {t.Helper()return dbfx.Issue(t, title, testutil.Cols{- "status": issuestatus.Triage,- "number": nextWorkspaceIssueNumber(t),+ "triage_state": "pending",+ "number": nextWorkspaceIssueNumber(t),})}@@ -31,6 +36,13 @@ func issueStatusOf(t *testing.T, issueID string) string {return status}+func triageStateOf(t *testing.T, issueID string) string {+ t.Helper()+ var state pgtype.Text+ dbfx.QueryRow(t, `SELECT triage_state FROM issue WHERE id = $1`, issueID).Scan(&state)+ return state.String+}+func wantErrorCode(t *testing.T, resp *testutil.Response, code string) {t.Helper()if got := resp.Want(http.StatusBadRequest).Map()["code"]; got != code {@@ -111,53 +123,71 @@ func TestCustomStatusCannotClaimTriage(t *testing.T) {}}-func TestIssueInTriageKeepsStatusProjectAndParent(t *testing.T) {+// Status, project and parent on a Triage entry are the triager's proposal, and+// accept is what confirms them — so ordinary writes reach them like any other+// issue. What no write can reach is the Triage marker itself: it is not a field+// of the issue API, so there is nothing to lock.+func TestIssueInTriageAcceptsOrdinaryFieldWrites(t *testing.T) {+ seedTestCatalog(t)issueID := triageIssueForTest(t, "waiting in triage")projectID := dbfx.Project(t, "triage target project")++ var resp IssueResponse+ testutil.Call(t, testHandler.UpdateIssue, withURLParam(+ newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{+ "status": "in_progress", "project_id": projectID, "priority": "high",+ }), "id", issueID)).Want(http.StatusOK).JSON(&resp)+ if resp.Status != "in_progress" || resp.Priority != "high" {+ t.Fatalf("proposal write = {status:%q priority:%q}, want it applied", resp.Status, resp.Priority)+ }+ // The write moved the proposal, not the entry: it is still in Triage.+ if got := triageStateOf(t, issueID); got != "pending" {+ t.Fatalf("triage_state after an ordinary write = %q, want pending", got)+ }+}++// The parent is the one field held back. A Triage child is never terminal, so+// it would wedge stageBarrierClosed and land in ChildIssueProgress's+// denominator — both reached through parent_issue_id, so the write is where it+// has to be stopped.+func TestIssueInTriageRefusesAParent(t *testing.T) {+ seedTestCatalog(t)+ issueID := triageIssueForTest(t, "must not become a child")parentID := dbfx.Issue(t, "triage target parent")update := func(body map[string]any) *testutil.Response {return testutil.Call(t, testHandler.UpdateIssue, withURLParam(newRequest(http.MethodPut, "/api/issues/"+issueID, body), "id", issueID))}-+ // Both directions count as writing it: null clears, which is equally a+ // parent decision the triager does not get to make.for name, body := range map[string]map[string]any{- "status": {"status": "todo"},- "status unchanged": {"status": "triage"},- "project": {"project_id": projectID},- "clear project": {"project_id": nil},- "parent": {"parent_issue_id": parentID},- "status and title": {"status": "done", "title": "sneaky"},+ "set": {"parent_issue_id": parentID},+ "clear": {"parent_issue_id": nil},+ "alongside a proposal": {"parent_issue_id": parentID, "priority": "high"},} {t.Run(name, func(t *testing.T) {wantErrorCode(t, update(body), "issue_in_triage")})}- var status, title string- var projectSet, parentSet bool- dbfx.QueryRow(t, `SELECT status, title, project_id IS NOT NULL, parent_issue_id IS NOT NULL FROM issue WHERE id = $1`, issueID).- Scan(&status, &title, &projectSet, &parentSet)- if status != issuestatus.Triage || title != "waiting in triage" || projectSet || parentSet {- t.Fatalf("refused writes changed the issue: status=%q title=%q project=%v parent=%v", status, title, projectSet, parentSet)- }-- // Everything accept does not decide stays editable.- var resp IssueResponse- update(map[string]any{"priority": "high", "title": "retitled in triage"}).Want(http.StatusOK).JSON(&resp)- if resp.Status != issuestatus.Triage || resp.Priority != "high" || resp.Title != "retitled in triage" {- t.Fatalf("allowed update = {status:%q priority:%q title:%q}", resp.Status, resp.Priority, resp.Title)+ var parentSet bool+ var priority string+ dbfx.QueryRow(t, `SELECT parent_issue_id IS NOT NULL, priority FROM issue WHERE id = $1`, issueID).Scan(&parentSet, &priority)+ if parentSet {+ t.Fatal("refused write still set a parent")}- // A reserved key is its own category, with no catalog read.- if resp.StatusCategory != issuestatus.Triage {- t.Errorf("status_category = %q, want triage", resp.StatusCategory)+ if priority == "high" {+ t.Fatal("refused write applied the proposal it was carrying alongside")}}-// A batch that would move an issue out of Triage is refused whole, before any-// write, rather than updating the rest and skipping it silently.-func TestBatchUpdateRefusesIssuesInTriage(t *testing.T) {+// The batch is refused whole, before any write, rather than updating the rest+// and skipping the Triage entry with a short count and no reason.+func TestBatchUpdateRefusesAParentForIssuesInTriage(t *testing.T) {+ seedTestCatalog(t)triageID := triageIssueForTest(t, "batch triage member")todoID := dbfx.Issue(t, "batch todo member")+ parentID := dbfx.Issue(t, "batch target parent")batch := func(updates map[string]any) *testutil.Response {return testutil.Call(t, testHandler.BatchUpdateIssues, newRequest(http.MethodPatch,@@ -167,12 +197,13 @@ func TestBatchUpdateRefusesIssuesInTriage(t *testing.T) {}))}- wantErrorCode(t, batch(map[string]any{"status": "done"}), "issue_in_triage")- wantErrorCode(t, batch(map[string]any{"project_id": nil}), "issue_in_triage")- if got := issueStatusOf(t, todoID); got != "todo" {- t.Errorf("refused batch still updated its other issue: status = %q", got)+ wantErrorCode(t, batch(map[string]any{"parent_issue_id": parentID}), "issue_in_triage")+ if n := dbfx.Count(t, `SELECT count(*) FROM issue WHERE id = $1 AND parent_issue_id IS NOT NULL`, todoID); n != 0 {+ t.Error("refused batch still re-parented its other issue")}+ // Everything else in a batch still reaches a Triage entry: the lock is one+ // field, not the whole row.var out struct {Updated int `json:"updated"`}@@ -180,8 +211,8 @@ func TestBatchUpdateRefusesIssuesInTriage(t *testing.T) {if out.Updated != 2 {t.Errorf("priority batch updated %d issue(s), want 2", out.Updated)}- if got := issueStatusOf(t, triageID); got != issuestatus.Triage {- t.Errorf("triage issue status after priority batch = %q, want triage", got)+ if got := triageStateOf(t, triageID); got != "pending" {+ t.Errorf("triage_state after priority batch = %q, want pending", got)}}@@ -204,19 +235,10 @@ func TestPullRequestMergeDoesNotAdvanceTriageIssue(t *testing.T) {t.Fatalf("load issue: %v", err)}testHandler.advanceIssueToDone(context.Background(), issue, testWorkspaceID)- if got := issueStatusOf(t, issueID); got != issuestatus.Triage {- t.Fatalf("status after merged PR = %q, want triage", got)- }-}--// Triage has no board column; in a status sort it leads, ahead of Backlog.-func TestStatusOrderRanksTriageFirst(t *testing.T) {- rank := func(status string) int {- var got int- dbfx.QueryRow(t, `SELECT `+statusOrderExpression("$1::text"), status).Scan(&got)- return got+ if got := issueStatusOf(t, issueID); got == "done" {+ t.Fatalf("merged PR moved a Triage entry to done")}- if triage, backlog := rank(issuestatus.Triage), rank(issuestatus.Backlog); triage >= backlog {- t.Fatalf("status rank triage=%d backlog=%d, want triage first", triage, backlog)+ if got := triageStateOf(t, issueID); got != "pending" {+ t.Fatalf("triage_state after merged PR = %q, want pending", got)}}diff --git a/server/internal/handler/issue_triage_no_run_test.go b/server/internal/handler/issue_triage_no_run_test.gonew file mode 100644index 0000000000..9b34959cc7--- /dev/null+++ b/server/internal/handler/issue_triage_no_run_test.go@@ -0,0 +1,576 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/dispatch"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Triage has no executor (MUL-7189 §2.3).+//+// Nothing may derive one from the issue — the assignee, its squad's leader, a+// retry. A member naming an agent by hand is a conversation, not an executor,+// and keeps working.+//+// Every entry point below runs TWICE against the same agent, squad and quick+// action: once on an ordinary `todo` issue, where all of them must start a run,+// and once in Triage, where only the named ones may. The todo half is not+// redundant — a private agent, an unbound runtime or a missing allow-list row+// also produce zero rows, and without a positive control the Triage half would+// pass on a fixture that could never have enqueued anything.++type triageRunFixture struct {+ agentID string+ squadID string+ leaderID string+ actionID string+ runtimeID string+}++// newTriageRunFixture builds targets a plain workspace member is allowed to+// invoke, so a blocked run is blocked by Triage and not by the permission gate.+func newTriageRunFixture(t *testing.T) triageRunFixture {+ t.Helper()+ runtimeID := dbfx.Runtime(t, "triage no-run runtime")+ invocable := func(name string) string {+ id := dbfx.Agent(t, name, runtimeID, testutil.Cols{+ "visibility": "workspace",+ "permission_mode": "public_to",+ })+ dbfx.InsertNoID(t, "agent_invocation_target", testutil.Cols{+ "agent_id": id, "target_type": "workspace", "target_id": testWorkspaceID,+ }, "agent_id = $1 AND target_type = 'workspace' AND target_id = $2", id, testWorkspaceID)+ return id+ }+ agentID := invocable("triage no-run agent")+ leaderID := invocable("triage no-run leader")+ squadID := dbfx.Squad(t, "triage no-run squad", leaderID)++ var actionID string+ dbfx.QueryRow(t, `+ INSERT INTO quick_action (+ workspace_id, name, description, assignee_type, assignee_id, prompt,+ visibility, created_by_type, created_by_id+ ) VALUES ($1, 'Triage No Run', '', 'agent', $2, 'take a look', 'public', 'member', $3)+ RETURNING id+ `, testWorkspaceID, agentID, testUserID).Scan(&actionID)+ dbfx.Cleanup(t, `DELETE FROM quick_action WHERE id = $1`, actionID)++ return triageRunFixture{agentID: agentID, squadID: squadID, leaderID: leaderID, actionID: actionID, runtimeID: runtimeID}+}++// issueFor creates an issue assigned to the fixture agent. triageState is the+// value of the column that puts it in Triage; "" is an ordinary issue.+//+// Both halves carry status `todo`, which is the point: Triage is no longer a+// status, so the two issues differ in exactly one field and nothing else can+// explain a difference in behavior between them.+func (f triageRunFixture) issueFor(t *testing.T, triageState, title string) string {+ t.Helper()+ cols := testutil.Cols{+ "status": "todo",+ "assignee_type": "agent",+ "assignee_id": f.agentID,+ "number": nextWorkspaceIssueNumber(t),+ }+ if triageState != "" {+ cols["triage_state"] = triageState+ }+ issueID := dbfx.Issue(t, title, cols)+ dbfx.Cleanup(t, `DELETE FROM comment WHERE issue_id = $1`, issueID)+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)+ return issueID+}++// triagePending is the only Triage state today.+const triagePending = "pending"++func tasksOn(t *testing.T, issueID string) int {+ t.Helper()+ return dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, issueID)+}++func commentsOn(t *testing.T, issueID string) int {+ t.Helper()+ return dbfx.Count(t, `SELECT count(*) FROM comment WHERE issue_id = $1`, issueID)+}++// triageEntryPoints are the request-driven ways an issue reaches a run. The run+// itself is counted from agent_task_queue, which is what the rule is about;+// runsInTriage records which side of the line the entry point falls on.+type triageEntryPoint struct {+ name string+ // runsInTriage is true when a member named the agent, false when the+ // executor was derived from the issue.+ runsInTriage bool+ call func(t *testing.T, f triageRunFixture, issueID string) *testutil.Response+}++func triageEntryPoints() []triageEntryPoint {+ comment := func(t *testing.T, issueID, content string) *testutil.Response {+ t.Helper()+ return testutil.Call(t, testHandler.CreateComment, withURLParam(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{"content": content}), "id", issueID))+ }+ return []triageEntryPoint{+ {"comment mentioning an agent", true, func(t *testing.T, f triageRunFixture, issueID string) *testutil.Response {+ return comment(t, issueID, "[@Agent](mention://agent/"+f.agentID+") please take a look")+ }},+ {"comment mentioning a squad", true, func(t *testing.T, f triageRunFixture, issueID string) *testutil.Response {+ return comment(t, issueID, "[@Squad](mention://squad/"+f.squadID+") please take a look")+ }},+ // A member replying to what the agent said is still that member naming+ // it — the thread is the address.+ {"reply to an agent's comment", true, func(t *testing.T, f triageRunFixture, issueID string) *testutil.Response {+ parentID := dbfx.Comment(t, issueID, "here is what I found", testutil.Cols{+ "author_type": "agent", "author_id": f.agentID,+ })+ return testutil.Call(t, testHandler.CreateComment, withURLParam(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{+ "content": "thanks, what about the other case?", "parent_id": parentID,+ }), "id", issueID))+ }},+ // No mention at all: the route is the issue's assignee, which in Triage+ // is only a proposal.+ {"plain comment routed to the assignee", false, func(t *testing.T, f triageRunFixture, issueID string) *testutil.Response {+ return comment(t, issueID, "any progress?")+ }},+ {"manual rerun", false, func(t *testing.T, f triageRunFixture, issueID string) *testutil.Response {+ return testutil.Call(t, testHandler.RerunIssue, withURLParam(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/rerun", nil), "id", issueID))+ }},+ // A quick action carries its own target, so the rule would let it+ // through; the first phase refuses it because it is an instruction to+ // DO the action rather than an invitation to talk.+ {"quick action", false, func(t *testing.T, f triageRunFixture, issueID string) *testutil.Response {+ return testutil.Call(t, testHandler.RunQuickAction, testutil.WithURLParams(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/quick-actions/"+f.actionID+"/run", nil),+ "id", issueID, "quickActionId", f.actionID))+ }},+ // Reassigning is allowed in Triage (accept has not decided the owner+ // yet), so it is the one issue write that still reaches the trigger.+ {"reassignment", false, func(t *testing.T, f triageRunFixture, issueID string) *testutil.Response {+ return testutil.Call(t, testHandler.UpdateIssue, withURLParam(+ newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{+ "assignee_type": "squad", "assignee_id": f.squadID,+ }), "id", issueID))+ }},+ }+}++// The control: on an ordinary issue this fixture really does start runs.+func TestTriageNoRunEntryPointsRunOnAnOrdinaryIssue(t *testing.T) {+ f := newTriageRunFixture(t)+ for _, entry := range triageEntryPoints() {+ t.Run(entry.name, func(t *testing.T) {+ issueID := f.issueFor(t, "", "ordinary issue: "+entry.name)+ entry.call(t, f, issueID).WantOneOf(http.StatusOK, http.StatusCreated, http.StatusAccepted)+ if n := tasksOn(t, issueID); n == 0 {+ t.Fatalf("%s started no run on a todo issue, so the triage half of this test proves nothing", entry.name)+ }+ })+ }+}++func TestTriageRunsOnlyWhatAMemberNamed(t *testing.T) {+ f := newTriageRunFixture(t)+ for _, entry := range triageEntryPoints() {+ t.Run(entry.name, func(t *testing.T) {+ issueID := f.issueFor(t, triagePending, "triage issue: "+entry.name)+ entry.call(t, f, issueID)+ n := tasksOn(t, issueID)+ if entry.runsInTriage && n == 0 {+ t.Fatalf("%s is a member naming an agent, but started no run in Triage", entry.name)+ }+ if !entry.runsInTriage && n != 0 {+ t.Fatalf("%s derives its executor from the issue, but started %d run(s) in Triage", entry.name, n)+ }+ })+ }+}++// The two entry points the caller is waiting on a response from are refused+// outright, rather than accepted and silently dropped at the queue door.+func TestTriageRefusesRerunAndQuickActionWithAReason(t *testing.T) {+ f := newTriageRunFixture(t)++ t.Run("rerun", func(t *testing.T) {+ issueID := f.issueFor(t, triagePending, "triage rerun")+ resp := testutil.Call(t, testHandler.RerunIssue, withURLParam(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/rerun", nil), "id", issueID))+ if got := resp.Want(http.StatusForbidden).Map()["reason_code"]; got != string(dispatch.ReasonIssueInTriage) {+ t.Fatalf("reason_code = %v, want issue_in_triage: %s", got, resp.Text())+ }+ })++ // A quick action is a comment AND a run. Refusing it after the comment was+ // written would leave a prompt addressed to nobody, so nothing is written.+ t.Run("quick action writes no comment", func(t *testing.T) {+ issueID := f.issueFor(t, triagePending, "triage quick action")+ resp := testutil.Call(t, testHandler.RunQuickAction, testutil.WithURLParams(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/quick-actions/"+f.actionID+"/run", nil),+ "id", issueID, "quickActionId", f.actionID))+ if got := resp.Want(http.StatusForbidden).Map()["reason_code"]; got != string(dispatch.ReasonIssueInTriage) {+ t.Fatalf("reason_code = %v, want issue_in_triage: %s", got, resp.Text())+ }+ if n := commentsOn(t, issueID); n != 0 {+ t.Fatalf("refused quick action left %d comment(s) on the issue", n)+ }+ })+}++// The mention that used to be refused. A member @-ing an agent on a Triage+// entry is a conversation, so it dispatches like anywhere else and reports a+// normal queued outcome — no issue_in_triage, no silent nothing.+func TestTriageCommentMentionDispatchesNormally(t *testing.T) {+ f := newTriageRunFixture(t)+ issueID := f.issueFor(t, triagePending, "triage mention outcomes")++ var body struct {+ TriggerOutcomes []struct {+ TargetType string `json:"target_type"`+ TargetID string `json:"target_id"`+ Status string `json:"status"`+ ReasonCode string `json:"reason_code"`+ } `json:"trigger_outcomes"`+ }+ testutil.Call(t, testHandler.CreateComment, withURLParam(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{+ "content": "[@Agent](mention://agent/" + f.agentID + ") and " ++ "[@Squad](mention://squad/" + f.squadID + ") please look",+ }), "id", issueID)).Want(http.StatusCreated).JSON(&body)++ if len(body.TriggerOutcomes) != 2 {+ t.Fatalf("got %d trigger outcome(s), want one per named target: %+v", len(body.TriggerOutcomes), body.TriggerOutcomes)+ }+ want := map[string]string{"agent": f.agentID, "squad": f.squadID}+ for _, o := range body.TriggerOutcomes {+ if o.Status != string(DispatchQueued) {+ t.Errorf("%s outcome = (%s, %s), want queued", o.TargetType, o.Status, o.ReasonCode)+ }+ if want[o.TargetType] != o.TargetID {+ t.Errorf("%s outcome names %q, want %q", o.TargetType, o.TargetID, want[o.TargetType])+ }+ delete(want, o.TargetType)+ }+ if len(want) != 0 {+ t.Errorf("no outcome for %v", want)+ }+ // Both targets are the leader-vs-agent pair, so this is two distinct runs.+ if n := tasksOn(t, issueID); n != 2 {+ t.Errorf("mentions started %d run(s), want 2", n)+ }+}++// The preview has to agree with the door. A preview promising a run that the+// enqueue then discards is worse than no preview: dispatchIssueRun drops the+// error, so nothing would ever report the difference.+func TestPreviewIssueTriggerReportsNoRunForTriage(t *testing.T) {+ f := newTriageRunFixture(t)+ issueID := f.issueFor(t, triagePending, "triage preview")++ // Reassigning inside Triage is allowed and would otherwise preview a run:+ // assignment is the one trigger source that never looked at status.+ reassign := map[string]any{+ "issue_ids": []string{issueID},+ "assignee_type": "agent",+ "assignee_id": f.leaderID,+ }+ if preview := previewIssueTrigger(t, reassign); preview.TotalCount != 0 {+ t.Errorf("triage reassign previews %+v, want no run", preview)+ }++ // Accept clears the column and the issue becomes ordinary work. The same+ // request now previews a run, which is what makes the zero above the+ // column's doing rather than the fixture's.+ dbfx.Exec(t, `UPDATE issue SET triage_state = NULL WHERE id = $1`, issueID)+ accepted := previewIssueTrigger(t, reassign)+ if accepted.TotalCount != 1 || len(accepted.Triggers) != 1 {+ t.Fatalf("accepted issue previews %+v, want exactly one run", accepted)+ }+ if accepted.Triggers[0].Source != "assign" || accepted.Triggers[0].AgentID != f.leaderID {+ t.Errorf("accepted preview = %+v, want the new assignee started by an assign", accepted.Triggers[0])+ }+}++// The queue door itself, on the enqueue entry points no HTTP request reaches.+// This is the check the whole rule rests on: dispatchIssueRun discards enqueue+// errors, so a path that slipped past every short-circuit above would fail+// silently rather than loudly.+//+// The same funnel is exercised from both sides, because the door does not judge+// the funnel — it judges what the caller says the run is. Passing nothing is+// OriginDerived, so a future enqueue path cannot leak into Triage by omission.+func TestEnqueueRefusesADerivedRunInTriage(t *testing.T) {+ ctx := context.Background()+ f := newTriageRunFixture(t)+ issueID := f.issueFor(t, triagePending, "triage queue door")+ issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueID))+ if err != nil {+ t.Fatal(err)+ }+ agent, squad := parseUUID(f.agentID), parseUUID(f.squadID)+ leader := parseUUID(f.leaderID)++ derived := map[string]func() error{+ "assignee": func() error {+ _, err := testHandler.TaskService.EnqueueTaskForIssue(ctx, issue)+ return err+ },+ "mention funnel, derived": func() error {+ _, err := testHandler.TaskService.EnqueueTaskForMention(ctx, issue, agent, pgtype.UUID{}, service.OriginDerived)+ return err+ },+ "squad leader, derived": func() error {+ _, err := testHandler.TaskService.EnqueueTaskForSquadLeader(ctx, issue, leader, squad, pgtype.UUID{}, service.OriginDerived)+ return err+ },+ "squad leader on assign": func() error {+ _, err := testHandler.TaskService.EnqueueTaskForSquadLeaderByActor(ctx, issue, leader, squad, pgtype.UUID{})+ return err+ },+ "rerun with no source": func() error {+ _, err := testHandler.TaskService.RerunIssue(ctx, issue.ID, pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, nil)+ return err+ },+ }+ for name, call := range derived {+ t.Run(name, func(t *testing.T) {+ if err := call(); !errors.Is(err, service.ErrIssueInTriage) {+ t.Fatalf("enqueue = %v, want ErrIssueInTriage", err)+ }+ })+ }+ if n := tasksOn(t, issueID); n != 0 {+ t.Fatalf("refused enqueues still wrote %d task row(s)", n)+ }++ // The other side of the same door, so the refusals above are the origin's+ // doing and not the funnel's.+ named := map[string]func() error{+ "mention funnel, named": func() error {+ _, err := testHandler.TaskService.EnqueueTaskForMention(ctx, issue, agent, pgtype.UUID{}, service.OriginNamed)+ return err+ },+ "thread parent": func() error {+ _, err := testHandler.TaskService.EnqueueTaskForThreadParent(ctx, issue, leader, pgtype.UUID{})+ return err+ },+ }+ for name, call := range named {+ t.Run(name, func(t *testing.T) {+ if err := call(); err != nil {+ t.Fatalf("named enqueue = %v, want it admitted", err)+ }+ })+ }+ if n := tasksOn(t, issueID); n != len(named) {+ t.Fatalf("named enqueues wrote %d task row(s), want %d", n, len(named))+ }+}++// Auto-retry is the one enqueue with no caller to refuse: the sweeper decides+// on its own. A failed run on an issue in Triage stays failed.+func TestAutoRetrySkipsAnIssueInTriage(t *testing.T) {+ ctx := context.Background()+ f := newTriageRunFixture(t)+ issueID := f.issueFor(t, triagePending, "triage auto retry")+ taskID := dbfx.Task(t, f.agentID, testutil.Cols{+ "runtime_id": f.runtimeID,+ "issue_id": issueID,+ "status": "failed",+ "failure_reason": "timeout",+ "attempt": 1,+ "max_attempts": 2,+ "started_at": testutil.Raw("now() - interval '2 minutes'"),+ "completed_at": testutil.Raw("now() - interval '1 minute'"),+ })+ parent, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ // Nothing about this task is itself unretryable — on a todo issue the same+ // row retries — so the skip below can only come from the issue's status.+ if !retryableOnItsOwn(parent) {+ t.Fatal("fixture task is not retryable on its own terms")+ }+ child, err := testHandler.TaskService.MaybeRetryFailedTask(ctx, parent)+ if err != nil {+ t.Fatalf("MaybeRetryFailedTask = %v, want no error", err)+ }+ if child != nil {+ t.Fatalf("auto-retry created task %s for an issue in Triage", uuidToString(child.ID))+ }+ if n := tasksOn(t, issueID); n != 1 {+ t.Fatalf("issue has %d task(s), want only the original failed one", n)+ }+}++// retryableOnItsOwn mirrors the budget/reason half of the retry decision so the+// test above can prove the skip came from Triage and not from an exhausted+// fixture. It deliberately does not call retryEligible, which is in another+// package and is itself part of what this change altered.+func retryableOnItsOwn(t db.AgentTaskQueue) bool {+ return t.Status == "failed" && t.FailureReason.String == "timeout" &&+ t.Attempt < t.MaxAttempts && t.IssueID.Valid && !t.AutopilotRunID.Valid+}++// A triage run must not outlive Triage as something to repeat (MUL-7189 §5.6).+//+// This is the one path that survives accept: once the issue is runnable again+// nothing above refuses it, and rerun resolves its session from the task the+// user named rather than from GetLastTaskSession — so the query-level exclusion+// cannot see it. It would also target the triager instead of the assignee.+func TestRerunRefusesAHistoricalTriageTaskAfterAccept(t *testing.T) {+ f := newTriageRunFixture(t)+ // Already accepted: the issue itself runs fine, which is what makes the+ // source task the only thing left to refuse.+ issueID := f.issueFor(t, "", "accepted out of triage")++ sourceTask := func(cols testutil.Cols) string {+ base := testutil.Cols{+ "runtime_id": f.runtimeID,+ "issue_id": issueID,+ "status": "completed",+ "session_id": "TRIAGE-SESSION",+ "work_dir": "/tmp/triage",+ "started_at": testutil.Raw("now() - interval '2 minutes'"),+ "completed_at": testutil.Raw("now() - interval '1 minute'"),+ }+ for k, v := range cols {+ base[k] = v+ }+ return dbfx.Task(t, f.agentID, base)+ }+ rerun := func(taskID string) *testutil.Response {+ return testutil.Call(t, testHandler.RerunIssue, withURLParam(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/rerun", map[string]any{"task_id": taskID}), "id", issueID))+ }++ // The control: an ordinary historical task on this issue reruns.+ before := tasksOn(t, issueID)+ rerun(sourceTask(nil)).Want(http.StatusAccepted)+ if got := tasksOn(t, issueID); got != before+2 {+ t.Fatalf("ordinary rerun left %d task(s), want the source plus a rerun", got-before)+ }++ triageID := sourceTask(testutil.Cols{"context": testutil.Raw(`'{"type":"triage"}'::jsonb`)})+ before = tasksOn(t, issueID)+ if body := rerun(triageID).Want(http.StatusBadRequest).Map()["error"]; body == nil {+ t.Fatal("refused triage rerun carried no error message")+ }+ if got := tasksOn(t, issueID); got != before {+ t.Fatalf("refused triage rerun created %d task(s)", got-before)+ }+}++// Rerun follows its source. Naming a discussion run repeats a conversation the+// member started, so it is allowed even while the issue sits in Triage; naming+// nothing means "run the assignee again", which is the derived executor Triage+// does not have (covered by the queue-door test above).+func TestRerunInTriageFollowsItsSource(t *testing.T) {+ f := newTriageRunFixture(t)+ issueID := f.issueFor(t, triagePending, "triage rerun by source")++ // A discussion run: what a member's @mention leaves behind on a Triage entry.+ discussionID := dbfx.Task(t, f.agentID, testutil.Cols{+ "runtime_id": f.runtimeID,+ "issue_id": issueID,+ "status": "completed",+ "started_at": testutil.Raw("now() - interval '2 minutes'"),+ "completed_at": testutil.Raw("now() - interval '1 minute'"),+ })+ before := tasksOn(t, issueID)+ testutil.Call(t, testHandler.RerunIssue, withURLParam(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/rerun", map[string]any{"task_id": discussionID}),+ "id", issueID)).Want(http.StatusAccepted)+ if got := tasksOn(t, issueID); got != before+1 {+ t.Fatalf("rerunning a discussion run added %d task(s), want 1", got-before)+ }++ // The triage run itself is still refused, with its own reason.+ triageID := dbfx.Task(t, f.agentID, testutil.Cols{+ "runtime_id": f.runtimeID,+ "issue_id": issueID,+ "status": "completed",+ "context": testutil.Raw(`'{"type":"triage"}'::jsonb`),+ "started_at": testutil.Raw("now() - interval '2 minutes'"),+ "completed_at": testutil.Raw("now() - interval '1 minute'"),+ })+ before = tasksOn(t, issueID)+ testutil.Call(t, testHandler.RerunIssue, withURLParam(+ newRequest(http.MethodPost, "/api/issues/"+issueID+"/rerun", map[string]any{"task_id": triageID}),+ "id", issueID)).Want(http.StatusBadRequest)+ if got := tasksOn(t, issueID); got != before {+ t.Fatalf("refused triage rerun created %d task(s)", got-before)+ }+}++// The claim-side half of the same rule. The service refuses first, so this+// guards a rerun row written by an older server during a rolling deploy — the+// one case where the refusal above was not in effect when the row was created.+func TestRerunSourceScopeRejectsATriageSource(t *testing.T) {+ agent := parseUUID(testUserID)+ issue := pgtype.UUID{Bytes: [16]byte{7}, Valid: true}+ task := db.AgentTaskQueue{AgentID: agent, IssueID: issue}+ ordinary := db.AgentTaskQueue{AgentID: agent, IssueID: issue}+ triage := db.AgentTaskQueue{AgentID: agent, IssueID: issue, Context: []byte(`{"type":"triage"}`)}++ if !rerunSourceMatchesTaskScope(task, ordinary) {+ t.Fatal("an ordinary same-issue source is in scope, so the triage case below proves nothing")+ }+ if rerunSourceMatchesTaskScope(task, triage) {+ t.Error("a triage source is in scope, so its session and workdir would be reused")+ }+}++// FailTask's in-transaction retry is the one enqueue that must refuse WITHOUT+// failing: the transaction also carries the parent's failed status, so aborting+// would leave the task stuck in 'running'.+func TestFailTaskRetryStartsNoRunForATriageIssue(t *testing.T) {+ ctx := context.Background()+ f := newTriageRunFixture(t)++ for _, tc := range []struct {+ name string+ triageState string+ wantChild bool+ wantOnFail string+ }{+ {"ordinary", "", true, "an ordinary issue retries, so the triage case below proves nothing"},+ {"triage", triagePending, false, "an issue in Triage was given a retry"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ issueID := f.issueFor(t, tc.triageState, "fail task retry: "+tc.name)+ taskID := dbfx.Task(t, f.agentID, testutil.Cols{+ "runtime_id": f.runtimeID,+ "issue_id": issueID,+ "status": "running",+ "attempt": 1,+ "max_attempts": 2,+ "started_at": testutil.Raw("now() - interval '1 minute'"),+ })+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(taskID), "runtime went away", "", "", "", "timeout", false, "", ""); err != nil {+ t.Fatalf("FailTask: %v", err)+ }+ // The parent must land failed either way. A guard that aborted the+ // transaction would leave it 'running' and the task stuck forever.+ var status string+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status)+ if status != "failed" {+ t.Fatalf("parent task status = %q, want failed", status)+ }+ children := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND id <> $2`, issueID, taskID)+ if (children > 0) != tc.wantChild {+ t.Fatalf("%s (children = %d)", tc.wantOnFail, children)+ }+ })+ }+}diff --git a/server/internal/handler/quick_action.go b/server/internal/handler/quick_action.goindex c1bca86326..7a664c309a 100644--- a/server/internal/handler/quick_action.go+++ b/server/internal/handler/quick_action.go@@ -868,6 +868,19 @@ func (h *Handler) RunQuickAction(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "quick action is archived")return}+ // A quick action carries its OWN configured target, so under the "derived vs+ // named" rule it could be let through. It is refused in the first phase for a+ // product reason rather than a rule one: it is an instruction to go and DO+ // the action, not an invitation to talk, and Triage is where nobody has+ // agreed the work should be done yet. Opening it later is deleting this if.+ //+ // Before the comment is written, not after: a quick action is a comment AND+ // a run, and posting the prompt to an entry that will never run it leaves an+ // instruction addressed to nobody (MUL-7189 §2.3).+ if issue.TriageState.Valid {+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonIssueInTriage)+ return+ }target := h.resolveQuickActionTarget(r.Context(), qa)if !target.Found {diff --git a/server/internal/handler/task_lifecycle.go b/server/internal/handler/task_lifecycle.goindex 03e4fbfbb9..500296d0c3 100644--- a/server/internal/handler/task_lifecycle.go+++ b/server/internal/handler/task_lifecycle.go@@ -213,6 +213,13 @@ func (h *Handler) RerunIssue(w http.ResponseWriter, r *http.Request) {h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)return}+ if errors.Is(err, service.ErrIssueInTriage) {+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonIssueInTriage)+ return+ }+ // Not a dispatch refusal: the issue may well be runnable, and only the named+ // source is ineligible. It falls through to the 400 below with the+ // sentinel's own sentence, like the sibling "does not belong to this issue".if err != nil {slog.Warn("issue rerun failed", "issue_id", id, "error", err)writeError(w, http.StatusBadRequest, err.Error())diff --git a/server/internal/issueguard/duplicate.go b/server/internal/issueguard/duplicate.goindex ee4b1ade93..b5e10ab1f0 100644--- a/server/internal/issueguard/duplicate.go+++ b/server/internal/issueguard/duplicate.go@@ -43,14 +43,17 @@ func NewActiveDuplicateError(issue db.Issue, issuePrefix string) *ActiveDuplicat}// inactiveStatusKeys are the status keys the duplicate guards never count as an-// active duplicate: the terminal categories, plus Triage. An issue waiting in-// Triage has not been taken on yet, so it must not block anyone filing the same-// work; a duplicate there is resolved by merging it from Triage.+// active duplicate: the terminal categories.+//+// A Triage entry is also never an active duplicate — it has not been taken on,+// so it must not block anyone filing the same work; a duplicate there is+// resolved by merging it out of Triage. That is not expressible here because+// Triage is not a status: the duplicate queries carry `triage_state IS NULL`+// instead (MUL-7189 §2.6).func inactiveStatusKeys(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID) ([]string, error) {return issuestatus.ExpandCategories(ctx, q, workspaceID, []string{issuestatus.CategoryDone,issuestatus.CategoryClosed,- issuestatus.Triage,})}diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.goindex 13c3d9c2b3..82af88228d 100644--- a/server/internal/issuestatus/issuestatus.go+++ b/server/internal/issuestatus/issuestatus.go@@ -9,8 +9,7 @@// lifecycle independently. WireCategory adapts response enums for installed// clients without persisting or granting legacy behavior.//-// One key sits outside the catalog and outside the four categories: Triage,-// reserved for issues waiting in Triage — see Triage.+// One key is reserved and belongs to no category: Triage — see Triage.package issuestatusimport (@@ -37,19 +36,17 @@ const (Cancelled = "cancelled")-// Triage is the RESERVED status key of an issue waiting in Triage (MUL-7189).+// Triage is a RESERVED status key, and nothing more (MUL-7189).//-// It is platform-owned like the 7 canonical keys — no workspace can mint a-// custom status with it — but it is deliberately not one of them: it has no-// catalog row, it is not one of the four lifecycle categories, and it is not a-// board column. An issue enters it only through Triage intake and leaves it-// only by being accepted, so no ordinary write may set it or move an issue out-// of it. It is its own category, which is what lets Category answer for it-// without a catalog read.+// Triage itself is NOT a status — an issue in Triage is marked by+// issue.triage_state, because "is this work at all" is a different question+// from "how far along is this work", and answering the first inside the second+// field makes every reader of status re-answer it.//-// Because no custom key can resolve to it, the SQL literal `status = 'triage'`-// is exactly equivalent to the Go-side check, and read paths can filter on the-// bare indexed column.+// What survives here is the name: no workspace may mint a custom status keyed+// `triage`, so the word means one thing. The catalog carries the same rule as a+// CHECK (migration 475), and Resolve refuses the key so a write is turned away+// by the resolver rather than by the database.const Triage = "triage"// The four stored lifecycle categories.@@ -100,8 +97,8 @@ var categoryRank = func() map[string]int {// catalog, or present but archived.var ErrUnknownStatus = errors.New("unknown issue status")-// ErrReservedStatus is returned by Resolve for Triage: the key is valid to-// read but never a target an ordinary write may set.+// ErrReservedStatus is returned by Resolve for Triage: the name is reserved, so+// no status write may name it.var ErrReservedStatus = errors.New("issue status is reserved for triage")// keyPattern mirrors the issue_status.key CHECK constraint. Keys are lowercase@@ -126,9 +123,7 @@ func Canonical() []string {}// IsBuiltIn reports whether key is platform-owned: one of the 7 canonical-// statuses or the reserved Triage key. Each is its own category, so callers-// can read the category off the key without a catalog lookup, and none can be-// reused as a custom key.+// statuses, or the reserved Triage name. None can be reused as a custom key.func IsBuiltIn(key string) bool {_, ok := canonicalRank[key]return ok || key == Triage@@ -168,10 +163,6 @@ func CategoryForBehavior(behavior string) (string, bool) {return CategoryDone, truecase Cancelled:return CategoryClosed, true- case Triage:- // Not one of the four stored categories: no catalog row may hold it,- // and the pair below keeps Triage answerable without a catalog read.- return Triage, truedefault:return "", false}@@ -189,23 +180,13 @@ func BehaviorsForCategory(category string) []string {return []string{Done}case CategoryClosed:return []string{Cancelled}- case Triage:- return []string{Triage}default:return nil}}// ParseCategory normalizes API spellings and pre-backfill stored categories.-//-// Triage is refused: CategoryForBehavior answers for it so a Triage issue can-// still be rendered and grouped, but it is not a category a caller may name —-// accepting it here would let `{key: "foo", category: "triage"}` reach the-// catalog, whose CHECK holds only the four stored categories.func ParseCategory(value string) (string, bool) {- if value == Triage {- return "", false- }if IsCategory(value) {return value, true}@@ -743,17 +724,10 @@ func (r *Resolver) Name(ctx context.Context, q Querier, status string) string {// category's column.//// An unseeded workspace yields no rows; the concrete built-in behavior keys are-// added explicitly so filtering remains complete. The reserved Triage key-// expands to exactly itself — no custom status can carry it.+// added explicitly so filtering remains complete.func ExpandCategories(ctx context.Context, q Querier, workspaceID pgtype.UUID, categories []string) ([]string, error) {behaviors := make([]string, 0, len(categories)*2)- triage := falsefor _, c := range categories {- if c == Triage {- // The reserved key owns no catalog row, so it expands to itself.- triage = true- continue- }if IsCategory(c) {behaviors = append(behaviors, c)continue@@ -766,9 +740,6 @@ func ExpandCategories(ctx context.Context, q Querier, workspaceID pgtype.UUID, c}}if len(behaviors) == 0 {- if triage {- return []string{Triage}, nil- }return nil, nil}seenBehaviors := make(map[string]bool, len(behaviors))@@ -804,9 +775,6 @@ func ExpandCategories(ctx context.Context, q Querier, workspaceID pgtype.UUID, c}}}- if triage {- out = append(out, Triage)- }return out, nil}diff --git a/server/internal/issuestatus/issuestatus_test.go b/server/internal/issuestatus/issuestatus_test.goindex ba3965bb99..67e1ebe2af 100644--- a/server/internal/issuestatus/issuestatus_test.go+++ b/server/internal/issuestatus/issuestatus_test.go@@ -19,7 +19,7 @@ func TestCategoryWithError(t *testing.T) {ctx := context.Background()q := newFakeQuerier()q.err = errors.New("catalog unavailable")- for _, status := range append(Canonical(), Triage) {+ for _, status := range Canonical() {want, _ := CategoryForBehavior(status)if got, err := CategoryWithError(ctx, q, testWorkspace, status); err != nil || got != want {t.Errorf("built-in %s: category=%q err=%v; want %q", status, got, err, want)@@ -280,43 +280,24 @@ func TestTriageIsReservedButNotACategory(t *testing.T) {// Triage resolves to itself on every read path without a catalog read, and is// never a write target. (MUL-7212)-func TestTriageResolvesWithoutTheCatalog(t *testing.T) {+func TestTriageIsAReservedNameNotAStatus(t *testing.T) {ctx := context.Background()q := newFakeQuerier(custom("human_review", InReview))- if got := Effective(ctx, q, testWorkspace, Triage); got != Triage {- t.Errorf("Effective(triage) = %q, want triage", got)+ // Triage is not a status an issue can hold, so nothing resolves it to a+ // category. What the name still does is refuse: no status write may take it+ // and no custom status may claim it.+ if got, ok := CategoryForBehavior(Triage); ok {+ t.Errorf("CategoryForBehavior(triage) = %q, %v; want refused — triage is not a category", got, ok)}- behavior, name := EffectiveAndName(ctx, q, testWorkspace, Triage)- if behavior != Triage || name != "" {- t.Errorf("EffectiveAndName(triage) = (%q, %q), want (triage, \"\") — clients localize it from the key", behavior, name)- }- // Triage is its own category, so the lifecycle question stays answerable- // for an issue whose status has no catalog row.- if got, ok := CategoryForBehavior(Triage); !ok || got != Triage {- t.Errorf("CategoryForBehavior(triage) = %q, %v; want triage, true", got, ok)- }- if got := Category(ctx, q, testWorkspace, Triage); got != Triage {- t.Errorf("Category(triage) = %q, want triage", got)- }- // ParseCategory is the input side: naming triage as a category must fail,- // or a custom status could declare it and land a row the catalog's CHECK- // rejects.if got, ok := ParseCategory(Triage); ok {t.Errorf("ParseCategory(triage) = %q, %v; want refused", got, ok)}- if got := WireCategory(Triage, Triage); got != Triage {- t.Errorf("WireCategory(triage) = %q, want triage", got)- }- r := NewResolver(testWorkspace)- if got := r.Effective(ctx, q, Triage); got != Triage {- t.Errorf("Resolver.Effective(triage) = %q, want triage", got)- }- if got := r.Category(ctx, q, Triage); got != Triage {- t.Errorf("Resolver.Category(triage) = %q, want triage", got)+ if IsCategory(Triage) {+ t.Error("IsCategory(triage) = true, want false")}- if got := r.Name(ctx, q, Triage); got != "" {- t.Errorf("Resolver.Name(triage) = %q, want empty", got)+ if !IsBuiltIn(Triage) {+ t.Error("IsBuiltIn(triage) = false; the name stays reserved against custom keys")}for _, input := range []string{Triage, " TRIAGE "} {if _, err := Resolve(ctx, q, testWorkspace, input); !errors.Is(err, ErrReservedStatus) {@@ -324,7 +305,7 @@ func TestTriageResolvesWithoutTheCatalog(t *testing.T) {}}if q.lookups != 0 || q.lists != 0 {- t.Errorf("triage resolution touched the catalog: %d lookup(s), %d list(s)", q.lookups, q.lists)+ t.Errorf("refusing triage touched the catalog: %d lookup(s), %d list(s)", q.lookups, q.lists)}// A key that merely starts with triage still needs a catalog row: the@@ -721,26 +702,24 @@ func TestExpandCategories(t *testing.T) {}})- t.Run("triage expands to exactly itself", func(t *testing.T) {- q := newFakeQuerier(custom("human_review", InReview))- got, err := ExpandCategories(ctx, q, testWorkspace, []string{Triage, Triage})+ // Triage is not a category, so naming it expands to nothing. Callers that+ // need Triage entries filter on issue.triage_state instead.+ t.Run("triage is not a category to expand", func(t *testing.T) {+ q := newFakeQuerier(custom("shipped", CategoryDone))+ got, err := ExpandCategories(ctx, q, testWorkspace, []string{Triage})if err != nil {t.Fatalf("expand: %v", err)}- if !slices.Equal(got, []string{Triage}) {- t.Errorf("expand(triage) = %v, want [triage] — no custom status can carry it", got)+ if got != nil {+ t.Errorf("expand(triage) = %v, want nil", got)}- })-- t.Run("triage rides along with real categories", func(t *testing.T) {- q := newFakeQuerier(custom("shipped", CategoryDone))- got, err := ExpandCategories(ctx, q, testWorkspace, []string{CategoryDone, CategoryClosed, Triage})+ alongside, err := ExpandCategories(ctx, q, testWorkspace, []string{CategoryDone, CategoryClosed, Triage})if err != nil {t.Fatalf("expand: %v", err)}- slices.Sort(got)- if want := []string{Cancelled, Done, "shipped", Triage}; !slices.Equal(got, want) {- t.Errorf("expand(done, closed, triage) = %v, want %v", got, want)+ slices.Sort(alongside)+ if want := []string{Cancelled, Done, "shipped"}; !slices.Equal(alongside, want) {+ t.Errorf("expand(done, closed, triage) = %v, want %v", alongside, want)}})}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 670e4a12e9..28e4b1a5e3 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -366,7 +366,7 @@ func (s *AutopilotService) ensureWebhookCreateIssueTask(ctx context.Context, autif err != nil {return fmt.Errorf("dispatch for webhook delivery: resolve squad leader: %w", err)}- if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, autopilot.AssigneeID, pgtype.UUID{}); err != nil {+ if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, autopilot.AssigneeID, pgtype.UUID{}, OriginDerived); err != nil {return fmt.Errorf("dispatch for webhook delivery: repair squad task: %w", err)}return nil@@ -849,7 +849,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopiif _, err := s.TaskSvc.EnqueueTaskForSquadLeaderByActor(ctx, issue, leader.ID, ap.AssigneeID, actorUserID); err != nil {return fmt.Errorf("enqueue squad leader task: %w", err)}- } else if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, ap.AssigneeID, pgtype.UUID{}); err != nil {+ } else if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, ap.AssigneeID, pgtype.UUID{}, OriginDerived); err != nil {return fmt.Errorf("enqueue squad leader task: %w", err)}} else if actorUserID.Valid {diff --git a/server/internal/service/delegated_failure_recovery_test.go b/server/internal/service/delegated_failure_recovery_test.goindex 2f608a43dd..ed8be23e78 100644--- a/server/internal/service/delegated_failure_recovery_test.go+++ b/server/internal/service/delegated_failure_recovery_test.go@@ -94,7 +94,6 @@ func TestDelegatedFailureRecoveryStatusEligibility(t *testing.T) {{status: "blocked", allowed: true},{status: "done"},{status: "cancelled"},- {status: "triage"},{status: "missing_recovery_status", unresolved: true},{status: "custom_unstarted", category: "unstarted", allowed: true},{status: "custom_started", category: "started", allowed: true},@@ -1171,3 +1170,66 @@ func TestDelegatedFailureRecoveryTaskDoesNotRecursivelyWake(t *testing.T) {t.Fatalf("recursive recovery comments = %d, want 0", comments)}}++// A worker failure must not wake a coordinator whose issue is in Triage: that+// coordinator is the issue's own assignee, the derived executor Triage does not+// have (MUL-7189 §2.3).+//+// Both the pending-recovery query and canDispatchDelegatedFailureRecovery+// exclude a Triage source, which is why the sweep does not even scan the+// comment. This test is what keeps that true.+//+// The obligation is not discharged either: the comment stays in the outbox and+// dispatches once the issue is accepted.+func TestPendingDelegatedFailureSweepSkipsTriageSourceIssue(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)+ if _, err := f.pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET failure_reason = 'agent_error.process_failure', error = 'worker exited', completed_at = now()+ WHERE id = $1`, failedID); err != nil {+ t.Fatalf("stamp failed task: %v", err)+ }+ if target, created, err := svc.ensureDelegatedFailureRecoveryComment(ctx, failedID); err != nil || target == nil || !created {+ t.Fatalf("ensure recovery comment = target %v created %v err %v", target != nil, created, err)+ }++ recoveryTasks := func() int {+ t.Helper()+ var n int+ if err := f.pool.QueryRow(ctx, `+ SELECT count(*) FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1`, failedID).Scan(&n); err != nil {+ t.Fatalf("count recovery tasks: %v", err)+ }+ return n+ }++ if _, err := f.pool.Exec(ctx, `UPDATE issue SET triage_state = 'pending' WHERE id = $1`, f.issueID); err != nil {+ t.Fatalf("move source issue into triage: %v", err)+ }+ result, err := svc.RecoverPendingDelegatedFailures(ctx, 100)+ if err != nil {+ t.Fatalf("triage-source recovery sweep: %v", err)+ }+ if result != (DelegatedFailureRecoverySweepResult{}) {+ t.Fatalf("triage-source sweep = %+v, want nothing selected and nothing replayed", result)+ }+ if n := recoveryTasks(); n != 0 {+ t.Fatalf("recovery tasks = %d, want none while the source issue is in Triage", n)+ }++ // Accept clears the marker and the same pending comment wakes the+ // coordinator — which is what makes the zero above the column's doing and+ // not an inert fixture. The status never moved: only triage_state did.+ if _, err := f.pool.Exec(ctx, `UPDATE issue SET triage_state = NULL WHERE id = $1`, f.issueID); err != nil {+ t.Fatalf("accept source issue: %v", err)+ }+ if result, err := svc.RecoverPendingDelegatedFailures(ctx, 100); err != nil || result.Replayed != 1 {+ t.Fatalf("post-accept sweep = %+v, %v; want one replay", result, err)+ }+ if n := recoveryTasks(); n != 1 {+ t.Fatalf("recovery tasks after accept = %d, want 1", n)+ }+}diff --git a/server/internal/service/duplicate_pending_task_test.go b/server/internal/service/duplicate_pending_task_test.goindex 8af01914a5..31c2c2cf74 100644--- a/server/internal/service/duplicate_pending_task_test.go+++ b/server/internal/service/duplicate_pending_task_test.go@@ -72,12 +72,12 @@ func TestEnqueueTaskForMentionCoalescesDuplicatePendingTask(t *testing.T) {svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}// First mention creates the pending task.- if _, err := svc.EnqueueTaskForMention(ctx, issueStruct, util.MustParseUUID(agentID), pgtype.UUID{}); err != nil {+ if _, err := svc.EnqueueTaskForMention(ctx, issueStruct, util.MustParseUUID(agentID), pgtype.UUID{}, OriginNamed); err != nil {t.Fatalf("first EnqueueTaskForMention: %v", err)}// Second mention for the same (issue, agent) collides on the unique index.- _, err := svc.EnqueueTaskForMention(ctx, issueStruct, util.MustParseUUID(agentID), pgtype.UUID{})+ _, err := svc.EnqueueTaskForMention(ctx, issueStruct, util.MustParseUUID(agentID), pgtype.UUID{}, OriginNamed)if !errors.Is(err, ErrDuplicatePendingTask) {t.Fatalf("second EnqueueTaskForMention: err = %v, want ErrDuplicatePendingTask", err)}diff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex ce02e98989..f4f2033dec 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -739,7 +739,10 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,}// Backlog is the parking lot: nothing runs from it, so nothing here needs// explaining either. Custom unstarted statuses do not inherit parking.- if issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status) == "backlog" {+ //+ // Triage refuses for a different reason and so returns just as quietly: the+ // entry is not yet work anyone agreed to do (MUL-7189 §2.3).+ if issue.TriageState.Valid || issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status) == "backlog" {return pgtype.UUID{}}verdict, admitted := agentAssigneeVerdict(ctx, s.runtimeLookup(s.Queries), issue)@@ -785,7 +788,9 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,func (s *IssueService) shouldEnqueueAgentTaskWithQueries(ctx context.Context, q *db.Queries, issue db.Issue) bool {// Resolved through q, not s.Queries: this runs inside the create// transaction and must see the same snapshot as the rest of it. (MUL-6243)- if issuestatus.Effective(ctx, q, issue.WorkspaceID, issue.Status) == "backlog" {+ // That snapshot is also the only place a just-created Triage issue is+ // visible, which is why the Triage check belongs on the same read.+ if issue.TriageState.Valid || issuestatus.Effective(ctx, q, issue.WorkspaceID, issue.Status) == "backlog" {return false}return isAgentAssigneeReadyWithQueries(ctx, s.runtimeLookup(q), issue)@@ -818,7 +823,7 @@ func agentAssigneeVerdict(ctx context.Context, lookup RuntimeLookup, issue db.Is}func (s *IssueService) shouldEnqueueSquadLeaderOnAssign(ctx context.Context, issue db.Issue) bool {- if issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status) == "backlog" {+ if issue.TriageState.Valid || issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status) == "backlog" {return false}return s.isSquadLeaderReady(ctx, issue)@@ -863,7 +868,7 @@ func (s *IssueService) enqueueSquadLeaderTask(ctx context.Context, issue db.Issuif err != nil || hasPending {return}- if _, err := s.TaskService.EnqueueTaskForSquadLeader(ctx, issue, squad.LeaderID, squad.ID, triggerCommentID); err != nil {+ if _, err := s.TaskService.EnqueueTaskForSquadLeader(ctx, issue, squad.LeaderID, squad.ID, triggerCommentID, OriginDerived); err != nil {slog.Warn("enqueue squad leader task on create failed","issue_id", util.UUIDToString(issue.ID),"squad_id", util.UUIDToString(squad.ID),diff --git a/server/internal/service/issue_trigger.go b/server/internal/service/issue_trigger.goindex 40dc5bd75c..582c1af29d 100644--- a/server/internal/service/issue_trigger.go+++ b/server/internal/service/issue_trigger.go@@ -111,6 +111,18 @@ func (s *IssueService) WillEnqueueRun(ctx context.Context, in IssueTriggerInput,currentStatus := issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status)prevStatus := issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, in.PrevStatus)+ // Triage is stricter than the backlog parking lot: backlog defers a run,+ // Triage refuses one outright (MUL-7189 §2.3). Deciding it here is what+ // keeps the trigger PREVIEW honest — the queue door would refuse the insert+ // either way, but silently, and the preview would have promised a run.+ //+ // Leaving Triage needs no case of its own. Triage is not a status, so accept+ // clears this field and then takes the ordinary create / assign path; there+ // is no "was in triage" transition for this predicate to recognise.+ if issue.TriageState.Valid {+ return IssueRunTrigger{}, false+ }+var source RunEnqueueSourceswitch {case in.IsCreate || in.AssigneeChanged:diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 0dc03c40f3..6e3a7bc20a 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1123,7 +1123,7 @@ func (s *TaskService) EnqueueTaskForIssue(ctx context.Context, issue db.Issue, tif len(triggerCommentID) > 0 {commentID = triggerCommentID[0]}- return s.enqueueIssueTask(ctx, issue, commentID, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{})+ return s.enqueueIssueTask(ctx, issue, commentID, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{}, OriginDerived)}// EnqueueDeferredChannelIssueTask persists the assigned task for a media-backed@@ -1131,7 +1131,7 @@ func (s *TaskService) EnqueueTaskForIssue(ctx context.Context, issue db.Issue, t// crash-safe fallback; the channel router promotes the task as soon as the// detached attachment transaction settles.func (s *TaskService) EnqueueDeferredChannelIssueTask(ctx context.Context, issue db.Issue, fireAt time.Time) (db.AgentTaskQueue, error) {- task, err := s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{Time: fireAt, Valid: true})+ task, err := s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{Time: fireAt, Valid: true}, OriginDerived)if err != nil {return db.AgentTaskQueue{}, err}@@ -1149,7 +1149,7 @@ func (s *TaskService) EnqueueDeferredChannelIssueTask(ctx context.Context, issue// commit without holding database locks across a network call.func (s *TaskService) createDeferredChannelIssueTaskWithQueries(ctx context.Context, q *db.Queries, issue db.Issue, fireAt time.Time) (db.AgentTaskQueue, error) {txService := &TaskService{Queries: q}- return txService.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{Time: fireAt, Valid: true})+ return txService.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{Time: fireAt, Valid: true}, OriginDerived)}// hydrateDeferredChannelIssueTaskOverlay fills the optional Composio overlay@@ -1189,7 +1189,7 @@ func (s *TaskService) hydrateDeferredChannelIssueTaskOverlay(ctx context.Context// assign/promote and becomes the accountable human for the run (MUL-4302 §4);// invalid when the caller has no member actor.func (s *TaskService) EnqueueTaskForIssueByActor(ctx context.Context, issue db.Issue, actorUserID pgtype.UUID) (db.AgentTaskQueue, error) {- return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, "", actorUserID, pgtype.UUID{}, pgtype.Timestamptz{})+ return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, "", actorUserID, pgtype.UUID{}, pgtype.Timestamptz{}, OriginDerived)}// EnqueueTaskForIssueWithHandoff is the backward-compatible assign/promote@@ -1197,7 +1197,7 @@ func (s *TaskService) EnqueueTaskForIssueByActor(ctx context.Context, issue db.I// persisted on the task so both old and current daemons can render it in the// run's opening prompt. Empty text behaves like EnqueueTaskForIssueByActor.func (s *TaskService) EnqueueTaskForIssueWithHandoff(ctx context.Context, issue db.Issue, handoffNote string, actorUserID pgtype.UUID) (db.AgentTaskQueue, error) {- return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, handoffNote, actorUserID, pgtype.UUID{}, pgtype.Timestamptz{})+ return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, handoffNote, actorUserID, pgtype.UUID{}, pgtype.Timestamptz{}, OriginDerived)}// enqueueIssueTask is the shared implementation behind EnqueueTaskForIssue@@ -1245,15 +1245,18 @@ func (s *TaskService) ResolveIssueReviewSHAParam(ctx context.Context, issueID pgreturn headShaText(s.ResolveIssueReviewSHA(ctx, issueID))}-func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, fireAt pgtype.Timestamptz) (db.AgentTaskQueue, error) {- return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, nil, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID, fireAt)+func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, fireAt pgtype.Timestamptz, origin RunOrigin) (db.AgentTaskQueue, error) {+ return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, nil, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID, fireAt, origin)}-func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, fireAt pgtype.Timestamptz) (db.AgentTaskQueue, error) {+func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, fireAt pgtype.Timestamptz, origin RunOrigin) (db.AgentTaskQueue, error) {if !issue.AssigneeID.Valid {slog.Error("task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "error", "issue has no assignee")return db.AgentTaskQueue{}, fmt.Errorf("issue has no assignee")}+ if err := guardIssueNotInTriage(ctx, s.Queries, issue.ID, origin); err != nil {+ return db.AgentTaskQueue{}, err+ }agent, err := s.Queries.GetAgent(ctx, issue.AssigneeID)if err != nil {@@ -1379,14 +1382,15 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue// EnqueueTaskForMention creates a queued task for a mentioned agent on an issue.// Unlike EnqueueTaskForIssue, this takes an explicit agent ID rather than// deriving it from the issue assignee.-func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {- return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{})+func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, origin RunOrigin) (db.AgentTaskQueue, error) {+ return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{}, origin)}// EnqueueTaskForThreadParent creates a queued task for the agent who authored// the direct parent comment a member replied to.func (s *TaskService) EnqueueTaskForThreadParent(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {- return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{})+ // Always named: the only caller is a member replying to what this agent said.+ return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{}, OriginNamed)}// EnqueueTaskForSquadLeader is the leader-role variant of EnqueueTaskForMention.@@ -1400,8 +1404,8 @@ func (s *TaskService) EnqueueTaskForThreadParent(ctx context.Context, issue db.I// handler can locate the squad and inject its briefing regardless of how the// leader task was triggered (comment @squad, issue assign, autopilot,// sub-issue done callback). See migration 127.-func (s *TaskService) EnqueueTaskForSquadLeader(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, squadID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {- return s.enqueueMentionTask(ctx, issue, leaderID, triggerCommentID, true, squadID, false, "", pgtype.UUID{}, pgtype.UUID{})+func (s *TaskService) EnqueueTaskForSquadLeader(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, squadID pgtype.UUID, triggerCommentID pgtype.UUID, origin RunOrigin) (db.AgentTaskQueue, error) {+ return s.enqueueMentionTask(ctx, issue, leaderID, triggerCommentID, true, squadID, false, "", pgtype.UUID{}, pgtype.UUID{}, origin)}// EnqueueTaskForSquadLeaderByActor is the assign/promote variant of@@ -1409,20 +1413,23 @@ func (s *TaskService) EnqueueTaskForSquadLeader(ctx context.Context, issue db.Is// assign/promote and becomes the accountable human (MUL-4302 §4); invalid when// the caller has no member actor.func (s *TaskService) EnqueueTaskForSquadLeaderByActor(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, squadID pgtype.UUID, actorUserID pgtype.UUID) (db.AgentTaskQueue, error) {- return s.enqueueMentionTask(ctx, issue, leaderID, pgtype.UUID{}, true, squadID, false, "", actorUserID, pgtype.UUID{})+ return s.enqueueMentionTask(ctx, issue, leaderID, pgtype.UUID{}, true, squadID, false, "", actorUserID, pgtype.UUID{}, OriginDerived)}// EnqueueTaskForSquadLeaderWithHandoff is the squad equivalent of// EnqueueTaskForIssueWithHandoff.func (s *TaskService) EnqueueTaskForSquadLeaderWithHandoff(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, squadID pgtype.UUID, handoffNote string, actorUserID pgtype.UUID) (db.AgentTaskQueue, error) {- return s.enqueueMentionTask(ctx, issue, leaderID, pgtype.UUID{}, true, squadID, false, handoffNote, actorUserID, pgtype.UUID{})+ return s.enqueueMentionTask(ctx, issue, leaderID, pgtype.UUID{}, true, squadID, false, handoffNote, actorUserID, pgtype.UUID{}, OriginDerived)}-func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {- return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, nil, isLeader, squadID, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID)+func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin) (db.AgentTaskQueue, error) {+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, nil, isLeader, squadID, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID, origin)}-func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {+func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin) (db.AgentTaskQueue, error) {+ if err := guardIssueNotInTriage(ctx, s.Queries, issue.ID, origin); err != nil {+ return db.AgentTaskQueue{}, err+ }agent, err := s.Queries.GetAgent(ctx, agentID)if err != nil {slog.Error("mention task enqueue failed: agent not found", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)@@ -4863,6 +4870,21 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,createRetry = false}}+ // The queue door, on the one insert path that cannot fail loudly. A+ // refusal here must never abort the transaction — it also carries the+ // parent's failed status, and losing that leaves the task stuck in+ // 'running' — so both a Triage issue and an unreadable status skip the+ // retry instead of returning, exactly as the ErrNoRows case below does.+ if createRetry {+ if gerr := guardIssueNotInTriage(ctx, qtx, t.IssueID, OriginDerived); gerr != nil {+ slog.Info("fail task auto-retry skipped: issue does not run",+ "task_id", util.UUIDToString(taskID),+ "issue_id", util.UUIDToString(t.IssueID),+ "error", gerr,+ )+ createRetry = false+ }+ }if createRetry {child, cerr := qtx.CreateRetryTask(ctx, db.CreateRetryTaskParams{NewTaskID: dbid.NewV7(),@@ -5204,13 +5226,19 @@ func ResumeUnsafeFailure(failureReason, errorText string) bool {// retryEligible reports whether a failed task qualifies for an automatic retry// attempt: an infrastructure-shaped failure_reason, remaining attempt budget,-// not an autopilot run, and linked to an issue or chat session. Shared by-// FailTask's in-transaction retry and the orphan sweeper's MaybeRetryFailedTask-// so both agree on which failures re-run.+// not an autopilot run, not a Triage run, and linked to an issue or chat+// session. Shared by FailTask's in-transaction retry and the orphan sweeper's+// MaybeRetryFailedTask so both agree on which failures re-run.+//+// A Triage run is excluded for the reason autopilot runs are (MUL-7189 §5.6):+// it has its own recovery. Re-triaging reads the entry as it stands now, which+// a human may have edited in the meantime, so replaying the failed attempt is+// never what the workspace wants.func retryEligible(failureReason string, t db.AgentTaskQueue) bool {return retryableReasons[failureReason] &&t.Attempt < retryAttemptCeiling(failureReason, t.MaxAttempts) &&!t.AutopilotRunID.Valid &&+ !IsTriageTask(t) &&(t.IssueID.Valid || t.ChatSessionID.Valid || isSourceContextQuickCreateTask(t))}@@ -5337,6 +5365,15 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT}defer tx.Rollback(ctx)qtx := s.Queries.WithTx(tx)+ if err := guardIssueNotInTriage(ctx, qtx, parent.IssueID, OriginDerived); err != nil {+ if errors.Is(err, ErrIssueInTriage) {+ slog.Info("task auto-retry skipped: issue is in triage",+ "parent_task_id", util.UUIDToString(parent.ID),+ "issue_id", util.UUIDToString(parent.IssueID))+ return nil, nil+ }+ return nil, err+ }child, err := qtx.CreateRetryTask(ctx, db.CreateRetryTaskParams{NewTaskID: dbid.NewV7(),ID: parent.ID,@@ -5478,6 +5515,21 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourcif err != nil {return nil, fmt.Errorf("load issue: %w", err)}+ // In Triage a rerun follows its source, and the decision is made here —+ // before anything is cancelled. The queue door would refuse a derived rerun+ // anyway, but this path cancels the prior run on its way there, so a late+ // refusal would leave the issue with one fewer run and no new one.+ //+ // Naming no source means "run the assignee again", which is the derived+ // executor Triage does not have. Naming a discussion run is repeating a+ // conversation the member started, so it is allowed; naming the triage run+ // itself is refused further down, with its own reason.+ rerunOrigin := OriginDerived+ if sourceTaskID.Valid {+ rerunOrigin = OriginNamed+ } else if issue.TriageState.Valid {+ return nil, ErrIssueInTriage+ }// Determine the target agent for the rerun.var (@@ -5494,6 +5546,17 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourcif !sourceTask.IssueID.Valid || util.UUIDToString(sourceTask.IssueID) != util.UUIDToString(issueID) {return nil, fmt.Errorf("source task does not belong to this issue")}+ // A triage run is not an execution run to repeat (MUL-7189 §5.6). This+ // is the only path that names a source task directly, and it would+ // otherwise outlive Triage: after accept the issue is runnable again, so+ // nothing above stops a rerun pointed at the triage task — which resumes+ // its session through rerun_of_task_id (the claim handler reads the+ // named source, not GetLastTaskSession) and targets the triager rather+ // than the issue's assignee. Redoing triage is re-triage, a different+ // action on a different status.+ if IsTriageTask(sourceTask) {+ return nil, ErrRerunSourceIsTriage+ }agentID = sourceTask.AgentIDisLeader = sourceTask.IsLeaderTask// Carry the source task's squad provenance so a rerun of a leader@@ -5612,7 +5675,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc// sourceTaskID is the rerun lineage: it rides the CreateAgentTask insert// (rerun_of_task_id) so the queued event / daemon claim never sees a NULL// lineage, and it stays distinct from system-retry's retry_of_task_id (§5).- task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID)+ task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID, rerunOrigin)if pendingSlotTakenErr(err) {// The clear above and this enqueue are separate commits, so a system// retry created by a concurrent FailTask can take the pending slot in@@ -5628,7 +5691,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc"agent_id", util.UUIDToString(agentID),)cancelledCount += clearPendingSlot()- task, err = s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID)+ task, err = s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID, rerunOrigin)}if err != nil {return nil, err@@ -5712,12 +5775,12 @@ func (s *TaskService) promoteNewestSurvivingComment(ctx context.Context, ids []p// handler ignores this flag for reruns and instead reads the exact source task// (rerun_of_task_id) to reuse its workdir and, when the failure did not poison// the conversation, resume its session (MUL-4869).-func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {+func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, origin RunOrigin) (db.AgentTaskQueue, error) {if issue.AssigneeType.String == "agent" && issue.AssigneeID.Valid &&util.UUIDToString(issue.AssigneeID) == util.UUIDToString(agentID) {- return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, coalescedCommentIDs, true, "", actorUserID, rerunOfTaskID, pgtype.Timestamptz{})+ return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, coalescedCommentIDs, true, "", actorUserID, rerunOfTaskID, pgtype.Timestamptz{}, origin)}- return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "", actorUserID, rerunOfTaskID)+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "", actorUserID, rerunOfTaskID, origin)}// The bulk terminal writes below are the sweeper, archive and daemon-recovery@@ -6073,6 +6136,11 @@ func loadDelegatedFailureRecoveryTarget(ctx context.Context, q *db.Queries, fail// ListPendingDelegatedFailureRecoveries. It must not gate signal creation:// catalog failures are retryable only after the outbox comment is committed.func canDispatchDelegatedFailureRecovery(ctx context.Context, q *db.Queries, issue db.Issue) (bool, error) {+ // A coordinator waiting in Triage is the entry's proposed owner, not its+ // owner, so a worker failure must not wake it (MUL-7189 §2.3).+ if issue.TriageState.Valid {+ return false, nil+ }category, err := issuestatus.CategoryWithError(ctx, q, issue.WorkspaceID, issue.Status)if err != nil {return false, err@@ -6336,6 +6404,12 @@ func (s *TaskService) dispatchDelegatedFailureRecovery(ctx context.Context, targ// Signal creation has committed before reaching this shared dispatch path.// Refresh the issue because its status may have changed since creation or// sweep selection; a paused/unreadable lifecycle never settles the signal.+ //+ // This is also the queue door for Triage on this path (MUL-7189 §2.3), and+ // it needs no separate check: Triage is its own category, so it is neither+ // unstarted nor started and canDispatchDelegatedFailureRecovery already+ // refuses it. "Covered" is the honest outcome — no further dispatch is owed,+ // and the run that would answer the comment arrives with accept.issue, err := s.Queries.GetIssue(ctx, target.issue.ID)if errors.Is(err, pgx.ErrNoRows) {return delegatedFailureRecoveryCovered, nildiff --git a/server/internal/service/task_triage_guard.go b/server/internal/service/task_triage_guard.gonew file mode 100644index 0000000000..99b806a7f7--- /dev/null+++ b/server/internal/service/task_triage_guard.go@@ -0,0 +1,122 @@+package service++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// The queue door for Triage (MUL-7189 §2.3).+//+// The rule is narrower than "an issue in Triage runs nothing": Triage has no+// EXECUTOR. Nothing may derive one from the issue — the assignee, a prefilled+// owner, a squad leader, an automatic retry — because that is precisely what+// the triager is still deciding. Prefilling an owner is how a run starts today,+// and the triager must record its reasoning as a comment, so without this the+// triager would dispatch the very owner it was only proposing.+//+// A person naming an agent by hand is a different act. It is a conversation+// with that agent, its cost is one the person chose, and no triager action+// produces it, so it keeps working — the same shape as backlog, which parks+// assignment but lets comments through, one notch tighter because in Triage the+// assignee is only a proposal.+//+// The check cannot live at the call sites: several paths enqueue without+// looking at status at all, and dispatchIssueRun discards the enqueue error+// entirely, so a missed call site would fail silently. It sits at the last+// point every issue-linked task passes through — immediately before the INSERT+// — and the upstream short-circuits exist only to make previews and dispatch+// reasons correct.+//+// Exactly two enqueue paths are exempt, and both are Triage's own:+//+// - the Triage run itself, the one run an issue in Triage is allowed;+// - accept, which moves the issue out of Triage in the same transaction that+// enqueues the execution run, so it passes this check anyway.+//+// Both belong to sub-issues that are not built yet.++// RunOrigin tells the queue door where a run came from, which is the whole of+// what Triage decides on.+//+// OriginDerived is the zero value on purpose: a caller that says nothing gets+// the strict answer, so a new enqueue path cannot leak into Triage by omission.+type RunOrigin int++const (+ // OriginDerived: the executor was worked out from the issue — its assignee,+ // its squad's leader, the parent of a finished sub-issue, a retry of an+ // earlier run. Refused in Triage.+ OriginDerived RunOrigin = iota+ // OriginNamed: a person wrote this agent's name — an @mention, or a reply+ // to something it said. Allowed in Triage.+ OriginNamed+)++// ErrIssueInTriage is returned by a derived enqueue path when the issue is+// waiting in Triage. Handlers render it as 403 issue_in_triage; background+// callers log it and drop the trigger.+var ErrIssueInTriage = errors.New("the issue is in triage, so nothing derived from it runs")++// ErrRerunSourceIsTriage is returned when a manual rerun names a triage run as+// the task to repeat. Handlers render it as 400: the request is well-formed and+// the issue may well be runnable — it is the target that is not an execution+// run. Redoing triage is re-triage.+var ErrRerunSourceIsTriage = errors.New("the source task is a triage run, which is redone by re-triaging the issue rather than by rerunning it")++// guardIssueNotInTriage refuses a DERIVED enqueue for an issue in Triage. q is+// the caller's own query handle so a transaction-scoped enqueue reads the+// status its own transaction wrote — the deferred-channel path creates the+// issue and its task together, and an uncommitted Triage issue must still be+// seen.+//+// A named run skips the read entirely: Triage never refuses it, so there is+// nothing to look up.+//+// A missing issue is not in Triage: the enqueue proceeds and fails (or not) on+// its own terms. A read error refuses, because a run that cannot be shown to be+// allowed must not start.+func guardIssueNotInTriage(ctx context.Context, q *db.Queries, issueID pgtype.UUID, origin RunOrigin) error {+ if origin == OriginNamed || !issueID.Valid {+ return nil+ }+ state, err := q.GetIssueTriageState(ctx, issueID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil+ }+ return fmt.Errorf("triage guard: load issue triage state: %w", err)+ }+ if state.Valid {+ return ErrIssueInTriage+ }+ return nil+}++// TriageContextType marks a task as a Triage run in its context JSONB+// (MUL-7189 §3.6). Triage runs carry no retry budget and no resumable session:+// a fresh triage of the current entry is always the right recovery, and a later+// execution run on the accepted issue must not inherit the triage conversation.+const TriageContextType = "triage"++// IsTriageTask reports whether a task is a Triage run. The marker lives in the+// task's context rather than a column, so a task written before Triage existed+// reads as false.+//+// Exported because the daemon claim handler needs the same answer: it resolves+// a manual rerun's session from the named source task, which no query-level+// exclusion can reach.+func IsTriageTask(t db.AgentTaskQueue) bool {+ if len(t.Context) == 0 {+ return false+ }+ var payload struct {+ Type string `json:"type"`+ }+ return json.Unmarshal(t.Context, &payload) == nil && payload.Type == TriageContextType+}diff --git a/server/internal/service/task_triage_guard_test.go b/server/internal/service/task_triage_guard_test.gonew file mode 100644index 0000000000..15edc13790--- /dev/null+++ b/server/internal/service/task_triage_guard_test.go@@ -0,0 +1,43 @@+package service++import (+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// A triage run is not retried (MUL-7189 §5.6). Re-triaging reads the entry as+// it stands now, so replaying a failed attempt is never the recovery wanted.+func TestRetryEligibleExcludesTriageRuns(t *testing.T) {+ issueLinked := func(context string) db.AgentTaskQueue {+ return db.AgentTaskQueue{+ Attempt: 1,+ MaxAttempts: 2,+ IssueID: pgtype.UUID{Bytes: [16]byte{1}, Valid: true},+ Context: []byte(context),+ }+ }+ cases := map[string]struct {+ context string+ want bool+ }{+ // The baseline: without the marker this reason/attempt pair retries, so+ // a `false` below is the marker's doing and nothing else.+ "no context": {"", true},+ "unrelated context": {`{"head_sha":"abc123"}`, true},+ "other context type": {`{"type":"quick_create"}`, true},+ "triage run": {`{"type":"triage"}`, false},+ "triage with revision": {`{"type":"triage","triage_revision":3}`, false},+ // A context that is not an object cannot claim to be a triage run, and+ // must not make the whole eligibility check fall over either.+ "malformed context": {`not json`, true},+ }+ for name, tc := range cases {+ t.Run(name, func(t *testing.T) {+ if got := retryEligible("timeout", issueLinked(tc.context)); got != tc.want {+ t.Errorf("retryEligible with context %q = %v, want %v", tc.context, got, tc.want)+ }+ })+ }+}diff --git a/server/migrations/483_issue_triage_state.down.sql b/server/migrations/483_issue_triage_state.down.sqlnew file mode 100644index 0000000000..4e674dcbcb--- /dev/null+++ b/server/migrations/483_issue_triage_state.down.sql@@ -0,0 +1,3 @@+ALTER TABLE issue+ DROP CONSTRAINT IF EXISTS issue_triage_state_known,+ DROP COLUMN IF EXISTS triage_state;diff --git a/server/migrations/483_issue_triage_state.up.sql b/server/migrations/483_issue_triage_state.up.sqlnew file mode 100644index 0000000000..e0d7148614--- /dev/null+++ b/server/migrations/483_issue_triage_state.up.sql@@ -0,0 +1,19 @@+-- Move Triage off `issue.status` and onto the issue's own attribute+-- (MUL-7213, design MUL-7189).+--+-- `status` answers "how far along is this work"; Triage answers "is this work+-- at all". Holding the second question in the first field makes every reader of+-- `status` re-answer it, which is where the scattered `<> 'triage'` checks came+-- from. A column of its own asks it once.+--+-- NULL is an ordinary issue and is the whole meaning of "not in Triage", so no+-- backfill and no default: adding a nullable column with no default is a+-- catalog-only change in PostgreSQL 11+, so this does not rewrite the table.+--+-- `pending` is the only state Triage can be in today. The outcomes a triager+-- records (declined, merged into another issue) are their own sub-issue and+-- extend this CHECK when they land; keeping the constraint narrow now is what+-- makes that a deliberate change rather than a silent typo.+ALTER TABLE issue+ ADD COLUMN triage_state TEXT,+ ADD CONSTRAINT issue_triage_state_known CHECK (triage_state IS NULL OR triage_state IN ('pending'));diff --git a/server/migrations/484_issue_triage_state_index.down.sql b/server/migrations/484_issue_triage_state_index.down.sqlnew file mode 100644index 0000000000..fbba5c36eb--- /dev/null+++ b/server/migrations/484_issue_triage_state_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_triage_state;diff --git a/server/migrations/484_issue_triage_state_index.up.sql b/server/migrations/484_issue_triage_state_index.up.sqlnew file mode 100644index 0000000000..ff82de5747--- /dev/null+++ b/server/migrations/484_issue_triage_state_index.up.sql@@ -0,0 +1,6 @@+-- The Triage queue reads exactly the rows this index holds, and every other+-- issue surface reads none of them. A partial index keeps it the size of the+-- queue rather than the size of the issue table.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_triage_state+ON issue (workspace_id, created_at ASC)+WHERE triage_state IS NOT NULL;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex dbc543ecd4..43b0e9d922 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -4320,11 +4320,13 @@ WITH retired_sessions AS (SELECT DISTINCT r.retired_session_id AS session_idFROM agent_task_queue rWHERE r.agent_id = $1 AND r.issue_id = $2+ AND COALESCE(r.context->>'type', '') <> 'triage'AND r.retired_session_id IS NOT NULL), resume_overflow_at AS (SELECT MAX(COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at)) AS atFROM agent_task_queue tWHERE t.agent_id = $1 AND t.issue_id = $2+ AND COALESCE(t.context->>'type', '') <> 'triage'AND t.status = 'failed'AND (COALESCE(t.failure_reason, '') = 'codex_resume_oversized'@@ -4336,6 +4338,7 @@ WITH retired_sessions AS (COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) AS terminal_atFROM agent_task_queue tWHERE t.agent_id = $1 AND t.issue_id = $2+ AND COALESCE(t.context->>'type', '') <> 'triage'AND t.session_id IS NOT NULLAND t.status IN ('completed', 'failed', 'cancelled')ORDER BY t.session_id, COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) DESC@@ -4484,6 +4487,14 @@ type GetLastTaskSessionRow struct {// emptyContentRe and historyMessageLocatorRe in pkg/taskfailure/resume.go.// Keep the three in sync.//+// Triage runs are excluded from all three CTEs (MUL-7189 §5.6). A triage run+// and the execution run that follows accept are the same (agent_id, issue_id)+// pair, so without this the first execution run would resume the conversation+// in which the agent was deciding whether the entry was worth keeping. From the+// execution side an accepted issue is a new issue, and it starts cold. The+// exclusion is symmetric: a triage run does not resume an execution session+// either, which is what force_fresh_session on the triage task already ensures.+//// retired_sessions is the explicit half of the same rule (GH #6066). The// per-session latest state above can only judge sessions that some row still// POINTS at, so it cannot see a session a run deliberately abandoned: a fresh@@ -4584,6 +4595,7 @@ func (q *Queries) GetLatestTaskRoleForIssueAndAgent(ctx context.Context, arg Getconst getLatestTaskRolloutMissing = `-- name: GetLatestTaskRolloutMissing :oneSELECT COALESCE(session_rollout_missing, FALSE) FROM agent_task_queueWHERE agent_id = $1 AND issue_id = $2+ AND COALESCE(context->>'type', '') <> 'triage'AND status IN ('completed', 'failed')AND started_at IS NOT NULLORDER BY COALESCE(completed_at, started_at, dispatched_at, created_at) DESC@@ -4601,6 +4613,12 @@ type GetLatestTaskRolloutMissingParams struct {// disclose that the most recent turn's context could not be carried over. Any// later task that records a real session resets this to FALSE by being the new// most-recent row, so the disclosure fires once and then clears.+//+// Triage runs are excluded for the same reason GetLastTaskSession excludes them+// (MUL-7189 §5.6), and the two must agree: this query only reports whether THAT+// one fell back. A triage run is invisible to it, so a triage run reported here+// would tell the first execution run after accept that the previous turn's+// context could not be carried over — about a turn it was never entitled to.func (q *Queries) GetLatestTaskRolloutMissing(ctx context.Context, arg GetLatestTaskRolloutMissingParams) (bool, error) {row := q.db.QueryRow(ctx, getLatestTaskRolloutMissing, arg.AgentID, arg.IssueID)var session_rollout_missing bool@@ -5740,12 +5758,15 @@ WHERE recovery.author_type = 'system'-- for open work; parking belongs exclusively to the fixed Backlog status.-- Built-ins resolve without catalog rows; unknown custom states stay pending.AND source_issue.status <> 'backlog'+ -- A coordinator waiting in Triage is the entry's proposed owner, not its+ -- owner, so a worker failure must not wake it (MUL-7189 §2.3). Triage is not+ -- a status, so it is a predicate of its own rather than a CASE arm.+ AND source_issue.triage_state IS NULLAND CASEWHEN source_issue.status IN ('backlog', 'todo') THEN 'unstarted'WHEN source_issue.status IN ('in_progress', 'in_review', 'blocked') THEN 'started'WHEN source_issue.status = 'done' THEN 'done'WHEN source_issue.status = 'cancelled' THEN 'closed'- WHEN source_issue.status = 'triage' THEN 'triage'ELSE issue_status_category(source_status.category)END IN ('unstarted', 'started')AND source_agent.archived_at IS NULLdiff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex d505d27b5a..3b39fa16bf 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -175,6 +175,27 @@ func (q *Queries) CountIssues(ctx context.Context, arg CountIssuesParams) (int64return count, err}+const countIssuesInTriage = `-- name: CountIssuesInTriage :one+SELECT count(*) FROM issue+WHERE workspace_id = $1+ AND id = ANY($2::uuid[])+ AND triage_state IS NOT NULL+`++type CountIssuesInTriageParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueIds []pgtype.UUID `json:"issue_ids"`+}++// How many of these issues are in Triage. The batch parent-write guard only+// needs "any", and a count keeps the check one round trip regardless of size.+func (q *Queries) CountIssuesInTriage(ctx context.Context, arg CountIssuesInTriageParams) (int64, error) {+ row := q.db.QueryRow(ctx, countIssuesInTriage, arg.WorkspaceID, arg.IssueIds)+ var count int64+ err := row.Scan(&count)+ return count, err+}+const countIssuesUpTo = `-- name: CountIssuesUpTo :oneSELECT COUNT(*)::bigintFROM (@@ -209,7 +230,7 @@ INSERT INTO issue () VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,$16, now(), COALESCE($17::uuid, gen_random_uuid())-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state`type CreateIssueParams struct {@@ -282,6 +303,7 @@ func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}@@ -295,7 +317,7 @@ INSERT INTO issue () VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,$16, $17, $18, now(), COALESCE($19::uuid, gen_random_uuid())-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state`type CreateIssueWithOriginParams struct {@@ -372,6 +394,7 @@ func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWith&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}@@ -460,7 +483,7 @@ SET parent_issue_id = NULL,WHERE workspace_id = $1AND parent_issue_id = $2AND NOT COALESCE(id = ANY($3::uuid[]), false)-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state`type DetachDirectChildIssuesParams struct {@@ -507,6 +530,7 @@ func (q *Queries) DetachDirectChildIssues(ctx context.Context, arg DetachDirectC&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,); err != nil {return nil, err}@@ -519,10 +543,14 @@ func (q *Queries) DetachDirectChildIssues(ctx context.Context, arg DetachDirectC}const findActiveDuplicateIssue = `-- name: FindActiveDuplicateIssue :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state FROM issueWHERE workspace_id = $1-- Negate only known terminal keys so an unknown legacy key remains active.AND NOT (status = ANY($2::text[]))+ -- An entry waiting in Triage has not been taken on, so it never blocks+ -- someone filing the same work; a duplicate there is resolved by merging+ -- it out of Triage (MUL-7189 §2.6).+ AND triage_state IS NULLAND project_id IS NOT DISTINCT FROM $3::uuidAND parent_issue_id IS NOT DISTINCT FROM $4::uuidAND lower(btrim(regexp_replace(title, '[[:space:]]+', ' ', 'g'))) = $5@@ -576,15 +604,20 @@ func (q *Queries) FindActiveDuplicateIssue(ctx context.Context, arg FindActiveDu&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}const findRecentAutopilotDuplicateIssue = `-- name: FindRecentAutopilotDuplicateIssue :one-SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at FROM issue i+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state FROM issue iWHERE i.workspace_id = $1-- Negate only known terminal keys so an unknown legacy key remains active.AND NOT (i.status = ANY($3::text[]))+ -- An entry waiting in Triage has not been taken on, so it never blocks+ -- someone filing the same work; a duplicate there is resolved by merging+ -- it out of Triage (MUL-7189 §2.6).+ AND i.triage_state IS NULLAND i.origin_type = 'autopilot'AND i.origin_id = $2AND i.project_id IS NOT DISTINCT FROM $4::uuid@@ -649,12 +682,13 @@ func (q *Queries) FindRecentAutopilotDuplicateIssue(ctx context.Context, arg Fin&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}const getIssue = `-- name: GetIssue :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state FROM issueWHERE id = $1`@@ -690,12 +724,13 @@ func (q *Queries) GetIssue(ctx context.Context, id pgtype.UUID) (Issue, error) {&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}const getIssueByNumber = `-- name: GetIssueByNumber :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state FROM issueWHERE workspace_id = $1 AND number = $2`@@ -736,12 +771,13 @@ func (q *Queries) GetIssueByNumber(ctx context.Context, arg GetIssueByNumberPara&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}const getIssueByOrigin = `-- name: GetIssueByOrigin :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state FROM issueWHERE workspace_id = $1AND origin_type = $2AND origin_id = $3@@ -791,6 +827,7 @@ func (q *Queries) GetIssueByOrigin(ctx context.Context, arg GetIssueByOriginPara&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}@@ -815,7 +852,7 @@ func (q *Queries) GetIssueGCStatus(ctx context.Context, id pgtype.UUID) (GetIssu}const getIssueInWorkspace = `-- name: GetIssueInWorkspace :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state FROM issueWHERE id = $1 AND workspace_id = $2`@@ -856,6 +893,7 @@ func (q *Queries) GetIssueInWorkspace(ctx context.Context, arg GetIssueInWorkspa&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}@@ -884,8 +922,22 @@ func (q *Queries) GetIssueMetadataInWorkspace(ctx context.Context, arg GetIssueMreturn i, err}+const getIssueTriageState = `-- name: GetIssueTriageState :one+SELECT triage_state FROM issue WHERE id = $1+`++// Answers "is this issue in Triage" for the queue door, which runs immediately+// before an INSERT and must see the status its own transaction wrote. NULL is+// an ordinary issue.+func (q *Queries) GetIssueTriageState(ctx context.Context, id pgtype.UUID) (pgtype.Text, error) {+ row := q.db.QueryRow(ctx, getIssueTriageState, id)+ var triage_state pgtype.Text+ err := row.Scan(&triage_state)+ return triage_state, err+}+const listChildIssues = `-- name: ListChildIssues :many-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state FROM issueWHERE parent_issue_id = $1ORDER BY number ASC`@@ -934,6 +986,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,); err != nil {return nil, err}@@ -946,7 +999,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID}const listChildrenByParents = `-- name: ListChildrenByParents :many-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state FROM issueWHERE workspace_id = $1AND parent_issue_id = ANY($2::uuid[])ORDER BY parent_issue_id, number ASC@@ -1002,6 +1055,7 @@ func (q *Queries) ListChildrenByParents(ctx context.Context, arg ListChildrenByP&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,); err != nil {return nil, err}@@ -1499,7 +1553,7 @@ func (q *Queries) LockIssueForDelete(ctx context.Context, arg LockIssueForDelete}const lockIssueForDescriptionUpdate = `-- name: LockIssueForDescriptionUpdate :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state FROM issueWHERE id = $1 AND workspace_id = $2FOR UPDATE`@@ -1545,6 +1599,7 @@ func (q *Queries) LockIssueForDescriptionUpdate(ctx context.Context, arg LockIss&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}@@ -1594,7 +1649,7 @@ SET description = CASEupdated_at = now()WHERE id = $4AND workspace_id = $5-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state`type MaterializeIssueChannelMediaMarkdownParams struct {@@ -1650,6 +1705,7 @@ func (q *Queries) MaterializeIssueChannelMediaMarkdown(ctx context.Context, arg&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}@@ -1706,7 +1762,7 @@ func (q *Queries) SetIssueMetadataKey(ctx context.Context, arg SetIssueMetadataKconst updateIssue = `-- name: UpdateIssue :oneWITH candidate AS (SELECT- i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at,+ i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state,COALESCE($3::text, i.title) AS next_title,COALESCE($4::text, i.description) AS next_description,COALESCE($5::text, i.status) AS next_status,@@ -1751,7 +1807,7 @@ WITH candidate AS (AND ($2::bigint IS NULL OR i.revision = $2::bigint)), changed AS (SELECT- candidate.id, candidate.workspace_id, candidate.title, candidate.description, candidate.status, candidate.priority, candidate.assignee_type, candidate.assignee_id, candidate.creator_type, candidate.creator_id, candidate.parent_issue_id, candidate.acceptance_criteria, candidate.context_refs, candidate.position, candidate.due_date, candidate.created_at, candidate.updated_at, candidate.number, candidate.project_id, candidate.origin_type, candidate.origin_id, candidate.first_executed_at, candidate.start_date, candidate.metadata, candidate.stage, candidate.properties, candidate.revision, candidate.last_activity_at, candidate.next_title, candidate.next_description, candidate.next_status, candidate.next_priority, candidate.next_assignee_type, candidate.next_assignee_id, candidate.next_position, candidate.next_start_date, candidate.next_due_date, candidate.next_parent_issue_id, candidate.next_project_id, candidate.next_stage,+ candidate.id, candidate.workspace_id, candidate.title, candidate.description, candidate.status, candidate.priority, candidate.assignee_type, candidate.assignee_id, candidate.creator_type, candidate.creator_id, candidate.parent_issue_id, candidate.acceptance_criteria, candidate.context_refs, candidate.position, candidate.due_date, candidate.created_at, candidate.updated_at, candidate.number, candidate.project_id, candidate.origin_type, candidate.origin_id, candidate.first_executed_at, candidate.start_date, candidate.metadata, candidate.stage, candidate.properties, candidate.revision, candidate.last_activity_at, candidate.triage_state, candidate.next_title, candidate.next_description, candidate.next_status, candidate.next_priority, candidate.next_assignee_type, candidate.next_assignee_id, candidate.next_position, candidate.next_start_date, candidate.next_due_date, candidate.next_parent_issue_id, candidate.next_project_id, candidate.next_stage,ROW(title, description, status, priority, assignee_type, assignee_id,position, start_date, due_date, parent_issue_id, project_id, stage@@ -1796,7 +1852,7 @@ WHERE i.id = changed.id-- from the same snapshot; EvalPlanQual re-evaluates this target-row predicate-- after waiting for the first writer, leaving the stale writer with 0 rows.AND ($2::bigint IS NULL OR i.revision = $2::bigint)-RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at+RETURNING i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state`type UpdateIssueParams struct {@@ -1863,6 +1919,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}@@ -1883,7 +1940,7 @@ UPDATE issue AS i SETEND,updated_at = now()WHERE i.id = $1 AND i.workspace_id = $3-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state`type UpdateIssueStatusParams struct {@@ -1929,6 +1986,7 @@ func (q *Queries) UpdateIssueStatus(ctx context.Context, arg UpdateIssueStatusPa&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}diff --git a/server/pkg/db/generated/issue_property.sql.go b/server/pkg/db/generated/issue_property.sql.goindex 676f97f0fe..809cc84b6e 100644--- a/server/pkg/db/generated/issue_property.sql.go+++ b/server/pkg/db/generated/issue_property.sql.go@@ -126,7 +126,7 @@ SET properties = properties - $1::text,END,updated_at = CASE WHEN properties ? $1::text THEN now() ELSE updated_at ENDWHERE id = $2::uuid AND workspace_id = $3::uuid-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state`type DeleteIssuePropertyValueParams struct {@@ -167,6 +167,7 @@ func (q *Queries) DeleteIssuePropertyValue(ctx context.Context, arg DeleteIssueP&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}@@ -280,7 +281,7 @@ SET properties = jsonb_set(properties, ARRAY[$1::text], $2::jsonb, true),END,updated_at = CASE WHEN properties -> $1::text IS DISTINCT FROM $2::jsonb THEN now() ELSE updated_at ENDWHERE id = $3::uuid AND workspace_id = $4::uuid-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state`type SetIssuePropertyValueParams struct {@@ -330,6 +331,7 @@ func (q *Queries) SetIssuePropertyValue(ctx context.Context, arg SetIssuePropert&i.Properties,&i.Revision,&i.LastActivityAt,+ &i.TriageState,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex faaf514d94..330a7cd833 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -802,6 +802,7 @@ type Issue struct {Properties []byte `json:"properties"`Revision int64 `json:"revision"`LastActivityAt pgtype.Timestamptz `json:"last_activity_at"`+ TriageState pgtype.Text `json:"triage_state"`}type IssueDependency struct {diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 6010553289..e36577fd1d 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -1084,6 +1084,14 @@ RETURNING *;-- emptyContentRe and historyMessageLocatorRe in pkg/taskfailure/resume.go.-- Keep the three in sync.--+-- Triage runs are excluded from all three CTEs (MUL-7189 §5.6). A triage run+-- and the execution run that follows accept are the same (agent_id, issue_id)+-- pair, so without this the first execution run would resume the conversation+-- in which the agent was deciding whether the entry was worth keeping. From the+-- execution side an accepted issue is a new issue, and it starts cold. The+-- exclusion is symmetric: a triage run does not resume an execution session+-- either, which is what force_fresh_session on the triage task already ensures.+---- retired_sessions is the explicit half of the same rule (GH #6066). The-- per-session latest state above can only judge sessions that some row still-- POINTS at, so it cannot see a session a run deliberately abandoned: a fresh@@ -1096,11 +1104,13 @@ WITH retired_sessions AS (SELECT DISTINCT r.retired_session_id AS session_idFROM agent_task_queue rWHERE r.agent_id = $1 AND r.issue_id = $2+ AND COALESCE(r.context->>'type', '') <> 'triage'AND r.retired_session_id IS NOT NULL), resume_overflow_at AS (SELECT MAX(COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at)) AS atFROM agent_task_queue tWHERE t.agent_id = $1 AND t.issue_id = $2+ AND COALESCE(t.context->>'type', '') <> 'triage'AND t.status = 'failed'AND (COALESCE(t.failure_reason, '') = 'codex_resume_oversized'@@ -1112,6 +1122,7 @@ WITH retired_sessions AS (COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) AS terminal_atFROM agent_task_queue tWHERE t.agent_id = $1 AND t.issue_id = $2+ AND COALESCE(t.context->>'type', '') <> 'triage'AND t.session_id IS NOT NULLAND t.status IN ('completed', 'failed', 'cancelled')ORDER BY t.session_id, COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) DESC@@ -1162,8 +1173,15 @@ LIMIT 1;-- disclose that the most recent turn's context could not be carried over. Any-- later task that records a real session resets this to FALSE by being the new-- most-recent row, so the disclosure fires once and then clears.+--+-- Triage runs are excluded for the same reason GetLastTaskSession excludes them+-- (MUL-7189 §5.6), and the two must agree: this query only reports whether THAT+-- one fell back. A triage run is invisible to it, so a triage run reported here+-- would tell the first execution run after accept that the previous turn's+-- context could not be carried over — about a turn it was never entitled to.SELECT COALESCE(session_rollout_missing, FALSE) FROM agent_task_queueWHERE agent_id = $1 AND issue_id = $2+ AND COALESCE(context->>'type', '') <> 'triage'AND status IN ('completed', 'failed')AND started_at IS NOT NULLORDER BY COALESCE(completed_at, started_at, dispatched_at, created_at) DESC@@ -2129,12 +2147,15 @@ WHERE recovery.author_type = 'system'-- for open work; parking belongs exclusively to the fixed Backlog status.-- Built-ins resolve without catalog rows; unknown custom states stay pending.AND source_issue.status <> 'backlog'+ -- A coordinator waiting in Triage is the entry's proposed owner, not its+ -- owner, so a worker failure must not wake it (MUL-7189 §2.3). Triage is not+ -- a status, so it is a predicate of its own rather than a CASE arm.+ AND source_issue.triage_state IS NULLAND CASEWHEN source_issue.status IN ('backlog', 'todo') THEN 'unstarted'WHEN source_issue.status IN ('in_progress', 'in_review', 'blocked') THEN 'started'WHEN source_issue.status = 'done' THEN 'done'WHEN source_issue.status = 'cancelled' THEN 'closed'- WHEN source_issue.status = 'triage' THEN 'triage'ELSE issue_status_category(source_status.category)END IN ('unstarted', 'started')AND source_agent.archived_at IS NULLdiff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 08d7c62112..5d5d8b845f 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -66,6 +66,20 @@ LIMIT $2 OFFSET $3;SELECT * FROM issueWHERE id = $1;+-- name: CountIssuesInTriage :one+-- How many of these issues are in Triage. The batch parent-write guard only+-- needs "any", and a count keeps the check one round trip regardless of size.+SELECT count(*) FROM issue+WHERE workspace_id = sqlc.arg('workspace_id')+ AND id = ANY(sqlc.arg('issue_ids')::uuid[])+ AND triage_state IS NOT NULL;++-- name: GetIssueTriageState :one+-- Answers "is this issue in Triage" for the queue door, which runs immediately+-- before an INSERT and must see the status its own transaction wrote. NULL is+-- an ordinary issue.+SELECT triage_state FROM issue WHERE id = $1;+-- name: GetIssueGCStatus :oneSELECT workspace_id, status, updated_atFROM issue@@ -315,6 +329,10 @@ SELECT * FROM issueWHERE workspace_id = $1-- Negate only known terminal keys so an unknown legacy key remains active.AND NOT (status = ANY(sqlc.arg('terminal_status_keys')::text[]))+ -- An entry waiting in Triage has not been taken on, so it never blocks+ -- someone filing the same work; a duplicate there is resolved by merging+ -- it out of Triage (MUL-7189 §2.6).+ AND triage_state IS NULLAND project_id IS NOT DISTINCT FROM sqlc.arg('project_id')::uuidAND parent_issue_id IS NOT DISTINCT FROM sqlc.arg('parent_issue_id')::uuidAND lower(btrim(regexp_replace(title, '[[:space:]]+', ' ', 'g'))) = sqlc.arg('normalized_title')@@ -326,6 +344,10 @@ SELECT i.* FROM issue iWHERE i.workspace_id = $1-- Negate only known terminal keys so an unknown legacy key remains active.AND NOT (i.status = ANY(sqlc.arg('terminal_status_keys')::text[]))+ -- An entry waiting in Triage has not been taken on, so it never blocks+ -- someone filing the same work; a duplicate there is resolved by merging+ -- it out of Triage (MUL-7189 §2.6).+ AND i.triage_state IS NULLAND i.origin_type = 'autopilot'AND i.origin_id = $2AND i.project_id IS NOT DISTINCT FROM sqlc.arg('project_id')::uuid