Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6243 feat(issue-status): per-workspace custom issue statuses over 7 canonical categories (#7065)
Bohan Jiang446080bd57e1
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 96039f65de..667f6b8be5 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -116,6 +116,10 @@ import type {CreateLabelRequest,UpdateLabelRequest,ListLabelsResponse,+ ListIssueStatusesResponse,+ IssueStatusEntry,+ CreateIssueStatusRequest,+ UpdateIssueStatusRequest,IssueLabelsResponse,LabelResourceType,ResourceLabelsResponse,@@ -344,6 +348,8 @@ import {EMPTY_NOTIFICATION_PREFERENCE_RESPONSE,LabelSchema,ListLabelsResponseSchema,+ ListIssueStatusesResponseSchema,+ IssueStatusEntrySchema,IssuePropertySchema,ListPropertiesResponseSchema,IssuePropertiesResponseSchema,@@ -362,6 +368,8 @@ import {ResourceLabelsResponseSchema,EMPTY_LABEL,EMPTY_LIST_LABELS_RESPONSE,+ EMPTY_LIST_ISSUE_STATUSES_RESPONSE,+ EMPTY_ISSUE_STATUS_ENTRY,EMPTY_RESOURCE_LABELS_RESPONSE,GitHubConnectResponseSchema,ListGitHubInstallationsResponseSchema,@@ -3246,6 +3254,47 @@ export class ApiClient {await this.fetch(`/api/labels/${id}`, { method: "DELETE" });}+ // Issue status catalog (MUL-6243). Reads are open to any workspace member;+ // the mutations below are owner/admin only and return 403 otherwise.+ async listIssueStatuses(includeArchived = false): Promise<ListIssueStatusesResponse> {+ const query = includeArchived ? "?include_archived=true" : "";+ const raw = await this.fetch<unknown>(`/api/issue-statuses${query}`);+ return parseWithFallback(raw, ListIssueStatusesResponseSchema, EMPTY_LIST_ISSUE_STATUSES_RESPONSE, {+ endpoint: "GET /api/issue-statuses",+ });+ }++ async createIssueStatus(data: CreateIssueStatusRequest): Promise<IssueStatusEntry> {+ const raw = await this.fetch<unknown>(`/api/issue-statuses`, {+ method: "POST",+ body: JSON.stringify(data),+ });+ return parseWithFallback(raw, IssueStatusEntrySchema, EMPTY_ISSUE_STATUS_ENTRY, {+ endpoint: "POST /api/issue-statuses",+ });+ }++ async updateIssueStatus(id: string, data: UpdateIssueStatusRequest): Promise<IssueStatusEntry> {+ const raw = await this.fetch<unknown>(`/api/issue-statuses/${id}`, {+ method: "PATCH",+ body: JSON.stringify(data),+ });+ return parseWithFallback(raw, IssueStatusEntrySchema, EMPTY_ISSUE_STATUS_ENTRY, {+ endpoint: "PATCH /api/issue-statuses/{id}",+ });+ }++ /**+ * Archives a custom status. The server returns 409 while any issue still+ * sits on it — move those issues first. Built-in statuses return 403.+ */+ async archiveIssueStatus(id: string): Promise<IssueStatusEntry> {+ const raw = await this.fetch<unknown>(`/api/issue-statuses/${id}`, { method: "DELETE" });+ return parseWithFallback(raw, IssueStatusEntrySchema, EMPTY_ISSUE_STATUS_ENTRY, {+ endpoint: "DELETE /api/issue-statuses/{id}",+ });+ }+// Custom issue propertiesasync listProperties(includeArchived = false): Promise<ListPropertiesResponse> {const suffix = includeArchived ? "?include_archived=true" : "";diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 311bb4cc96..676ed8da3f 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -55,6 +55,12 @@ import {EMPTY_REMOTE_MCP_OAUTH_START_RESPONSE,} from "./schemas";import { IssueViewSchema, IssueViewListSchema } from "./schemas";+import {+ ListIssueStatusesResponseSchema,+ IssueStatusEntrySchema,+ EMPTY_LIST_ISSUE_STATUSES_RESPONSE,+ EMPTY_ISSUE_STATUS_ENTRY,+} from "./schemas";import { parseWithFallback } from "./schema";const baseIssue = {@@ -1447,3 +1453,79 @@ describe("Plugin catalog schemas", () => {expect(parsed.supported).toBe(false);});});++// Issue status catalog (MUL-6243). The catalog drives how every status renders,+// so a drifting or malformed response must degrade to the built-ins rather than+// leaving the UI with no statuses at all.+describe("issue status catalog schemas", () => {+ const baseStatus = {+ id: "status-1",+ workspace_id: "ws-1",+ key: "human_review",+ name: "Human Review",+ description: "Waiting on a person",+ category: "in_review",+ color: "#22c55e",+ is_system: false,+ position: 1,+ archived_at: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };++ it("parses a full catalog response", () => {+ const parsed = ListIssueStatusesResponseSchema.parse({+ statuses: [baseStatus],+ categories: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],+ total: 1,+ });+ expect(parsed.statuses[0]?.key).toBe("human_review");+ expect(parsed.statuses[0]?.category).toBe("in_review");+ expect(parsed.categories).toHaveLength(7);+ });++ it("falls back to the built-in categories on a malformed response", () => {+ const parsed = parseWithFallback(+ { statuses: "not-an-array", categories: 7 },+ ListIssueStatusesResponseSchema,+ EMPTY_LIST_ISSUE_STATUSES_RESPONSE,+ { endpoint: "GET /api/issue-statuses" },+ );+ expect(parsed).toEqual(EMPTY_LIST_ISSUE_STATUSES_RESPONSE);+ // The fallback still names all 7 categories, so a client talking to a+ // server that predates this endpoint can still render every built-in.+ expect(parsed.categories).toHaveLength(7);+ expect(parsed.statuses).toEqual([]);+ });++ it("defaults the optional presentation fields the server may omit", () => {+ const { color: _c, is_system: _s, position: _p, description: _d, archived_at: _a, ...minimal } = baseStatus;+ const parsed = IssueStatusEntrySchema.parse(minimal);+ expect(parsed.color).toBe("#6b7280");+ expect(parsed.is_system).toBe(false);+ expect(parsed.position).toBe(0);+ expect(parsed.archived_at).toBeNull();+ });++ it("keeps an unknown category as a string instead of failing the whole catalog", () => {+ // A newer server could report a category this build does not know. Dropping+ // the entry (or throwing) would leave the board unable to render issues+ // already sitting on it, so the value is carried through verbatim.+ const parsed = ListIssueStatusesResponseSchema.parse({+ statuses: [{ ...baseStatus, category: "started" }],+ categories: ["started"],+ total: 1,+ });+ expect(parsed.statuses[0]?.category).toBe("started");+ });++ it("falls back to an empty entry on a malformed single status", () => {+ const parsed = parseWithFallback(+ { id: 12345 },+ IssueStatusEntrySchema,+ EMPTY_ISSUE_STATUS_ENTRY,+ { endpoint: "POST /api/issue-statuses" },+ );+ expect(parsed).toEqual(EMPTY_ISSUE_STATUS_ENTRY);+ });+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex e56e570386..43f980f0be 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -58,6 +58,8 @@ import type {ListGitHubRepositoriesResponse,ListLabelsResponse,ListWebhookDeliveriesResponse,+ IssueStatusEntry,+ ListIssueStatusesResponse,NotificationPreferenceResponse,PluginCatalogResponse,PluginInstallation,@@ -391,6 +393,55 @@ export const EMPTY_LIST_LABELS_RESPONSE: ListLabelsResponse = {total: 0,};+// Issue status catalog (MUL-6243). `category` is parsed as a plain string+// rather than an enum: a newer server could in principle report a category this+// build does not know, and failing the whole catalog parse would leave the UI+// with no statuses at all. Consumers fall back to rendering by `color`/`name`+// when they do not recognize a category.+export const IssueStatusEntrySchema = z.object({+ id: z.string(),+ workspace_id: z.string(),+ key: z.string(),+ name: z.string(),+ description: z.string().optional().default(""),+ category: z.string(),+ color: z.string().optional().default("#6b7280"),+ is_system: z.boolean().optional().default(false),+ position: z.number().optional().default(0),+ archived_at: z.string().nullable().optional().default(null),+ created_at: z.string(),+ updated_at: z.string(),+}).loose();++export const EMPTY_ISSUE_STATUS_ENTRY: IssueStatusEntry = {+ id: "",+ workspace_id: "",+ key: "",+ name: "",+ description: "",+ category: "backlog",+ color: "#6b7280",+ is_system: false,+ position: 0,+ archived_at: null,+ created_at: "",+ updated_at: "",+};++export const ListIssueStatusesResponseSchema = z.object({+ statuses: z.array(IssueStatusEntrySchema).default([]),+ categories: z.array(z.string()).default([]),+ total: z.number().default(0),+}).loose();++// The fallback carries the 7 built-ins' keys as categories, so a client talking+// to a server that predates this endpoint still has the canonical list.+export const EMPTY_LIST_ISSUE_STATUSES_RESPONSE: ListIssueStatusesResponse = {+ statuses: [],+ categories: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],+ total: 0,+};+export const ResourceLabelsResponseSchema = z.object({labels: z.array(LabelSchema).default([]),}).loose();@@ -941,6 +992,12 @@ export const IssueSchema = z.object({title: z.string(),description: z.string().nullable(),status: z.string(),+ // The canonical status whose platform behavior `status` carries — equal to+ // `status` for the 7 built-ins, and the inherited category for a custom+ // status. Optional because only endpoints that resolve it emit it, so+ // consumers must fall back to `status` rather than treat "" as a category.+ // (MUL-6243)+ status_category: z.string().optional(),priority: z.string(),assignee_type: z.string().nullable(),assignee_id: z.string().nullable(),diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 6a8756da7e..5d659d6d72 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -1,4 +1,11 @@export type { Issue, IssueStatus, IssuePriority, IssueAssigneeType, IssueMetadata, IssueMetadataValue, IssueReaction } from "./issue";+export type {+ IssueStatusCategory,+ IssueStatusEntry,+ ListIssueStatusesResponse,+ CreateIssueStatusRequest,+ UpdateIssueStatusRequest,+} from "./issue-status";export type {Agent,AgentStatus,diff --git a/packages/core/types/issue-status.ts b/packages/core/types/issue-status.tsnew file mode 100644index 0000000000..45ef496458--- /dev/null+++ b/packages/core/types/issue-status.ts@@ -0,0 +1,74 @@+import type { IssueStatus } from "./issue";++/**+ * A workspace's issue status catalog (MUL-6243).+ *+ * The 7 categories map one-to-one onto the 7 built-in statuses: a category's+ * value IS its canonical status key. A custom status names a category and+ * inherits that canonical status's platform behavior in full — a custom status+ * in the `todo` category starts an agent exactly like Todo does, one in the+ * `in_review` category finalizes an autopilot run exactly like In Review does.+ *+ * That is why there is no separate "behavior" field here: the category is the+ * behavior.+ */++/** A status category, identical to the set of built-in status keys. */+export type IssueStatusCategory = IssueStatus;++export interface IssueStatusEntry {+ id: string;+ workspace_id: string;+ /**+ * Stable machine handle, immutable after creation. This is the value stored+ * in `issue.status`, accepted by `multica issue status`, and referenced in+ * agent instructions — so it does NOT track renames of `name`.+ */+ key: string;+ /** Human-facing label. Editable for custom statuses; locked for built-ins. */+ name: string;+ description: string;+ category: IssueStatusCategory;+ /** "#rrggbb". */+ color: string;+ /**+ * True for the 7 built-ins. They cannot be renamed, recolored, archived, or+ * have their category changed: each one is its category's canonical+ * definition, and the default workspace must look identical for every user+ * who never opens the status settings.+ */+ is_system: boolean;+ /** Ordering within the category. */+ position: number;+ archived_at: string | null;+ created_at: string;+ updated_at: string;+}++export interface ListIssueStatusesResponse {+ statuses: IssueStatusEntry[];+ /** The 7 categories, in display order. */+ categories: IssueStatusCategory[];+ total: number;+}++export interface CreateIssueStatusRequest {+ /** Optional; derived from `name` when omitted. Immutable once created. */+ key?: string;+ name: string;+ description?: string;+ category: IssueStatusCategory;+ color: string;+}++/**+ * `key` and `category` are absent by design — both are immutable. Changing a+ * category would silently rewrite the machine semantics of every issue already+ * on that status; changing a key would strand them.+ */+export interface UpdateIssueStatusRequest {+ name?: string;+ description?: string;+ color?: string;+ position?: number;+}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 6af5c911c7..0333ed01fb 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -191,6 +191,9 @@ var concurrentIndexCleanups = map[string]string{"328_workspace_share_link_id_uidx": "workspace_share_link_pkey_uidx","330_workspace_share_link_active_ws_uidx": "workspace_share_link_active_ws_uidx","331_workspace_share_link_code_uidx": "workspace_share_link_code_uidx",+ "333_issue_status_pkey_index": "issue_status_pkey_uidx",+ "335_issue_status_workspace_key_index": "idx_issue_status_workspace_key",+ "336_issue_status_workspace_name_index": "idx_issue_status_workspace_name_active",}// concurrentDownIndexCleanups covers every migration whose down directiondiff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex a7ec13ea31..f64531ba48 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -10,6 +10,7 @@ import ("net/url""os""path/filepath"+ "regexp""sort""strconv""strings"@@ -369,6 +370,10 @@ var issueSearchCmd = &cobra.Command{RunE: runIssueSearch,}+// 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.var validIssueStatuses = []string{"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled",}@@ -398,10 +403,31 @@ var directionalIssueSortColumns = func() []string {return cols}()+// validateIssueStatus checks the shape of a status key, not its membership.+//+// Since MUL-6243 a workspace can define custom statuses, so the CLI cannot know+// the valid set without a round trip. It validates the format locally — that+// still catches the common typo classes instantly and offline — and lets the+// server reject an unknown key, which it does with a 400 listing that+// workspace's actual statuses. Keeping a hard-coded list here would reject the+// custom statuses the feature exists to enable.func validateIssueStatus(status string) error {- return validateIssueEnum("status", status, validIssueStatuses)+ trimmed := strings.ToLower(strings.TrimSpace(status))+ if trimmed == "" {+ return fmt.Errorf("invalid status %q; valid values: %s",+ status, strings.Join(validIssueStatuses, ", "))+ }+ if !issueStatusKeyPattern.MatchString(trimmed) {+ return fmt.Errorf(+ "invalid status %q; a status key is 1-32 characters of lowercase letters, digits or underscore. Built-in values: %s",+ status, strings.Join(validIssueStatuses, ", "))+ }+ return nil}+// issueStatusKeyPattern mirrors the issue_status.key storage constraint.+var issueStatusKeyPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_]{0,31}$`)+func validateIssuePriority(priority string) error {return validateIssueEnum("priority", priority, validIssuePriorities)}@@ -955,7 +981,7 @@ func runIssueChildren(cmd *cobra.Command, args []string) error {}stages[gi].Issues = append(stages[gi].Issues, c)stages[gi].Total++- if st := strVal(c, "status"); st == "done" || st == "cancelled" {+ if isTerminalChildIssue(c) {stages[gi].Done++}}@@ -966,6 +992,22 @@ func runIssueChildren(cmd *cobra.Command, args []string) error {})}+// isTerminalChildIssue reports whether a child issue counts as finished for+// stage progress.+//+// Prefers `status_category`, which the server resolves for custom statuses: a+// workspace can define its own statuses, and one in the `done` category must+// count as done here or an agent reads the wrong progress. Falls back to the+// raw status when the field is absent, so an older backend still reports the+// built-in statuses correctly. (MUL-6243)+func isTerminalChildIssue(c map[string]any) bool {+ status := strVal(c, "status_category")+ if status == "" {+ status = strVal(c, "status")+ }+ return status == "done" || status == "cancelled"+}+// isHTTPURL reports whether path is an http:// or https:// URL.// Used to skip URL-shaped values passed to --attachment, which only// accepts local file paths. Trims surrounding whitespace becausediff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex a12bcbfd2c..9c3d5805d9 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -2705,18 +2705,49 @@ func TestValidIssueStatuses(t *testing.T) {}}+// TestValidateIssueStatus pins the post-MUL-6243 contract: the CLI validates+// the SHAPE of a status key, not its membership. A workspace can define custom+// statuses, so only the server knows the valid set; rejecting an unknown key+// locally would make every custom status unreachable from the CLI.func TestValidateIssueStatus(t *testing.T) {for _, s := range validIssueStatuses {if err := validateIssueStatus(s); err != nil {- t.Errorf("status %q should be valid, got: %v", s, err)+ t.Errorf("built-in status %q should be valid, got: %v", s, err)}}- err := validateIssueStatus("active")++ // Well-formed keys pass locally even though they are not built-ins — they+ // may name a custom status. The server returns a 400 listing the+ // workspace's real statuses when they do not.+ for _, s := range []string{"human_review", "gate_approved", "rework", "active", "s1"} {+ if err := validateIssueStatus(s); err != nil {+ t.Errorf("well-formed custom status key %q should pass CLI validation, got: %v", s, err)+ }+ }++ // Malformed keys are still caught locally, offline and instantly.+ for _, s := range []string{+ "", // empty+ " ", // whitespace only+ "In Review", // spaces+ "in-review", // hyphen is not in the key charset+ "_leading", // must start with a letter or digit+ "Ünicode", // non-ASCII+ strings.Repeat("a", 33), // over the 32-character limit+ } {+ if err := validateIssueStatus(s); err == nil {+ t.Errorf("malformed status key %q should be rejected", s)+ }+ }++ // The error still names the built-ins, so a user who typo'd one is pointed+ // back at the common set.+ err := validateIssueStatus("In Review")if err == nil {- t.Fatal("status \"active\" should be rejected")+ t.Fatal("expected an error for a malformed key")}if !strings.Contains(err.Error(), "backlog") {- t.Errorf("error should list valid statuses, got: %v", err)+ t.Errorf("error should list the built-in statuses, got: %v", err)}}@@ -2748,16 +2779,20 @@ func TestValidateIssuePriority(t *testing.T) {}}+// The status must be MALFORMED, not merely unknown: since MUL-6243 a workspace+// can define custom statuses, so an unknown-but-well-formed key is the server's+// call, not the CLI's. What still has to hold is that a malformed one never+// costs a network round trip.func TestRunIssueCreateRejectsInvalidStatusBeforeRequest(t *testing.T) {cmd := newIssueCreateTestCmd()_ = cmd.Flags().Set("title", "Invalid status")- _ = cmd.Flags().Set("status", "active")+ _ = cmd.Flags().Set("status", "not a status")err := runIssueCreate(cmd, nil)if err == nil {- t.Fatal("runIssueCreate should reject invalid status")+ t.Fatal("runIssueCreate should reject a malformed status")}- if !strings.Contains(err.Error(), "valid values") {- t.Fatalf("expected valid values error, got: %v", err)+ if !strings.Contains(err.Error(), "valid values") && !strings.Contains(err.Error(), "status key") {+ t.Fatalf("expected a local validation error, got: %v", err)}}@@ -2778,13 +2813,13 @@ func TestRunIssueUpdateRejectsInvalidStatusBeforeRequest(t *testing.T) {cmd := &cobra.Command{Use: "update"}cmd.Flags().String("status", "", "")cmd.Flags().String("priority", "", "")- _ = cmd.Flags().Set("status", "active")+ _ = cmd.Flags().Set("status", "not a status")err := runIssueUpdate(cmd, []string{"MUL-1"})if err == nil {- t.Fatal("runIssueUpdate should reject invalid status")+ t.Fatal("runIssueUpdate should reject a malformed status")}- if !strings.Contains(err.Error(), "valid values") {- t.Fatalf("expected valid values error, got: %v", err)+ if !strings.Contains(err.Error(), "valid values") && !strings.Contains(err.Error(), "status key") {+ t.Fatalf("expected a local validation error, got: %v", err)}}@@ -3830,3 +3865,61 @@ func TestRunIssueCommentListCompactWiring(t *testing.T) {}}}++// TestIsTerminalChildIssue pins the stage-progress terminal test used by+// `multica issue children --output json`. Since MUL-6243 a workspace can define+// custom statuses, so counting only the literal done/cancelled would report+// wrong progress to an agent reading the stage summary.+func TestIsTerminalChildIssue(t *testing.T) {+ cases := []struct {+ name string+ issue map[string]any+ want bool+ }{+ {+ name: "built-in done",+ issue: map[string]any{"status": "done", "status_category": "done"},+ want: true,+ },+ {+ name: "built-in cancelled",+ issue: map[string]any{"status": "cancelled", "status_category": "cancelled"},+ want: true,+ },+ {+ name: "built-in in_progress",+ issue: map[string]any{"status": "in_progress", "status_category": "in_progress"},+ want: false,+ },+ {+ // The case the literal comparison got wrong.+ name: "custom status in the done category",+ issue: map[string]any{"status": "gate_approved", "status_category": "done"},+ want: true,+ },+ {+ name: "custom status in the in_review category is not terminal",+ issue: map[string]any{"status": "human_review", "status_category": "in_review"},+ want: false,+ },+ {+ // Older backend: no status_category at all. Falling back to the raw+ // status keeps the built-ins correct rather than reporting zero.+ name: "no category from an older backend falls back to status",+ issue: map[string]any{"status": "done"},+ want: true,+ },+ {+ name: "unknown custom status with no category is not counted",+ issue: map[string]any{"status": "gate_approved"},+ want: false,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := isTerminalChildIssue(tc.issue); got != tc.want {+ t.Errorf("isTerminalChildIssue(%v) = %v, want %v", tc.issue, got, tc.want)+ }+ })+ }+}diff --git a/server/cmd/server/autopilot_listeners.go b/server/cmd/server/autopilot_listeners.goindex e281949a8b..425e6601c6 100644--- a/server/cmd/server/autopilot_listeners.go+++ b/server/cmd/server/autopilot_listeners.go@@ -6,6 +6,7 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/handler"+ "github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/pkg/protocol")@@ -30,8 +31,15 @@ func registerAutopilotListeners(bus *events.Bus, svc *service.AutopilotService)if !ok {return}- // Only handle statuses that finalize an autopilot run.- if issue.Status != "done" && issue.Status != "in_review" && issue.Status != "cancelled" && issue.Status != "blocked" {+ // Only handle statuses that finalize an autopilot run. This gate exists+ // to skip the issue load for routine forward progress, so it stays a+ // literal comparison for built-in keys. A custom status carries the+ // behavior of the canonical status it inherits, but resolving that+ // needs a catalog read — so let non-built-in keys through and let+ // SyncRunFromIssue normalize once it has the issue. (MUL-6243)+ if issuestatus.IsBuiltIn(issue.Status) &&+ issue.Status != "done" && issue.Status != "in_review" &&+ issue.Status != "cancelled" && issue.Status != "blocked" {return}// Load the full issue from DB to check origin_type.diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.goindex c69c981177..53f2b3cd25 100644--- a/server/cmd/server/notification_listeners.go+++ b/server/cmd/server/notification_listeners.go@@ -8,6 +8,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/handler"+ "github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -359,6 +360,12 @@ func notifyIssueSubscribers(notified := map[string]bool{}tierSuppressed := map[string]bool{}+ // Normalize a custom status to the canonical status it inherits, so the+ // delegated tier's status allowlist below keys off behavior rather than a+ // literal. A built-in key returns itself without a query, so the common+ // path is unchanged. (MUL-6243)+ issueStatus = issuestatus.Effective(ctx, queries, parseUUID(workspaceID), issueStatus)+subs, err := queries.ListIssueSubscribers(ctx, parseUUID(subscriberIssueID))if err != nil {slog.Error("failed to list subscribers for notification",@@ -755,7 +762,9 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {// cancelled), retire any stale task_failed inbox rows so the// inbox reflects the current state of the work, not its history.// The activity log keeps the full failure history for audit.- if terminalStatusForTaskFailedDismiss[issue.Status] {+ if terminalStatusForTaskFailedDismiss[issuestatus.Effective(+ ctx, queries, parseUUID(e.WorkspaceID), issue.Status,+ )] {archiveStaleTaskFailedInbox(ctx, queries, bus, e.WorkspaceID, issue.ID)}}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex b93a955717..ca95af719d 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1639,6 +1639,18 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus})})+ // Issue status catalog (MUL-6243). Reads are open to any member —+ // every client needs the catalog to render a status. Writes are+ // gated to workspace owner/admin inside the handlers.+ r.Route("/api/issue-statuses", func(r chi.Router) {+ r.Get("/", h.ListIssueStatuses)+ r.Post("/", h.CreateIssueStatus)+ r.Route("/{id}", func(r chi.Router) {+ r.Patch("/", h.UpdateIssueStatus)+ r.Delete("/", h.ArchiveIssueStatus)+ })+ })+// Projectsr.Route("/api/projects", func(r chi.Router) {r.Get("/search", h.SearchProjects)diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.goindex 46583f92d8..00b295bf64 100644--- a/server/cmd/server/runtime_sweeper.go+++ b/server/cmd/server/runtime_sweeper.go@@ -12,6 +12,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/handler"+ "github.com/multica-ai/multica/server/internal/issuestatus"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"@@ -514,7 +515,15 @@ func broadcastFailedTasks(ctx context.Context, queries *db.Queries, taskSvc *serif issue, err := queries.GetIssue(ctx, t.IssueID); err == nil {workspaceID = util.UUIDToString(issue.WorkspaceID)issueKey := util.UUIDToString(t.IssueID)- if issue.Status == "in_progress" && !processedIssues[issueKey] {+ // Only issues whose status means "an agent is actively working"+ // get reset. in_review and blocked are deliberately excluded —+ // they mean a human or an external dependency owns the issue+ // now, and resetting those to todo would re-trigger an agent on+ // work someone else is holding. A custom status resolves to the+ // canonical status it inherits, so a custom review gate is+ // excluded for the same reason In Review is. (MUL-6243)+ effectiveStatus := issuestatus.Effective(ctx, queries, issue.WorkspaceID, issue.Status)+ if effectiveStatus == "in_progress" && !processedIssues[issueKey] {processedIssues[issueKey] = trueif hasActive, herr := queries.HasActiveTaskForIssue(ctx, t.IssueID); herr == nil && !hasActive {queries.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{ID: t.IssueID, Status: "todo", WorkspaceID: issue.WorkspaceID})diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.goindex c9af98d736..0343812468 100644--- a/server/internal/featureflags/keys.go+++ b/server/internal/featureflags/keys.go@@ -23,6 +23,24 @@ const (// gate pinned Task/Run execution: disabling discovery and management must not// mutate an immutable execution manifest that is already in flight.PluginsV1 = "plugins_v1"+ // CustomIssueStatuses gates CREATING a custom issue status (MUL-6243). It is+ // a rollout gate, not a behavior switch, and it is deliberately one-way.+ //+ // The readers ship unconditionally and are safe to: issuestatus.Effective is+ // the identity function on the 7 built-in keys, so a pod running this code+ // behaves exactly as before until a custom status exists. The hazard is the+ // other direction — the first custom status written by a new pod is a value+ // an OLD pod cannot interpret, and old pods would fall back to literal+ // comparisons and mishandle the issue's events and tasks. Gating creation+ // means that value cannot come into existence until the whole fleet can read+ // it, which removes the need for a coordinated restart.+ //+ // Enable only after every pod is running this version or later. Once a+ // workspace has custom statuses, turning it back off stops new ones being+ // created but does NOT make the existing ones safe for an older binary; a+ // true rollback requires migrating those issues back to built-in statuses+ // first (migration 337's down direction refuses precisely because of this).+ CustomIssueStatuses = "custom_issue_statuses"// agentBuilderCompat is no longer a release flag. Keep publishing the key// as enabled so installed desktop clients that still gate the AI creation// entry on this config decision receive the permanently enabled behavior.@@ -58,6 +76,13 @@ func PluginsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {return flags.IsEnabled(ctx, PluginsV1, false)}+// CustomIssueStatusesEnabled reports whether creating custom issue statuses is+// allowed. Default false: a fleet mid-rollout must not be able to mint a status+// value its older pods cannot interpret.+func CustomIssueStatusesEnabled(ctx context.Context, flags *featureflag.Service) bool {+ return flags.IsEnabled(ctx, CustomIssueStatuses, false)+}+func EvaluateFrontendPublicFlags(ctx context.Context, flags *featureflag.Service) map[string]bool {out := make(map[string]bool, len(frontendPublicFlags)+3)for _, key := range frontendPublicFlags {diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 6f7324423a..98e823c267 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -22,6 +22,7 @@ import ("github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/daemonws""github.com/multica-ai/multica/server/internal/integrations/slack"+ "github.com/multica-ai/multica/server/internal/issuestatus"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/runtimeapps"@@ -4756,7 +4757,12 @@ func (h *Handler) BatchIssueGCCheck(w http.ResponseWriter, r *http.Request) {row, found := rows[canonicalIDs[i]]item := batchIssueGCCheckItem{ID: issueID, Found: found}if found {- item.Status = row.Status+ // The daemon consumes this purely as a machine signal ("is this+ // issue terminal, so its workdir can be reclaimed?") and has no+ // database of its own, so the canonical status is resolved here.+ // Normalizing server-side also means daemons that predate custom+ // statuses keep making correct GC decisions. (MUL-6243)+ item.Status = issuestatus.Effective(r.Context(), h.Queries, workspaceUUID, row.Status)updatedAt := row.UpdatedAt.Timeitem.UpdatedAt = &updatedAt}@@ -4783,7 +4789,9 @@ func (h *Handler) GetIssueGCCheck(w http.ResponseWriter, r *http.Request) {return}writeJSON(w, http.StatusOK, map[string]any{- "status": issue.Status,+ // Same reasoning as BatchIssueGCCheck: normalize server-side so the+ // daemon's terminal-status test stays correct. (MUL-6243)+ "status": issuestatus.Effective(r.Context(), h.Queries, issue.WorkspaceID, issue.Status),"updated_at": issue.UpdatedAt.Time,})}diff --git a/server/internal/handler/featureflag_test.go b/server/internal/handler/featureflag_test.goindex 683f159849..3f7c2edee3 100644--- a/server/internal/handler/featureflag_test.go+++ b/server/internal/handler/featureflag_test.go@@ -15,6 +15,10 @@ func withPluginsV1Flag(t *testing.T, h *Handler, enabled bool) {withFeatureFlag(t, h, featureflags.PluginsV1, enabled)}+func withCustomIssueStatusesFlag(t *testing.T, h *Handler, enabled bool) {+ withFeatureFlag(t, h, featureflags.CustomIssueStatuses, enabled)+}+func withFeatureFlag(t *testing.T, h *Handler, key string, enabled bool) {t.Helper()provider := featureflag.NewStaticProvider()diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex 4cfaba2160..0ba873f849 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -24,6 +24,7 @@ import ("github.com/golang-jwt/jwt/v5""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/middleware"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -1668,7 +1669,8 @@ func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype// intent was ever delivered, the user should decide manually.if state == "merged" || state == "closed" {for _, issue := range reevalIssues {- if issue.Status == "done" || issue.Status == "cancelled" {+ // A custom terminal status counts as terminal here. (MUL-6243)+ if s := issuestatus.Effective(ctx, h.Queries, issue.WorkspaceID, issue.Status); s == "done" || s == "cancelled" {continue}// Combined across providers: an issue may also carry a still-opendiff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex c17105389a..b1f7f63220 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -21,6 +21,7 @@ import ("github.com/multica-ai/multica/server/internal/channelmedia""github.com/multica-ai/multica/server/internal/dispatch""github.com/multica-ai/multica/server/internal/issueguard"+ "github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/logger""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/service"@@ -32,21 +33,27 @@ import (// IssueResponse is the JSON response for an issue.type IssueResponse struct {- ID string `json:"id"`- WorkspaceID string `json:"workspace_id"`- Number int32 `json:"number"`- Identifier string `json:"identifier"`- Title string `json:"title"`- Description *string `json:"description"`- Status string `json:"status"`- Priority string `json:"priority"`- AssigneeType *string `json:"assignee_type"`- AssigneeID *string `json:"assignee_id"`- CreatorType string `json:"creator_type"`- CreatorID string `json:"creator_id"`- ParentIssueID *string `json:"parent_issue_id"`- ProjectID *string `json:"project_id"`- Position float64 `json:"position"`+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ Number int32 `json:"number"`+ Identifier string `json:"identifier"`+ Title string `json:"title"`+ Description *string `json:"description"`+ Status string `json:"status"`+ // StatusCategory is the canonical status whose platform behavior Status+ // carries — identical to Status for the 7 built-ins, and the inherited+ // category for a custom status. Omitted when the endpoint does not resolve+ // it, so consumers must fall back to Status rather than assume a blank+ // value means "no category". (MUL-6243)+ StatusCategory string `json:"status_category,omitempty"`+ Priority string `json:"priority"`+ AssigneeType *string `json:"assignee_type"`+ AssigneeID *string `json:"assignee_id"`+ CreatorType string `json:"creator_type"`+ CreatorID string `json:"creator_id"`+ ParentIssueID *string `json:"parent_issue_id"`+ ProjectID *string `json:"project_id"`+ Position float64 `json:"position"`// Stage groups sub-issues under the same parent into ordered barrier// groups (null = unstaged). See issue_child_done.go for how a closed// stage gates the child-done -> parent wake.@@ -73,13 +80,140 @@ type IssueResponse struct {Labels *[]LabelResponse `json:"labels,omitempty"`}-// validIssueStatuses / validIssuePriorities mirror the CHECK constraints on-// the issue table. Write handlers pre-validate these so callers get a clean-// 400 with the allowed values instead of a database CHECK violation bubbling-// up as a 500.-var validIssueStatuses = []string{"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"}+// validIssuePriorities mirrors the CHECK constraint on the issue table. Write+// handlers pre-validate it so callers get a clean 400 with the allowed values+// instead of a database CHECK violation bubbling up as a 500.var validIssuePriorities = []string{"urgent", "high", "medium", "low", "none"}+// validIssueStatuses is the 7 BUILT-IN status keys. Since MUL-6243 it is no+// longer the set of writable statuses — write paths validate against the+// workspace's catalog via validateIssueStatusKey — and it survives only for the+// issue-table grouping/filtering paths, which key their group descriptors and+// compound cells off a fixed status list.+//+// KNOWN LIMITATION: a custom status is therefore not yet selectable as an+// issue-table group or filter value. That is a self-contained follow-up (the+// table's group descriptors and compound cell keys need to become catalog+// driven); it is scoped out here so this change cannot alter the table view for+// workspaces that have no custom statuses.+var validIssueStatuses = issuestatus.Canonical()++// resolveIssueStatusKey checks a status against the workspace's catalog and+// returns the CANONICAL key to store. This is the application-layer replacement+// for the enum CHECK that migration 337 dropped, so every write path must route+// through it — a missed entrypoint is how an unresolvable key would reach the+// column.+//+// Returning the resolved key (rather than a bare bool) is load-bearing:+// resolution is case- and whitespace-insensitive, so `" HUMAN_REVIEW "` and+// `"human_review"` both validate. Writing the caller's raw string back would+// then store a value the column's format constraint rejects, turning an input+// the API just accepted into a 500. Callers must persist what this returns.+func (h *Handler) resolveIssueStatusKey(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, status string) (string, bool) {+ key, _, ok := h.resolveIssueStatusKeyKind(w, r, workspaceID, status)+ return key, ok+}++// resolveIssueStatusKeyKind is resolveIssueStatusKey plus whether the target is+// a CUSTOM status. Callers use that to decide whether the write needs the+// shared catalog lock — see runWithIssueStatusGuard.+func (h *Handler) resolveIssueStatusKeyKind(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, status string) (string, bool, bool) {+ entry, err := issuestatus.Resolve(r.Context(), h.Queries, workspaceID, status)+ if err != nil {+ if errors.Is(err, issuestatus.ErrUnknownStatus) {+ allowed, listErr := issuestatus.ActiveKeys(r.Context(), h.Queries, workspaceID)+ if listErr != nil || len(allowed) == 0 {+ allowed = issuestatus.Canonical()+ }+ writeError(w, http.StatusBadRequest, fmt.Sprintf(+ "invalid status %q; valid values: %s", status, strings.Join(allowed, ", ")))+ return "", false, false+ }+ slog.Warn("resolve issue status failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to validate status")+ return "", false, false+ }+ return entry.Key, !entry.IsSystem, true+}++// errIssueStatusArchivedRace signals that the target custom status was archived+// between the request's pre-flight validation and the write itself. Callers map+// it to 409: the request was valid when it arrived, and retrying against the+// refreshed catalog is the right remedy.+var errIssueStatusArchivedRace = errors.New("issue status was archived while the write was in flight")++// assertIssueStatusStillActive is the write half of the archive race guard. It+// takes the SHARED catalog lock and RE-RESOLVES the status inside the caller's+// transaction.+//+// The re-resolve is the part that actually closes the race. Handlers resolve a+// status up front, before any transaction, to answer a bad request with a clean+// 400 — but an archive can commit between that pre-flight check and the write.+// Re-checking here, under the lock, means the status is provably active at the+// moment the row is written. ArchiveIssueStatus holds the EXCLUSIVE side around+// its in-use census, so the two orderings are both covered:+//+// - archive first: it commits, this re-resolve then fails and the write is+// rejected, so no issue is stranded on an archived status;+// - writer first: the census blocks until this transaction commits, then sees+// the issue and refuses the archive with a conflict.+//+// A built-in status is a no-op: it can never be archived (enforced by+// issue_status_system_not_archivable), so the common path takes no lock and+// pays nothing. (MUL-6243)+func assertIssueStatusStillActive(ctx context.Context, qtx *db.Queries, workspaceID pgtype.UUID, statusKey string) error {+ if statusKey == "" || issuestatus.IsBuiltIn(statusKey) {+ return nil+ }+ // Catalog lock before any row lock, everywhere, so the two write paths+ // cannot deadlock against each other.+ if err := qtx.LockIssueStatusCatalogShared(ctx, workspaceID); err != nil {+ return err+ }+ if _, err := issuestatus.Resolve(ctx, qtx, workspaceID, statusKey); err != nil {+ if errors.Is(err, issuestatus.ErrUnknownStatus) {+ return errIssueStatusArchivedRace+ }+ return err+ }+ return nil+}++// runWithIssueStatusGuard runs an issue write that lands on a custom status+// inside a transaction that re-verifies the status under the shared catalog+// lock (see assertIssueStatusStillActive). A built-in target skips the+// transaction entirely.+func (h *Handler) runWithIssueStatusGuard(ctx context.Context, workspaceID pgtype.UUID, statusKey string, fn func(q *db.Queries) error) error {+ if statusKey == "" || issuestatus.IsBuiltIn(statusKey) {+ return fn(h.Queries)+ }+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)++ qtx := h.Queries.WithTx(tx)+ if err := assertIssueStatusStillActive(ctx, qtx, workspaceID, statusKey); err != nil {+ return err+ }+ if err := fn(qtx); err != nil {+ return err+ }+ return tx.Commit(ctx)+}++// writeIssueStatusRaceError renders errIssueStatusArchivedRace as a 409 and+// reports whether it handled the error.+func writeIssueStatusRaceError(w http.ResponseWriter, err error) bool {+ if errors.Is(err, errIssueStatusArchivedRace) {+ writeError(w, http.StatusConflict,+ "the target status was archived while this request was in flight; reload the status list and retry")+ return true+ }+ return false+}+func validateIssueEnum(w http.ResponseWriter, field, value string, allowed []string) bool {for _, a := range allowed {if value == a {@@ -475,7 +609,7 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,whereClause := "(" + strings.Join(whereParts, " OR ") + ")"if !includeClosed {- whereClause += " AND i.status NOT IN ('done', 'cancelled')"+ whereClause += " AND issue_effective_status(i.workspace_id, i.status) NOT IN ('done', 'cancelled')"}// --- ORDER BY clause ---@@ -1946,9 +2080,16 @@ func (h *Handler) ListChildIssues(w http.ResponseWriter, r *http.Request) {ids[i] = child.ID}labelsMap := h.labelsByIssue(r.Context(), issue.WorkspaceID, ids)+ // Sub-issue progress is computed from these rows (the CLI's `issue children`+ // stage counts, among others), so they carry the resolved category — a+ // custom done status must count as done. One Resolver for the whole list:+ // built-in statuses still cost no query, and a list full of custom ones+ // costs one catalog read rather than one per row.+ statusResolver := issuestatus.NewResolver(issue.WorkspaceID)resp := make([]IssueResponse, len(children))for i, child := range children {resp[i] = issueToResponse(child, prefix)+ resp[i].StatusCategory = statusResolver.Effective(r.Context(), h.Queries, child.Status)labels := labelsMap[resp[i].ID]if labels == nil {labels = []LabelResponse{}@@ -2025,9 +2166,16 @@ func (h *Handler) ListChildrenByParents(w http.ResponseWriter, r *http.Request)ids[i] = child.ID}labelsMap := h.labelsByIssue(r.Context(), wsUUID, ids)+ // Sub-issue progress is computed from these rows (the CLI's `issue children`+ // stage counts, among others), so they carry the resolved category — a+ // custom done status must count as done. One Resolver for the whole list:+ // built-in statuses still cost no query, and a list full of custom ones+ // costs one catalog read rather than one per row.+ statusResolver := issuestatus.NewResolver(wsUUID)resp := make([]IssueResponse, len(children))for i, child := range children {resp[i] = issueToResponse(child, prefix)+ resp[i].StatusCategory = statusResolver.Effective(r.Context(), h.Queries, child.Status)labels := labelsMap[resp[i].ID]if labels == nil {labels = []LabelResponse{}@@ -2471,7 +2619,8 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {if priority == "" {priority = "none"}- if !validateIssueEnum(w, "status", status, validIssueStatuses) {+ status, ok = h.resolveIssueStatusKey(w, r, wsUUID, status)+ if !ok {return}if !validateIssueEnum(w, "priority", priority, validIssuePriorities) {@@ -2691,6 +2840,11 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "one or more labels not found in this workspace")return}+ if errors.Is(err, service.ErrIssueStatusUnavailable) {+ writeError(w, http.StatusConflict,+ "the target status was archived while this request was in flight; reload the status list and retry")+ return+ }if err != nil {slog.Warn("create issue failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)writeError(w, http.StatusInternalServerError, "failed to create issue: "+err.Error())@@ -2824,7 +2978,7 @@ func refreshUntouchedNullableIssueParams(params *db.UpdateIssueParams, current d}}-func (h *Handler) updateIssueWithDescriptionMerge(ctx context.Context, workspaceID pgtype.UUID, params db.UpdateIssueParams, rawFields map[string]json.RawMessage, base *string) (db.Issue, db.Issue, error) {+func (h *Handler) updateIssueWithDescriptionMerge(ctx context.Context, workspaceID pgtype.UUID, params db.UpdateIssueParams, rawFields map[string]json.RawMessage, base *string, statusKey string) (db.Issue, db.Issue, error) {if h.TxStarter == nil {return db.Issue{}, db.Issue{}, errors.New("issue description update requires transaction starter")}@@ -2835,6 +2989,12 @@ func (h *Handler) updateIssueWithDescriptionMerge(ctx context.Context, workspacedefer tx.Rollback(ctx)qtx := h.Queries.WithTx(tx)+ // This path opens its own transaction, so it carries the archive-race guard+ // itself rather than going through runWithIssueStatusGuard. Taken before the+ // row lock below to keep the global catalog-then-row lock order. (MUL-6243)+ if err := assertIssueStatusStillActive(ctx, qtx, workspaceID, statusKey); err != nil {+ return db.Issue{}, db.Issue{}, err+ }current, err := qtx.LockIssueForDescriptionUpdate(ctx, db.LockIssueForDescriptionUpdateParams{ID: params.ID,WorkspaceID: workspaceID,@@ -2919,11 +3079,17 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {if req.Description != nil {params.Description = pgtype.Text{String: *req.Description, Valid: true}}+ // statusKeyForGuard is the resolved key when this request sets a status, and+ // empty otherwise. Empty means "this write does not touch status", which the+ // guard treats as nothing to protect.+ statusKeyForGuard := ""if req.Status != nil {- if !validateIssueEnum(w, "status", *req.Status, validIssueStatuses) {+ statusKey, _, ok := h.resolveIssueStatusKeyKind(w, r, prevIssue.WorkspaceID, *req.Status)+ if !ok {return}- params.Status = pgtype.Text{String: *req.Status, Valid: true}+ statusKeyForGuard = statusKey+ params.Status = pgtype.Text{String: statusKey, Valid: true}}if req.Priority != nil {if !validateIssueEnum(w, "priority", *req.Priority, validIssuePriorities) {@@ -3073,15 +3239,22 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {if req.Description != nil {var lockedPrev db.Issueissue, lockedPrev, err = h.updateIssueWithDescriptionMerge(- r.Context(), prevIssue.WorkspaceID, params, rawFields, req.DescriptionBase,+ r.Context(), prevIssue.WorkspaceID, params, rawFields, req.DescriptionBase, statusKeyForGuard,)if err == nil {prevIssue = lockedPrev}} else {- issue, err = h.Queries.UpdateIssue(r.Context(), params)+ err = h.runWithIssueStatusGuard(r.Context(), prevIssue.WorkspaceID, statusKeyForGuard, func(q *db.Queries) error {+ var innerErr error+ issue, innerErr = q.UpdateIssue(r.Context(), params)+ return innerErr+ })}if err != nil {+ if writeIssueStatusRaceError(w, err) {+ return+ }slog.Warn("update issue failed", append(logger.RequestAttrs(r), "error", err, "issue_id", id, "workspace_id", workspaceID)...)writeError(w, http.StatusInternalServerError, "failed to update issue: "+err.Error())return@@ -3258,7 +3431,8 @@ func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, wor// triggering execution. Moving out of backlog is handled separately in// UpdateIssue.func (h *Handler) shouldEnqueueAgentTask(ctx context.Context, issue db.Issue) bool {- if issue.Status == "backlog" {+ // A custom status in the backlog category parks like Backlog. (MUL-6243)+ if issuestatus.Effective(ctx, h.Queries, issue.WorkspaceID, issue.Status) == "backlog" {return false}return h.isAgentAssigneeReady(ctx, issue)@@ -3493,11 +3667,6 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, map[string]any{"updated": 0})return}- if req.Updates.Status != nil {- if !validateIssueEnum(w, "status", *req.Updates.Status, validIssueStatuses) {- return- }- }if req.Updates.Priority != nil {if !validateIssueEnum(w, "priority", *req.Updates.Priority, validIssuePriorities) {return@@ -3509,6 +3678,17 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {if !ok {return}+ // Status is validated against this workspace's catalog, so it has to wait+ // for wsUUID above. One check for the whole batch — every issue in it+ // shares the workspace — and a rejection rather than a silent skip, so a+ // bad status cannot report `{"updated": N}`. (MUL-6243)+ batchStatusKey := ""+ if req.Updates.Status != nil {+ batchStatusKey, _, ok = h.resolveIssueStatusKeyKind(w, r, wsUUID, *req.Updates.Status)+ if !ok {+ return+ }+ }// The batch shares one project_id, so it is checked once here rather than// per issue, and rejected instead of skipped like the per-item guards in// the loop: a foreign project invalidates the whole request.@@ -3570,7 +3750,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {params.Description = pgtype.Text{String: *req.Updates.Description, Valid: true}}if req.Updates.Status != nil {- params.Status = pgtype.Text{String: *req.Updates.Status, Valid: true}+ params.Status = pgtype.Text{String: batchStatusKey, Valid: true}}if req.Updates.Priority != nil {params.Priority = pgtype.Text{String: *req.Updates.Priority, Valid: true}@@ -3690,15 +3870,25 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {// legacy single-update clients that omit description_base.var lockedPrev db.Issueissue, lockedPrev, err = h.updateIssueWithDescriptionMerge(- r.Context(), prevIssue.WorkspaceID, params, rawUpdates, nil,+ r.Context(), prevIssue.WorkspaceID, params, rawUpdates, nil, batchStatusKey,)if err == nil {prevIssue = lockedPrev}} else {- issue, err = h.Queries.UpdateIssue(r.Context(), params)+ err = h.runWithIssueStatusGuard(r.Context(), wsUUID, batchStatusKey, func(q *db.Queries) error {+ var innerErr error+ issue, innerErr = q.UpdateIssue(r.Context(), params)+ return innerErr+ })}if err != nil {+ // The archive race is a property of the batch's shared target+ // status, not of one issue, so every remaining item would fail the+ // same way. Abort with 409 instead of reporting a partial update.+ if writeIssueStatusRaceError(w, err) {+ return+ }slog.Warn("batch update issue failed", "issue_id", issueID, "error", err)continue}@@ -3750,9 +3940,19 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {// notifyParentsOfBatchChildDone below evaluate each parent once against// the batch's final committed state. Same transition guard as// notifyParentOfChildDone: a non-terminal -> terminal move on a child.- if statusChanged && issue.ParentIssueID.Valid &&- !isTerminalChildStatus(prevIssue.Status) && isTerminalChildStatus(issue.Status) {- childDoneCompleted = append(childDoneCompleted, issue)+ // Resolve both sides to the canonical status they inherit before the+ // terminal test, so a batch that moves the last child onto a CUSTOM+ // done/cancelled status still enters the stage barrier below. A literal+ // comparison here left childDoneCompleted empty and silently skipped+ // notifyParentsOfBatchChildDone entirely. (MUL-6243)+ if statusChanged && issue.ParentIssueID.Valid {+ prevTerminal := isTerminalChildStatus(+ issuestatus.Effective(r.Context(), h.Queries, prevIssue.WorkspaceID, prevIssue.Status))+ nowTerminal := isTerminalChildStatus(+ issuestatus.Effective(r.Context(), h.Queries, issue.WorkspaceID, issue.Status))+ if !prevTerminal && nowTerminal {+ childDoneCompleted = append(childDoneCompleted, issue)+ }}updated++diff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.goindex 2df0736e80..b072187d68 100644--- a/server/internal/handler/issue_child_done.go+++ b/server/internal/handler/issue_child_done.go@@ -9,6 +9,7 @@ import ("strings""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/issuestatus"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -76,7 +77,12 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Is// last open child of a stage is cancelled. Keying on the transition also// makes a later cancelled -> done edit a no-op (terminal -> terminal), which// avoids a lagging duplicate wake.- if isTerminalChildStatus(prev.Status) || !isTerminalChildStatus(issue.Status) {+ // Both sides of the transition are resolved to the canonical status they+ // inherit, so a move into a custom done/cancelled status fires the barrier+ // exactly like a move into Done or Cancelled. (MUL-6243)+ prevTerminal := isTerminalChildStatus(issuestatus.Effective(ctx, h.Queries, prev.WorkspaceID, prev.Status))+ nowTerminal := isTerminalChildStatus(issuestatus.Effective(ctx, h.Queries, issue.WorkspaceID, issue.Status))+ if prevTerminal || !nowTerminal {return}parent, err := h.Queries.GetIssue(ctx, issue.ParentIssueID)@@ -87,7 +93,11 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Is"parent_id", uuidToString(issue.ParentIssueID))return}- if parent.Status == "done" || parent.Status == "cancelled" {+ // Custom statuses inherit the canonical status they name, so a custom+ // terminal status closes this out and a custom backlog status parks it,+ // exactly like Done/Cancelled and Backlog do. (MUL-6243)+ parentStatus := issuestatus.Effective(ctx, h.Queries, parent.WorkspaceID, parent.Status)+ if parentStatus == "done" || parentStatus == "cancelled" {return}// A parent parked in backlog is deliberately held for later. Posting the@@ -95,7 +105,7 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Is// promote sibling backlog sub-issues into todo — the surprise auto-// activation reported in #4320 / MUL-3497. Skip the whole notification so// a backlog parent stays inert until the user explicitly promotes it.- if parent.Status == "backlog" {+ if parentStatus == "backlog" {return}// Human-assigned parents read their own timeline; an automated system@@ -121,7 +131,7 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Is"parent_id", uuidToString(parent.ID))return}- if !stageBarrierClosed(children, issue) {+ if !stageBarrierClosed(children, issue, h.terminalChildPredicate(ctx)) {return}staged := siblingsAreStaged(children)@@ -185,10 +195,11 @@ func (h *Handler) notifyParentsOfBatchChildDone(ctx context.Context, completed [continue}// Same parent guards as the single path (see notifyParentOfChildDone).- if parent.Status == "done" || parent.Status == "cancelled" {+ parentStatus := issuestatus.Effective(ctx, h.Queries, parent.WorkspaceID, parent.Status)+ if parentStatus == "done" || parentStatus == "cancelled" {continue}- if parent.Status == "backlog" {+ if parentStatus == "backlog" {continue}if parent.AssigneeType.Valid && parent.AssigneeType.String == "member" {@@ -202,12 +213,13 @@ func (h *Handler) notifyParentsOfBatchChildDone(ctx context.Context, completed [continue}+ isTerminal := h.terminalChildPredicate(ctx)batch := len(g.children) > 1if !siblingsAreStaged(children) {// Unstaged: one implicit stage. Fire once iff every child is terminal// in the final state. stageBarrierClosed ignores `completed` on the// unstaged path, so any completed child stands in for the barrier check.- if !stageBarrierClosed(children, g.children[0]) {+ if !stageBarrierClosed(children, g.children[0], isTerminal) {continue}h.postChildDoneComment(ctx, parent, g.children[0], children, false, 0, batch)@@ -229,7 +241,7 @@ func (h *Handler) notifyParentsOfBatchChildDone(ctx context.Context, completed [if !c.Stage.Valid {continue // an unstaged child in a staged set closes no stage}- if !stageBarrierClosed(children, c) {+ if !stageBarrierClosed(children, c, isTerminal) {continue}if !found || c.Stage.Int32 > bestStage {@@ -270,7 +282,7 @@ func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed dbvar content stringif staged {- summary, nextStage := stageProgressSummary(children, closedStage)+ summary, nextStage := stageProgressSummary(children, closedStage, h.terminalChildPredicate(ctx))advance := stageAdvanceInstruction(nextStage, parentID)if batch {content = fmt.Sprintf(@@ -337,10 +349,28 @@ func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed db// isTerminalChildStatus reports whether a child issue status counts as// "finished" for stage-barrier purposes. Cancelled counts as terminal: a// cancelled sibling will never complete, so it must not hold a stage open.+//+// Takes a CANONICAL status. Callers that hold a raw `issue.status` must pass it+// through terminalChildPredicate first, so a custom status in the done or+// cancelled category closes a stage exactly like Done and Cancelled do.func isTerminalChildStatus(status string) bool {return status == "done" || status == "cancelled"}+// terminalChildPredicate returns the terminal test for a sibling set, resolving+// each child's status to the canonical status it inherits. Built-in keys+// resolve to themselves without a query, so this is free for every workspace+// that has not defined a custom status. (MUL-6243)+//+// A predicate rather than a rewritten []db.Issue on purpose: the same slice is+// also rendered into the stage-progress comment, and mutating Status there+// would show the category instead of the status the user actually picked.+func (h *Handler) terminalChildPredicate(ctx context.Context) func(db.Issue) bool {+ return func(c db.Issue) bool {+ return isTerminalChildStatus(issuestatus.Effective(ctx, h.Queries, c.WorkspaceID, c.Status))+ }+}+// siblingsAreStaged reports whether any child in the set carries an explicit// stage. A set with no stages is treated as a single implicit stage.func siblingsAreStaged(children []db.Issue) bool {@@ -367,10 +397,10 @@ func siblingsAreStaged(children []db.Issue) bool {// stage <= S is terminal (frontier closure). Later stages are normally// parked in `backlog`, so they cannot fire out of order; the caller's// idempotency guard collapses any duplicate wake.-func stageBarrierClosed(children []db.Issue, completed db.Issue) bool {+func stageBarrierClosed(children []db.Issue, completed db.Issue, isTerminal func(db.Issue) bool) bool {if !siblingsAreStaged(children) {for _, c := range children {- if !isTerminalChildStatus(c.Status) {+ if !isTerminal(c) {return false}}@@ -386,7 +416,7 @@ func stageBarrierClosed(children []db.Issue, completed db.Issue) bool {if !c.Stage.Valid {continue // unstaged children are ignored by the frontier}- if c.Stage.Int32 <= s && !isTerminalChildStatus(c.Status) {+ if c.Stage.Int32 <= s && !isTerminal(c) {return false}}@@ -399,7 +429,7 @@ func stageBarrierClosed(children []db.Issue, completed db.Issue) bool {// children — the next group to promote — or 0 when none remain. Unstaged// children are skipped (they are not part of any stage), so the breakdown// never renders a "Stage 0".-func stageProgressSummary(children []db.Issue, closedStage int32) (summary string, nextStage int32) {+func stageProgressSummary(children []db.Issue, closedStage int32, isTerminal func(db.Issue) bool) (summary string, nextStage int32) {type agg struct{ total, done int }byStage := map[int32]*agg{}order := []int32{}@@ -415,7 +445,7 @@ func stageProgressSummary(children []db.Issue, closedStage int32) (summary strinorder = append(order, s)}a.total++- if isTerminalChildStatus(c.Status) {+ if isTerminal(c) {a.done++}}diff --git a/server/internal/handler/issue_child_done_stage_test.go b/server/internal/handler/issue_child_done_stage_test.goindex 130433e2d3..fc4e90e5da 100644--- a/server/internal/handler/issue_child_done_stage_test.go+++ b/server/internal/handler/issue_child_done_stage_test.go@@ -49,7 +49,7 @@ func TestStageBarrierClosed_Unstaged(t *testing.T) {t.Run(tt.name, func(t *testing.T) {// completed is one of the terminal children; identity doesn't matter// for the unstaged path.- if got := stageBarrierClosed(tt.children, child(0, "done")); got != tt.want {+ if got := stageBarrierClosed(tt.children, child(0, "done"), literalTerminalChild); got != tt.want {t.Fatalf("stageBarrierClosed = %v, want %v", got, tt.want)}})@@ -64,7 +64,7 @@ func TestStageBarrierClosed_Staged(t *testing.T) {child(2, "backlog"), child(2, "backlog"),child(3, "backlog"),}- if stageBarrierClosed(children, child(1, "done")) {+ if stageBarrierClosed(children, child(1, "done"), literalTerminalChild) {t.Fatal("expected barrier not closed while stage 1 has an open child")}})@@ -75,7 +75,7 @@ func TestStageBarrierClosed_Staged(t *testing.T) {child(2, "backlog"), child(2, "backlog"),child(3, "backlog"),}- if !stageBarrierClosed(children, child(1, "done")) {+ if !stageBarrierClosed(children, child(1, "done"), literalTerminalChild) {t.Fatal("expected stage 1 barrier to close")}})@@ -86,7 +86,7 @@ func TestStageBarrierClosed_Staged(t *testing.T) {child(2, "done"), child(2, "done"),child(3, "backlog"),}- if !stageBarrierClosed(children, child(2, "done")) {+ if !stageBarrierClosed(children, child(2, "done"), literalTerminalChild) {t.Fatal("expected stage 2 barrier to close")}})@@ -97,7 +97,7 @@ func TestStageBarrierClosed_Staged(t *testing.T) {child(2, "done"), child(2, "done"),child(3, "done"),}- if !stageBarrierClosed(children, child(3, "done")) {+ if !stageBarrierClosed(children, child(3, "done"), literalTerminalChild) {t.Fatal("expected final stage barrier to close")}})@@ -109,7 +109,7 @@ func TestStageProgressSummary(t *testing.T) {child(2, "backlog"), child(2, "backlog"), child(2, "backlog"), child(2, "backlog"),child(3, "backlog"), child(3, "backlog"),}- summary, next := stageProgressSummary(children, 1)+ summary, next := stageProgressSummary(children, 1, literalTerminalChild)want := "Stage 1: 3/3 done; Stage 2: 0/4 done (next); Stage 3: 0/2 done"if summary != want {t.Fatalf("summary = %q, want %q", summary, want)@@ -124,7 +124,7 @@ func TestStageProgressSummary_FinalStageNoNext(t *testing.T) {child(1, "done"), child(1, "done"),child(2, "done"),}- _, next := stageProgressSummary(children, 2)+ _, next := stageProgressSummary(children, 2, literalTerminalChild)if next != 0 {t.Fatalf("nextStage = %d, want 0 (no further stages)", next)}@@ -137,7 +137,7 @@ func TestStageProgressSummary_SkipsUnstaged(t *testing.T) {child(1, "done"), child(1, "done"),child(2, "backlog"),}- summary, next := stageProgressSummary(children, 1)+ summary, next := stageProgressSummary(children, 1, literalTerminalChild)want := "Stage 1: 2/2 done; Stage 2: 0/1 done (next)"if summary != want {t.Fatalf("summary = %q, want %q", summary, want)@@ -193,13 +193,13 @@ func TestStageBarrierClosed_CancelledClosesStage(t *testing.T) {child(1, "done"), child(1, "cancelled"),child(2, "backlog"),}- if !stageBarrierClosed(children, child(1, "cancelled")) {+ if !stageBarrierClosed(children, child(1, "cancelled"), literalTerminalChild) {t.Fatal("expected the stage to close when its last open child is cancelled")}})t.Run("unstaged: cancel of the last open child closes the implicit stage", func(t *testing.T) {children := []db.Issue{child(0, "done"), child(0, "cancelled")}- if !stageBarrierClosed(children, child(0, "cancelled")) {+ if !stageBarrierClosed(children, child(0, "cancelled"), literalTerminalChild) {t.Fatal("expected the implicit stage to close on cancel")}})@@ -213,7 +213,7 @@ func TestStageBarrierClosed_UnstagedIgnoredInStagedSet(t *testing.T) {child(1, "done"), child(1, "done"),child(0, "backlog"), // unstaged, still open — must NOT block}- if !stageBarrierClosed(children, child(1, "done")) {+ if !stageBarrierClosed(children, child(1, "done"), literalTerminalChild) {t.Fatal("expected stage 1 to close; an unstaged child must not hold it open")}})@@ -222,8 +222,17 @@ func TestStageBarrierClosed_UnstagedIgnoredInStagedSet(t *testing.T) {child(1, "backlog"),child(0, "done"), // the just-completed unstaged child}- if stageBarrierClosed(children, child(0, "done")) {+ if stageBarrierClosed(children, child(0, "done"), literalTerminalChild) {t.Fatal("an unstaged child's completion must not fire a stage barrier")}})}++// literalTerminalChild is the pre-MUL-6243 terminal test: it reads the status+// literal directly, with no catalog resolution. The stage-barrier logic these+// tests cover is pure and operates on CANONICAL statuses, so pinning it with a+// literal predicate keeps them testing the barrier itself rather than status+// resolution (which has its own coverage in issue_status_test.go).+func literalTerminalChild(c db.Issue) bool {+ return isTerminalChildStatus(c.Status)+}diff --git a/server/internal/handler/issue_status.go b/server/internal/handler/issue_status.gonew file mode 100644index 0000000000..0e97f63c36--- /dev/null+++ b/server/internal/handler/issue_status.go@@ -0,0 +1,385 @@+package handler++import (+ "encoding/json"+ "errors"+ "log/slog"+ "net/http"+ "strings"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/featureflags"+ "github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/logger"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Issue status catalog API (MUL-6243).+//+// Reading the catalog is open to any workspace member — every client needs it+// to render a status. Mutating it is owner/admin only: a status is workflow+// configuration shared by the whole workspace, and creating one changes what+// agents can be told to do.++type IssueStatusResponse struct {+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ Key string `json:"key"`+ Name string `json:"name"`+ Description string `json:"description"`+ Category string `json:"category"`+ Color string `json:"color"`+ IsSystem bool `json:"is_system"`+ Position float64 `json:"position"`+ ArchivedAt *string `json:"archived_at"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++func issueStatusToResponse(s db.IssueStatus) IssueStatusResponse {+ return IssueStatusResponse{+ ID: uuidToString(s.ID),+ WorkspaceID: uuidToString(s.WorkspaceID),+ Key: s.Key,+ Name: s.Name,+ Description: s.Description,+ Category: s.Category,+ Color: s.Color,+ IsSystem: s.IsSystem,+ Position: s.Position,+ ArchivedAt: timestampToPtr(s.ArchivedAt),+ CreatedAt: timestampToString(s.CreatedAt),+ UpdatedAt: timestampToString(s.UpdatedAt),+ }+}++type CreateIssueStatusRequest struct {+ // Key is optional; it is derived from Name when omitted. Immutable once+ // created, because it is the value stored in issue.status.+ Key string `json:"key"`+ Name string `json:"name"`+ Description string `json:"description"`+ Category string `json:"category"`+ Color string `json:"color"`+}++// UpdateIssueStatusRequest deliberately has no Key or Category field. Both are+// immutable: changing a category would silently rewrite the machine semantics+// of every issue already on that status, and changing a key would strand them.+type UpdateIssueStatusRequest struct {+ Name *string `json:"name"`+ Description *string `json:"description"`+ Color *string `json:"color"`+ Position *float64 `json:"position"`+}++// ListIssueStatuses returns the workspace's status catalog in display order.+// Any member may read it.+func (h *Handler) ListIssueStatuses(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ if _, ok := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found"); !ok {+ return+ }++ // Self-heal: a workspace created by a pod that predates this feature has no+ // catalog rows. Seeding on read keeps the endpoint correct during a rolling+ // deploy without a second backfill pass. Idempotent, so this is a no-op+ // once the rows exist.+ if err := issuestatus.Ensure(r.Context(), h.Queries, wsUUID); err != nil {+ slog.Warn("failed to ensure issue status catalog", append(logger.RequestAttrs(r), "error", err)...)+ }++ includeArchived := strings.EqualFold(r.URL.Query().Get("include_archived"), "true")+ entries, err := h.Queries.ListIssueStatusEntries(r.Context(), db.ListIssueStatusEntriesParams{+ WorkspaceID: wsUUID,+ IncludeArchived: includeArchived,+ })+ if err != nil {+ slog.Warn("ListIssueStatuses failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to list issue statuses")+ return+ }++ resp := make([]IssueStatusResponse, len(entries))+ for i, e := range entries {+ resp[i] = issueStatusToResponse(e)+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "statuses": resp,+ "categories": issuestatus.Canonical(),+ "total": len(resp),+ })+}++// CreateIssueStatus adds a custom status to the workspace catalog.+func (h *Handler) CreateIssueStatus(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ if _, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin"); !ok {+ return+ }++ // Rollout gate (see featureflags.CustomIssueStatuses). Creating the first+ // custom status mints a value older pods cannot interpret, so it stays+ // closed until the whole fleet is running code that resolves categories.+ // Only creation is gated — reading and resolving are safe unconditionally.+ if !featureflags.CustomIssueStatusesEnabled(r.Context(), h.FeatureFlags) {+ writeError(w, http.StatusForbidden, "custom issue statuses are not enabled for this deployment")+ return+ }++ var req CreateIssueStatusRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ name := strings.TrimSpace(req.Name)+ if name == "" || len([]rune(name)) > 64 {+ writeError(w, http.StatusBadRequest, "name must be 1-64 characters")+ return+ }+ if len([]rune(req.Description)) > 256 {+ writeError(w, http.StatusBadRequest, "description must be at most 256 characters")+ return+ }+ if !issuestatus.IsCategory(req.Category) {+ writeError(w, http.StatusBadRequest, "category must be one of: "+strings.Join(issuestatus.Canonical(), ", "))+ return+ }+ color, err := normalizeColor(req.Color)+ if err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }++ // An explicit key wins; otherwise derive one from the name so the common+ // case is a single field. Either way it is validated against the reserved+ // built-in keys and the storage pattern.+ var key string+ if strings.TrimSpace(req.Key) != "" {+ key, err = issuestatus.ValidateKey(req.Key)+ } else {+ key, err = issuestatus.SlugifyKey(name)+ }+ if err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }++ entry, err := h.Queries.CreateIssueStatusEntry(r.Context(), db.CreateIssueStatusEntryParams{+ WorkspaceID: wsUUID,+ Key: key,+ Name: name,+ Description: req.Description,+ Category: req.Category,+ Color: strings.ToLower(color),+ })+ if err != nil {+ if isUniqueViolation(err) {+ writeError(w, http.StatusConflict, "a status with this key or name already exists")+ return+ }+ slog.Warn("CreateIssueStatus failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to create issue status")+ return+ }+ writeJSON(w, http.StatusCreated, issueStatusToResponse(entry))+}++// UpdateIssueStatus edits a custom status's presentation. Built-in statuses are+// immutable in v1 — name and color included — so the default workspace looks+// and behaves identically for everyone who never opens this settings page.+func (h *Handler) UpdateIssueStatus(w http.ResponseWriter, r *http.Request) {+ entry, wsUUID, ok := h.loadIssueStatusForAdmin(w, r)+ if !ok {+ return+ }++ var req UpdateIssueStatusRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ if entry.IsSystem {+ writeError(w, http.StatusForbidden, "built-in statuses cannot be modified")+ return+ }+ if entry.ArchivedAt.Valid {+ writeError(w, http.StatusConflict, "archived statuses cannot be modified")+ return+ }++ var name pgtype.Text+ if req.Name != nil {+ trimmed := strings.TrimSpace(*req.Name)+ if trimmed == "" || len([]rune(trimmed)) > 64 {+ writeError(w, http.StatusBadRequest, "name must be 1-64 characters")+ return+ }+ name = pgtype.Text{String: trimmed, Valid: true}+ }+ var description pgtype.Text+ if req.Description != nil {+ if len([]rune(*req.Description)) > 256 {+ writeError(w, http.StatusBadRequest, "description must be at most 256 characters")+ return+ }+ description = pgtype.Text{String: *req.Description, Valid: true}+ }+ var color pgtype.Text+ if req.Color != nil {+ normalized, err := normalizeColor(*req.Color)+ if err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }+ color = pgtype.Text{String: strings.ToLower(normalized), Valid: true}+ }+ var position pgtype.Float8+ if req.Position != nil {+ position = pgtype.Float8{Float64: *req.Position, Valid: true}+ }++ updated, err := h.Queries.UpdateIssueStatusEntry(r.Context(), db.UpdateIssueStatusEntryParams{+ ID: entry.ID,+ WorkspaceID: wsUUID,+ Name: name,+ Description: description,+ Color: color,+ Position: position,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ // The row moved out from under us (archived concurrently, or the+ // is_system guard in the statement rejected it).+ writeError(w, http.StatusConflict, "status is no longer editable")+ return+ }+ if isUniqueViolation(err) {+ writeError(w, http.StatusConflict, "a status with this name already exists")+ return+ }+ slog.Warn("UpdateIssueStatus failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to update issue status")+ return+ }+ writeJSON(w, http.StatusOK, issueStatusToResponse(updated))+}++// ArchiveIssueStatus retires a custom status. It refuses while any issue still+// sits on the status: silently rewriting those issues would change their+// machine semantics with no audit trail, so the caller migrates them first.+func (h *Handler) ArchiveIssueStatus(w http.ResponseWriter, r *http.Request) {+ entry, wsUUID, ok := h.loadIssueStatusForAdmin(w, r)+ if !ok {+ return+ }++ if entry.IsSystem {+ writeError(w, http.StatusForbidden, "built-in statuses cannot be archived")+ return+ }+ if entry.ArchivedAt.Valid {+ writeJSON(w, http.StatusOK, issueStatusToResponse(entry))+ return+ }++ // The census and the archive run in ONE transaction under the EXCLUSIVE+ // catalog lock. Without it the two steps race: a concurrent issue write can+ // pass its active-status check, this handler can then observe zero usage and+ // archive, and the write lands afterwards — stranding an issue on an+ // archived status. Issue writes that target a custom status take the shared+ // side of this lock (runWithIssueStatusGuard), so they cannot interleave+ // with the census. (MUL-6243)+ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ slog.Warn("ArchiveIssueStatus begin failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to archive issue status")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ if err := qtx.LockIssueStatusCatalog(r.Context(), wsUUID); err != nil {+ slog.Warn("ArchiveIssueStatus lock failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to archive issue status")+ return+ }++ inUse, err := qtx.CountIssuesUsingStatusKey(r.Context(), db.CountIssuesUsingStatusKeyParams{+ WorkspaceID: wsUUID,+ Key: entry.Key,+ })+ if err != nil {+ slog.Warn("ArchiveIssueStatus count failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to archive issue status")+ return+ }+ if inUse > 0 {+ writeError(w, http.StatusConflict,+ "move the issues still using this status to another status before archiving it")+ return+ }++ archived, err := qtx.ArchiveIssueStatusEntry(r.Context(), db.ArchiveIssueStatusEntryParams{+ ID: entry.ID,+ WorkspaceID: wsUUID,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusConflict, "status is no longer archivable")+ return+ }+ slog.Warn("ArchiveIssueStatus failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to archive issue status")+ return+ }+ if err := tx.Commit(r.Context()); err != nil {+ slog.Warn("ArchiveIssueStatus commit failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to archive issue status")+ return+ }+ writeJSON(w, http.StatusOK, issueStatusToResponse(archived))+}++// loadIssueStatusForAdmin resolves the {id} path param inside the caller's+// workspace and enforces the owner/admin gate.+func (h *Handler) loadIssueStatusForAdmin(w http.ResponseWriter, r *http.Request) (db.IssueStatus, pgtype.UUID, bool) {+ workspaceID := h.resolveWorkspaceID(r)+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return db.IssueStatus{}, pgtype.UUID{}, false+ }+ if _, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin"); !ok {+ return db.IssueStatus{}, pgtype.UUID{}, false+ }+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "issue status id")+ if !ok {+ return db.IssueStatus{}, pgtype.UUID{}, false+ }+ entry, err := h.Queries.GetIssueStatusEntryByID(r.Context(), db.GetIssueStatusEntryByIDParams{+ ID: idUUID,+ WorkspaceID: wsUUID,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "issue status not found")+ return db.IssueStatus{}, pgtype.UUID{}, false+ }+ slog.Warn("load issue status failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to load issue status")+ return db.IssueStatus{}, pgtype.UUID{}, false+ }+ return entry, wsUUID, true+}diff --git a/server/internal/handler/issue_status_test.go b/server/internal/handler/issue_status_test.gonew file mode 100644index 0000000000..1a216a8be3--- /dev/null+++ b/server/internal/handler/issue_status_test.go@@ -0,0 +1,957 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/issuestatus"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Issue status catalog tests (MUL-6243).++// seedTestCatalog makes the shared test workspace's catalog present. The+// fixture creates its workspace with raw SQL, so it has no catalog rows —+// which is itself the unseeded case covered by TestUnseededWorkspaceStillAccepts.+func seedTestCatalog(t *testing.T) {+ t.Helper()+ if err := issuestatus.Ensure(context.Background(), testHandler.Queries, parseUUID(testWorkspaceID)); err != nil {+ t.Fatalf("seed catalog: %v", err)+ }+}++// createTestCustomStatus inserts a custom status directly and removes it after+// the test, so catalog state cannot leak between tests in the shared workspace.+func createTestCustomStatus(t *testing.T, key, category string) db.IssueStatus {+ t.Helper()+ seedTestCatalog(t)+ entry, err := testHandler.Queries.CreateIssueStatusEntry(context.Background(), db.CreateIssueStatusEntryParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ Key: key,+ Name: key,+ Description: "",+ Category: category,+ Color: "#123456",+ })+ if err != nil {+ t.Fatalf("create custom status %q: %v", key, err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE id = $1`, entry.ID)+ })+ return entry+}++// TestEnsureIsIdempotent covers the rolling-deploy case: two pods can seed the+// same workspace concurrently and the second must be a no-op, not an error.+func TestEnsureIsIdempotent(t *testing.T) {+ ctx := context.Background()+ seedTestCatalog(t)+ if err := issuestatus.Ensure(ctx, testHandler.Queries, parseUUID(testWorkspaceID)); err != nil {+ t.Fatalf("second Ensure should be a no-op, got: %v", err)+ }++ entries, err := testHandler.Queries.ListIssueStatusEntries(ctx, db.ListIssueStatusEntriesParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ })+ if err != nil {+ t.Fatalf("list catalog: %v", err)+ }++ systemByKey := map[string]db.IssueStatus{}+ for _, e := range entries {+ if e.IsSystem {+ systemByKey[e.Key] = e+ }+ }+ if len(systemByKey) != 7 {+ t.Fatalf("expected exactly 7 built-in rows after double seeding, got %d", len(systemByKey))+ }+ // Every built-in must be its own category's canonical — the invariant that+ // makes Effective an identity function on built-in keys.+ for key, entry := range systemByKey {+ if entry.Category != key {+ t.Errorf("built-in %q has category %q; a built-in must be its own category's canonical", key, entry.Category)+ }+ }+}++// TestCatalogOrderMatchesHistoricalStatusOrder pins the default board order.+// A workspace with no custom statuses must list exactly as it did before this+// feature, or every existing user's board silently rearranges.+func TestCatalogOrderMatchesHistoricalStatusOrder(t *testing.T) {+ seedTestCatalog(t)+ entries, err := testHandler.Queries.ListIssueStatusEntries(context.Background(), db.ListIssueStatusEntriesParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ })+ if err != nil {+ t.Fatalf("list catalog: %v", err)+ }++ var gotSystem []string+ for _, e := range entries {+ if e.IsSystem {+ gotSystem = append(gotSystem, e.Key)+ }+ }+ want := []string{"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"}+ for i := range want {+ if i >= len(gotSystem) || gotSystem[i] != want[i] {+ t.Fatalf("built-in order = %v, want %v (frontend STATUS_ORDER)", gotSystem, want)+ }+ }+}++// TestUnseededWorkspaceStillAcceptsBuiltInStatuses is the regression guard for+// the failure mode found while wiring this up: requiring a catalog row to+// validate a status made every issue write fail in a workspace whose seed had+// not landed. The built-ins must resolve with or without a row.+func TestUnseededWorkspaceStillAcceptsBuiltInStatuses(t *testing.T) {+ ctx := context.Background()+ // Strip the catalog to simulate a workspace created by a pod that predates+ // the feature, or one the seed migration has not reached yet.+ if _, err := testPool.Exec(ctx, `DELETE FROM issue_status WHERE workspace_id = $1`, parseUUID(testWorkspaceID)); err != nil {+ t.Fatalf("clear catalog: %v", err)+ }+ t.Cleanup(func() { seedTestCatalog(t) })++ for _, key := range issuestatus.Canonical() {+ if _, err := issuestatus.Resolve(ctx, testHandler.Queries, parseUUID(testWorkspaceID), key); err != nil {+ t.Errorf("built-in %q must resolve in an unseeded workspace, got: %v", key, err)+ }+ if got := issuestatus.Effective(ctx, testHandler.Queries, parseUUID(testWorkspaceID), key); got != key {+ t.Errorf("Effective(%q) = %q in an unseeded workspace, want the key unchanged", key, got)+ }+ }++ // A non-built-in key still needs a catalog row, so failing open is scoped+ // exactly to the set that was valid before this feature.+ if _, err := issuestatus.Resolve(ctx, testHandler.Queries, parseUUID(testWorkspaceID), "human_review"); err == nil {+ t.Error("a custom key with no catalog row must not resolve")+ }++ // The error message must never omit a key that Resolve accepts.+ keys, err := issuestatus.ActiveKeys(ctx, testHandler.Queries, parseUUID(testWorkspaceID))+ if err != nil {+ t.Fatalf("ActiveKeys: %v", err)+ }+ if len(keys) != 7 {+ t.Errorf("ActiveKeys on an unseeded workspace = %v, want the 7 built-ins", keys)+ }+}++// TestCustomStatusInheritsItsCategoryBehavior is the core promise of the+// model: a custom status behaves as the canonical status it names.+func TestCustomStatusInheritsItsCategoryBehavior(t *testing.T) {+ ctx := context.Background()+ cases := []struct{ key, category string }{+ {"human_review_t", issuestatus.InReview},+ {"rework_t", issuestatus.Todo},+ {"gate_approved_t", issuestatus.Done},+ {"waiting_customer_t", issuestatus.Blocked},+ {"triage_later_t", issuestatus.Backlog},+ }+ for _, tc := range cases {+ createTestCustomStatus(t, tc.key, tc.category)+ got := issuestatus.Effective(ctx, testHandler.Queries, parseUUID(testWorkspaceID), tc.key)+ if got != tc.category {+ t.Errorf("Effective(%q) = %q, want %q", tc.key, got, tc.category)+ }+ }+}++// TestIssueWriteAcceptsCustomStatusAndRejectsUnknown exercises the real HTTP+// write path, which is where the dropped enum CHECK has to be replaced.+func TestIssueWriteAcceptsCustomStatusAndRejectsUnknown(t *testing.T) {+ createTestCustomStatus(t, "human_review_w", issuestatus.InReview)++ t.Run("custom status is accepted", func(t *testing.T) {+ req := newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "custom status write",+ "status": "human_review_w",+ })+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, req)+ if rec.Code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", rec.Code, rec.Body.String())+ }+ var created struct {+ ID string `json:"id"`+ Status string `json:"status"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &created); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if created.Status != "human_review_w" {+ t.Errorf("issue.status = %q, want the custom key stored verbatim", created.Status)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, parseUUID(created.ID))+ })+ })++ t.Run("unknown status is rejected", func(t *testing.T) {+ req := newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "unknown status write",+ "status": "not_a_status",+ })+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for an unknown status, got %d: %s", rec.Code, rec.Body.String())+ }+ })++ t.Run("archived status is rejected", func(t *testing.T) {+ entry := createTestCustomStatus(t, "retired_w", issuestatus.InProgress)+ if _, err := testHandler.Queries.ArchiveIssueStatusEntry(context.Background(), db.ArchiveIssueStatusEntryParams{+ ID: entry.ID,+ WorkspaceID: parseUUID(testWorkspaceID),+ }); err != nil {+ t.Fatalf("archive: %v", err)+ }+ req := newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "archived status write",+ "status": "retired_w",+ })+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for an archived status, got %d: %s", rec.Code, rec.Body.String())+ }+ })+}++// TestBuiltInStatusesAreImmutable pins the product decision that built-in+// statuses cannot be renamed, recolored, or archived, so the default workspace+// is identical for every user who never opens the settings page.+func TestBuiltInStatusesAreImmutable(t *testing.T) {+ ctx := context.Background()+ seedTestCatalog(t)+ builtIn, err := testHandler.Queries.GetIssueStatusEntryByKey(ctx, db.GetIssueStatusEntryByKeyParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ Key: "in_review",+ })+ if err != nil {+ t.Fatalf("load built-in: %v", err)+ }++ t.Run("rename is refused at the API", func(t *testing.T) {+ req := withURLParam(+ newRequest(http.MethodPatch, "/api/issue-statuses/"+uuidToString(builtIn.ID), map[string]any{"name": "Renamed"}),+ "id", uuidToString(builtIn.ID))+ rec := httptest.NewRecorder()+ testHandler.UpdateIssueStatus(rec, req)+ if rec.Code != http.StatusForbidden {+ t.Fatalf("expected 403 renaming a built-in, got %d: %s", rec.Code, rec.Body.String())+ }+ })++ t.Run("archive is refused at the API", func(t *testing.T) {+ req := withURLParam(+ newRequest(http.MethodDelete, "/api/issue-statuses/"+uuidToString(builtIn.ID), nil),+ "id", uuidToString(builtIn.ID))+ rec := httptest.NewRecorder()+ testHandler.ArchiveIssueStatus(rec, req)+ if rec.Code != http.StatusForbidden {+ t.Fatalf("expected 403 archiving a built-in, got %d: %s", rec.Code, rec.Body.String())+ }+ })++ // Defense in depth: even a direct query cannot rename or archive a+ // built-in, because the statements carry an is_system guard.+ t.Run("storage layer refuses too", func(t *testing.T) {+ if _, err := testHandler.Queries.UpdateIssueStatusEntry(ctx, db.UpdateIssueStatusEntryParams{+ ID: builtIn.ID,+ WorkspaceID: parseUUID(testWorkspaceID),+ Name: pgtype.Text{String: "Renamed", Valid: true},+ }); err == nil {+ t.Error("UpdateIssueStatusEntry must not touch a built-in row")+ }+ if _, err := testHandler.Queries.ArchiveIssueStatusEntry(ctx, db.ArchiveIssueStatusEntryParams{+ ID: builtIn.ID,+ WorkspaceID: parseUUID(testWorkspaceID),+ }); err == nil {+ t.Error("ArchiveIssueStatusEntry must not touch a built-in row")+ }+ })+}++// TestArchiveRefusesWhileIssuesStillUseTheStatus is the decision recorded on+// the issue: migrate the issues first rather than silently rewriting them.+func TestArchiveRefusesWhileIssuesStillUseTheStatus(t *testing.T) {+ ctx := context.Background()+ entry := createTestCustomStatus(t, "in_use_a", issuestatus.InProgress)++ req := newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "occupies the status",+ "status": "in_use_a",+ })+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, req)+ if rec.Code != http.StatusCreated {+ t.Fatalf("create issue: %d %s", rec.Code, rec.Body.String())+ }+ var created struct {+ ID string `json:"id"`+ }+ json.Unmarshal(rec.Body.Bytes(), &created)+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, parseUUID(created.ID))+ })++ archiveReq := withURLParam(+ newRequest(http.MethodDelete, "/api/issue-statuses/"+uuidToString(entry.ID), nil),+ "id", uuidToString(entry.ID))+ archiveRec := httptest.NewRecorder()+ testHandler.ArchiveIssueStatus(archiveRec, archiveReq)+ if archiveRec.Code != http.StatusConflict {+ t.Fatalf("expected 409 while the status is in use, got %d: %s", archiveRec.Code, archiveRec.Body.String())+ }++ // After moving the issue off it, archiving succeeds.+ if _, err := testPool.Exec(ctx, `UPDATE issue SET status = 'todo' WHERE id = $1`, parseUUID(created.ID)); err != nil {+ t.Fatalf("move issue: %v", err)+ }+ retryRec := httptest.NewRecorder()+ testHandler.ArchiveIssueStatus(retryRec, withURLParam(+ newRequest(http.MethodDelete, "/api/issue-statuses/"+uuidToString(entry.ID), nil),+ "id", uuidToString(entry.ID)))+ if retryRec.Code != http.StatusOK {+ t.Fatalf("expected 200 once the status is unused, got %d: %s", retryRec.Code, retryRec.Body.String())+ }+}++// TestCreateIssueStatusValidation covers the reserved-key and category rules.+func TestCreateIssueStatusValidation(t *testing.T) {+ seedTestCatalog(t)+ withCustomIssueStatusesFlag(t, testHandler, true)++ cases := []struct {+ name string+ body map[string]any+ want int+ }{+ {"reserved built-in key", map[string]any{"name": "Mine", "key": "in_review", "category": "in_review", "color": "#123456"}, http.StatusBadRequest},+ {"name slugifying onto a built-in", map[string]any{"name": "In Review", "category": "in_review", "color": "#123456"}, http.StatusBadRequest},+ {"unknown category", map[string]any{"name": "Weird", "category": "started", "color": "#123456"}, http.StatusBadRequest},+ {"missing category", map[string]any{"name": "Weird2", "color": "#123456"}, http.StatusBadRequest},+ {"bad color", map[string]any{"name": "Weird3", "category": "todo", "color": "red"}, http.StatusBadRequest},+ {"empty name", map[string]any{"name": " ", "category": "todo", "color": "#123456"}, http.StatusBadRequest},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ rec := httptest.NewRecorder()+ testHandler.CreateIssueStatus(rec, newRequest(http.MethodPost, "/api/issue-statuses", tc.body))+ if rec.Code != tc.want {+ t.Fatalf("expected %d, got %d: %s", tc.want, rec.Code, rec.Body.String())+ }+ })+ }+}++// TestCreateIssueStatusIsGatedOnRollout pins the rollout gate. Creating the+// first custom status mints a value older pods cannot interpret, so it must be+// impossible until the whole fleet is on this code. Reads stay open.+func TestCreateIssueStatusIsGatedOnRollout(t *testing.T) {+ seedTestCatalog(t)+ withCustomIssueStatusesFlag(t, testHandler, false)++ rec := httptest.NewRecorder()+ testHandler.CreateIssueStatus(rec, newRequest(http.MethodPost, "/api/issue-statuses", map[string]any{+ "name": "Human Review", "category": "in_review", "color": "#123456",+ }))+ if rec.Code != http.StatusForbidden {+ t.Fatalf("expected 403 while the rollout gate is closed, got %d: %s", rec.Code, rec.Body.String())+ }++ // Reading the catalog is never gated — clients need it to render statuses.+ listRec := httptest.NewRecorder()+ testHandler.ListIssueStatuses(listRec, newRequest(http.MethodGet, "/api/issue-statuses", nil))+ if listRec.Code != http.StatusOK {+ t.Fatalf("listing must stay open while the gate is closed, got %d: %s", listRec.Code, listRec.Body.String())+ }+}++// TestIssueWriteStoresCanonicalStatusKey guards the 500 found in review:+// resolution is case- and whitespace-insensitive, so writing the caller's raw+// string back would store a value the column's format constraint rejects.+func TestIssueWriteStoresCanonicalStatusKey(t *testing.T) {+ createTestCustomStatus(t, "human_review_c", issuestatus.InReview)++ for _, input := range []string{"HUMAN_REVIEW_C", " human_review_c ", "Human_Review_C"} {+ t.Run(input, func(t *testing.T) {+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "canonical key " + input, "status": input,+ }))+ if rec.Code != http.StatusCreated {+ t.Fatalf("expected 201 for %q, got %d: %s", input, rec.Code, rec.Body.String())+ }+ var created struct {+ ID string `json:"id"`+ Status string `json:"status"`+ }+ json.Unmarshal(rec.Body.Bytes(), &created)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, parseUUID(created.ID))+ })+ if created.Status != "human_review_c" {+ t.Errorf("stored status = %q, want the canonical key %q", created.Status, "human_review_c")+ }+ // The stored value must satisfy the column's format constraint; a+ // non-canonical write would have failed as a 500 above, but assert+ // the persisted row too so the guarantee is explicit.+ var persisted string+ if err := testPool.QueryRow(context.Background(),+ `SELECT status FROM issue WHERE id = $1`, parseUUID(created.ID)).Scan(&persisted); err != nil {+ t.Fatalf("read back: %v", err)+ }+ if persisted != "human_review_c" {+ t.Errorf("persisted status = %q, want %q", persisted, "human_review_c")+ }+ })+ }+}++// TestCustomTerminalStatusCountsAsTerminalInSQL covers the SQL-side consumers+// the Go resolver cannot reach. Before issue_effective_status existed, each of+// these read the status literal, so a custom status in the `done` category+// still counted as open for the duplicate guard and was missed by sub-issue and+// project completion counts.+func TestCustomTerminalStatusCountsAsTerminalInSQL(t *testing.T) {+ ctx := context.Background()+ createTestCustomStatus(t, "gate_approved_s", issuestatus.Done)++ mkIssue := func(title, status string) pgtype.UUID {+ t.Helper()+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": title, "status": status,+ }))+ if rec.Code != http.StatusCreated {+ t.Fatalf("create %q: %d %s", title, rec.Code, rec.Body.String())+ }+ var created struct {+ ID string `json:"id"`+ }+ json.Unmarshal(rec.Body.Bytes(), &created)+ id := parseUUID(created.ID)+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, id) })+ return id+ }++ t.Run("duplicate guard treats it as closed", func(t *testing.T) {+ title := "sql terminal duplicate probe"+ mkIssue(title, "gate_approved_s")+ if _, err := testHandler.Queries.FindActiveDuplicateIssue(ctx, db.FindActiveDuplicateIssueParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ NormalizedTitle: title,+ }); err == nil {+ t.Error("an issue on a custom done status must not count as an active duplicate")+ }+ })++ t.Run("project completion counts it as done", func(t *testing.T) {+ var projectID pgtype.UUID+ if err := testPool.QueryRow(ctx,+ `INSERT INTO project (workspace_id, title) VALUES ($1, 'Status SQL Probe') RETURNING id`,+ parseUUID(testWorkspaceID)).Scan(&projectID); err != nil {+ t.Fatalf("create project fixture: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, projectID) })++ for _, id := range []pgtype.UUID{+ mkIssue("sql project custom done", "gate_approved_s"),+ mkIssue("sql project open", "todo"),+ } {+ if _, err := testPool.Exec(ctx, `UPDATE issue SET project_id = $1 WHERE id = $2`, projectID, id); err != nil {+ t.Fatalf("attach to project: %v", err)+ }+ }++ stats, err := testHandler.Queries.GetProjectIssueStats(ctx, []pgtype.UUID{projectID})+ if err != nil {+ t.Fatalf("GetProjectIssueStats: %v", err)+ }+ if len(stats) != 1 {+ t.Fatalf("expected stats for one project, got %d", len(stats))+ }+ if stats[0].TotalCount != 2 || stats[0].DoneCount != 1 {+ t.Errorf("project stats = %d done / %d total, want 1/2 (the custom done status must count)",+ stats[0].DoneCount, stats[0].TotalCount)+ }+ })++ t.Run("sub-issue progress counts it as done", func(t *testing.T) {+ parent := mkIssue("sql child progress parent", "in_progress")+ for _, id := range []pgtype.UUID{+ mkIssue("sql child custom done", "gate_approved_s"),+ mkIssue("sql child open", "todo"),+ } {+ if _, err := testPool.Exec(ctx, `UPDATE issue SET parent_issue_id = $1 WHERE id = $2`, parent, id); err != nil {+ t.Fatalf("attach child: %v", err)+ }+ }++ rows, err := testHandler.Queries.ChildIssueProgress(ctx, parseUUID(testWorkspaceID))+ if err != nil {+ t.Fatalf("ChildIssueProgress: %v", err)+ }+ for _, row := range rows {+ if row.ParentIssueID == parent {+ if row.Total != 2 || row.Done != 1 {+ t.Errorf("child progress = %d done / %d total, want 1/2 (the custom done status must count)",+ row.Done, row.Total)+ }+ return+ }+ }+ t.Error("no progress row for the parent issue")+ })+}++// archiveStatusVia runs the real archive endpoint and returns its status code.+func archiveStatusVia(t *testing.T, entry db.IssueStatus) int {+ t.Helper()+ rec := httptest.NewRecorder()+ testHandler.ArchiveIssueStatus(rec, withURLParam(+ newRequest(http.MethodDelete, "/api/issue-statuses/"+uuidToString(entry.ID), nil),+ "id", uuidToString(entry.ID)))+ return rec.Code+}++// holdExclusiveCatalogLock takes the archive side of the catalog lock and holds+// it until the returned release func runs, so a test can pin one ordering.+func holdExclusiveCatalogLock(t *testing.T) (release func()) {+ t.Helper()+ ctx := context.Background()+ tx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin lock holder: %v", err)+ }+ if _, err := tx.Exec(ctx,+ `SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':issue_status', 0))`,+ parseUUID(testWorkspaceID)); err != nil {+ t.Fatalf("take exclusive lock: %v", err)+ }+ released := false+ return func() {+ if released {+ return+ }+ released = true+ tx.Rollback(ctx)+ }+}++// TestWritesRejectAnArchivedStatus covers the SEQUENTIAL case: the status is+// already archived before the request arrives, so the pre-flight validation+// alone is enough to refuse it.+//+// This is deliberately NOT the race test — no archive is interleaved with a+// write here, and these cases would pass even without the in-transaction+// re-resolve. The interleaved counterexample is+// TestArchiveCommitsInsideTheWriteRaceWindow below.+func TestWritesRejectAnArchivedStatus(t *testing.T) {+ ctx := context.Background()+ for _, tc := range []struct {+ name string+ key string+ write func(t *testing.T, key string) int+ }{+ {"create", "race_a_create", func(t *testing.T, key string) int {+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "race create " + key, "status": key,+ }))+ return rec.Code+ }},+ {"update", "race_a_update", func(t *testing.T, key string) int {+ seed := mustCreateIssue(t, "race update seed "+key, "todo")+ rec := httptest.NewRecorder()+ testHandler.UpdateIssue(rec, withURLParam(+ newRequest(http.MethodPatch, "/api/issues/"+uuidToString(seed), map[string]any{"status": key}),+ "id", uuidToString(seed)))+ return rec.Code+ }},+ {"update with description merge", "race_a_upd_merge", func(t *testing.T, key string) int {+ seed := mustCreateIssue(t, "race merge seed "+key, "todo")+ rec := httptest.NewRecorder()+ testHandler.UpdateIssue(rec, withURLParam(+ newRequest(http.MethodPatch, "/api/issues/"+uuidToString(seed), map[string]any{+ "status": key, "description": "merged body",+ }),+ "id", uuidToString(seed)))+ return rec.Code+ }},+ {"batch", "race_a_batch", func(t *testing.T, key string) int {+ seed := mustCreateIssue(t, "race batch seed "+key, "todo")+ rec := httptest.NewRecorder()+ testHandler.BatchUpdateIssues(rec, newRequest(http.MethodPatch, "/api/issues/batch", map[string]any{+ "issue_ids": []string{uuidToString(seed)},+ "updates": map[string]any{"status": key},+ }))+ return rec.Code+ }},+ {"batch with description merge", "race_a_batch_merge", func(t *testing.T, key string) int {+ seed := mustCreateIssue(t, "race batch merge seed "+key, "todo")+ rec := httptest.NewRecorder()+ testHandler.BatchUpdateIssues(rec, newRequest(http.MethodPatch, "/api/issues/batch", map[string]any{+ "issue_ids": []string{uuidToString(seed)},+ "updates": map[string]any{"status": key, "description": "merged body"},+ }))+ return rec.Code+ }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ key := tc.key+ entry := createTestCustomStatus(t, key, issuestatus.InProgress)++ if code := archiveStatusVia(t, entry); code != http.StatusOK {+ t.Fatalf("archive setup returned %d", code)+ }++ code := tc.write(t, key)+ if code == http.StatusOK || code == http.StatusCreated {+ t.Fatalf("%s succeeded (%d) against an archived status", tc.name, code)+ }++ // Whatever the code, the invariant is that nothing references the+ // archived status.+ var stranded int+ if err := testPool.QueryRow(ctx,+ `SELECT count(*) FROM issue WHERE workspace_id = $1 AND status = $2`,+ parseUUID(testWorkspaceID), key).Scan(&stranded); err != nil {+ t.Fatalf("count stranded: %v", err)+ }+ if stranded != 0 {+ t.Errorf("%d issue(s) left referencing archived status %q", stranded, key)+ }+ })+ }++}++// TestArchiveRefusesAfterACommittedWrite is the other ordering: once an issue is+// committed on the status, the archive's census must see it and refuse.+func TestArchiveRefusesAfterACommittedWrite(t *testing.T) {+ ctx := context.Background()+ t.Run("writer wins: archive refuses with conflict", func(t *testing.T) {+ entry := createTestCustomStatus(t, "race_b_writer", issuestatus.InProgress)++ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "race writer wins", "status": "race_b_writer",+ }))+ if rec.Code != http.StatusCreated {+ t.Fatalf("create on custom status: %d %s", rec.Code, rec.Body.String())+ }+ var created struct {+ ID string `json:"id"`+ }+ json.Unmarshal(rec.Body.Bytes(), &created)+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, parseUUID(created.ID)) })++ if code := archiveStatusVia(t, entry); code != http.StatusConflict {+ t.Fatalf("archive after a committed write = %d, want 409", code)+ }+ })++ // The writer must genuinely BLOCK on the archive's exclusive lock rather+ // than racing past it — otherwise the interleaved case below would only be+ // closed by luck.+ t.Run("writer blocks while archive holds the exclusive lock", func(t *testing.T) {+ createTestCustomStatus(t, "race_block", issuestatus.InProgress)+ release := holdExclusiveCatalogLock(t)+ defer release()++ done := make(chan int, 1)+ go func() {+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "race blocked writer", "status": "race_block",+ }))+ done <- rec.Code+ }()++ select {+ case code := <-done:+ t.Fatalf("write completed (%d) while the archive lock was held", code)+ case <-time.After(400 * time.Millisecond):+ // Blocked as required.+ }++ release()+ select {+ case code := <-done:+ if code != http.StatusCreated {+ t.Fatalf("write after the lock released = %d, want 201", code)+ }+ testPool.Exec(ctx, `DELETE FROM issue WHERE workspace_id = $1 AND status = 'race_block'`,+ parseUUID(testWorkspaceID))+ case <-time.After(10 * time.Second):+ t.Fatal("write never completed after the archive lock released")+ }+ })+}++// TestArchiveCommitsInsideTheWriteRaceWindow is the sharp counterexample, run+// against EVERY write endpoint that can land on a custom status.+//+// It interleaves the two operations so the writer's PRE-FLIGHT validation+// observes an active status and the archive commits before the write lands.+// That is the exact hole the first implementation had: the pre-flight Resolve+// ran outside the transaction and was never rechecked, so the writer sailed+// past the released lock and stored an archived key. Verified to fail without+// the in-transaction re-resolve (the issue is left stranded) and pass with it.+//+// Seed issues for the update/batch cases are created BEFORE the exclusive lock+// is taken, so the only thing racing the archive is the status write itself.+func TestArchiveCommitsInsideTheWriteRaceWindow(t *testing.T) {+ cases := []struct {+ name string+ key string+ seed func(t *testing.T, key string) pgtype.UUID+ write func(t *testing.T, key string, seed pgtype.UUID) int+ }{+ {+ name: "create",+ key: "win_create",+ write: func(t *testing.T, key string, _ pgtype.UUID) int {+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "race window create", "status": key,+ }))+ return rec.Code+ },+ },+ {+ name: "update",+ key: "win_update",+ seed: func(t *testing.T, key string) pgtype.UUID {+ return mustCreateIssue(t, "race window update "+key, "todo")+ },+ write: func(t *testing.T, key string, seed pgtype.UUID) int {+ rec := httptest.NewRecorder()+ testHandler.UpdateIssue(rec, withURLParam(+ newRequest(http.MethodPatch, "/api/issues/"+uuidToString(seed), map[string]any{"status": key}),+ "id", uuidToString(seed)))+ return rec.Code+ },+ },+ {+ name: "update with description merge",+ key: "win_upd_merge",+ seed: func(t *testing.T, key string) pgtype.UUID {+ return mustCreateIssue(t, "race window merge "+key, "todo")+ },+ write: func(t *testing.T, key string, seed pgtype.UUID) int {+ rec := httptest.NewRecorder()+ testHandler.UpdateIssue(rec, withURLParam(+ newRequest(http.MethodPatch, "/api/issues/"+uuidToString(seed), map[string]any{+ "status": key, "description": "merged body",+ }),+ "id", uuidToString(seed)))+ return rec.Code+ },+ },+ {+ name: "batch",+ key: "win_batch",+ seed: func(t *testing.T, key string) pgtype.UUID {+ return mustCreateIssue(t, "race window batch "+key, "todo")+ },+ write: func(t *testing.T, key string, seed pgtype.UUID) int {+ rec := httptest.NewRecorder()+ testHandler.BatchUpdateIssues(rec, newRequest(http.MethodPatch, "/api/issues/batch", map[string]any{+ "issue_ids": []string{uuidToString(seed)},+ "updates": map[string]any{"status": key},+ }))+ return rec.Code+ },+ },+ {+ name: "batch with description merge",+ key: "win_batch_merge",+ seed: func(t *testing.T, key string) pgtype.UUID {+ return mustCreateIssue(t, "race window batch merge "+key, "todo")+ },+ write: func(t *testing.T, key string, seed pgtype.UUID) int {+ rec := httptest.NewRecorder()+ testHandler.BatchUpdateIssues(rec, newRequest(http.MethodPatch, "/api/issues/batch", map[string]any{+ "issue_ids": []string{uuidToString(seed)},+ "updates": map[string]any{"status": key, "description": "merged body"},+ }))+ return rec.Code+ },+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ ctx := context.Background()+ entry := createTestCustomStatus(t, tc.key, issuestatus.InProgress)++ var seedID pgtype.UUID+ if tc.seed != nil {+ seedID = tc.seed(t, tc.key)+ }++ // Hold the archive side first, so the writer is guaranteed to park+ // on the lock AFTER its pre-flight validation (which runs outside+ // any transaction) and BEFORE its write.+ tx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback(ctx)+ if _, err := tx.Exec(ctx,+ `SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':issue_status', 0))`,+ parseUUID(testWorkspaceID)); err != nil {+ t.Fatalf("take exclusive lock: %v", err)+ }++ done := make(chan int, 1)+ go func() { done <- tc.write(t, tc.key, seedID) }()++ select {+ case code := <-done:+ t.Fatalf("write completed (%d) before the archive released the lock", code)+ case <-time.After(400 * time.Millisecond):+ // Parked on the lock, as required.+ }++ // Archive inside the held lock and commit: from the writer's point+ // of view the status was active at validation time and archived by+ // write time.+ if _, err := tx.Exec(ctx,+ `UPDATE issue_status SET archived_at = now() WHERE id = $1`, entry.ID); err != nil {+ t.Fatalf("archive inside the window: %v", err)+ }+ if err := tx.Commit(ctx); err != nil {+ t.Fatalf("commit archive: %v", err)+ }++ select {+ case code := <-done:+ if code == http.StatusOK || code == http.StatusCreated {+ t.Errorf("%s succeeded (%d) against a status archived inside the race window", tc.name, code)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("write never completed after the archive committed")+ }++ var stranded int+ if err := testPool.QueryRow(ctx,+ `SELECT count(*) FROM issue WHERE workspace_id = $1 AND status = $2`,+ parseUUID(testWorkspaceID), tc.key).Scan(&stranded); err != nil {+ t.Fatalf("count stranded: %v", err)+ }+ if stranded != 0 {+ t.Errorf("%d issue(s) stranded on a status archived inside the race window", stranded)+ }+ })+ }+}++// mustCreateIssue creates an issue through the real endpoint and returns its id.+func mustCreateIssue(t *testing.T, title, status string) pgtype.UUID {+ t.Helper()+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": title, "status": status,+ }))+ if rec.Code != http.StatusCreated {+ t.Fatalf("seed issue %q: %d %s", title, rec.Code, rec.Body.String())+ }+ var created struct {+ ID string `json:"id"`+ }+ json.Unmarshal(rec.Body.Bytes(), &created)+ id := parseUUID(created.ID)+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, id) })+ return id+}++// TestBatchCustomTerminalStatusEntersStageBarrier is the regression guard for+// the batch stage-barrier prefilter. It compared status literals, so a batch+// that moved the last child onto a CUSTOM done status left childDoneCompleted+// empty and skipped the parent notification entirely — the already-fixed+// barrier logic downstream never ran.+func TestBatchCustomTerminalStatusEntersStageBarrier(t *testing.T) {+ ctx := context.Background()+ createTestCustomStatus(t, "batch_done_s", issuestatus.Done)++ parent := mustCreateIssue(t, "batch barrier parent", "in_progress")+ child := mustCreateIssue(t, "batch barrier child", "todo")+ if _, err := testPool.Exec(ctx, `UPDATE issue SET parent_issue_id = $1 WHERE id = $2`, parent, child); err != nil {+ t.Fatalf("attach child: %v", err)+ }++ rec := httptest.NewRecorder()+ testHandler.BatchUpdateIssues(rec, newRequest(http.MethodPatch, "/api/issues/batch", map[string]any{+ "issue_ids": []string{uuidToString(child)},+ "updates": map[string]any{"status": "batch_done_s"},+ }))+ if rec.Code != http.StatusOK {+ t.Fatalf("batch update: %d %s", rec.Code, rec.Body.String())+ }++ // The observable effect of entering the barrier is the system comment on+ // the parent. Without the fix the batch is silent.+ var comments int+ if err := testPool.QueryRow(ctx,+ `SELECT count(*) FROM comment WHERE issue_id = $1`, parent).Scan(&comments); err != nil {+ t.Fatalf("count parent comments: %v", err)+ }+ if comments == 0 {+ t.Error("moving the last child to a custom done status did not close the stage barrier")+ }+}++// TestChildrenResponseCarriesStatusCategory pins the field the CLI's+// `issue children` stage progress reads. Without it the CLI counts only literal+// done/cancelled and reports wrong progress to an agent.+func TestChildrenResponseCarriesStatusCategory(t *testing.T) {+ ctx := context.Background()+ createTestCustomStatus(t, "children_done_s", issuestatus.Done)++ parent := mustCreateIssue(t, "children category parent", "in_progress")+ child := mustCreateIssue(t, "children category child", "children_done_s")+ if _, err := testPool.Exec(ctx, `UPDATE issue SET parent_issue_id = $1 WHERE id = $2`, parent, child); err != nil {+ t.Fatalf("attach child: %v", err)+ }++ rec := httptest.NewRecorder()+ testHandler.ListChildIssues(rec, withURLParam(+ newRequest(http.MethodGet, "/api/issues/"+uuidToString(parent)+"/children", nil),+ "id", uuidToString(parent)))+ if rec.Code != http.StatusOK {+ t.Fatalf("list children: %d %s", rec.Code, rec.Body.String())+ }++ var payload struct {+ Issues []struct {+ Status string `json:"status"`+ StatusCategory string `json:"status_category"`+ } `json:"issues"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(payload.Issues) != 1 {+ t.Fatalf("expected 1 child, got %d: %s", len(payload.Issues), rec.Body.String())+ }+ if payload.Issues[0].Status != "children_done_s" {+ t.Errorf("status = %q, want the custom key", payload.Issues[0].Status)+ }+ if payload.Issues[0].StatusCategory != "done" {+ t.Errorf("status_category = %q, want %q", payload.Issues[0].StatusCategory, "done")+ }+}diff --git a/server/internal/handler/vcs_webhook.go b/server/internal/handler/vcs_webhook.goindex 132c64bc92..b0eada47ac 100644--- a/server/internal/handler/vcs_webhook.go+++ b/server/internal/handler/vcs_webhook.go@@ -11,6 +11,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/integrations/vcs"+ "github.com/multica-ai/multica/server/internal/issuestatus"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -260,7 +261,8 @@ func (h *Handler) mirrorVCSPullRequest(ctx context.Context, conn db.VcsConnectioif ev.State == "merged" || ev.State == "closed" {for _, issue := range reevalIssues {- if issue.Status == "done" || issue.Status == "cancelled" {+ // A custom terminal status counts as terminal here. (MUL-6243)+ if s := issuestatus.Effective(ctx, h.Queries, issue.WorkspaceID, issue.Status); s == "done" || s == "cancelled" {continue}counts, err := h.Queries.GetIssueCombinedPullRequestCloseAggregate(ctx, issue.ID)diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 889edc39e5..bcf99572a0 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -15,6 +15,7 @@ import ("github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/logger"obsmetrics "github.com/multica-ai/multica/server/internal/metrics"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -283,6 +284,14 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {return}+ // Seed the 7 built-in issue statuses inside the same transaction, so a+ // workspace is never visible without its status catalog — an issue cannot+ // be created before its status can be resolved. (MUL-6243)+ if err := issuestatus.Ensure(r.Context(), qtx, ws.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to seed issue statuses: "+err.Error())+ return+ }+// NOTE: CreateWorkspace deliberately does NOT mark the user as// onboarded. The `onboarded_at` flag is owned by CompleteOnboarding// (Step 3 of the flow) and by AcceptInvitation (invitee joining an@@ -1250,6 +1259,16 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {name: "delete issue roots",run: func() error { return qtx.DeleteWorkspaceIssueRoots(ctx, requester.WorkspaceID) },},+ {+ // issue_status carries no foreign key by project rule, so its rows+ // are swept explicitly. Placed after the issue deletes so no issue+ // row outlives the catalog its status key resolves against.+ // (MUL-6243)+ name: "delete issue statuses",+ run: func() error {+ return qtx.DeleteIssueStatusEntriesForWorkspace(ctx, requester.WorkspaceID)+ },+ },{name: "delete autopilot children",run: func() error { return qtx.DeleteWorkspaceAutopilotChildren(ctx, requester.WorkspaceID) },diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex e61deb947b..8cb5e7192c 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -69,6 +69,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"issue_property": workspaceDelete,"issue_pull_request": workspaceDelete,"issue_reaction": workspaceDelete,+ "issue_status": workspaceDelete,"issue_subscriber": workspaceDelete,"issue_to_label": workspaceDelete,"issue_vcs_pull_request": workspaceDelete,diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.gonew file mode 100644index 0000000000..04b9b60590--- /dev/null+++ b/server/internal/issuestatus/issuestatus.go@@ -0,0 +1,319 @@+// Package issuestatus owns the per-workspace issue status catalog (MUL-6243).+//+// MODEL. There are 7 categories and they map one-to-one onto the 7 built-in+// statuses: a category's value IS its canonical status key. A custom status+// declares a category and inherits that canonical's platform behavior in full.+//+// That one-to-one correspondence is what makes this cheap. Category is defined+// as a BEHAVIOR EQUIVALENCE CLASS — two statuses share a category only when the+// platform treats them identically — and by that definition the 7 built-ins are+// 7 distinct classes: in_progress, in_review and blocked differ on whether they+// finalize an autopilot run, whether they notify a delegated subscriber,+// whether they dismiss stale task_failed inbox rows, and whether the stuck-issue+// sweeper resets them. Collapsing them into one "started" category (the Linear+// model) is what would force a second per-status "behaves_as" concept to+// re-express the difference, and with it the possibility of a status that+// inherits only half a behavior.+//+// CONSEQUENCES. Effective is the identity function on built-in keys, so every+// existing `issue.Status == "todo"` comparison keeps its exact meaning and+// `issue.status` stays the authoritative TEXT column: no status_id, no+// backfill, no double-write. Behavior changes only on custom statuses, a set+// that is empty until an admin creates one.+package issuestatus++import (+ "context"+ "errors"+ "fmt"+ "regexp"+ "strings"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// The 7 canonical status keys. Each is simultaneously a status key and the+// name of the category it defines.+const (+ Backlog = "backlog"+ Todo = "todo"+ InProgress = "in_progress"+ InReview = "in_review"+ Done = "done"+ Blocked = "blocked"+ Cancelled = "cancelled"+)++// canonicalOrder is the historical STATUS_ORDER from the frontend's static+// status config. Category ranking copies it verbatim so a workspace with no+// custom statuses sees a board and picker identical to before this feature.+//+// Note the order is NOT grouped by lifecycle: in_review and done sit between+// in_progress and blocked. That is the shipped order, and reordering it to look+// tidier would visibly rearrange every existing user's board.+var canonicalOrder = []string{+ Backlog,+ Todo,+ InProgress,+ InReview,+ Done,+ Blocked,+ Cancelled,+}++var canonicalRank = func() map[string]int {+ m := make(map[string]int, len(canonicalOrder))+ for i, key := range canonicalOrder {+ m[key] = i+ }+ return m+}()++// ErrUnknownStatus is returned when a status key is absent from a workspace's+// catalog, or present but archived.+var ErrUnknownStatus = errors.New("unknown issue status")++// keyPattern mirrors the issue_status.key CHECK constraint. Keys are lowercase+// so `multica issue status <id> human_review` is unambiguous to type.+var keyPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_]{0,31}$`)++// Querier is the slice of the generated query set this package needs. Taking an+// interface keeps the resolver testable without a live database.+type Querier interface {+ GetIssueStatusEntryByKey(ctx context.Context, arg db.GetIssueStatusEntryByKeyParams) (db.IssueStatus, error)+ ListIssueStatusEntries(ctx context.Context, arg db.ListIssueStatusEntriesParams) ([]db.IssueStatus, error)+ SeedIssueStatusEntries(ctx context.Context, workspaceID pgtype.UUID) error+}++// Canonical returns the 7 built-in status keys in display order.+func Canonical() []string {+ out := make([]string, len(canonicalOrder))+ copy(out, canonicalOrder)+ return out+}++// IsBuiltIn reports whether key is one of the 7 canonical statuses.+func IsBuiltIn(key string) bool {+ _, ok := canonicalRank[key]+ return ok+}++// IsCategory reports whether value names a valid category. Identical to+// IsBuiltIn by construction — categories and canonical keys are the same set —+// and exists so calling code can say which of the two it means.+func IsCategory(value string) bool { return IsBuiltIn(value) }++// CategoryRank returns the display rank of a category, or len(canonicalOrder)+// for an unrecognized one so it sorts last instead of colliding with rank 0.+func CategoryRank(category string) int {+ if rank, ok := canonicalRank[category]; ok {+ return rank+ }+ return len(canonicalOrder)+}++// ValidateKey checks a proposed custom status key against the storage+// constraint and the reserved built-in names.+func ValidateKey(key string) (string, error) {+ key = strings.ToLower(strings.TrimSpace(key))+ if key == "" {+ return "", errors.New("status key is required")+ }+ if !keyPattern.MatchString(key) {+ return "", errors.New("status key must be 1-32 characters of lowercase letters, digits or underscore, starting with a letter or digit")+ }+ if IsBuiltIn(key) {+ return "", fmt.Errorf("%q is a built-in status key and cannot be reused", key)+ }+ return key, nil+}++// SlugifyKey derives a candidate key from a display name, for callers that let+// an admin type only a name. Returns an error when nothing usable survives.+func SlugifyKey(name string) (string, error) {+ var b strings.Builder+ lastUnderscore := false+ for _, r := range strings.ToLower(strings.TrimSpace(name)) {+ switch {+ case (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9'):+ b.WriteRune(r)+ lastUnderscore = false+ case !lastUnderscore && b.Len() > 0:+ b.WriteRune('_')+ lastUnderscore = true+ }+ }+ slug := strings.Trim(b.String(), "_")+ if len(slug) > 32 {+ slug = strings.Trim(slug[:32], "_")+ }+ if slug == "" {+ return "", errors.New("cannot derive a status key from that name; provide one explicitly")+ }+ return ValidateKey(slug)+}++// Ensure idempotently seeds a workspace's 7 built-in statuses. Safe to call+// concurrently — the unique (workspace_id, key) index turns a losing racer into+// a no-op, which matters during a rolling deploy where an old pod may create a+// workspace while a new pod seeds it.+func Ensure(ctx context.Context, q Querier, workspaceID pgtype.UUID) error {+ return q.SeedIssueStatusEntries(ctx, workspaceID)+}++// Effective maps a status key to the canonical key whose platform behavior it+// carries. This is THE function that keeps existing logic correct:+//+// - a built-in key returns itself, unchanged, WITHOUT touching the database,+// so no existing code path gains a query or changes behavior;+// - a custom key returns its category, i.e. the canonical status it inherits.+//+// On an unresolvable key it returns the key unchanged. That is the fail-safe+// direction: an unrecognized status matches none of the canonical comparisons,+// so the issue is left alone rather than being swept, auto-triggered, or having+// its autopilot run finalized on a guess.+func Effective(ctx context.Context, q Querier, workspaceID pgtype.UUID, status string) string {+ if IsBuiltIn(status) {+ return status+ }+ entry, err := q.GetIssueStatusEntryByKey(ctx, db.GetIssueStatusEntryByKeyParams{+ WorkspaceID: workspaceID,+ Key: status,+ })+ if err != nil {+ return status+ }+ if !IsCategory(entry.Category) {+ return status+ }+ return entry.Category+}++// Resolve validates that status is usable in this workspace, returning the+// catalog entry. Write paths use this; it is the application-layer replacement+// for the enum CHECK that migration 337 dropped.+//+// The 7 built-in keys resolve even when the workspace has no catalog row for+// them. The catalog EXTENDS the built-in statuses; it does not define them, and+// a workspace has always been able to use all 7. Requiring a row would mean a+// workspace whose seed has not landed yet — created by a pod that predates this+// feature, or mid-rollout before migration 339 runs — could not create or+// update an issue at all. Failing open here is limited precisely to the set+// that was valid before this feature existed; anything else still needs a row.+func Resolve(ctx context.Context, q Querier, workspaceID pgtype.UUID, status string) (db.IssueStatus, error) {+ key := strings.ToLower(strings.TrimSpace(status))+ if key == "" {+ return db.IssueStatus{}, ErrUnknownStatus+ }+ entry, err := q.GetIssueStatusEntryByKey(ctx, db.GetIssueStatusEntryByKeyParams{+ WorkspaceID: workspaceID,+ Key: key,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ if IsBuiltIn(key) {+ return builtInEntry(workspaceID, key), nil+ }+ return db.IssueStatus{}, ErrUnknownStatus+ }+ return db.IssueStatus{}, err+ }+ if entry.ArchivedAt.Valid {+ // A built-in can never be archived (enforced by a table constraint),+ // so reaching here means a custom status was retired.+ return db.IssueStatus{}, ErrUnknownStatus+ }+ return entry, nil+}++// builtInEntry synthesizes the catalog row for a built-in status in a workspace+// whose seed has not landed. It carries the fields that define behavior — key+// and category, which are equal by construction — and is deliberately not+// persisted: Ensure owns seeding.+func builtInEntry(workspaceID pgtype.UUID, key string) db.IssueStatus {+ return db.IssueStatus{+ WorkspaceID: workspaceID,+ Key: key,+ Category: key,+ IsSystem: true,+ }+}++// ActiveKeys returns the workspace's usable status keys in display order, for+// error messages and CLI validation. An unseeded workspace still reports the 7+// built-ins, so an error message can never omit a key that Resolve accepts.+func ActiveKeys(ctx context.Context, q Querier, workspaceID pgtype.UUID) ([]string, error) {+ entries, err := q.ListIssueStatusEntries(ctx, db.ListIssueStatusEntriesParams{+ WorkspaceID: workspaceID,+ IncludeArchived: false,+ })+ if err != nil {+ return nil, err+ }+ keys := make([]string, 0, len(entries)+len(canonicalOrder))+ seen := make(map[string]bool, len(entries))+ for _, e := range entries {+ keys = append(keys, e.Key)+ seen[e.Key] = true+ }+ for _, key := range canonicalOrder {+ if !seen[key] {+ keys = append(keys, key)+ }+ }+ return keys, nil+}++// Resolver resolves many statuses against ONE workspace's catalog using at most+// one query, for list endpoints that would otherwise issue a lookup per row.+//+// The built-in fast path is unchanged: a built-in key returns itself without+// touching the catalog, so a workspace with no custom statuses still performs+// zero queries no matter how long the list is. The catalog is fetched lazily on+// the first custom key and reused for every row after it.+//+// Not safe for concurrent use, and scoped to a single request: it caches the+// catalog for its lifetime, so a long-lived Resolver would serve stale+// categories after an admin edits the catalog.+type Resolver struct {+ workspaceID pgtype.UUID+ categories map[string]string+ loaded bool+}++// NewResolver returns a Resolver for one workspace. It performs no I/O.+func NewResolver(workspaceID pgtype.UUID) *Resolver {+ return &Resolver{workspaceID: workspaceID}+}++// Effective mirrors the package-level Effective, but amortizes the catalog read+// across every call. Same fail-safe direction: an unresolvable key is returned+// unchanged rather than guessed at.+func (r *Resolver) Effective(ctx context.Context, q Querier, status string) string {+ if IsBuiltIn(status) {+ return status+ }+ if !r.loaded {+ r.loaded = true+ entries, err := q.ListIssueStatusEntries(ctx, db.ListIssueStatusEntriesParams{+ WorkspaceID: r.workspaceID,+ IncludeArchived: true,+ })+ if err != nil {+ // Leave the map nil; every custom key then falls back to itself,+ // which is the same fail-safe the single-shot resolver applies.+ return status+ }+ r.categories = make(map[string]string, len(entries))+ for _, e := range entries {+ r.categories[e.Key] = e.Category+ }+ }+ category, ok := r.categories[status]+ if !ok || !IsCategory(category) {+ return status+ }+ return category+}diff --git a/server/internal/issuestatus/issuestatus_test.go b/server/internal/issuestatus/issuestatus_test.gonew file mode 100644index 0000000000..ed3526160e--- /dev/null+++ b/server/internal/issuestatus/issuestatus_test.go@@ -0,0 +1,311 @@+package issuestatus++import (+ "context"+ "errors"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++var testWorkspace = pgtype.UUID{Bytes: [16]byte{1}, Valid: true}++// fakeQuerier is an in-memory catalog keyed by (workspace, key). It records+// lookups so a test can assert that the built-in fast path issues NO query.+type fakeQuerier struct {+ entries map[string]db.IssueStatus+ lookups int+ lists int+ err error+}++func newFakeQuerier(entries ...db.IssueStatus) *fakeQuerier {+ m := make(map[string]db.IssueStatus, len(entries))+ for _, e := range entries {+ m[e.Key] = e+ }+ return &fakeQuerier{entries: m}+}++func (f *fakeQuerier) GetIssueStatusEntryByKey(_ context.Context, arg db.GetIssueStatusEntryByKeyParams) (db.IssueStatus, error) {+ f.lookups+++ if f.err != nil {+ return db.IssueStatus{}, f.err+ }+ entry, ok := f.entries[arg.Key]+ if !ok {+ return db.IssueStatus{}, pgx.ErrNoRows+ }+ return entry, nil+}++func (f *fakeQuerier) ListIssueStatusEntries(_ context.Context, _ db.ListIssueStatusEntriesParams) ([]db.IssueStatus, error) {+ f.lists+++ if f.err != nil {+ return nil, f.err+ }+ out := make([]db.IssueStatus, 0, len(f.entries))+ for _, e := range f.entries {+ if e.ArchivedAt.Valid {+ continue+ }+ out = append(out, e)+ }+ return out, nil+}++func (f *fakeQuerier) SeedIssueStatusEntries(_ context.Context, _ pgtype.UUID) error {+ return f.err+}++func custom(key, category string) db.IssueStatus {+ return db.IssueStatus{Key: key, Category: category, WorkspaceID: testWorkspace}+}++// TestEffectiveIsIdentityOnBuiltInsWithoutQuerying is the load-bearing+// guarantee of MUL-6243: every pre-existing status check keeps its exact+// meaning, and no existing code path gains a database round trip.+func TestEffectiveIsIdentityOnBuiltInsWithoutQuerying(t *testing.T) {+ q := newFakeQuerier()+ for _, key := range Canonical() {+ if got := Effective(context.Background(), q, testWorkspace, key); got != key {+ t.Errorf("Effective(%q) = %q, want the key unchanged", key, got)+ }+ }+ if q.lookups != 0 {+ t.Errorf("built-in resolution made %d catalog lookups, want 0", q.lookups)+ }+}++func TestEffectiveMapsCustomStatusToItsCategory(t *testing.T) {+ q := newFakeQuerier(+ custom("human_review", InReview),+ custom("rework", Todo),+ custom("gate_approved", Done),+ custom("waiting_on_customer", Blocked),+ )++ cases := map[string]string{+ "human_review": InReview,+ "rework": Todo,+ "gate_approved": Done,+ "waiting_on_customer": Blocked,+ }+ for key, want := range cases {+ if got := Effective(context.Background(), q, testWorkspace, key); got != want {+ t.Errorf("Effective(%q) = %q, want %q", key, got, want)+ }+ }+}++// An unresolvable key must resolve to itself, not to a guess. Returning a+// canonical key here would let an unknown status trigger an agent, finalize an+// autopilot run, or be swept back to todo.+func TestEffectiveFailsSafeOnUnknownAndBrokenCatalog(t *testing.T) {+ t.Run("absent from catalog", func(t *testing.T) {+ q := newFakeQuerier()+ if got := Effective(context.Background(), q, testWorkspace, "ghost"); got != "ghost" {+ t.Errorf("Effective(ghost) = %q, want %q", got, "ghost")+ }+ })++ t.Run("database error", func(t *testing.T) {+ q := newFakeQuerier()+ q.err = errors.New("connection refused")+ if got := Effective(context.Background(), q, testWorkspace, "human_review"); got != "human_review" {+ t.Errorf("Effective on DB error = %q, want the key unchanged", got)+ }+ })++ t.Run("corrupt category", func(t *testing.T) {+ q := newFakeQuerier(custom("weird", "not_a_category"))+ if got := Effective(context.Background(), q, testWorkspace, "weird"); got != "weird" {+ t.Errorf("Effective with bad category = %q, want the key unchanged", got)+ }+ })+}++// The catalog EXTENDS the built-in statuses rather than defining them, so all+// 7 must resolve even with an entirely empty catalog. Requiring a row here was+// a real regression: it made every issue write fail in a workspace whose seed+// had not landed yet.+func TestResolveAcceptsBuiltInsWithoutACatalogRow(t *testing.T) {+ q := newFakeQuerier()+ for _, key := range Canonical() {+ entry, err := Resolve(context.Background(), q, testWorkspace, key)+ if err != nil {+ t.Errorf("Resolve(%q) with an empty catalog failed: %v", key, err)+ continue+ }+ if entry.Key != key || entry.Category != key {+ t.Errorf("synthesized entry for %q = {key:%q category:%q}, want both %q",+ key, entry.Key, entry.Category, key)+ }+ }+ // Failing open is scoped to the built-ins; a custom key still needs a row.+ if _, err := Resolve(context.Background(), q, testWorkspace, "human_review"); !errors.Is(err, ErrUnknownStatus) {+ t.Errorf("a custom key with no row = %v, want ErrUnknownStatus", err)+ }+}++func TestResolveRejectsUnknownAndArchived(t *testing.T) {+ archived := custom("retired", InProgress)+ archived.ArchivedAt = pgtype.Timestamptz{Valid: true}+ q := newFakeQuerier(custom("human_review", InReview), archived)++ if _, err := Resolve(context.Background(), q, testWorkspace, "human_review"); err != nil {+ t.Errorf("Resolve of an active status failed: %v", err)+ }+ if _, err := Resolve(context.Background(), q, testWorkspace, "ghost"); !errors.Is(err, ErrUnknownStatus) {+ t.Errorf("Resolve of an unknown status = %v, want ErrUnknownStatus", err)+ }+ if _, err := Resolve(context.Background(), q, testWorkspace, "retired"); !errors.Is(err, ErrUnknownStatus) {+ t.Errorf("Resolve of an archived status = %v, want ErrUnknownStatus", err)+ }+ if _, err := Resolve(context.Background(), q, testWorkspace, " "); !errors.Is(err, ErrUnknownStatus) {+ t.Errorf("Resolve of a blank status = %v, want ErrUnknownStatus", err)+ }+}++// Every category must be the key of a built-in, and every built-in the name of+// a category. This one-to-one correspondence is what lets Effective return+// entry.Category directly as a status key, with no mapping step.+func TestCategoriesAndBuiltInsAreTheSameSet(t *testing.T) {+ for _, key := range Canonical() {+ if !IsCategory(key) {+ t.Errorf("built-in %q is not a valid category", key)+ }+ }+ if len(Canonical()) != 7 {+ t.Fatalf("expected 7 canonical statuses, got %d", len(Canonical()))+ }+}++// The display order is copied from the frontend's historical STATUS_ORDER.+// Reordering it would visibly rearrange every existing user's board, so it is+// pinned here rather than left to look tidy.+func TestCategoryRankPreservesHistoricalStatusOrder(t *testing.T) {+ want := []string{"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"}+ got := Canonical()+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("Canonical()[%d] = %q, want %q (order matches frontend STATUS_ORDER)", i, got[i], want[i])+ }+ if CategoryRank(want[i]) != i {+ t.Errorf("CategoryRank(%q) = %d, want %d", want[i], CategoryRank(want[i]), i)+ }+ }+ if CategoryRank("not_a_category") != len(want) {+ t.Errorf("an unknown category should sort last, got rank %d", CategoryRank("not_a_category"))+ }+}++func TestValidateKeyRejectsReservedAndMalformed(t *testing.T) {+ for _, key := range Canonical() {+ if _, err := ValidateKey(key); err == nil {+ t.Errorf("built-in key %q must be reserved against reuse", key)+ }+ }+ for _, key := range []string{"", " ", "In Review", "in-review", "_leading", "Ünicode", strings.Repeat("a", 33)} {+ if _, err := ValidateKey(key); err == nil {+ t.Errorf("malformed key %q should be rejected", key)+ }+ }+ got, err := ValidateKey(" Human_Review ")+ if err != nil {+ t.Fatalf("ValidateKey on a well-formed key failed: %v", err)+ }+ if got != "human_review" {+ t.Errorf("ValidateKey normalized to %q, want %q", got, "human_review")+ }+}++func TestSlugifyKey(t *testing.T) {+ cases := map[string]string{+ "Human Review": "human_review",+ "Gate Approved!": "gate_approved",+ " Rework ": "rework",+ "Waiting — 客户": "waiting",+ }+ for name, want := range cases {+ got, err := SlugifyKey(name)+ if err != nil {+ t.Errorf("SlugifyKey(%q) failed: %v", name, err)+ continue+ }+ if got != want {+ t.Errorf("SlugifyKey(%q) = %q, want %q", name, got, want)+ }+ }++ // A name that slugifies onto a built-in key must be refused, not silently+ // shadow the built-in.+ if _, err := SlugifyKey("In Progress"); err == nil {+ t.Error("a name slugifying to a built-in key should be rejected")+ }+ if _, err := SlugifyKey("客户"); err == nil {+ t.Error("a name with no slug-able characters should be rejected")+ }+}++// TestResolverAmortizesTheCatalogRead pins the list-endpoint guarantee: built-in+// statuses still cost nothing, and N custom rows cost ONE catalog read rather+// than one lookup per row.+func TestResolverAmortizesTheCatalogRead(t *testing.T) {+ q := newFakeQuerier(+ custom("human_review", InReview),+ custom("gate_approved", Done),+ )+ r := NewResolver(testWorkspace)+ ctx := context.Background()++ // Built-ins: no catalog access at all, however many times they are seen.+ for range 50 {+ for _, key := range Canonical() {+ if got := r.Effective(ctx, q, key); got != key {+ t.Fatalf("Effective(%q) = %q, want the key unchanged", key, got)+ }+ }+ }+ if q.lists != 0 || q.lookups != 0 {+ t.Errorf("built-in resolution touched the catalog: %d list(s), %d lookup(s)", q.lists, q.lookups)+ }++ // Custom keys: the catalog is read once and reused.+ for range 50 {+ if got := r.Effective(ctx, q, "human_review"); got != InReview {+ t.Fatalf("Effective(human_review) = %q, want %q", got, InReview)+ }+ if got := r.Effective(ctx, q, "gate_approved"); got != Done {+ t.Fatalf("Effective(gate_approved) = %q, want %q", got, Done)+ }+ }+ if q.lists != 1 {+ t.Errorf("catalog read %d times, want exactly 1", q.lists)+ }+ if q.lookups != 0 {+ t.Errorf("Resolver made %d per-key lookups, want 0", q.lookups)+ }++ // Unknown keys stay fail-safe and do not trigger a re-read.+ if got := r.Effective(ctx, q, "ghost"); got != "ghost" {+ t.Errorf("Effective(ghost) = %q, want the key unchanged", got)+ }+ if q.lists != 1 {+ t.Errorf("an unknown key re-read the catalog: %d reads", q.lists)+ }+}++// A catalog read failure must degrade to the fail-safe identity rather than+// guessing a category.+func TestResolverFailsSafeWhenTheCatalogReadFails(t *testing.T) {+ q := newFakeQuerier()+ q.err = errors.New("connection refused")+ r := NewResolver(testWorkspace)+ if got := r.Effective(context.Background(), q, "human_review"); got != "human_review" {+ t.Errorf("Effective on a failed catalog read = %q, want the key unchanged", got)+ }+}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 2309a38693..7bf7557902 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -19,6 +19,7 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/issueposition"+ "github.com/multica-ai/multica/server/internal/issuestatus"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -306,7 +307,7 @@ func (s *AutopilotService) ensureWebhookCreateIssueTask(ctx context.Context, autif err != nil {return fmt.Errorf("dispatch for webhook delivery: load linked issue: %w", err)}- if issue.Status != "todo" && issue.Status != "in_progress" {+ if effective := issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status); effective != "todo" && effective != "in_progress" {return nil}if autopilot.AssigneeType == "squad" {@@ -972,7 +973,15 @@ func (s *AutopilotService) SyncRunFromIssue(ctx context.Context, issue db.Issue)wsID := util.UUIDToString(issue.WorkspaceID)- switch issue.Status {+ // A custom status finalizes the run exactly like the canonical status it+ // inherits. Built-in keys resolve to themselves without a query, so this+ // is a no-op for every workspace that has not defined a custom status.+ // The failure reason below deliberately keeps issue.Status, not the+ // normalized key, so the audit trail names the status a human actually+ // chose. (MUL-6243)+ effectiveStatus := issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status)++ switch effectiveStatus {case "done", "in_review":updatedRun, err := s.Queries.UpdateAutopilotRunCompleted(ctx, db.UpdateAutopilotRunCompletedParams{ID: run.ID,diff --git a/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md b/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.mdindex fab80dc3b8..2a258a1b7d 100644--- a/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md+++ b/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md@@ -273,6 +273,12 @@ multica issue children <parent-id> # sub-issues grouped by stagemultica issue status <stage-2-child-id> todo # promote when its deps are met```+`issue children --output json` reports per-stage `done` counts. A workspace may+define custom statuses beyond the 7 built-ins; a custom status counts as done+here when its category is `done` or `cancelled`, which is what `status_category`+on each child carries. Read `status_category` rather than matching `status`+against the built-in names.+Read each sub-issue's description before promoting and only promote items whosestated dependencies are met; if a description conflicts with the parent'sbreakdown, leave it `backlog` and comment to confirm first.diff --git a/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md b/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.mdindex 226a93754e..21d2604512 100644--- a/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md+++ b/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md@@ -168,7 +168,7 @@ on those assignments creating their normal queued runs.| Stage barrier: notify+wake fire only when the lowest unfinished stage is all-terminal; unstaged set = one implicit stage | `server/internal/handler/issue_child_done.go:231` (`stageBarrierClosed`) || Per-stage summary + next stage for the wake comment | `server/internal/handler/issue_child_done.go:254` (`stageProgressSummary`) || `--stage` on `issue create` / `issue update` | `server/cmd/multica/cmd_issue.go:328,350` |-| `multica issue children <id>` (sub-issues grouped by stage) | `server/cmd/multica/cmd_issue.go:114,678`; route `GET /api/issues/{id}/children` → `ListChildIssues` |+| `multica issue children <id>` (sub-issues grouped by stage) | `server/cmd/multica/cmd_issue.go:114,678`; stage `done` counting via `isTerminalChildIssue` (reads `status_category`, MUL-6243); route `GET /api/issues/{id}/children` → `ListChildIssues` |Advancement is agent-driven: the server only detects the closed barrier andwakes the parent assignee. Promoting the next stage's `backlog` sub-issues todiff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex 3d82db73ac..bcaefca4ed 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -14,6 +14,7 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/issueposition"+ "github.com/multica-ai/multica/server/internal/issuestatus"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -148,6 +149,12 @@ var ErrProjectNotFound = errors.New("project not found in this workspace")// label set. Callers translate this into their transport's 400.var ErrIssueLabelNotFound = errors.New("issue label not found in this workspace")+// ErrIssueStatusUnavailable signals that the requested custom status was+// archived between the caller's pre-flight validation and the create+// transaction. Callers translate this into a 409 — the request was valid when+// it arrived, so retrying against the refreshed catalog is the remedy.+var ErrIssueStatusUnavailable = errors.New("issue status is no longer available")+// IssueCreateResult is the typed return from IssueService.Create.//// - On the happy path: Issue is the new row, Attachments lists the@@ -200,6 +207,25 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Issdefer tx.Rollback(ctx)qtx := s.Queries.WithTx(tx)+ // A create landing on a CUSTOM status takes the shared catalog lock AND+ // re-resolves the status inside this transaction. The caller validated the+ // status before the transaction opened, which is early enough to return a+ // clean 400 but too early to be safe: an archive can commit in between.+ // Re-checking under the lock is what makes the status provably active at+ // the moment the row is written. Built-in statuses skip both — they can+ // never be archived, so the common path is unchanged. (MUL-6243)+ if !issuestatus.IsBuiltIn(p.Status) {+ if err := qtx.LockIssueStatusCatalogShared(ctx, p.WorkspaceID); err != nil {+ return IssueCreateResult{}, err+ }+ if _, err := issuestatus.Resolve(ctx, qtx, p.WorkspaceID, p.Status); err != nil {+ if errors.Is(err, issuestatus.ErrUnknownStatus) {+ return IssueCreateResult{}, ErrIssueStatusUnavailable+ }+ return IssueCreateResult{}, err+ }+ }+// Resolve and validate parent / project before reading from the// duplicate guard so a forged parent or project ID is rejected// before we touch the issue counter. Both checks scope by@@ -584,8 +610,9 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,return pgtype.UUID{}}// Backlog is the parking lot: nothing runs from it, so nothing here needs- // explaining either.- if issue.Status == "backlog" {+ // explaining either. A custom status in the backlog category parks the+ // same way. (MUL-6243)+ if issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status) == "backlog" {return pgtype.UUID{}}verdict, admitted := agentAssigneeVerdict(ctx, s.Queries, issue)@@ -629,7 +656,9 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,// Mirrors handler.shouldEnqueueAgentTask; kept here to make the service// self-contained, since both code paths must move together.func (s *IssueService) shouldEnqueueAgentTaskWithQueries(ctx context.Context, q *db.Queries, issue db.Issue) bool {- if issue.Status == "backlog" {+ // 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" {return false}return isAgentAssigneeReadyWithQueries(ctx, q, issue)@@ -662,7 +691,7 @@ func agentAssigneeVerdict(ctx context.Context, q *db.Queries, issue db.Issue) (A}func (s *IssueService) shouldEnqueueSquadLeaderOnAssign(ctx context.Context, issue db.Issue) bool {- if issue.Status == "backlog" {+ if issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status) == "backlog" {return false}return s.isSquadLeaderReady(ctx, issue)diff --git a/server/internal/service/issue_trigger.go b/server/internal/service/issue_trigger.goindex b2734a6088..09d1abfcb4 100644--- a/server/internal/service/issue_trigger.go+++ b/server/internal/service/issue_trigger.go@@ -4,6 +4,7 @@ import ("context""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/issuestatus"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -103,16 +104,25 @@ func (s *IssueService) WillEnqueueRun(ctx context.Context, in IssueTriggerInput,canAccess = allowAllAgents}+ // Both sides of the transition are normalized to the canonical status they+ // inherit, so a custom status in the `backlog` category parks exactly like+ // Backlog and a custom status in the `todo` category starts a run exactly+ // like Todo. Built-in keys resolve to themselves without a query, leaving+ // this decision bit-identical for workspaces with no custom statuses —+ // which is the whole set of them until an admin defines one. (MUL-6243)+ currentStatus := issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status)+ prevStatus := issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, in.PrevStatus)+var source RunEnqueueSourceswitch {case in.IsCreate || in.AssigneeChanged:// Backlog is the parking lot: assigning into backlog never starts a run.- if issue.Status == "backlog" {+ if currentStatus == "backlog" {return IssueRunTrigger{}, false}source = RunSourceAssign- case in.StatusChanged && in.PrevStatus == "backlog" &&- issue.Status != "done" && issue.Status != "cancelled":+ case in.StatusChanged && prevStatus == "backlog" &&+ currentStatus != "done" && currentStatus != "cancelled":if probe.IsSelfLoop != nil && probe.IsSelfLoop() {return IssueRunTrigger{}, false}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 91e3aec423..1b36ee7417 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -20,6 +20,7 @@ import ("github.com/multica-ai/multica/server/internal/attribution""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/featureflags"+ "github.com/multica-ai/multica/server/internal/issuestatus"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/realtime""github.com/multica-ai/multica/server/internal/runtimeapps"@@ -4762,7 +4763,13 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTas// Reset stuck in_progress issues only when no other active// task exists for the issue and no retry was just enqueued.issueKey := util.UUIDToString(t.IssueID)- if issue.Status == "in_progress" && !processedIssues[issueKey] && !retriedIssues[issueKey] {+ // Only "an agent is actively working" resets. in_review and+ // blocked are excluded — a human or an external dependency owns+ // the issue then — and a custom status resolves to the canonical+ // status it inherits, so a custom review gate is excluded for+ // the same reason In Review is. (MUL-6243)+ effectiveStatus := issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status)+ if effectiveStatus == "in_progress" && !processedIssues[issueKey] && !retriedIssues[issueKey] {processedIssues[issueKey] = truehasActive, checkErr := s.Queries.HasActiveTaskForIssue(ctx, t.IssueID)if checkErr != nil {diff --git a/server/migrations/332_issue_status.down.sql b/server/migrations/332_issue_status.down.sqlnew file mode 100644index 0000000000..f55bb7a2be--- /dev/null+++ b/server/migrations/332_issue_status.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS issue_status;diff --git a/server/migrations/332_issue_status.up.sql b/server/migrations/332_issue_status.up.sqlnew file mode 100644index 0000000000..ab0090fa6a--- /dev/null+++ b/server/migrations/332_issue_status.up.sql@@ -0,0 +1,62 @@+-- Custom Issue Status catalog (MUL-6243).+--+-- MODEL: the 7 categories map ONE-TO-ONE onto the 7 built-in statuses, and a+-- category's value IS its canonical status key. A custom status names a+-- category and inherits that canonical's platform behavior wholesale, so there+-- is no second "behaves_as" concept and no way to build a status that inherits+-- only half of a behavior.+--+-- `issue.status` stays the authoritative TEXT column and keeps holding a key+-- from this catalog, so no status_id, no backfill, and no double-write: every+-- existing `WHERE status = 'todo'` and `issue.Status == "backlog"` keeps+-- working verbatim because the 7 built-in keys never change.+--+-- No foreign keys (workspace_id is an application-layer relation, per the+-- project's database rules); cleanup is handled by the application.+--+-- id is NOT declared inline as PRIMARY KEY: the repo convention (see migrations+-- 327-329) is to build the table without a primary key, create the backing+-- unique index CONCURRENTLY in its own single-statement migration (333), then+-- attach it with PRIMARY KEY USING INDEX (334). An inline PRIMARY KEY would+-- build its index non-concurrently, which the project's migration rules forbid+-- even on a new table.+CREATE TABLE issue_status (+ id UUID NOT NULL DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,++ -- Stable machine handle. Immutable after create: it is what `issue.status`+ -- stores, what the CLI accepts, and what agent instructions reference.+ key TEXT NOT NULL CHECK (key ~ '^[a-z0-9][a-z0-9_]{0,31}$'),++ -- Human-facing label. Editable for custom statuses; locked for built-ins.+ name TEXT NOT NULL CHECK (char_length(name) BETWEEN 1 AND 64),+ description TEXT NOT NULL DEFAULT '' CHECK (char_length(description) <= 256),++ -- Behavior equivalence class. Immutable after create — changing it would+ -- silently rewrite the machine semantics of every issue already sitting on+ -- this status, with no audit trail.+ category TEXT NOT NULL CHECK (+ category IN ('backlog', 'todo', 'in_progress', 'in_review', 'done', 'blocked', 'cancelled')+ ),++ -- "#rrggbb". Built-in rows carry the seeded palette for API consumers, but+ -- clients that already know a built-in key keep rendering it from their own+ -- config, so the default experience stays pixel-identical.+ color TEXT NOT NULL CHECK (color ~ '^#[0-9a-f]{6}$'),++ is_system BOOLEAN NOT NULL DEFAULT FALSE,+ position DOUBLE PRECISION NOT NULL DEFAULT 0,+ archived_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),++ -- A built-in row IS its category's canonical, so its key must equal its+ -- category. This is what makes Effective() an identity function on built-in+ -- keys, which is in turn what keeps every existing status check correct.+ CONSTRAINT issue_status_system_is_canonical+ CHECK (NOT is_system OR key = category),++ -- Archiving a built-in would delete its category's behavior definition.+ CONSTRAINT issue_status_system_not_archivable+ CHECK (NOT is_system OR archived_at IS NULL)+);diff --git a/server/migrations/333_issue_status_pkey_index.down.sql b/server/migrations/333_issue_status_pkey_index.down.sqlnew file mode 100644index 0000000000..fa9219b354--- /dev/null+++ b/server/migrations/333_issue_status_pkey_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS issue_status_pkey_uidx;diff --git a/server/migrations/333_issue_status_pkey_index.up.sql b/server/migrations/333_issue_status_pkey_index.up.sqlnew file mode 100644index 0000000000..06fc76a91f--- /dev/null+++ b/server/migrations/333_issue_status_pkey_index.up.sql@@ -0,0 +1,5 @@+-- Backing index for issue_status's primary key, attached in 334 via+-- PRIMARY KEY USING INDEX. Own single-statement migration so CONCURRENTLY runs+-- outside an implicit transaction (repo convention).+CREATE UNIQUE INDEX CONCURRENTLY issue_status_pkey_uidx+ ON issue_status (id);diff --git a/server/migrations/334_issue_status_primary_key.down.sql b/server/migrations/334_issue_status_primary_key.down.sqlnew file mode 100644index 0000000000..aa20a2cd06--- /dev/null+++ b/server/migrations/334_issue_status_primary_key.down.sql@@ -0,0 +1,3 @@+-- Dropping the constraint drops the index it took over, leaving 333's down+-- direction a no-op via IF EXISTS.+ALTER TABLE issue_status DROP CONSTRAINT IF EXISTS issue_status_pkey;diff --git a/server/migrations/334_issue_status_primary_key.up.sql b/server/migrations/334_issue_status_primary_key.up.sqlnew file mode 100644index 0000000000..a5ed2b635d--- /dev/null+++ b/server/migrations/334_issue_status_primary_key.up.sql@@ -0,0 +1,3 @@+-- Attach the CONCURRENTLY-built unique index as the table's primary key.+ALTER TABLE issue_status+ ADD CONSTRAINT issue_status_pkey PRIMARY KEY USING INDEX issue_status_pkey_uidx;diff --git a/server/migrations/335_issue_status_workspace_key_index.down.sql b/server/migrations/335_issue_status_workspace_key_index.down.sqlnew file mode 100644index 0000000000..cf8afca1d2--- /dev/null+++ b/server/migrations/335_issue_status_workspace_key_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_status_workspace_key;diff --git a/server/migrations/335_issue_status_workspace_key_index.up.sql b/server/migrations/335_issue_status_workspace_key_index.up.sqlnew file mode 100644index 0000000000..2cd5ef158e--- /dev/null+++ b/server/migrations/335_issue_status_workspace_key_index.up.sql@@ -0,0 +1,6 @@+-- The catalog lookup that every status resolution and the ordering join use:+-- (workspace_id, key) is how `issue.status` is resolved back to its category.+-- Unique because a workspace cannot hold two statuses with the same key, and+-- this is what stops a custom status from colliding with a built-in one.+CREATE UNIQUE INDEX CONCURRENTLY idx_issue_status_workspace_key+ ON issue_status (workspace_id, key);diff --git a/server/migrations/336_issue_status_workspace_name_index.down.sql b/server/migrations/336_issue_status_workspace_name_index.down.sqlnew file mode 100644index 0000000000..4f10112b76--- /dev/null+++ b/server/migrations/336_issue_status_workspace_name_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_status_workspace_name_active;diff --git a/server/migrations/336_issue_status_workspace_name_index.up.sql b/server/migrations/336_issue_status_workspace_name_index.up.sqlnew file mode 100644index 0000000000..df9a1d0507--- /dev/null+++ b/server/migrations/336_issue_status_workspace_name_index.up.sql@@ -0,0 +1,5 @@+-- Display names must stay unambiguous among ACTIVE statuses; archived rows are+-- excluded so an archived name can be reused.+CREATE UNIQUE INDEX CONCURRENTLY idx_issue_status_workspace_name_active+ ON issue_status (workspace_id, lower(name))+ WHERE archived_at IS NULL;diff --git a/server/migrations/337_issue_status_open_check.down.sql b/server/migrations/337_issue_status_open_check.down.sqlnew file mode 100644index 0000000000..d6188372fe--- /dev/null+++ b/server/migrations/337_issue_status_open_check.down.sql@@ -0,0 +1,8 @@+-- Restoring the enum constraint FAILS if any issue sits on a custom status.+-- That is deliberate: silently rewriting those rows to a built-in status would+-- destroy user data. Migrate custom-status issues back to built-ins first.+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_status_format_check;++ALTER TABLE issue+ ADD CONSTRAINT issue_status_check+ CHECK (status IN ('backlog', 'todo', 'in_progress', 'in_review', 'done', 'blocked', 'cancelled'));diff --git a/server/migrations/337_issue_status_open_check.up.sql b/server/migrations/337_issue_status_open_check.up.sqlnew file mode 100644index 0000000000..399d6f0e9d--- /dev/null+++ b/server/migrations/337_issue_status_open_check.up.sql@@ -0,0 +1,17 @@+-- Open `issue.status` to catalog keys (MUL-6243).+--+-- The old constraint hard-coded the 7 built-in statuses, which is exactly the+-- thing a per-workspace catalog has to be able to extend. Membership validation+-- moves to the application layer, where it is checked against issue_status for+-- the issue's OWN workspace — something a table-level CHECK cannot express.+--+-- A format constraint stays behind as defense in depth: it cannot know whether+-- a key exists in the catalog, but it does keep an empty string or arbitrary+-- text out of the column if a write path ever forgets to validate. Added+-- NOT VALID so it takes no table scan under lock; migration 338 validates it.+ALTER TABLE issue DROP CONSTRAINT issue_status_check;++ALTER TABLE issue+ ADD CONSTRAINT issue_status_format_check+ CHECK (status ~ '^[a-z0-9][a-z0-9_]{0,31}$')+ NOT VALID;diff --git a/server/migrations/338_issue_status_validate_format.down.sql b/server/migrations/338_issue_status_validate_format.down.sqlnew file mode 100644index 0000000000..73113015dc--- /dev/null+++ b/server/migrations/338_issue_status_validate_format.down.sql@@ -0,0 +1,4 @@+-- Re-marking a validated constraint as NOT VALID is not expressible in+-- Postgres, and dropping it here would fight migration 337's down direction.+-- Rolling back validation alone is a no-op.+SELECT 1;diff --git a/server/migrations/338_issue_status_validate_format.up.sql b/server/migrations/338_issue_status_validate_format.up.sqlnew file mode 100644index 0000000000..d1a490ca4d--- /dev/null+++ b/server/migrations/338_issue_status_validate_format.up.sql@@ -0,0 +1,5 @@+-- Validates the format constraint added NOT VALID in 330. Existing rows all+-- hold one of the 7 built-in keys, which match the pattern, so this scan+-- confirms rather than repairs. SHARE UPDATE EXCLUSIVE — reads and writes+-- continue during the scan.+ALTER TABLE issue VALIDATE CONSTRAINT issue_status_format_check;diff --git a/server/migrations/339_seed_issue_status_catalog.down.sql b/server/migrations/339_seed_issue_status_catalog.down.sqlnew file mode 100644index 0000000000..18d8bd1bb8--- /dev/null+++ b/server/migrations/339_seed_issue_status_catalog.down.sql@@ -0,0 +1,3 @@+-- Drops only the seeded built-ins, leaving any custom statuses an admin+-- created. Deleting those would strand every issue sitting on one.+DELETE FROM issue_status WHERE is_system = TRUE;diff --git a/server/migrations/339_seed_issue_status_catalog.up.sql b/server/migrations/339_seed_issue_status_catalog.up.sqlnew file mode 100644index 0000000000..7aea4bdabc--- /dev/null+++ b/server/migrations/339_seed_issue_status_catalog.up.sql@@ -0,0 +1,24 @@+-- Seed the 7 built-in statuses for every EXISTING workspace (MUL-6243).+--+-- New workspaces are seeded inside their create transaction; this covers the+-- ones that already exist. Idempotent via the unique (workspace_id, key)+-- index from migration 335, so a re-run or a concurrent seed from a pod that+-- already booted the new code is a no-op rather than an error.+--+-- Not a hazard if it is slow: until a workspace has custom statuses, the+-- resolver treats a built-in key as itself without consulting this table at+-- all, so an unseeded workspace keeps behaving exactly as it does today.+INSERT INTO issue_status (workspace_id, key, name, description, category, color, is_system, position)+SELECT w.id, s.key, s.name, s.description, s.key, s.color, TRUE, 0+FROM workspace w+CROSS JOIN (+ VALUES+ ('backlog', 'Backlog', 'Parked. Assigning an issue here never starts an agent run.', '#6b7280'),+ ('todo', 'Todo', 'Queued for work. Moving an issue here starts the assigned agent.', '#6b7280'),+ ('in_progress', 'In Progress', 'Actively being worked on.', '#f59e0b'),+ ('in_review', 'In Review', 'Work delivered, waiting on human review. Finalizes the autopilot run.', '#22c55e'),+ ('done', 'Done', 'Completed.', '#3b82f6'),+ ('blocked', 'Blocked', 'Stalled on an external dependency.', '#ef4444'),+ ('cancelled', 'Cancelled', 'Decided not to do.', '#6b7280')+) AS s(key, name, description, color)+ON CONFLICT DO NOTHING;diff --git a/server/migrations/340_issue_effective_status_fn.down.sql b/server/migrations/340_issue_effective_status_fn.down.sqlnew file mode 100644index 0000000000..ed52ffd466--- /dev/null+++ b/server/migrations/340_issue_effective_status_fn.down.sql@@ -0,0 +1 @@+DROP FUNCTION IF EXISTS issue_effective_status(UUID, TEXT);diff --git a/server/migrations/340_issue_effective_status_fn.up.sql b/server/migrations/340_issue_effective_status_fn.up.sqlnew file mode 100644index 0000000000..7ccb8f1153--- /dev/null+++ b/server/migrations/340_issue_effective_status_fn.up.sql@@ -0,0 +1,37 @@+-- SQL mirror of issuestatus.Effective (MUL-6243).+--+-- Several queries have to ask "is this issue terminal / open?" in SQL, where+-- the Go resolver cannot reach. Without this, a custom status in the `done`+-- category would still count as open for the duplicate guard, and would be+-- missed by sub-issue and project completion counts.+--+-- The built-in fast path comes FIRST and short-circuits, so a workspace with no+-- custom statuses performs no catalog lookup at all — the same guarantee the Go+-- resolver gives. The lookup for a custom key is a single point read on+-- idx_issue_status_workspace_key.+--+-- Falls back to the raw status when the key is unknown or its category is+-- corrupt, matching the Go resolver's fail-safe direction: an unrecognized+-- status matches none of the canonical comparisons, so the issue is left alone+-- rather than being treated as terminal on a guess.+--+-- STABLE (not IMMUTABLE): the result depends on catalog rows, so it must not be+-- folded into an index or cached across statements.+CREATE FUNCTION issue_effective_status(p_workspace_id UUID, p_status TEXT)+RETURNS TEXT+LANGUAGE sql+STABLE+PARALLEL SAFE+AS $$+ SELECT CASE+ WHEN p_status IN ('backlog', 'todo', 'in_progress', 'in_review', 'done', 'blocked', 'cancelled')+ THEN p_status+ ELSE COALESCE(+ (SELECT s.category+ FROM issue_status s+ WHERE s.workspace_id = p_workspace_id+ AND s.key = p_status+ AND s.category IN ('backlog', 'todo', 'in_progress', 'in_review', 'done', 'blocked', 'cancelled')),+ p_status)+ END+$$;diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex 453bc180be..189d9c1bdf 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -50,7 +50,11 @@ func (q *Queries) ArchiveAllReadInbox(ctx context.Context, arg ArchiveAllReadInbconst archiveCompletedInbox = `-- name: ArchiveCompletedInbox :execrowsUPDATE inbox_item i SET archived = trueWHERE i.workspace_id = $1 AND i.recipient_type = 'member' AND i.recipient_id = $2 AND i.archived = false- AND i.issue_id IN (SELECT id FROM issue WHERE status IN ('done', 'cancelled'))+ AND i.issue_id IN (+ SELECT id FROM issue+ WHERE workspace_id = $1+ AND issue_effective_status(workspace_id, status) IN ('done', 'cancelled')+ )`type ArchiveCompletedInboxParams struct {diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 3408dca076..731148564d 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -14,7 +14,7 @@ import (const childIssueProgress = `-- name: ChildIssueProgress :manySELECT parent_issue_id,COUNT(*)::bigint AS total,- COUNT(*) FILTER (WHERE status IN ('done', 'cancelled'))::bigint AS done+ COUNT(*) FILTER (WHERE issue_effective_status(workspace_id, status) IN ('done', 'cancelled'))::bigint AS doneFROM issueWHERE workspace_id = $1AND parent_issue_id IS NOT NULL@@ -427,7 +427,7 @@ func (q *Queries) DeleteIssueMetadataKey(ctx context.Context, arg DeleteIssueMetconst findActiveDuplicateIssue = `-- name: FindActiveDuplicateIssue :oneSELECT 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 FROM issueWHERE workspace_id = $1- AND status NOT IN ('done', 'cancelled')+ AND issue_effective_status(workspace_id, status) NOT IN ('done', 'cancelled')AND project_id IS NOT DISTINCT FROM $2::uuidAND parent_issue_id IS NOT DISTINCT FROM $3::uuidAND lower(btrim(regexp_replace(title, '[[:space:]]+', ' ', 'g'))) = $4@@ -484,7 +484,7 @@ func (q *Queries) FindActiveDuplicateIssue(ctx context.Context, arg FindActiveDuconst findRecentAutopilotDuplicateIssue = `-- name: FindRecentAutopilotDuplicateIssue :oneSELECT 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 FROM issue iWHERE i.workspace_id = $1- AND i.status NOT IN ('done', 'cancelled')+ AND issue_effective_status(i.workspace_id, i.status) NOT IN ('done', 'cancelled')AND i.origin_type = 'autopilot'AND i.origin_id = $2AND i.project_id IS NOT DISTINCT FROM $3::uuid@@ -1075,7 +1075,7 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.propertiesFROM issue iWHERE i.workspace_id = $1- AND i.status NOT IN ('done', 'cancelled')+ AND issue_effective_status(i.workspace_id, i.status) NOT IN ('done', 'cancelled')AND ($2::text IS NULL OR i.priority = $2)AND ($3::uuid IS NULL OR i.assignee_id = $3)AND ($4::uuid[] IS NULL OR i.assignee_id = ANY($4::uuid[]))diff --git a/server/pkg/db/generated/issue_status.sql.go b/server/pkg/db/generated/issue_status.sql.gonew file mode 100644index 0000000000..1af7310a03--- /dev/null+++ b/server/pkg/db/generated/issue_status.sql.go@@ -0,0 +1,367 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: issue_status.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const archiveIssueStatusEntry = `-- name: ArchiveIssueStatusEntry :one+UPDATE issue_status SET+ archived_at = now(),+ updated_at = now()+WHERE id = $1::uuid+ AND workspace_id = $2::uuid+ AND is_system = FALSE+ AND archived_at IS NULL+RETURNING id, workspace_id, key, name, description, category, color, is_system, position, archived_at, created_at, updated_at+`++type ArchiveIssueStatusEntryParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Built-ins are excluded by is_system: archiving one would delete its+// category's behavior definition. Callers must migrate issues off the status+// first; CountIssuesUsingStatusKey is the guard.+func (q *Queries) ArchiveIssueStatusEntry(ctx context.Context, arg ArchiveIssueStatusEntryParams) (IssueStatus, error) {+ row := q.db.QueryRow(ctx, archiveIssueStatusEntry, arg.ID, arg.WorkspaceID)+ var i IssueStatus+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Key,+ &i.Name,+ &i.Description,+ &i.Category,+ &i.Color,+ &i.IsSystem,+ &i.Position,+ &i.ArchivedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const countIssuesUsingStatusKey = `-- name: CountIssuesUsingStatusKey :one+SELECT COUNT(*)::bigint FROM issue+WHERE workspace_id = $1::uuid+ AND status = $2::text+`++type CountIssuesUsingStatusKeyParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Key string `json:"key"`+}++func (q *Queries) CountIssuesUsingStatusKey(ctx context.Context, arg CountIssuesUsingStatusKeyParams) (int64, error) {+ row := q.db.QueryRow(ctx, countIssuesUsingStatusKey, arg.WorkspaceID, arg.Key)+ var column_1 int64+ err := row.Scan(&column_1)+ return column_1, err+}++const createIssueStatusEntry = `-- name: CreateIssueStatusEntry :one+INSERT INTO issue_status (workspace_id, key, name, description, category, color, position)+VALUES (+ $1::uuid,+ $2::text,+ $3::text,+ $4::text,+ $5::text,+ $6::text,+ COALESCE(+ (SELECT MAX(position) + 1 FROM issue_status+ WHERE workspace_id = $1::uuid+ AND category = $5::text),+ 0+ )+)+RETURNING id, workspace_id, key, name, description, category, color, is_system, position, archived_at, created_at, updated_at+`++type CreateIssueStatusEntryParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Key string `json:"key"`+ Name string `json:"name"`+ Description string `json:"description"`+ Category string `json:"category"`+ Color string `json:"color"`+}++// Custom statuses only: is_system is never set here, so the canonical-key and+// non-archivable CHECK constraints can only ever apply to seeded rows.+func (q *Queries) CreateIssueStatusEntry(ctx context.Context, arg CreateIssueStatusEntryParams) (IssueStatus, error) {+ row := q.db.QueryRow(ctx, createIssueStatusEntry,+ arg.WorkspaceID,+ arg.Key,+ arg.Name,+ arg.Description,+ arg.Category,+ arg.Color,+ )+ var i IssueStatus+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Key,+ &i.Name,+ &i.Description,+ &i.Category,+ &i.Color,+ &i.IsSystem,+ &i.Position,+ &i.ArchivedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const deleteIssueStatusEntriesForWorkspace = `-- name: DeleteIssueStatusEntriesForWorkspace :exec+DELETE FROM issue_status WHERE workspace_id = $1::uuid+`++// No foreign keys by project rule, so workspace teardown cleans up here.+func (q *Queries) DeleteIssueStatusEntriesForWorkspace(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteIssueStatusEntriesForWorkspace, workspaceID)+ return err+}++const getIssueStatusEntryByID = `-- name: GetIssueStatusEntryByID :one+SELECT id, workspace_id, key, name, description, category, color, is_system, position, archived_at, created_at, updated_at FROM issue_status+WHERE id = $1::uuid+ AND workspace_id = $2::uuid+`++type GetIssueStatusEntryByIDParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetIssueStatusEntryByID(ctx context.Context, arg GetIssueStatusEntryByIDParams) (IssueStatus, error) {+ row := q.db.QueryRow(ctx, getIssueStatusEntryByID, arg.ID, arg.WorkspaceID)+ var i IssueStatus+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Key,+ &i.Name,+ &i.Description,+ &i.Category,+ &i.Color,+ &i.IsSystem,+ &i.Position,+ &i.ArchivedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getIssueStatusEntryByKey = `-- name: GetIssueStatusEntryByKey :one+SELECT id, workspace_id, key, name, description, category, color, is_system, position, archived_at, created_at, updated_at FROM issue_status+WHERE workspace_id = $1::uuid+ AND key = $2::text+`++type GetIssueStatusEntryByKeyParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Key string `json:"key"`+}++func (q *Queries) GetIssueStatusEntryByKey(ctx context.Context, arg GetIssueStatusEntryByKeyParams) (IssueStatus, error) {+ row := q.db.QueryRow(ctx, getIssueStatusEntryByKey, arg.WorkspaceID, arg.Key)+ var i IssueStatus+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Key,+ &i.Name,+ &i.Description,+ &i.Category,+ &i.Color,+ &i.IsSystem,+ &i.Position,+ &i.ArchivedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const listIssueStatusEntries = `-- name: ListIssueStatusEntries :many+SELECT id, workspace_id, key, name, description, category, color, is_system, position, archived_at, created_at, updated_at FROM issue_status+WHERE workspace_id = $1::uuid+ AND ($2::bool OR archived_at IS NULL)+ORDER BY+ CASE category+ WHEN 'backlog' THEN 0+ WHEN 'todo' THEN 1+ WHEN 'in_progress' THEN 2+ WHEN 'in_review' THEN 3+ WHEN 'done' THEN 4+ WHEN 'blocked' THEN 5+ WHEN 'cancelled' THEN 6+ ELSE 7+ END,+ position,+ key+`++type ListIssueStatusEntriesParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IncludeArchived bool `json:"include_archived"`+}++// Ordered by category rank (the historical STATUS_ORDER, so the default board+// and picker stay pixel-identical for a workspace with no custom statuses),+// then intra-category position, then key as a stable tiebreak.+func (q *Queries) ListIssueStatusEntries(ctx context.Context, arg ListIssueStatusEntriesParams) ([]IssueStatus, error) {+ rows, err := q.db.Query(ctx, listIssueStatusEntries, arg.WorkspaceID, arg.IncludeArchived)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueStatus{}+ for rows.Next() {+ var i IssueStatus+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Key,+ &i.Name,+ &i.Description,+ &i.Category,+ &i.Color,+ &i.IsSystem,+ &i.Position,+ &i.ArchivedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const lockIssueStatusCatalog = `-- name: LockIssueStatusCatalog :exec+SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':issue_status', 0))+`++// EXCLUSIVE transaction lock over a workspace's status catalog, held by archive+// so no issue can be written onto a status between the in-use census and the+// archive itself. pg_advisory_xact_lock (not pg_try_) so a concurrent archive+// queues instead of failing.+func (q *Queries) LockIssueStatusCatalog(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, lockIssueStatusCatalog, workspaceID)+ return err+}++const lockIssueStatusCatalogShared = `-- name: LockIssueStatusCatalogShared :exec+SELECT pg_advisory_xact_lock_shared(hashtextextended($1::uuid::text || ':issue_status', 0))+`++// SHARED counterpart, taken by a write that puts an issue ON a custom status.+// Shared holders do not block each other, so concurrent issue writes keep their+// current throughput; they only block against archive's exclusive lock.+//+// Built-in statuses deliberately do NOT take this lock: a built-in can never be+// archived (enforced by issue_status_system_not_archivable), so there is nothing+// to race with, and the overwhelmingly common write path stays lock-free.+func (q *Queries) LockIssueStatusCatalogShared(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, lockIssueStatusCatalogShared, workspaceID)+ return err+}++const seedIssueStatusEntries = `-- name: SeedIssueStatusEntries :exec++INSERT INTO issue_status (workspace_id, key, name, description, category, color, is_system, position)+VALUES+ ($1::uuid, 'backlog', 'Backlog', 'Parked. Assigning an issue here never starts an agent run.', 'backlog', '#6b7280', TRUE, 0),+ ($1::uuid, 'todo', 'Todo', 'Queued for work. Moving an issue here starts the assigned agent.', 'todo', '#6b7280', TRUE, 0),+ ($1::uuid, 'in_progress', 'In Progress', 'Actively being worked on.', 'in_progress', '#f59e0b', TRUE, 0),+ ($1::uuid, 'in_review', 'In Review', 'Work delivered, waiting on human review. Finalizes the autopilot run.', 'in_review', '#22c55e', TRUE, 0),+ ($1::uuid, 'done', 'Done', 'Completed.', 'done', '#3b82f6', TRUE, 0),+ ($1::uuid, 'blocked', 'Blocked', 'Stalled on an external dependency.', 'blocked', '#ef4444', TRUE, 0),+ ($1::uuid, 'cancelled', 'Cancelled', 'Decided not to do.', 'cancelled', '#6b7280', TRUE, 0)+ON CONFLICT DO NOTHING+`++// Issue status catalog (MUL-6243). Each workspace holds the 7 built-in+// statuses plus any custom ones. A category's value IS its canonical built-in+// key, so resolving a custom status to its platform behavior is a plain column+// read — no mapping table, no second concept.+// Idempotent seed of the 7 built-ins. Safe to call concurrently from multiple+// pods during a rolling deploy: the unique (workspace_id, key) index makes a+// losing racer a no-op rather than an error. Positions are intra-category, and+// each built-in is the only member of its category at seed time, so all 0.+func (q *Queries) SeedIssueStatusEntries(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, seedIssueStatusEntries, workspaceID)+ return err+}++const updateIssueStatusEntry = `-- name: UpdateIssueStatusEntry :one+UPDATE issue_status SET+ name = COALESCE($1, name),+ description = COALESCE($2, description),+ color = COALESCE($3, color),+ position = COALESCE($4, position),+ updated_at = now()+WHERE id = $5::uuid+ AND workspace_id = $6::uuid+ AND is_system = FALSE+ AND archived_at IS NULL+RETURNING id, workspace_id, key, name, description, category, color, is_system, position, archived_at, created_at, updated_at+`++type UpdateIssueStatusEntryParams struct {+ Name pgtype.Text `json:"name"`+ Description pgtype.Text `json:"description"`+ Color pgtype.Text `json:"color"`+ Position pgtype.Float8 `json:"position"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// key and category are absent on purpose: both are immutable after create.+// The is_system guard is what enforces "built-in name and color are locked" at+// the storage layer, so a handler bug cannot rename a built-in.+func (q *Queries) UpdateIssueStatusEntry(ctx context.Context, arg UpdateIssueStatusEntryParams) (IssueStatus, error) {+ row := q.db.QueryRow(ctx, updateIssueStatusEntry,+ arg.Name,+ arg.Description,+ arg.Color,+ arg.Position,+ arg.ID,+ arg.WorkspaceID,+ )+ var i IssueStatus+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Key,+ &i.Name,+ &i.Description,+ &i.Category,+ &i.Color,+ &i.IsSystem,+ &i.Position,+ &i.ArchivedAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 8abcafcf6f..722150b301 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -725,6 +725,21 @@ type IssueReaction struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}+type IssueStatus struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Key string `json:"key"`+ Name string `json:"name"`+ Description string `json:"description"`+ Category string `json:"category"`+ Color string `json:"color"`+ IsSystem bool `json:"is_system"`+ Position float64 `json:"position"`+ ArchivedAt pgtype.Timestamptz `json:"archived_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type IssueSubscriber struct {IssueID pgtype.UUID `json:"issue_id"`UserType string `json:"user_type"`diff --git a/server/pkg/db/generated/project.sql.go b/server/pkg/db/generated/project.sql.goindex 656a631309..4410548c46 100644--- a/server/pkg/db/generated/project.sql.go+++ b/server/pkg/db/generated/project.sql.go@@ -152,7 +152,7 @@ func (q *Queries) GetProjectInWorkspace(ctx context.Context, arg GetProjectInWorconst getProjectIssueStats = `-- name: GetProjectIssueStats :manySELECT project_id,count(*)::bigint AS total_count,- count(*) FILTER (WHERE status IN ('done', 'cancelled'))::bigint AS done_count+ count(*) FILTER (WHERE issue_effective_status(workspace_id, status) IN ('done', 'cancelled'))::bigint AS done_countFROM issueWHERE project_id = ANY($1::uuid[])GROUP BY project_iddiff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex 79063b5d49..1256bd4e41 100644--- a/server/pkg/db/queries/inbox.sql+++ b/server/pkg/db/queries/inbox.sql@@ -144,4 +144,8 @@ WHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2 AND-- name: ArchiveCompletedInbox :execrowsUPDATE inbox_item i SET archived = trueWHERE i.workspace_id = $1 AND i.recipient_type = 'member' AND i.recipient_id = $2 AND i.archived = false- AND i.issue_id IN (SELECT id FROM issue WHERE status IN ('done', 'cancelled'));+ AND i.issue_id IN (+ SELECT id FROM issue+ WHERE workspace_id = $1+ AND issue_effective_status(workspace_id, status) IN ('done', 'cancelled')+ );diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 867b60b133..290490b500 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -182,7 +182,7 @@ SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0));-- name: FindActiveDuplicateIssue :oneSELECT * FROM issueWHERE workspace_id = $1- AND status NOT IN ('done', 'cancelled')+ AND issue_effective_status(workspace_id, status) NOT IN ('done', 'cancelled')AND 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')@@ -192,7 +192,7 @@ LIMIT 1;-- name: FindRecentAutopilotDuplicateIssue :oneSELECT i.* FROM issue iWHERE i.workspace_id = $1- AND i.status NOT IN ('done', 'cancelled')+ AND issue_effective_status(i.workspace_id, i.status) NOT IN ('done', 'cancelled')AND i.origin_type = 'autopilot'AND i.origin_id = $2AND i.project_id IS NOT DISTINCT FROM sqlc.arg('project_id')::uuid@@ -241,7 +241,7 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.propertiesFROM issue iWHERE i.workspace_id = $1- AND i.status NOT IN ('done', 'cancelled')+ AND issue_effective_status(i.workspace_id, i.status) NOT IN ('done', 'cancelled')AND (sqlc.narg('priority')::text IS NULL OR i.priority = sqlc.narg('priority'))AND (sqlc.narg('assignee_id')::uuid IS NULL OR i.assignee_id = sqlc.narg('assignee_id'))AND (sqlc.narg('assignee_ids')::uuid[] IS NULL OR i.assignee_id = ANY(sqlc.narg('assignee_ids')::uuid[]))@@ -397,7 +397,7 @@ GROUP BY assignee_type, assignee_id;-- name: ChildIssueProgress :manySELECT parent_issue_id,COUNT(*)::bigint AS total,- COUNT(*) FILTER (WHERE status IN ('done', 'cancelled'))::bigint AS done+ COUNT(*) FILTER (WHERE issue_effective_status(workspace_id, status) IN ('done', 'cancelled'))::bigint AS doneFROM issueWHERE workspace_id = $1AND parent_issue_id IS NOT NULLdiff --git a/server/pkg/db/queries/issue_status.sql b/server/pkg/db/queries/issue_status.sqlnew file mode 100644index 0000000000..027e5d9044--- /dev/null+++ b/server/pkg/db/queries/issue_status.sql@@ -0,0 +1,126 @@+-- Issue status catalog (MUL-6243). Each workspace holds the 7 built-in+-- statuses plus any custom ones. A category's value IS its canonical built-in+-- key, so resolving a custom status to its platform behavior is a plain column+-- read — no mapping table, no second concept.++-- name: SeedIssueStatusEntries :exec+-- Idempotent seed of the 7 built-ins. Safe to call concurrently from multiple+-- pods during a rolling deploy: the unique (workspace_id, key) index makes a+-- losing racer a no-op rather than an error. Positions are intra-category, and+-- each built-in is the only member of its category at seed time, so all 0.+INSERT INTO issue_status (workspace_id, key, name, description, category, color, is_system, position)+VALUES+ (sqlc.arg('workspace_id')::uuid, 'backlog', 'Backlog', 'Parked. Assigning an issue here never starts an agent run.', 'backlog', '#6b7280', TRUE, 0),+ (sqlc.arg('workspace_id')::uuid, 'todo', 'Todo', 'Queued for work. Moving an issue here starts the assigned agent.', 'todo', '#6b7280', TRUE, 0),+ (sqlc.arg('workspace_id')::uuid, 'in_progress', 'In Progress', 'Actively being worked on.', 'in_progress', '#f59e0b', TRUE, 0),+ (sqlc.arg('workspace_id')::uuid, 'in_review', 'In Review', 'Work delivered, waiting on human review. Finalizes the autopilot run.', 'in_review', '#22c55e', TRUE, 0),+ (sqlc.arg('workspace_id')::uuid, 'done', 'Done', 'Completed.', 'done', '#3b82f6', TRUE, 0),+ (sqlc.arg('workspace_id')::uuid, 'blocked', 'Blocked', 'Stalled on an external dependency.', 'blocked', '#ef4444', TRUE, 0),+ (sqlc.arg('workspace_id')::uuid, 'cancelled', 'Cancelled', 'Decided not to do.', 'cancelled', '#6b7280', TRUE, 0)+ON CONFLICT DO NOTHING;++-- name: ListIssueStatusEntries :many+-- Ordered by category rank (the historical STATUS_ORDER, so the default board+-- and picker stay pixel-identical for a workspace with no custom statuses),+-- then intra-category position, then key as a stable tiebreak.+SELECT * FROM issue_status+WHERE workspace_id = sqlc.arg('workspace_id')::uuid+ AND (sqlc.arg('include_archived')::bool OR archived_at IS NULL)+ORDER BY+ CASE category+ WHEN 'backlog' THEN 0+ WHEN 'todo' THEN 1+ WHEN 'in_progress' THEN 2+ WHEN 'in_review' THEN 3+ WHEN 'done' THEN 4+ WHEN 'blocked' THEN 5+ WHEN 'cancelled' THEN 6+ ELSE 7+ END,+ position,+ key;++-- name: GetIssueStatusEntryByKey :one+SELECT * FROM issue_status+WHERE workspace_id = sqlc.arg('workspace_id')::uuid+ AND key = sqlc.arg('key')::text;++-- name: GetIssueStatusEntryByID :one+SELECT * FROM issue_status+WHERE id = sqlc.arg('id')::uuid+ AND workspace_id = sqlc.arg('workspace_id')::uuid;++-- name: CreateIssueStatusEntry :one+-- Custom statuses only: is_system is never set here, so the canonical-key and+-- non-archivable CHECK constraints can only ever apply to seeded rows.+INSERT INTO issue_status (workspace_id, key, name, description, category, color, position)+VALUES (+ sqlc.arg('workspace_id')::uuid,+ sqlc.arg('key')::text,+ sqlc.arg('name')::text,+ sqlc.arg('description')::text,+ sqlc.arg('category')::text,+ sqlc.arg('color')::text,+ COALESCE(+ (SELECT MAX(position) + 1 FROM issue_status+ WHERE workspace_id = sqlc.arg('workspace_id')::uuid+ AND category = sqlc.arg('category')::text),+ 0+ )+)+RETURNING *;++-- name: UpdateIssueStatusEntry :one+-- key and category are absent on purpose: both are immutable after create.+-- The is_system guard is what enforces "built-in name and color are locked" at+-- the storage layer, so a handler bug cannot rename a built-in.+UPDATE issue_status SET+ name = COALESCE(sqlc.narg('name'), name),+ description = COALESCE(sqlc.narg('description'), description),+ color = COALESCE(sqlc.narg('color'), color),+ position = COALESCE(sqlc.narg('position'), position),+ updated_at = now()+WHERE id = sqlc.arg('id')::uuid+ AND workspace_id = sqlc.arg('workspace_id')::uuid+ AND is_system = FALSE+ AND archived_at IS NULL+RETURNING *;++-- name: ArchiveIssueStatusEntry :one+-- Built-ins are excluded by is_system: archiving one would delete its+-- category's behavior definition. Callers must migrate issues off the status+-- first; CountIssuesUsingStatusKey is the guard.+UPDATE issue_status SET+ archived_at = now(),+ updated_at = now()+WHERE id = sqlc.arg('id')::uuid+ AND workspace_id = sqlc.arg('workspace_id')::uuid+ AND is_system = FALSE+ AND archived_at IS NULL+RETURNING *;++-- name: CountIssuesUsingStatusKey :one+SELECT COUNT(*)::bigint FROM issue+WHERE workspace_id = sqlc.arg('workspace_id')::uuid+ AND status = sqlc.arg('key')::text;++-- name: DeleteIssueStatusEntriesForWorkspace :exec+-- No foreign keys by project rule, so workspace teardown cleans up here.+DELETE FROM issue_status WHERE workspace_id = sqlc.arg('workspace_id')::uuid;++-- name: LockIssueStatusCatalog :exec+-- EXCLUSIVE transaction lock over a workspace's status catalog, held by archive+-- so no issue can be written onto a status between the in-use census and the+-- archive itself. pg_advisory_xact_lock (not pg_try_) so a concurrent archive+-- queues instead of failing.+SELECT pg_advisory_xact_lock(hashtextextended(sqlc.arg('workspace_id')::uuid::text || ':issue_status', 0));++-- name: LockIssueStatusCatalogShared :exec+-- SHARED counterpart, taken by a write that puts an issue ON a custom status.+-- Shared holders do not block each other, so concurrent issue writes keep their+-- current throughput; they only block against archive's exclusive lock.+--+-- Built-in statuses deliberately do NOT take this lock: a built-in can never be+-- archived (enforced by issue_status_system_not_archivable), so there is nothing+-- to race with, and the overwhelmingly common write path stays lock-free.+SELECT pg_advisory_xact_lock_shared(hashtextextended(sqlc.arg('workspace_id')::uuid::text || ':issue_status', 0));diff --git a/server/pkg/db/queries/project.sql b/server/pkg/db/queries/project.sqlindex bc67883b81..a399bd78e7 100644--- a/server/pkg/db/queries/project.sql+++ b/server/pkg/db/queries/project.sql@@ -61,7 +61,7 @@ WHERE project_id = $1;-- name: GetProjectIssueStats :manySELECT project_id,count(*)::bigint AS total_count,- count(*) FILTER (WHERE status IN ('done', 'cancelled'))::bigint AS done_count+ count(*) FILTER (WHERE issue_effective_status(workspace_id, status) IN ('done', 'cancelled'))::bigint AS done_countFROM issueWHERE project_id = ANY(sqlc.arg('project_ids')::uuid[])GROUP BY project_id;